Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): add qualified Hyprland isolated input (#3572)

Francesco Bonaccic5a15f3df3b2
diff --git a/.github/scripts/tests/test_ci_rust_linux_capture.py b/.github/scripts/tests/test_ci_rust_linux_capture.py
new file mode 100644
index 0000000000..f794eb0fe7
--- /dev/null
+++ b/.github/scripts/tests/test_ci_rust_linux_capture.py
@@ -0,0 +1,67 @@
+"""Execute the capture CI shell with synthetic commands and no desktop."""
+
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import tempfile
+import unittest
+
+import yaml
+
+
+ROOT = Path(__file__).resolve().parents[3]
+WORKFLOW = ROOT / ".github/workflows/ci-rust-linux.yml"
+
+
+def capture_script():
+ steps = yaml.safe_load(WORKFLOW.read_text())["jobs"]["unit"]["steps"]
+ return next(step["run"] for step in steps if step.get("name") ==
+ "Run X11 MIT-SHM capture correctness and performance regression")
+
+
+class CaptureCiTests(unittest.TestCase):
+ def run_script(self, script, cargo_status):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ commands = {
+ "Xvfb": "exec sleep 30",
+ "xdpyinfo": "exit 0",
+ "git": "printf '%040d\\n' 1",
+ "cargo": f"printf 'synthetic capture result\\n'; exit {cargo_status}",
+ "sha256sum": "exit 0",
+ }
+ for name, body in commands.items():
+ path = root / name
+ path.write_text("#!/bin/sh\n" + body + "\n")
+ path.chmod(0o700)
+ # GitHub's implicit bash runner uses -e, not pipefail. Execute the
+ # actual step, including its child-process cleanup and tee pipeline.
+ result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-c", script],
+ cwd=root, env={**os.environ, "PATH": str(root) + os.pathsep + os.environ["PATH"]},
+ text=True, capture_output=True, timeout=10)
+ self.assertIn("synthetic capture result", (root / "x11-capture-evidence.log").read_text())
+ return result.returncode
+
+ def test_capture_failure_is_not_hidden_by_tee(self):
+ self.assertNotEqual(self.run_script(capture_script(), 23), 0)
+
+ def test_capture_success_succeeds(self):
+ self.assertEqual(self.run_script(capture_script(), 0), 0)
+
+ def test_regression_reproduces_the_prior_false_green(self):
+ old = capture_script().replace("set -euo pipefail\n", "")
+ self.assertEqual(self.run_script(old, 23), 0)
+
+ def test_readiness_probes_do_not_reset_disposable_servers(self):
+ servers = [shlex.split(line) for line in capture_script().splitlines()
+ if line.startswith("Xvfb ")]
+ self.assertEqual(len(servers), 2)
+ self.assertTrue(all("-noreset" in command for command in servers))
+ source = (ROOT / "libs/cua-driver/rust/crates/platform-linux/src/capture.rs").read_text()
+ helper = source.split("impl XvfbServer {", 1)[1].split("fn stop(", 1)[0]
+ self.assertIn('"-noreset"', helper)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index 289c9454e1..489126811e 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -1,7 +1,11 @@
"""Regression tests for cua-driver-rs release and PyPI wiring."""
import json
+import os
from pathlib import Path
+import subprocess
+import tempfile
+import textwrap
import unittest
@@ -21,14 +25,14 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):
self.assertNotIn("branches:\n - main", workflow)
self.assertIn("github.event.workflow_run.conclusion == 'success'", workflow)
self.assertIn(" actions: read", workflow)
- self.assertIn('RUN_ID="${{ github.event.workflow_run.id }}"', workflow)
+ self.assertIn('RUN_ID: ${{ github.event.workflow_run.id }}', workflow)
self.assertIn(
'actions/runs/$RUN_ID/artifacts?per_page=100',
workflow,
)
self.assertIn("cua-driver-release-metadata-", workflow)
self.assertIn('"${#RELEASE_VERSIONS[@]}" -gt 1', workflow)
- sha_fallback = 'HEAD_SHA="${{ github.event.workflow_run.head_sha }}"'
+ sha_fallback = 'git tag --points-at "$HEAD_SHA"'
self.assertIn(sha_fallback, workflow)
self.assertLess(
workflow.index("cua-driver-release-metadata-"),
@@ -36,6 +40,150 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):
)
self.assertIn('gh release view "$TAG" --repo "$GITHUB_REPOSITORY"', workflow)
+ def run_sdk_version_step(
+ self, metadata: str, *, manual: bool = False, artifacts: str = "",
+ tag: str = "cua-driver-rs-v0.23.2", release_status: int = 0,
+ input_version: str = "0.23.2",
+ ) -> tuple[subprocess.CompletedProcess, dict[str, str]]:
+ workflow = self.read(".github/workflows/cd-py-cua-driver.yml")
+ step = workflow.split(" - name: Determine version\n", 1)[1]
+ script = textwrap.dedent(
+ step.split(" run: |\n", 1)[1].split("\n # Build wheels", 1)[0]
+ )
+ self.assertNotIn("${{", script)
+ mocks = r'''
+gh() {
+ if [ "$1" = api ]; then
+ printf '%s\n' "$TEST_ARTIFACTS"
+ elif [ "$*" = "release view $TEST_TAG --repo example/repo --json tagName,isDraft" ]; then
+ printf '%s' "$TEST_METADATA"
+ return "$TEST_RELEASE_STATUS"
+ else
+ echo "Unexpected gh arguments: $*" >&2
+ return 99
+ fi
+}
+git() {
+ case "$*" in
+ 'fetch --tags') ;;
+ "tag --points-at $HEAD_SHA") printf '%s\n' "$TEST_TAG" ;;
+ *) echo "Unexpected git arguments: $*" >&2; return 99 ;;
+ esac
+}
+# macOS ships Bash 3; emulate only the array read used by this Ubuntu step.
+if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
+ mapfile() {
+ [ "$*" = '-t RELEASE_VERSIONS' ] || return 99
+ RELEASE_VERSIONS=()
+ while IFS= read -r line; do
+ RELEASE_VERSIONS+=("$line")
+ done
+ }
+fi
+'''
+ with tempfile.TemporaryDirectory() as temp:
+ output = Path(temp) / "outputs"
+ result = subprocess.run(
+ ["bash", "-eo", "pipefail", "-c", mocks + script],
+ cwd=REPO_ROOT,
+ env={
+ **os.environ,
+ "EVENT_NAME": "workflow_dispatch" if manual else "workflow_run",
+ "INPUT_VERSION": input_version,
+ "RUN_ID": "123",
+ "HEAD_SHA": "a" * 40,
+ "GITHUB_REPOSITORY": "example/repo",
+ "GITHUB_OUTPUT": str(output),
+ "RUNNER_TEMP": temp,
+ "TEST_ARTIFACTS": artifacts,
+ "TEST_TAG": tag,
+ "TEST_METADATA": metadata,
+ "TEST_RELEASE_STATUS": str(release_status),
+ },
+ capture_output=True, text=True,
+ )
+ outputs = dict(
+ line.split("=", 1)
+ for line in (output.read_text().splitlines() if output.exists() else [])
+ )
+ return result, outputs
+
+ def test_sdk_publish_requires_exact_published_release_metadata(self) -> None:
+ tag = "cua-driver-rs-v0.23.2"
+ cases = {
+ "published": (json.dumps({"tagName": tag, "isDraft": False}), 0, True),
+ "published_prerelease": (
+ json.dumps({"tagName": tag, "isDraft": False, "isPrerelease": True}),
+ 0, True,
+ ),
+ "draft": (json.dumps({"tagName": tag, "isDraft": True}), 0, False),
+ "missing": ("", 1, False),
+ "wrong_tag": ('{"tagName":"cua-driver-rs-v9.9.9","isDraft":false}', 0, False),
+ "malformed": ("not json", 0, False),
+ "empty": ("", 0, False),
+ "null": ("null", 0, False),
+ "missing_draft": (json.dumps({"tagName": tag}), 0, False),
+ "string_draft": (json.dumps({"tagName": tag, "isDraft": "false"}), 0, False),
+ "multiple_objects": (
+ json.dumps({"tagName": tag, "isDraft": False}) + '\n{}', 0, False,
+ ),
+ }
+ for manual in (False, True):
+ for name, (metadata, status, publish) in cases.items():
+ with self.subTest(manual=manual, metadata=name):
+ result, outputs = self.run_sdk_version_step(
+ metadata, manual=manual, release_status=status,
+ )
+ if manual and not publish:
+ self.assertNotEqual(result.returncode, 0, result.stdout)
+ self.assertNotEqual(outputs.get("should_publish"), "true")
+ else:
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(outputs["should_publish"], str(publish).lower())
+ self.assertEqual(outputs["tag"], tag)
+
+ def test_sdk_publish_artifact_resolution_also_checks_publication(self) -> None:
+ for draft in (False, True):
+ with self.subTest(draft=draft):
+ result, outputs = self.run_sdk_version_step(
+ json.dumps({"tagName": "cua-driver-rs-v0.23.2", "isDraft": draft}),
+ artifacts="cua-driver-release-metadata-0.23.2",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(outputs["should_publish"], str(not draft).lower())
+
+ def test_sdk_publish_no_matching_tag_skips(self) -> None:
+ result, outputs = self.run_sdk_version_step("", tag="")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(outputs, {
+ "version": "0.0.0", "tag": "cua-driver-rs-v0.0.0", "should_publish": "false",
+ })
+
+ def test_sdk_publish_accepts_published_prerelease_versions(self) -> None:
+ for version in ("0.23.2-rc.1", "0.23.2+build.7", "0.23.2-rc.1+build.7"):
+ tag = "cua-driver-rs-v" + version
+ for manual, artifacts in ((True, ""), (False, ""),
+ (False, "cua-driver-release-metadata-" + version)):
+ with self.subTest(version=version, manual=manual, artifacts=artifacts):
+ result, outputs = self.run_sdk_version_step(
+ json.dumps({"tagName": tag, "isDraft": False, "isPrerelease": True}),
+ manual=manual, artifacts=artifacts, tag=tag, input_version=version,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(outputs, {
+ "version": version, "tag": tag, "should_publish": "true",
+ })
+
+ def test_sdk_publish_rejects_invalid_versions(self) -> None:
+ for version in ("0.23.2/other", "$(exit 0)", "0.23.2\nshould_publish=true"):
+ with self.subTest(version=version):
+ result, outputs = self.run_sdk_version_step(
+ "", manual=True, input_version=version,
+ )
+ self.assertNotEqual(result.returncode, 0, result.stdout)
+ self.assertIn("Invalid Cua Driver version:", result.stderr)
+ self.assertNotEqual(outputs.get("should_publish"), "true")
+
def test_python_publish_defaults_to_current_rust_version(self) -> None:
workflow = self.read(".github/workflows/cd-py-cua-driver.yml")
@@ -524,7 +672,7 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):
"github.event_name == 'workflow_dispatch' && inputs.publish && "
"format('refs/tags/cua-driver-rs-v{0}', inputs.version) || github.ref"
)
- self.assertEqual(workflow.count(immutable_ref), 6)
+ self.assertEqual(workflow.count(immutable_ref), 7)
self.assertIn(
"name: Ensure Rust target is installed\n"
" working-directory: libs/cua-driver/rust",
@@ -665,7 +813,7 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):
self.assertIn(
"[build-linux, build-windows, build-macos-universal, "
"verify-windows-node-runtime, "
- "verify-release-artifacts, verify-mcp-client-discovery]",
+ "verify-release-artifacts, verify-mcp-client-discovery, build-hyprland-plugin-source]",
workflow,
)
diff --git a/.github/workflows/cd-py-cua-driver.yml b/.github/workflows/cd-py-cua-driver.yml
index 825077763d..5137cf3470 100644
--- a/.github/workflows/cd-py-cua-driver.yml
+++ b/.github/workflows/cd-py-cua-driver.yml
@@ -39,19 +39,22 @@ jobs:
id: version
env:
GH_TOKEN: ${{ github.token }}
+ EVENT_NAME: ${{ github.event_name }}
+ INPUT_VERSION: ${{ inputs.version }}
+ RUN_ID: ${{ github.event.workflow_run.id }}
+ HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
- if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
- VERSION="${{ inputs.version }}"
+ if [ "$EVENT_NAME" == "workflow_dispatch" ]; then
+ VERSION="$INPUT_VERSION"
if [ -z "$VERSION" ]; then
VERSION=$(sed -n -E 's/^version = "([^"]+)"/\1/p' libs/cua-driver/rust/Cargo.toml | head -1)
fi
- SHOULD_PUBLISH="true"
+ TAG="cua-driver-rs-v$VERSION"
else
# Publish dispatches run from main, so workflow_run.head_sha is the
# workflow revision rather than the immutable release tag. Resolve
# those runs from the exact metadata artifact produced by the
# successful release job.
- RUN_ID="${{ github.event.workflow_run.id }}"
if ! echo "$RUN_ID" | grep -qE '^[0-9]+$'; then
echo "Invalid workflow run ID: $RUN_ID" >&2
exit 1
@@ -63,7 +66,7 @@ jobs:
> "$ARTIFACTS_FILE"
mapfile -t RELEASE_VERSIONS < <(
sed -nE \
- 's/^cua-driver-release-metadata-([0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.-]+)?)$/\1/p' \
+ 's/^cua-driver-release-metadata-([0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?)$/\1/p' \
"$ARTIFACTS_FILE" | sort -u
)
@@ -78,7 +81,6 @@ jobs:
# Tag-triggered candidate builds do not run the release job and
# therefore have no release metadata artifact. Preserve the tag
# SHA fallback so those runs continue to skip until publication.
- HEAD_SHA="${{ github.event.workflow_run.head_sha }}"
if ! echo "$HEAD_SHA" | grep -qE '^[0-9a-f]{40}$'; then
echo "Invalid SHA format: $HEAD_SHA" >&2
exit 1
@@ -88,16 +90,29 @@ jobs:
VERSION="${TAG#cua-driver-rs-v}"
fi
- if [ -n "$TAG" ] && gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
- SHOULD_PUBLISH="true"
- elif [ -n "$TAG" ]; then
- echo "GitHub Release $TAG is not available; skipping SDK publish."
- SHOULD_PUBLISH="false"
- else
+ if [ -z "$TAG" ]; then
VERSION="0.0.0"
- SHOULD_PUBLISH="false"
fi
fi
+
+ if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then
+ echo "Invalid Cua Driver version: $VERSION" >&2
+ exit 1
+ fi
+ SHOULD_PUBLISH="false"
+ # Authenticated release reads also find drafts. Only the exact,
+ # published component release may feed either SDK publisher.
+ if [ -n "$TAG" ] && RELEASE_METADATA=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json tagName,isDraft) &&
+ jq -e -s --arg tag "$TAG" \
+ 'length == 1 and (.[0] | type == "object" and .tagName == $tag and .isDraft == false)' \
+ <<< "$RELEASE_METADATA" >/dev/null 2>&1; then
+ SHOULD_PUBLISH="true"
+ elif [ "$EVENT_NAME" == "workflow_dispatch" ]; then
+ echo "GitHub Release $TAG must be published before SDK recovery." >&2
+ exit 1
+ else
+ echo "GitHub Release $TAG is not verified as published; skipping SDK publish."
+ fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "tag=cua-driver-rs-v$VERSION" >> "$GITHUB_OUTPUT"
echo "should_publish=$SHOULD_PUBLISH" >> "$GITHUB_OUTPUT"
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.yml
index 949d5bbfe8..5fb2cd12f0 100644
--- a/.github/workflows/cd-rust-cua-driver.yml
+++ b/.github/workflows/cd-rust-cua-driver.yml
@@ -907,6 +907,61 @@ jobs:
path: libs/cua-driver/rust/release/cua-driver-rs-*-darwin-*.tar.gz
if-no-files-found: error
+ # Source/build-kit assets only: native plugin certification is a separate gate.
+ # Nightly builds rewrite Cargo versions in the worktree, so they cannot supply
+ # a committed, stable-version source archive under the same provenance contract.
+ build-hyprland-plugin-source:
+ name: pinned Hyprland plugin source
+ needs: release-attribution-preflight
+ if: >-
+ inputs.channel != 'nightly' &&
+ (startsWith(github.ref, 'refs/tags/cua-driver-rs-v') ||
+ (github.event_name == 'workflow_dispatch' && inputs.publish == true))
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ ref: ${{ inputs.source_ref || github.event_name == 'workflow_dispatch' && inputs.publish && format('refs/tags/cua-driver-rs-v{0}', inputs.version) || github.ref }}
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - name: Generate exact-tag plugin source assets
+ id: source
+ env:
+ REQUESTED_VERSION: ${{ inputs.version }}
+ run: |
+ set -euo pipefail
+ if [[ "$GITHUB_REF" == refs/tags/cua-driver-rs-v* ]]; then
+ VERSION="${GITHUB_REF#refs/tags/cua-driver-rs-v}"
+ else
+ VERSION="$REQUESTED_VERSION"
+ fi
+ SHA=$(git rev-parse HEAD)
+ TAG_SHA=$(git rev-parse --verify "refs/tags/cua-driver-rs-v${VERSION}^{commit}")
+ test "$SHA" = "$TAG_SHA"
+ SOURCE_VERSION=$(git show "${SHA}:libs/cua-driver/rust/Cargo.toml" | \
+ python3 -c 'import sys, tomllib; print(tomllib.loads(sys.stdin.read())["workspace"]["package"]["version"])')
+ test "$VERSION" = "$SOURCE_VERSION"
+ # Historical tags predating the bundler retain Driver-only recovery.
+ # An existing helper that fails generation is never silently skipped.
+ if ! git cat-file -e "${SHA}:libs/cua-driver/hyprland-plugin/packaging/release/bundle.py"; then
+ echo "Legacy source has no plugin bundler; preserving Driver-only release."
+ exit 0
+ fi
+ # The generator requires tag SHA and committed Cargo version agreement.
+ python3 libs/cua-driver/hyprland-plugin/packaging/release/bundle.py \
+ --repo . --revision "$(git rev-parse HEAD)" \
+ --driver-version "$VERSION" --release-assets \
+ --output plugin-release-assets
+ echo "available=true" >> "$GITHUB_OUTPUT"
+ - uses: actions/upload-artifact@v4
+ if: steps.source.outputs.available == 'true'
+ with:
+ name: cua-hyprland-plugin-source
+ path: plugin-release-assets/*.tar.gz
+ if-no-files-found: error
+
# Verify the exact candidate archives before a release can publish. This is
# intentionally separate from the build steps: artifact upload/download is
# part of the release boundary, and checking only the staging directories
@@ -1017,7 +1072,7 @@ jobs:
# evidence exists.
release:
needs:
- [build-linux, build-windows, build-macos-universal, verify-windows-node-runtime, verify-release-artifacts, verify-mcp-client-discovery]
+ [build-linux, build-windows, build-macos-universal, verify-windows-node-runtime, verify-release-artifacts, verify-mcp-client-discovery, build-hyprland-plugin-source]
if: github.event_name == 'workflow_dispatch' && inputs.publish == true
runs-on: ubuntu-latest
steps:
@@ -1128,13 +1183,41 @@ jobs:
echo "Release files:"
ls -lh release-upload/
+ # Match the source job's Python/zlib runtime for deterministic archives.
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+
+ - name: Verify staged plugin source assets
+ run: |
+ set -euo pipefail
+ VERSION="${{ steps.version.outputs.version }}"
+ SHA="${{ steps.version.outputs.sha }}"
+ shopt -s nullglob
+ PLUGIN_ASSETS=(release-upload/cua-hyprland-plugin-*.tar.gz)
+ if git cat-file -e HEAD:libs/cua-driver/hyprland-plugin/packaging/release/bundle.py 2>/dev/null; then
+ test "${#PLUGIN_ASSETS[@]}" -eq 2
+ # Rebuild deterministic source assets from the exact tag. Missing,
+ # extra, misnamed, or changed downloads must fail before publication.
+ python3 libs/cua-driver/hyprland-plugin/packaging/release/bundle.py \
+ --repo . --revision "$SHA" --driver-version "$VERSION" \
+ --release-assets --output plugin-release-expected
+ for EXPECTED in plugin-release-expected/*.tar.gz; do
+ cmp "$EXPECTED" "release-upload/$(basename "$EXPECTED")"
+ done
+ else
+ # Legacy tag recovery has no plugin source job or plugin assets.
+ test "${#PLUGIN_ASSETS[@]}" -eq 0
+ fi
+
- name: Generate SHA256 checksums
run: |
cd release-upload
{
echo "## SHA256 Checksums"
echo '```'
- shasum -a 256 cua-driver-rs-*.{tar.gz,zip} 2>/dev/null | sort
+ shopt -s nullglob
+ shasum -a 256 cua-driver-rs-*.{tar.gz,zip} cua-hyprland-plugin-*.tar.gz 2>/dev/null | sort
echo '```'
} > checksums.txt
diff --git a/.github/workflows/ci-hyprland-plugin.yml b/.github/workflows/ci-hyprland-plugin.yml
index 240f430bde..dd9890aaa9 100644
--- a/.github/workflows/ci-hyprland-plugin.yml
+++ b/.github/workflows/ci-hyprland-plugin.yml
@@ -42,8 +42,11 @@ jobs:
run: |
python3 -c 'import ast; from pathlib import Path; [ast.parse(p.read_text()) for p in Path("tests").glob("*.py")]'
bash -n packaging/arch/PKGBUILD
+ bash -n packaging/release/PKGBUILD.in
- name: Check lifecycle runner cleanup
run: python3 -m unittest discover -s tests -p '*_test.py' -v
+ - name: Check pinned source-release contracts
+ run: python3 -m unittest discover -s packaging/release -p 'test_*.py' -v
# No real Hyprland headers, module load, or desktop certification in this job.
- name: Configure unit and mock tests
run: |
diff --git a/.github/workflows/ci-rust-linux.yml b/.github/workflows/ci-rust-linux.yml
index 359d57ab41..6458339b99 100644
--- a/.github/workflows/ci-rust-linux.yml
+++ b/.github/workflows/ci-rust-linux.yml
@@ -54,6 +54,11 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+ - name: Verify shared fixture scroll journal
+ run: node --test libs/cua-driver/tests/fixtures/shared/web/journal.test.cjs
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2
with:
@@ -64,10 +69,15 @@ jobs:
sudo apt-get install -y --no-install-recommends \
clang pkg-config libdbus-1-dev libpipewire-0.3-dev libspa-0.2-dev \
libei-dev libxkbcommon-dev libx11-dev libxi-dev libxtst-dev libxext-dev \
- imagemagick xvfb xauth x11-utils
+ imagemagick xvfb xauth x11-utils ffmpeg
- name: Run Linux Rust tests
working-directory: libs/cua-driver/rust
run: cargo test -p cua-driver -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: Verify final-frame extraction without a desktop
+ working-directory: libs/cua-driver/rust
+ run: |
+ cargo test -p cua-driver --test e2e_environment_preflight_test --locked -- \
+ --ignored --exact last_frame_extraction_handles_long_final_duration_and_invalid_input --nocapture
- name: Run X11 overlay click-through regression
working-directory: libs/cua-driver/rust
run: |
@@ -82,9 +92,10 @@ jobs:
- name: Run X11 MIT-SHM capture correctness and performance regression
working-directory: libs/cua-driver/rust
run: |
- Xvfb :98 -screen 0 1920x1080x24 -ac -nolisten tcp >xvfb-98.log 2>&1 &
+ set -euo pipefail
+ Xvfb :98 -screen 0 1920x1080x24 -ac -noreset -nolisten tcp >xvfb-98.log 2>&1 &
xvfb_primary=$!
- Xvfb :99 -screen 0 1920x1080x24 -ac -nolisten tcp >xvfb-99.log 2>&1 &
+ Xvfb :99 -screen 0 1920x1080x24 -ac -noreset -nolisten tcp >xvfb-99.log 2>&1 &
xvfb_secondary=$!
trap 'kill "$xvfb_primary" "$xvfb_secondary" 2>/dev/null || true' EXIT
for display in :98 :99; do
diff --git a/.github/workflows/ci-test-scripts.yml b/.github/workflows/ci-test-scripts.yml
index 1b7159394a..b9f83d39f3 100644
--- a/.github/workflows/ci-test-scripts.yml
+++ b/.github/workflows/ci-test-scripts.yml
@@ -9,6 +9,7 @@ on:
- ".github/release-backfill/**"
- ".github/releases/**"
- ".github/workflows/cd-rust-cua-driver.yml"
+ - ".github/workflows/cd-py-cua-driver.yml"
- ".github/workflows/ci-cua-driver-installer-compat.yml"
- ".github/workflows/ci-release-metadata.yml"
- ".github/workflows/cd-swift-lume.yml"
diff --git a/docs/content/docs/reference/cua-driver/platform-support.mdx b/docs/content/docs/reference/cua-driver/platform-support.mdx
index dbdbc06f40..1751f7eb2a 100644
--- a/docs/content/docs/reference/cua-driver/platform-support.mdx
+++ b/docs/content/docs/reference/cua-driver/platform-support.mdx
@@ -79,7 +79,7 @@ For the relationship between distributions, desktops, and compositors, read
| ------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| X11/Xorg | Supported | Window discovery and capture, AT-SPI trees and actions, foreground pointer and keyboard input, semantic background delivery, desktop scope, and structured refusals | Raw background delivery depends on the target toolkit. X11 accepting an event does not prove the application handled it. |
| Sway (wlroots reference lane) | Supported with limits | The complete typed Electron, Tauri, GTK, capture, and desktop-scope catalog, including foreground/background and AX/PX outcomes | Focus-bound and raw background input shapes without a target-addressed protocol return structured refusals. Other wlroots compositors are expected to share protocol support but are not yet proven. |
-| Hyprland / Omarchy | Experimental | Separate [driver-branch and plugin-foundation evidence](#hyprland-and-omarchy); neither establishes a released general Hyprland support claim | Do not inherit Sway coverage. The optional plugin is discovery-only and does not deliver input. Driver capture, activation, semantic actions, and raw background input require separate evidence. |
+| Hyprland / Omarchy | Experimental | Separate [driver, discovery-foundation, and input-candidate evidence](#hyprland-and-omarchy); no released general Hyprland support claim | Do not inherit Sway coverage. The default plugin build is discovery-only. The opt-in input v3 source candidate requires complete native harness acceptance, bounded qualified-app evidence, and release validation. |
| GNOME/Mutter | Supported with limits | AT-SPI actions, GTK controls, compositor-backed window geometry and capture, verified foreground activation, and portal/libei foreground input | The bundled WinRects Shell helper and one Shell-session restart are prerequisites for authoritative geometry and activation. Portal video recording remains incomplete. |
| KDE/KWin | Experimental | Plasma 6 session startup, GTK AT-SPI discovery, generic discovery where exposed, and portal interface availability | The optional KWin helper exposes read-only window identity and state, not activation or input. Raw target-addressed input refuses until a target-bound KWin input path exists; no complete behavioral matrix is accepted. |
| `cua-compositor` nested session | Experimental | Native GTK behavior, capture and scope, private route metadata, independent observation, and per-cell video | The complete shared renderer matrix is not accepted. Unicode text and a canonical parallel-drag row remain unproven; this route does not establish a stock-Wayland capability. |
@@ -90,23 +90,63 @@ For the relationship between distributions, desktops, and compositors, read
Omarchy uses Hyprland; it is not a separate display protocol. Modern Hyprland
is not based on wlroots, so its support must be recorded separately from Sway.
-The following is a source-work status snapshot as of September 5, 2026, not an
+The following is a source-work status snapshot as of September 7, 2026, not an
installer or release-support matrix:
| Work | Evidence and boundary |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Driver capture and observation | [Draft PR #3557](https://github.com/trycua/cua/pull/3557) reports scale-1 GTK3 capture, semantic actions, and independent focus/cursor checks at source `b50a4f78f277d05700200e84c5d0f0ea72f10c47`. Its canonical native suite stopped at the foreground-key preflight; no matrix cells ran. This is focused branch evidence, not desktop certification or released support. |
-| Optional Hyprland plugin | [PR #3547](https://github.com/trycua/cua/pull/3547) adds discovery and liveness only. Its [validation report](https://github.com/trycua/cua/blob/feat/hyprland-plugin-foundation/libs/cua-driver/hyprland-plugin/tests/validation.md) records native build and live lifecycle evidence on Hyprland `0.56.2`. All six input message types return `background_unavailable`; the foundation creates no synthetic seat and changes no Driver delivery route. |
-| Isolated raw background input | [Draft experiment #3572](https://github.com/trycua/cua/pull/3572) contains a separately opted-in synthetic-seat integration. Its [desktop-transition report](https://github.com/trycua/cua/blob/e8542dece6c8195a8db50ba79aba9615a78340b1/libs/cua-driver/hyprland-plugin/tests/desktop-state-validation.md) records focused Fleet evidence and tested revisions. The experiment is not part of the discovery foundation, a released capability, or an accepted production input/authorization contract. |
+| Driver capture and observation | [Merged PR #3557](https://github.com/trycua/cua/pull/3557) reports scale-1 GTK3 capture, semantic actions, and independent focus/cursor checks at source `b50a4f78f277d05700200e84c5d0f0ea72f10c47`. That candidate's canonical native suite stopped at the foreground-key preflight; no matrix cells ran. This is historical focused evidence, not desktop certification or released support. |
+| Optional Hyprland plugin | [Merged PR #3547](https://github.com/trycua/cua/pull/3547) adds discovery and liveness only. Its [validation report](https://github.com/trycua/cua/blob/7c58a4d5b078b81f657d8e7e906712f8e3a96148/libs/cua-driver/hyprland-plugin/tests/validation.md) records native build and live lifecycle evidence on Hyprland `0.56.2`. All six input message types return `background_unavailable`; the foundation creates no synthetic seat and changes no Driver delivery route. |
+| Isolated raw background input | [PR #3572](https://github.com/trycua/cua/pull/3572) records dated, exact-source validation results for the experimental input v3 candidate, using Driver's shared per-action policy and two independent compositor seats. Complete native harness acceptance and bounded qualified-app proof are separate requirements. Earlier [desktop-transition evidence](https://github.com/trycua/cua/blob/e8542dece6c8195a8db50ba79aba9615a78340b1/libs/cua-driver/hyprland-plugin/tests/desktop-state-validation.md) belongs to the separate signed experiment. The candidate is not released. |
The plugin is disabled by default and outside the portable driver installation
path. Switching driver channels alone does not install or enable it. Its
Hyprland ABI and compiler toolchain must match the compositor that loads it.
+The v3 candidate adds no Omarchy-specific approval panel or external signer.
+Driver applies its normal permission, resource, and lifecycle checks on every
+action. Same-user local sockets and application qualification do not sandbox
+native code running as the desktop user. The two seats, `Cua-Agent` and
+`Cua-Agent-2`, persist across configuration disable/re-enable; replacing the
+plugin requires a desktop restart.
+
+The initial native application qualification scope is Calc from
+`libreoffice-fresh 26.2.5-3` and Inkscape `1.4.4-6`. Driver checks the running
+executable against the expected package path and exact local package metadata
+before each action. Those checks establish eligibility for the candidate, not
+proof that every application operation works. The plugin requires a live native
+surface and the exact compiled default `evdev`/`pc105`/`us` keymap. Variants,
+options, remaps, multiple layout groups, Unicode, IME input, arbitrary held-key
+streams, and modified pointer gestures are outside the candidate. Chromium,
+Electron, and XWayland raw background input are also outside this scope.
+Semantic AT-SPI actions retain their separate behavior.
+
+The explicitly requested foreground route binds an exact native top-level
+surface and intentionally changes primary focus and, for pointer actions,
+cursor position. It does not restore either. The canonical native harness
+covers defined GTK3, Electron, and Tauri foreground cases; background refusals
+never select this route automatically.
+
+Bounded instrumented two-seat app proof and an uninstrumented smoke are retained
+from source `f180e8828b8f31cc153e3c44eaa89a9c13c5bc68`, with an unchanged
+plugin tree and uninstrumented module hash at
+`1133a06e4f205cf80188a7ac9e41102f37611fea`. This evidence covers only the
+recorded actions and observation intervals. It does not replace acceptance of
+the unchanged complete Linux canonical runner on native Hyprland.
+
+Unsupported targets and desktop states refuse. The candidate does not silently
+switch to foreground input, wake a display, or unlock a session. A dispatch
+acknowledgement does not prove an application effect; canceled, partial, or
+unknown actions must not be replayed automatically.
+
The recorded plugin Fleet environment used Omarchy `4.0.1-1` and Cua Driver
`0.22.2`. It does not certify the separate physical-host acceptance target of
-Omarchy `4.0.2-1` with Cua Driver `0.23.2`, or application control through
-either driver version. See the
+Omarchy `4.0.2-1` with Cua Driver `0.23.2`. The candidate source also reports
+`0.23.2`, but published Driver `0.23.2` does not contain these branch changes.
+Source evidence, compatible release artifacts, and final Fleet image packaging
+and lifecycle validation are separate gates. Physical-host parity requires a
+separate acceptance run; it is not a gate for publishing a validated Fleet
+image. See the
[Hyprland roadmap](/reference/cua-driver/platform-roadmap#hyprland-and-omarchy)
for the remaining design and validation gates.
diff --git a/libs/cua-driver/docs/action-support.md b/libs/cua-driver/docs/action-support.md
index a728cf9ec7..c86d1a4d2e 100644
--- a/libs/cua-driver/docs/action-support.md
+++ b/libs/cua-driver/docs/action-support.md
@@ -84,6 +84,22 @@ PX background left-click rows may resolve the screen point to an actionable
AT-SPI node. Such a pass proves the public PX-addressed behavior and its desktop
side effects, but it does not prove raw pixel delivery to canvases or games.
+The [accepted Hyprland foreground extension](https://github.com/trycua/cua/issues/3550#issuecomment-5564996417)
+is planned support, not an empirical pass in this table. Production protocol v3
+advertises `foreground_target:true` and binds `FOREGROUND_TARGET` to the exact
+native top-level surface for activation, click, key, scroll, and bounded drag.
+Driver expands bounded ASCII text under the exact US keymap; Unicode and IME
+input remain outside this route. Native GTK3, Electron, and Tauri foreground
+coverage still requires the complete canonical Linux suite in native Hyprland.
+
+Foreground delivery may activate the target and move the primary cursor, with
+no restoration promise. Held keys/buttons, grabs, constraints, and drag-and-drop
+must refuse before takeover; foreground drag interruption still requires review
+and native verification. This route has no Calc/Inkscape package gate. Background
+`TARGET` retains its Calc/Inkscape qualification and never escalates to
+foreground. Observation followed by global `wtype` input is not an exact-target
+fallback. Both routes retain the common permission and lifecycle contract.
+
## Maintenance rule
Update this document only when a typed row is added, removed, or changes
diff --git a/libs/cua-driver/docs/test-harnesses-guide.md b/libs/cua-driver/docs/test-harnesses-guide.md
index 6a4fed73a1..35cace94dd 100644
--- a/libs/cua-driver/docs/test-harnesses-guide.md
+++ b/libs/cua-driver/docs/test-harnesses-guide.md
@@ -50,6 +50,87 @@ Historical `*-plan.md`, `*-journal.md`, and release evidence documents record
what was run at that time. They are not current execution instructions and do
not override this guide or `scripts/ci/README.md`.
+### Hyprland validation decision (2026-09-07)
+
+[PR #3572](https://github.com/trycua/cua/pull/3572) is the dated, exact-source
+result record for the input v3 candidate. It distinguishes ordinary CI, the
+complete hosted X11, Sway, and Windows harnesses, native Hyprland acceptance,
+and bounded app evidence. A native behavioral pass with a failed wrapper or
+source-provenance check is not an accepted run. Use that record for results;
+the coverage requirements below do not assert a passing result or add macOS
+certification.
+
+The maintainer selects the same canonical Linux Rust harness for native
+Hyprland: run `scripts/ci/linux/run-rust-e2e.sh` with its complete `all` suite
+in the prepared native Hyprland desktop at the exact candidate SHA. Preserve
+the runner's required cells, assertions, and evidence checks. Record compositor
+and backend provenance; an X11 run does not establish native Hyprland coverage.
+Environment failures and failed cells remain failures, not permission to skip
+tests or change expected results.
+
+Before launching the native Hyprland harness, apply this map-time rule in the
+disposable desktop's Lua configuration and reload it:
+
+```lua
+hl.window_rule({
+ name = "cua-canonical-sentinel-animation",
+ match = {title = "^CuaTestHarness Sentinel \\[cdp=[0-9]+\\]$"},
+ no_anim = true,
+})
+```
+
+The preflight independently verifies `no_anim` for the exact sentinel, then
+waits for mapped fullscreen readiness before its first Driver activation.
+`hyprctl clients` reports geometry goals, not animated surface bounds; repeated
+equal goals alone cannot establish animation completion. This rule changes
+only the test sentinel's animation, not its placement or the product's geometry
+guard. Restore the original configuration after the run. It is a deterministic
+fixture requirement, not an Omarchy user configuration requirement.
+
+This is fixture regression coverage. For background `TARGET` input, the production compatibility gate in
+`platform-linux/src/wayland/hyprland_compatibility.rs` admits only the qualified
+native Calc `26.2.5-3` and Inkscape `1.4.4-6` packages. Ordinary GTK, Electron,
+and Tauri fixtures do not qualify for v3 background raw input. Their declared refusals
+can prove refusal behavior, but cannot prove plugin delivery or isolation.
+Do not widen background production admission or add a test bypass to make them qualify.
+
+The [accepted foreground extension](https://github.com/trycua/cua/issues/3550#issuecomment-5564996417)
+adds a separate production `FOREGROUND_TARGET` route for ordinary native
+top-level surfaces, advertised by `HELLO` with `foreground_target:true`.
+It does not apply the Calc/Inkscape background package gate. The existing
+complete suite covers defined native GTK3, Electron, and Tauri foreground
+cases. Acceptance requires those cases to pass. Preserve the runner and tests.
+Foreground activation and primary-cursor movement are intentional, with no
+restoration promise. Verify exact-target delivery and refusals for held
+keys/buttons, grabs, constraints, and drag-and-drop before primary takeover.
+Foreground drag cancellation on primary-input/focus transitions requires
+review and native evidence. No background refusal may escalate to this route.
+
+Retain a short real-app production smoke and instrumented isolation proof on
+both qualified apps as supporting compatibility evidence. Verify actual app
+effects, plugin transport attribution, primary-seat isolation, and cleanup;
+the uninstrumented smoke alone cannot establish those trace-based claims.
+The retained proof at source `f180e8828b8f31cc153e3c44eaa89a9c13c5bc68`
+includes 20 instrumented actions, nine pointer effects, and six observation
+intervals, plus an uninstrumented six-action smoke. Saved outputs confirm Calc
+cell A1 contains `a` and the Inkscape object's x-coordinate changes from 40 to
+42 while y remains 60. The plugin tree and uninstrumented module hash are
+unchanged at `1133a06e4f205cf80188a7ac9e41102f37611fea`. This is bounded
+supporting evidence, not a complete app matrix or release-byte proof. Raw
+background qualification remains native Calc from `libreoffice-fresh 26.2.5-3`,
+Inkscape `1.4.4-6`, the plain compiled `evdev`/`pc105`/`us` keymap, and two
+seats. Chromium, Electron, and XWayland raw background input remain unqualified;
+semantic AT-SPI actions are separate.
+See [production proof preparation](../hyprland-plugin/tests/production-proof.md)
+for the bounded plans and their limits.
+
+Three complete repetitions of the long Python Calc/Inkscape plan, including
+the 34 policy cases across both apps, are no longer a merge requirement.
+Extended Python stress runs remain diagnostics for specific unresolved
+failures. This decision changes test strategy, records no new passing result,
+and does not waive the affected CI, native evidence, or release gates in
+[RFC 3550](../../../rfcs/3550-hyprland-isolated-input.md).
+
## Repository Map
```text
diff --git a/libs/cua-driver/hyprland-plugin/CMakeLists.txt b/libs/cua-driver/hyprland-plugin/CMakeLists.txt
index 584ec9efaa..e507463bbc 100644
--- a/libs/cua-driver/hyprland-plugin/CMakeLists.txt
+++ b/libs/cua-driver/hyprland-plugin/CMakeLists.txt
@@ -3,6 +3,16 @@ cmake_minimum_required(VERSION 3.30)
project(cua_hyprland_plugin VERSION 0.1.0 LANGUAGES CXX)
option(CUA_HYPRLAND_BUILD_PLUGIN "Build the ABI-pinned Hyprland plugin" ON)
+option(CUA_HYPRLAND_INPUT "Build trusted-local per-action input protocol v3 candidate" OFF)
+option(CUA_HYPRLAND_INPUT_TRACE "Instrument v3 input for native certification only" OFF)
+option(CUA_HYPRLAND_TEST_INPUT "Build nonshipping isolated-input VM experiment" OFF)
+if(CUA_HYPRLAND_INPUT AND CUA_HYPRLAND_TEST_INPUT)
+ message(FATAL_ERROR "Production v3 and signed experimental input are mutually exclusive")
+endif()
+if(CUA_HYPRLAND_INPUT_TRACE AND NOT CUA_HYPRLAND_INPUT)
+ message(FATAL_ERROR "Input trace instrumentation requires CUA_HYPRLAND_INPUT")
+endif()
+set(CUA_HYPRLAND_TEST_OPERATOR_KEY "" CACHE STRING "Test operator Ed25519 public key (hex); never a private key")
set(CUA_HYPRLAND_EXPECTED_VERSION "" CACHE STRING
"Require an exact hyprland pkg-config version when building the plugin")
@@ -30,6 +40,36 @@ cua_hyprland_harden(cua_hyprland_protocol)
set_target_properties(cua_hyprland_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)
if(BUILD_TESTING)
+ add_executable(cua_hyprland_foreground_route_test tests/foreground_route_test.cpp)
+ target_compile_features(cua_hyprland_foreground_route_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_foreground_route_test PRIVATE src)
+ target_compile_options(cua_hyprland_foreground_route_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ add_test(NAME cua_hyprland_foreground_route_test COMMAND cua_hyprland_foreground_route_test)
+
+ add_executable(cua_hyprland_passive_pointer_target_test tests/passive_pointer_target_test.cpp)
+ target_compile_features(cua_hyprland_passive_pointer_target_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_passive_pointer_target_test PRIVATE src)
+ target_compile_options(cua_hyprland_passive_pointer_target_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ add_test(NAME cua_hyprland_passive_pointer_target_test COMMAND cua_hyprland_passive_pointer_target_test)
+
+ add_executable(cua_hyprland_input_client_deadline_test tests/input_client_deadline_test.cpp)
+ target_compile_features(cua_hyprland_input_client_deadline_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_input_client_deadline_test PRIVATE src)
+ target_compile_options(cua_hyprland_input_client_deadline_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ add_test(NAME cua_hyprland_input_client_deadline_test COMMAND cua_hyprland_input_client_deadline_test)
+
+ add_executable(cua_hyprland_input_grant_test tests/input_grant_test.cpp)
+ target_compile_features(cua_hyprland_input_grant_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_input_grant_test PRIVATE src)
+ target_compile_options(cua_hyprland_input_grant_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ add_test(NAME cua_hyprland_input_grant_test COMMAND cua_hyprland_input_grant_test)
+
+ add_executable(cua_hyprland_drag_geometry_test tests/drag_geometry_test.cpp)
+ target_compile_features(cua_hyprland_drag_geometry_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_drag_geometry_test PRIVATE src)
+ target_compile_options(cua_hyprland_drag_geometry_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ add_test(NAME cua_hyprland_drag_geometry_test COMMAND cua_hyprland_drag_geometry_test)
+
add_test(NAME cua_hyprland_cmake_api_test
COMMAND ${CMAKE_COMMAND}
-S ${CMAKE_CURRENT_SOURCE_DIR}/tests/cmake-api
@@ -82,6 +122,34 @@ if(UNIX)
set_target_properties(cua_hyprland_transport PROPERTIES POSITION_INDEPENDENT_CODE ON)
if(BUILD_TESTING)
+ foreach(lifetime_test IN ITEMS owned_socket_path seat_lifetime)
+ add_executable(cua_hyprland_${lifetime_test}_test tests/${lifetime_test}_test.cpp)
+ target_compile_features(cua_hyprland_${lifetime_test}_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_${lifetime_test}_test PRIVATE src)
+ target_compile_options(cua_hyprland_${lifetime_test}_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ add_test(NAME cua_hyprland_${lifetime_test}_test COMMAND cua_hyprland_${lifetime_test}_test)
+ endforeach()
+ add_executable(cua_hyprland_plugin_input_lifetime_test
+ tests/plugin_input_lifetime_test.cpp src/plugin.cpp)
+ target_compile_features(cua_hyprland_plugin_input_lifetime_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_plugin_input_lifetime_test PRIVATE tests tests/mock-hyprland include src)
+ target_compile_definitions(cua_hyprland_plugin_input_lifetime_test PRIVATE
+ CUA_HYPRLAND_PLUGIN_VERSION="${PROJECT_VERSION}" CUA_HYPRLAND_SOCKET1_API=0 CUA_HYPRLAND_TEST_INPUT=1)
+ target_compile_options(cua_hyprland_plugin_input_lifetime_test PRIVATE
+ -Wall -Wextra -Wpedantic -Werror -Wno-return-type-c-linkage)
+ target_link_libraries(cua_hyprland_plugin_input_lifetime_test PRIVATE cua_hyprland_transport)
+ add_test(NAME cua_hyprland_plugin_input_lifetime_test COMMAND cua_hyprland_plugin_input_lifetime_test)
+ add_executable(cua_hyprland_plugin_v3_lifetime_test
+ tests/plugin_input_lifetime_test.cpp src/plugin.cpp)
+ target_compile_features(cua_hyprland_plugin_v3_lifetime_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_plugin_v3_lifetime_test PRIVATE tests tests/mock-hyprland include src)
+ target_compile_definitions(cua_hyprland_plugin_v3_lifetime_test PRIVATE
+ CUA_HYPRLAND_PLUGIN_VERSION="${PROJECT_VERSION}" CUA_HYPRLAND_SOCKET1_API=0 CUA_HYPRLAND_INPUT=1)
+ target_compile_options(cua_hyprland_plugin_v3_lifetime_test PRIVATE
+ -Wall -Wextra -Wpedantic -Werror -Wno-return-type-c-linkage)
+ target_link_libraries(cua_hyprland_plugin_v3_lifetime_test PRIVATE cua_hyprland_transport)
+ add_test(NAME cua_hyprland_plugin_v3_lifetime_test COMMAND cua_hyprland_plugin_v3_lifetime_test)
+
add_executable(cua_hyprland_transport_test tests/transport_test.cpp)
target_compile_options(cua_hyprland_transport_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
target_link_libraries(cua_hyprland_transport_test PRIVATE cua_hyprland_transport)
@@ -138,6 +206,35 @@ if(CUA_HYPRLAND_BUILD_PLUGIN)
endif()
add_library(cua_hyprland_plugin MODULE src/plugin.cpp)
+ if(CUA_HYPRLAND_TEST_INPUT OR CUA_HYPRLAND_INPUT)
+ if(NOT HYPRLAND_VERSION STREQUAL "0.56.2")
+ message(FATAL_ERROR "Input is pinned to Hyprland 0.56.2")
+ endif()
+ target_sources(cua_hyprland_plugin PRIVATE src/input_experiment.cpp)
+ endif()
+ if(CUA_HYPRLAND_INPUT)
+ target_compile_definitions(cua_hyprland_plugin PRIVATE CUA_HYPRLAND_INPUT=1)
+ endif()
+ if(CUA_HYPRLAND_INPUT_TRACE OR CUA_HYPRLAND_TEST_INPUT)
+ target_sources(cua_hyprland_plugin PRIVATE src/primary_trace.cpp)
+ endif()
+ if(CUA_HYPRLAND_INPUT_TRACE)
+ target_compile_definitions(cua_hyprland_plugin PRIVATE CUA_HYPRLAND_INPUT_TRACE=1)
+ endif()
+ if(CUA_HYPRLAND_TEST_INPUT)
+ if(NOT CUA_HYPRLAND_TEST_OPERATOR_KEY MATCHES "^[0-9a-f]+$")
+ message(FATAL_ERROR "Test input requires a lowercase Ed25519 public key")
+ endif()
+ string(LENGTH "${CUA_HYPRLAND_TEST_OPERATOR_KEY}" key_length)
+ if(NOT key_length EQUAL 64)
+ message(FATAL_ERROR "Test operator public key must be 32 bytes")
+ endif()
+ find_package(OpenSSL REQUIRED)
+ target_compile_definitions(cua_hyprland_plugin PRIVATE
+ CUA_HYPRLAND_TEST_INPUT=1
+ CUA_HYPRLAND_TEST_OPERATOR_KEY="${CUA_HYPRLAND_TEST_OPERATOR_KEY}")
+ target_link_libraries(cua_hyprland_plugin PRIVATE OpenSSL::Crypto)
+ endif()
target_compile_features(cua_hyprland_plugin PRIVATE cxx_std_26)
target_compile_definitions(cua_hyprland_plugin PRIVATE
CUA_HYPRLAND_PLUGIN_VERSION="${PROJECT_VERSION}"
@@ -158,6 +255,16 @@ if(CUA_HYPRLAND_BUILD_PLUGIN)
CXX_VISIBILITY_PRESET hidden
PREFIX ""
OUTPUT_NAME "cua-hyprland-plugin")
+ if(CUA_HYPRLAND_TEST_INPUT OR CUA_HYPRLAND_INPUT)
+ # Hyprland exports inline manager globals. Hidden visibility would bind
+ # a private null copy instead of the running compositor's managers.
+ # GNU-unique definitions also pin a module in memory across dlclose.
+ set_target_properties(cua_hyprland_plugin PROPERTIES CXX_VISIBILITY_PRESET default)
+ target_compile_options(cua_hyprland_plugin PRIVATE -fno-gnu-unique)
+ # Retired seat resources must accept late client release requests after
+ # global removal. Keep their inert callbacks mapped until process exit.
+ target_link_options(cua_hyprland_plugin PRIVATE -Wl,-z,nodelete)
+ endif()
if(NOT CMAKE_READELF)
message(FATAL_ERROR "readelf is required to verify the plugin C++ runtime")
diff --git a/libs/cua-driver/hyprland-plugin/README.md b/libs/cua-driver/hyprland-plugin/README.md
index 739209538f..21cb2b3133 100644
--- a/libs/cua-driver/hyprland-plugin/README.md
+++ b/libs/cua-driver/hyprland-plugin/README.md
@@ -15,13 +15,55 @@ build checks its ELF dependencies and rejects a static C++ runtime; a compiler
copied without its runtime libraries can otherwise silently select a static
archive. Do not load a module from a failed build.
-The current foundation is discovery-only. It advertises protocol status and
-liveness, but it rejects every input mutation with the typed
-`background_unavailable` result. Target-addressed mutation remains gated on
-successful second-seat spikes and acceptance of the corresponding RFC.
-Neither stable Cua Driver `0.23.2` nor nightly provides isolated background
-input through this plugin. Here, discovery means negotiation, status, and
-liveness; it does not mean application target discovery or input delivery.
+The default build is discovery-only. It advertises protocol status and
+liveness, but rejects input mutation with the typed `background_unavailable`
+result. Here, discovery means negotiation, status, and liveness, not
+application target discovery or input delivery.
+
+This branch adds an opt-in [input v3 candidate](protocol/cua-input-v3.md) using
+Driver's existing per-action permission checks and two independent compositor
+seats. It does not require a signer or an Omarchy-specific approval panel.
+The candidate remains experimental and unreleased. A source version of
+`0.23.2` does not mean released Driver `0.23.2` contains these changes.
+[PR #3572](https://github.com/trycua/cua/pull/3572) records dated, exact-source
+validation results. Acceptance requires the unchanged complete Linux canonical
+runner on native Hyprland and separate bounded qualified-app proof. See the
+[shared admission boundary](protocol/host-authority-boundary.md) and
+[production proof preparation](tests/production-proof.md) for the native
+testing, packaging, and release requirements.
+
+Bounded instrumented app proof and an uninstrumented smoke are retained from
+source `f180e8828b8f31cc153e3c44eaa89a9c13c5bc68`, with an unchanged plugin
+tree and uninstrumented module hash at
+`1133a06e4f205cf80188a7ac9e41102f37611fea`. Raw background qualification is
+limited to native Calc from `libreoffice-fresh 26.2.5-3`, Inkscape `1.4.4-6`,
+the plain compiled `evdev`/`pc105`/`us` keymap, and the two seats `Cua-Agent`
+and `Cua-Agent-2`. The proof covers the recorded actions and observation
+intervals. Chromium, Electron, and XWayland raw background input remain
+unqualified; semantic AT-SPI actions are separate.
+
+The exact-target foreground route intentionally changes primary focus and,
+for pointer actions, cursor position, without restoration. The canonical native
+harness covers defined GTK3, Electron, and Tauri foreground cases. A background
+refusal never authorizes a hidden foreground fallback.
+
+This branch also contains a separate, opt-in
+[isolated-input compatibility experiment](protocol/input-experiment.md).
+It is not enabled by the normal build or package. Its test-only operator
+boundary and resident-module unload workaround are not a production contract.
+See the [input experiment validation](tests/input-validation.md) for the exact
+single-seat artifacts and the [concurrent real-app
+validation](tests/realapp-validation.md) for two-lane Calc/Inkscape evidence,
+event-level primary-cursor measurement, and Cancel/Stop results. Those
+historical candidates needed app restarts after plugin reload. The candidate
+keeps seats across config toggles and requires a desktop restart for plugin
+replacement; that lifecycle requires native acceptance evidence. This experiment
+does not establish production hot-reload support.
+
+The [desktop-state safety record](tests/desktop-state-validation.md) covers
+matched fault-only controls and background drags during target movement,
+resizing, destruction, real session lock, and display-off. It documents the
+tested artifacts and remaining gates, not production certification.
This design builds on Dillon DuPont's Hyprland injection prototype. That credit
records the prototype lineage; it does not claim that the prototype or input
@@ -39,6 +81,12 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
```
+To compile the production-protocol candidate in a disposable test environment,
+add `-DCUA_HYPRLAND_INPUT=ON`. This is separate from
+`CUA_HYPRLAND_TEST_INPUT`; selecting both refuses. Detailed event measurement
+also requires `-DCUA_HYPRLAND_INPUT_TRACE=ON`. Do not ship that instrumentation
+in the production package. Neither build option loads or enables the plugin.
+
For a pinned acceptance build, also set
`-DCUA_HYPRLAND_EXPECTED_VERSION=0.56.2` (or the exact intended pkg-config
version). The build refuses a different header version. The status-command
@@ -118,8 +166,11 @@ does not start or stop it. To disable the transport, remove the setting or set
it to false in the configuration and reload. Unloading the plugin also closes
the socket and every connection immediately.
-This enables same-user status and liveness packets only. It does not enable
-pointer, keyboard, scroll, drag, target discovery, or another input route.
+For the default discovery build, this enables status and liveness only. For
+the opt-in v3 build, it also opens the two input endpoints. Enabling v3 is a
+trusted-local desktop configuration choice; Driver still checks each call
+under its normal permission policy. The candidate refuses clients, layouts,
+and operations outside its qualification scope.
## Security boundary
@@ -130,10 +181,11 @@ pointer, keyboard, scroll, drag, target discovery, or another input route.
- The server verifies `SO_PEERCRED` and accepts only peers with the compositor
user's UID. This authenticates only the local Unix user, not a particular Cua
process. Filesystem permissions are defense in depth, not authorization.
-- Same-UID discovery is acceptable for this mutation-free foundation. Mutation
- capabilities stay disabled until the RFC defines an operator authorization,
- credential or lease lifetime, revocation, and replay-resistant binding to the
- negotiated compositor epoch.
+- The default foundation remains mutation-free. The separate v3 candidate
+ uses normal Driver policy plus per-action compositor target binding. It does
+ not sandbox arbitrary native code running as the desktop user. An app
+ compatibility list, socket permissions, or cursor indicator is not such a
+ sandbox.
- The transport is bounded, nonblocking Unix `SOCK_SEQPACKET`; oversized,
truncated, malformed, or unsupported packets are rejected without mutation.
- A client must complete `HELLO` within five seconds. A negotiated client must
@@ -166,6 +218,14 @@ application-state evidence. The host Hyprland/plugin ABI pair, plugin transport,
opaque target binding, and isolated raw background input each require their
own acceptance evidence on the exact host and candidate module.
+The input candidate resolves display-scoped manifest resources through a
+content-free Hyprland IPC geometry query, with the existing same-compositor
+peer check. This path requires one unscaled, unrotated output at the origin.
+It does not use a screenshot or an XWayland root as display identity, and it
+does not relax the manifest. Other layouts refuse this metadata query; native
+display metadata on other Wayland compositors remains a separate limitation.
+This source change is not evidence that the capability has been released.
+
Compositor administration also remains explicit. Integrations may invoke
`hyprctl` for an operator-requested workspace, monitor, window-rule, focus, or
DPMS operation, but a Cua background action must never hide a target-delivery
@@ -176,8 +236,8 @@ delivery evidence; an all-black frame while DPMS is off is not success.
plugin adds `hyprctl -j cua:status`, but it does not turn arbitrary `hyprctl`
commands into application-targeted input or application-delivery proof. Tests
must observe whether the stock foreground route explicitly activated a window
-and must keep that behavior separate from plugin mutation, which remains
-disabled.
+and must keep that behavior separate from the opt-in plugin routes. Mutation
+remains disabled in the default discovery-only build.
Application enumeration and call authorization also stay in Cua Driver.
Filtering `list_apps`, choosing a one-shot `cua-driver call` versus a long-lived
@@ -187,12 +247,17 @@ protocol; it does not replace the driver's tool policy or process lifecycle.
## Acceptance path
-Promotion beyond discovery requires focused protocol and security tests, Fleet
-image packaging and lifecycle tests, and the repository's representative Linux
-catalogs. The final gate is a physical Omarchy machine running the exact
-candidate Hyprland/plugin pair, with focus, z-order, cursor, input-isolation,
-and fixture-state evidence. VM or Fleet evidence supplements but does not
-replace that physical gate, which must run after the Fleet lane passes.
+The Fleet release path requires focused protocol and security tests, the
+repository's complete native Linux harness, bounded qualified-app compatibility
+and isolation evidence, review and merge, compatible release artifacts, and
+image packaging and lifecycle validation. Source-built proof does not establish
+that the released package or final image works.
+
+Physical-host support requires a separate acceptance run on the exact
+Hyprland/plugin pair, with focus, z-order, cursor, input-isolation, and
+fixture-state evidence. Fleet evidence does not establish physical-host parity;
+that separate support claim is not a prerequisite for publishing a validated
+Fleet image.
The exact initial host acceptance baseline is:
@@ -207,7 +272,9 @@ The exact initial host acceptance baseline is:
This baseline is an acceptance target, not a statement that the reported host
or its Hyprland/plugin ABI pair has passed validation. It is also not a claim
that isolated background input ships in stable `0.23.2` or nightly. The plugin
-remains discovery-only. The final physical run has explicit foreground
+remains discovery-only in its normal build. The separate physical run has explicit foreground
activation observation, GTK3, GTK4, Qt6, LibreOffice, Chromium/Ozone, Electron,
DPMS-off refusal, and one-shot and long-lived graphical-session client rows;
-see `tests/README.md` for the required evidence.
+see `tests/README.md` for the required evidence. Those broader application rows
+do not widen the raw-background qualification beyond the exact Calc/Inkscape
+packages, plain US keymap, and two seats documented in the input v3 contract.
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/PKGBUILD.in b/libs/cua-driver/hyprland-plugin/packaging/release/PKGBUILD.in
new file mode 100644
index 0000000000..da6668a04a
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/PKGBUILD.in
@@ -0,0 +1,71 @@
+# Generated from an explicit committed revision. No checkout is needed.
+# shellcheck shell=bash disable=SC2034,SC2154
+pkgname=cua-hyprland-plugin
+pkgver=@DRIVER_VERSION@
+pkgrel=1
+pkgdesc='Cua production input candidate for pinned Hyprland 0.56.2'
+arch=('x86_64')
+url='https://github.com/trycua/cua'
+license=('MIT')
+depends=('hyprland=0.56.2-1' 'gcc-libs')
+makedepends=('cmake>=3.30' 'ninja' 'pkgconf' 'binutils' 'python>=3.11' 'gcc')
+options=('!strip' '!debug' '!lto')
+_revision='@REVISION@'
+_stem='@STEM@'
+_archive_sha256='@ARCHIVE_SHA256@'
+_manifest_sha256='@MANIFEST_SHA256@'
+source=("https://github.com/trycua/cua/releases/download/cua-driver-rs-v${pkgver}/${_stem}.tar.gz")
+sha256sums=('@ARCHIVE_SHA256@')
+_cxx="${CUA_RELEASE_CXX:-/usr/bin/g++}"
+
+_verify() {
+ # Recheck even when makepkg --skipinteg or --noextract was requested.
+ printf '%s %s\n' "$_archive_sha256" "$SRCDEST/${_stem}.tar.gz" | sha256sum -c - || return 1
+ printf '%s %s\n' "$_manifest_sha256" "$srcdir/$_stem/SOURCE-PROVENANCE.json" | sha256sum -c - || return 1
+ local verifier_sha
+ verifier_sha="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["files"]["verify.py"])' \
+ "$srcdir/$_stem/SOURCE-PROVENANCE.json")" || return 1
+ printf '%s %s\n' "$verifier_sha" "$srcdir/$_stem/verify.py" | sha256sum -c - || return 1
+ python3 "$srcdir/$_stem/verify.py" --source "$srcdir/$_stem" \
+ --revision "$_revision" --driver-version "$pkgver" --cxx "$_cxx" "$@"
+}
+
+prepare() {
+ _verify
+}
+
+build() {
+ _verify || return 1
+ cmake -S "$srcdir/$_stem" -B "$srcdir/build" -G Ninja \
+ -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER="$_cxx" \
+ -DBUILD_TESTING=ON -DCUA_HYPRLAND_BUILD_PLUGIN=ON \
+ -DCUA_HYPRLAND_EXPECTED_VERSION=0.56.2 \
+ -DCUA_HYPRLAND_INPUT=ON -DCUA_HYPRLAND_TEST_INPUT=OFF \
+ -DCUA_HYPRLAND_INPUT_TRACE=OFF -DCUA_HYPRLAND_TEST_OPERATOR_KEY= || return 1
+ cmake --build "$srcdir/build"
+}
+
+check() {
+ _verify || return 1
+ # package() runs under fakeroot, whose getuid() shim disagrees with kernel
+ # SO_PEERCRED. Test the real same-user boundary without changing the parent
+ # packaging environment or skipping the mandatory packaging-time test run.
+ (
+ unset LD_PRELOAD FAKEROOTKEY FAKED_MODE
+ ctest --test-dir "$srcdir/build" --output-on-failure --no-tests=error
+ )
+}
+
+package() {
+ # Packaging always runs the tests, including makepkg --nocheck / --repackage.
+ check || return 1
+ _verify --build "$srcdir/build" --output "$srcdir/BUILD-PROVENANCE.json" || return 1
+ install -Dm755 "$srcdir/build/cua-hyprland-plugin.so" \
+ "$pkgdir/usr/lib/cua/hyprland/cua-hyprland-plugin.so" || return 1
+ install -Dm644 "$srcdir/$_stem/LICENSE.md" \
+ "$pkgdir/usr/share/licenses/$pkgname/LICENSE" || return 1
+ install -Dm644 "$srcdir/$_stem/SOURCE-PROVENANCE.json" \
+ "$pkgdir/usr/share/$pkgname/SOURCE-PROVENANCE.json" || return 1
+ install -Dm644 "$srcdir/BUILD-PROVENANCE.json" \
+ "$pkgdir/usr/share/$pkgname/BUILD-PROVENANCE.json"
+}
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/README.md b/libs/cua-driver/hyprland-plugin/packaging/release/README.md
new file mode 100644
index 0000000000..1a63a46c95
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/README.md
@@ -0,0 +1,131 @@
+# Pinned source release
+
+This directory prepares a standalone Arch recipe and source archive for the
+production input candidate. It does not certify native behavior or publish
+assets. The existing `../arch/PKGBUILD` remains a discovery-only local recipe.
+
+The candidate requires Linux x86_64, Hyprland headers `0.56.2`, the Arch package
+`hyprland=0.56.2-1`, and GCC `16.1.1 20260728`. Both the compositor and a compiler
+probe must carry the exact ELF comment `GCC: (GNU) 16.1.1 20260728`. The selected
+compiler must resolve the shared runtime `libstdc++.so.6.0.36`. Other architectures
+and toolchains need separate validation and an explicit contract update.
+
+## Prepare release assets
+
+After committing the source and these helpers, run the generator with Python
+3.11 or later from the release checkout. Replace `COMMIT_SHA` with the full
+40-character commit SHA, `DRIVER_VERSION` with its Cargo workspace version, and
+`NEW_OUTPUT_DIRECTORY` with a directory that does not yet exist:
+
+```sh
+python3 libs/cua-driver/hyprland-plugin/packaging/release/bundle.py \
+ --repo . --revision COMMIT_SHA --driver-version DRIVER_VERSION \
+ --output NEW_OUTPUT_DIRECTORY
+```
+
+The generator reads an explicit allowlist of Git blobs at that commit, including
+the root license and the recipe/verifier. It ignores dirty and untracked files,
+live test scripts, evidence, and unrelated tracked content. Archive ordering,
+ownership, modes, and timestamps are fixed. The manifest records each source
+file's SHA-256, the source revision, component version, plugin version, ABI pins,
+and build options. The recipe pins the archive and manifest checksums. Generation
+refuses an existing output directory and mismatched versions.
+
+The output contains the source tarball, `PKGBUILD`, `SOURCE-PROVENANCE.json`,
+the standalone operator `README.md` from `USAGE.md`, `lifecycle.py`, and
+`SHA256SUMS`.
+The package version follows the Driver release version; the plugin's
+CMake version is recorded separately.
+
+For component release assets, add `--release-assets`. This mode requires the
+exact `cua-driver-rs-vDRIVER_VERSION` tag to resolve to `COMMIT_SHA` and emits
+only two uniquely named archives:
+
+- `cua-hyprland-plugin-DRIVER_VERSION-COMMIT_SHA.tar.gz`: pinned source.
+- `cua-hyprland-plugin-DRIVER_VERSION-COMMIT_SHA-build-kit.tar.gz`: `PKGBUILD`,
+ `SOURCE-PROVENANCE.json`, operator `README.md`, `lifecycle.py`, and `SHA256SUMS`.
+
+The Driver release workflow generates these assets for stable component tag
+builds and publishing dispatches, with the same source override as the native
+Driver builds. The tag and committed Cargo version must match that source.
+Nightly and manual build-only runs do not generate plugin release assets.
+Recovery of historical tags that contain no bundler produces Driver-only
+assets. If a tag contains a bundler but generation fails, publication is blocked.
+Publication waits for this job and includes both archives in the component
+release checksums. The kit's `SHA256SUMS` remains inside its archive to avoid
+colliding with other release assets. Existing output directories are refused.
+
+The default local preparation mode does not require a tag. Neither mode resolves
+a generic latest release. Review the generated assets before publication.
+Checksums establish consistency with the reviewed recipe; they are
+not an independent signature or native certification.
+The manifest's `native_certified: false` describes the generator's evidence
+scope. An independently certified release must publish its separate native
+evidence for the exact revision and environment; this field does not negate it.
+
+## Build without a checkout
+
+Download both archives from the same exact component release and verify them
+against its published checksums. Extract the build kit into a dedicated empty
+directory and place the source tarball alongside the extracted files. Verify
+`SHA256SUMS` from that directory. Use the generated `README.md` for installation,
+activation, upgrade, restart, and rollback instructions.
+Review the recipe, provide the pinned Hyprland package and matching compiler,
+and run `makepkg` as an ordinary user. `makepkg` can download the pinned source
+tarball itself; no Git checkout is needed.
+
+If the compiler is staged outside `/usr/bin/g++`, select its absolute executable
+path with `CUA_RELEASE_CXX` when invoking `makepkg`. The recipe does not download
+or install a compiler, configure a runtime search path, or replace a compositor.
+The compiler and compositor must use the matching shared C++ runtime in the
+target environment. The recipe records the compiler executable, compiler
+runtime, compositor, and module hashes as build provenance.
+It also checks that `ldd` resolves the compositor and built module to the same
+runtime bytes as the compiler. A custom compiler does not waive this check.
+
+The build enables `CUA_HYPRLAND_INPUT=ON`, disables experimental signed input and
+input tracing, and runs the bundled CTest suite. Packaging also runs tests, so
+`--nocheck` cannot produce an unchecked package. The package contains only the
+module, license, and source/build provenance. It has no install hooks, autoload,
+configuration edits, or hot replacement. Module activation and compositor
+restart belong to the separately validated operator workflow.
+
+CTest runs without fakeroot's identity shim, including when called by
+`package()`. Socket peer-credential tests need the real build-user identity;
+fakeroot remains active in the parent process for package file ownership.
+
+## Verify this preparation
+
+To qualify a candidate before publishing, generate the default development kit
+from the exact committed candidate SHA. Copy that directory to a disposable
+pinned Arch environment and run its `lifecycle.py` as documented in `USAGE.md`.
+The runner builds without a checkout, uses the recipe's compiler and ABI checks,
+and qualifies package transactions in fresh isolated ALPM roots. It leaves any
+running desktop untouched. Its dependency packages contain synthetic metadata;
+they prove package-manager constraints, while the native build proves the build
+environment checks. They do not prove runtime activation or restart safety.
+
+Retain the package, build provenance, transaction logs, and `RESULT.json`.
+Only a successful run writes `RESULT.json`; failed runs retain diagnostics.
+Keep raw logs local until reviewed for machine paths and environment details.
+The runner leaves its isolated roots and build output for inspection; dispose
+of them with the disposable test environment. Native input certification,
+fresh-session activation, upgrade/rollback across compositor restarts, and
+published component-download verification remain separate release gates.
+
+Run the focused packaging tests with Python 3.12 or later:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \
+ -s libs/cua-driver/hyprland-plugin/packaging/release -p 'test_*.py'
+```
+
+These tests cover deterministic archives, exclusion of unrelated and dirty
+content, checksum and version refusals, compiler/ABI contract checks with
+synthetic command responses, and the installation file list. They do not replace
+native validation. Before shipping, build the generated archive with `makepkg`
+in the pinned Arch environment, run the native input and desktop certification
+at the exact source SHA, inspect the package contents and ELF dependencies, and
+verify clean install, deliberate activation after restart, package upgrade,
+removal, and refusal after compositor/compiler drift. Release download and
+checksum verification from the published component tag also remain required.
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/USAGE.md b/libs/cua-driver/hyprland-plugin/packaging/release/USAGE.md
new file mode 100644
index 0000000000..f7c6737c13
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/USAGE.md
@@ -0,0 +1,170 @@
+# Install the pinned Hyprland plugin
+
+This source distribution builds the Cua production input candidate without a
+monorepo checkout. Use the exact Driver component release named by
+`release_tag` in `SOURCE-PROVENANCE.json`. The Arch package version follows that
+Driver release; the plugin's CMake version is recorded as `plugin_version`.
+
+The source generator does not perform native certification. Its
+`native_certified: false` field describes that limitation. Consult the release's
+separate native evidence for the exact source revision and environment before
+using the candidate. A checksum proves agreement with the reviewed recipe, not
+native compatibility by itself.
+
+## Build and install
+
+The supported build contract is Linux x86_64 with Hyprland `0.56.2-1`, headers
+`0.56.2`, GCC `16.1.1 20260728`, and shared `libstdc++.so.6.0.36`. The compiler,
+compositor, and module must resolve the same runtime bytes. A newer package or
+compiler does not satisfy this contract. Arrange the pinned dependencies in the
+target environment before building; the recipe does not install a toolchain or
+alter runtime search paths.
+
+Download the `cua-hyprland-plugin-DRIVER_VERSION-COMMIT_SHA.tar.gz` source archive
+and matching `cua-hyprland-plugin-DRIVER_VERSION-COMMIT_SHA-build-kit.tar.gz` from
+the same exact component release. The filenames contain the release version
+and full source commit SHA. Verify both archives against that release's
+published checksums before extracting the build kit into a dedicated empty
+directory. Place the source archive alongside its extracted `PKGBUILD`,
+`SOURCE-PROVENANCE.json`, `README.md`, `lifecycle.py`, and `SHA256SUMS`.
+
+From that directory, review the recipe and verify its files and source archive:
+
+```sh
+sha256sum -c SHA256SUMS
+```
+
+Run `makepkg` as an ordinary user in that directory. It uses `/usr/bin/g++` by
+default. If your matching compiler is staged elsewhere, set `CUA_RELEASE_CXX`
+to its absolute executable path before invoking `makepkg`. The verifier checks
+its identity, an emitted compiler probe, the compositor, and the shared runtime.
+The recipe builds and tests the plugin with production input enabled,
+experimental signed input disabled, and tracing disabled.
+
+Before installing or replacing a module, save your work and exit the Hyprland
+desktop session. From a text console, install the single package produced by
+the recipe:
+
+```sh
+package_file="$(makepkg --packagelist)"
+sudo pacman -U "$package_file"
+```
+
+Installation writes the module to
+`/usr/lib/cua/hyprland/cua-hyprland-plugin.so`, its license under
+`/usr/share/licenses/cua-hyprland-plugin/`, and source/build provenance under
+`/usr/share/cua-hyprland-plugin/`. It has no install hooks, automatic loading, or
+configuration changes. Keep the package file and its provenance for rollback.
+
+## Qualify package lifecycle in a disposable environment
+
+Before installing in a desktop session, run the standalone lifecycle gate in a
+disposable Linux x86_64 Arch environment with the pinned native dependencies,
+`makepkg`, `bsdtar`, `pacman`, Python 3.11 or later, and `sudo` available. Use an
+ordinary build user who can run `pacman` through `sudo -n` with existing
+authorization; the gate fails if sudo needs an interactive password. It does not
+install missing dependencies. It builds and tests using the recipe's native
+compiler, compositor, and shared-runtime checks.
+
+From a fresh, verified kit, replace `COMMIT_SHA` and `DRIVER_VERSION` with its
+manifest values and `NEW_EVIDENCE_DIRECTORY` with a path that does not exist:
+
+```sh
+python3 lifecycle.py --kit . --revision COMMIT_SHA \
+ --driver-version DRIVER_VERSION --output NEW_EVIDENCE_DIRECTORY
+```
+
+For a compiler staged outside `/usr/bin/g++`, add `--cxx` with its absolute path.
+A development kit generated from an explicit committed SHA also works before
+release publication; passing this gate does not claim that assets are published.
+
+The gate copies the kit into its evidence directory and runs `makepkg`. It
+checks the package's exact module, license, and provenance payload, rejects
+configuration files and install hooks, and checks module hashes against the
+build provenance. It uses `sudo pacman` only with new isolated filesystem and
+database roots, explicit configuration, disabled scriptlets, and empty hook
+directories. It installs, removes, and reinstalls the package, checking the
+installed bytes and an isolated operator-configuration sentinel after each
+transaction. A second root must refuse the package with a specific Hyprland
+dependency error. A successful install with matching dependency metadata is
+the positive control for that refusal.
+
+These roots contain metadata-only Hyprland and GCC runtime dependency fixtures.
+They test ALPM dependency resolution, not execution of those dependencies.
+The runner does not load a plugin, edit host desktop configuration, install a
+host package, or restart the compositor. It can run while a separate desktop
+proof is in progress. A pass writes `RESULT.json`; build and transaction logs,
+the package, and isolated roots remain for inspection in the evidence directory.
+Review logs before sharing them, and retain or discard the disposable environment
+through its normal lifecycle.
+
+This gate does not prove live activation, restart, upgrade, or rollback. To
+complete those gates, schedule the fresh-session procedures below after any
+ongoing desktop proof finishes. Preserve the prior package and matching native
+environment, verify activation and input after replacement and restart, then
+repeat with the saved package and another fresh compositor. Published release
+download and checksum verification also require separate evidence.
+
+## Activate in a fresh desktop session
+
+Start a fresh Hyprland session with the pinned compositor. Load the module
+explicitly and inspect its status:
+
+```sh
+hyprctl plugin load /usr/lib/cua/hyprland/cua-hyprland-plugin.so
+hyprctl -j cua:status
+```
+
+The local input transport is disabled by default. Enabling it grants trusted
+local desktop input capability; Driver continues to enforce its own permission
+policy on individual calls. In Omarchy's Lua configuration, add:
+
+```lua
+hl.config({plugin = {cua = {enabled = true}}})
+```
+
+For a legacy Hyprland configuration, add:
+
+```text
+plugin:cua:enabled = true
+```
+
+After editing the configuration, run `hyprctl reload`, then inspect
+`hyprctl -j cua:status` again. A runtime keyword or Lua evaluation without a
+configuration reload does not reconcile the input sockets. Check the status's
+protocol, capabilities, socket paths, and compositor identity. A loaded module
+alone does not prove input availability. Start the matching Driver with
+`CUA_DRIVER_RS_ENABLE_WAYLAND=1`; its production input protocol is v3 by default.
+
+The input path checks exact native application packages: `libreoffice-fresh
+26.2.5-3` for Calc and `inkscape 1.4.4-6`. It also requires the canonical
+`evdev/pc105/us` keyboard map without variants, remaps, or additional groups.
+There are two independent input lanes. A third concurrent owner receives a
+lane-busy refusal. Other application versions, Chromium/Electron, and XWayland
+are outside this input contract. Use normal Driver snapshots and background
+actions, then verify the application result; a delivery acknowledgement is not
+proof that the intended edit occurred. Do not automatically replay partial or
+unknown actions. The release's native evidence identifies the qualified
+operation cells within these limits.
+
+## Upgrade, rollback, or remove
+
+Keep a copy of the installed package and its exact compositor/compiler/runtime
+provenance before upgrading. Build and test the replacement against its declared
+pins. Exit the desktop session before replacing the package, install the
+replacement from a text console, then start a fresh desktop session and repeat
+activation and status checks. Do not hot-unload/reload the module to replace it:
+production input retains resources until the compositor process exits.
+
+If the replacement fails validation, exit the desktop session, reinstall the
+saved package with `pacman -U` and its exact saved package filename, and restore
+its matching compositor/runtime environment before starting a fresh session.
+Do not force installation past the exact Hyprland dependency. If matching pins
+are unavailable, leave the plugin inactive and use Driver without this plugin.
+
+To disable input, remove the enabling setting or set it to false and run
+`hyprctl reload`. To remove the package, remove any operator-added plugin load
+or enable settings, exit the desktop session, and run
+`sudo pacman -R cua-hyprland-plugin` from a text console. Start a fresh session
+afterward. Unloading, upgrading, or removing a file in a running compositor does
+not substitute for restarting that compositor.
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/bundle.py b/libs/cua-driver/hyprland-plugin/packaging/release/bundle.py
new file mode 100644
index 0000000000..ef23657160
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/bundle.py
@@ -0,0 +1,188 @@
+#!/usr/bin/env python3
+"""Create a deterministic, pinned plugin source release from one Git commit."""
+
+import argparse
+import gzip
+import hashlib
+import io
+import json
+from pathlib import Path
+import re
+import subprocess
+import tarfile
+import tomllib
+
+PLUGIN = "libs/cua-driver/hyprland-plugin/"
+RELEASE = PLUGIN + "packaging/release/"
+# Deliberate allowlist: adding source or build fixtures requires release review.
+# No directory traversal, live harnesses, documentation/evidence, or worktree reads.
+SOURCE_FILES = """
+CMakeLists.txt
+cmake/DetectHyprlandAPI.cmake
+cmake/VerifyRuntime.cmake
+include/cua_hyprland/protocol.hpp
+include/cua_hyprland/session.hpp
+include/cua_hyprland/status.hpp
+src/drag_geometry.hpp
+src/foreground_route.hpp
+src/inject_server.cpp
+src/inject_server.hpp
+src/input_client_deadline.hpp
+src/input_experiment.cpp
+src/input_experiment.hpp
+src/input_grant.hpp
+src/owned_socket_path.hpp
+src/passive_pointer_target.hpp
+src/plugin.cpp
+src/primary_trace.cpp
+src/primary_trace.hpp
+src/protocol.cpp
+src/seat_lifetime.hpp
+src/session.cpp
+src/status.cpp
+tests/cmake-api/CMakeLists.txt
+tests/cmake-api/include/src/plugins/PluginAPI.hpp
+tests/drag_geometry_test.cpp
+tests/foreground_route_test.cpp
+tests/input_grant_test.cpp
+tests/input_client_deadline_test.cpp
+tests/mock-hyprland/mock.hpp
+tests/mock-hyprland/src/config/values/types/BoolValue.hpp
+tests/mock-hyprland/src/plugins/PluginAPI.hpp
+tests/owned_socket_path_test.cpp
+tests/passive_pointer_target_test.cpp
+tests/plugin_api_test.cpp
+tests/plugin_input_lifetime_test.cpp
+tests/protocol_test.cpp
+tests/seat_lifetime_test.cpp
+tests/status_test.cpp
+tests/transport_test.cpp
+""".split()
+
+
+def sha256(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def json_bytes(value):
+ return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode()
+
+
+def git(repo, *args):
+ return subprocess.check_output(["git", "-C", str(repo), *args])
+
+
+def committed_file(repo, revision, path):
+ entry = git(repo, "ls-tree", revision, "--", path).decode().strip()
+ if not entry.startswith("100644 blob ") and not entry.startswith("100755 blob "):
+ raise ValueError(f"required committed regular file missing: {path}")
+ return git(repo, "show", f"{revision}:{path}")
+
+
+def deterministic_archive(payload):
+ raw_tar = io.BytesIO()
+ with tarfile.open(fileobj=raw_tar, mode="w", format=tarfile.USTAR_FORMAT) as archive:
+ for name, data in sorted(payload.items()):
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ info.mode = 0o644
+ info.mtime = 0
+ archive.addfile(info, io.BytesIO(data))
+ compressed = io.BytesIO()
+ with gzip.GzipFile(filename="", fileobj=compressed, mode="wb", mtime=0, compresslevel=9) as archive:
+ archive.write(raw_tar.getvalue())
+ return compressed.getvalue()
+
+
+def generate(repo, revision, driver_version, output, *, release_assets=False):
+ if not re.fullmatch(r"[0-9a-f]{40}", revision):
+ raise ValueError("source revision must be a full lowercase commit SHA")
+ if git(repo, "rev-parse", f"{revision}^{{commit}}").decode().strip() != revision:
+ raise ValueError("source revision must name a commit")
+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", driver_version):
+ raise ValueError("driver version must be a stable numeric release version")
+ cargo = tomllib.loads(committed_file(repo, revision, "libs/cua-driver/rust/Cargo.toml").decode())
+ if cargo["workspace"]["package"]["version"] != driver_version:
+ raise ValueError("driver version does not match committed Cargo.toml")
+ if release_assets:
+ tag = f"refs/tags/cua-driver-rs-v{driver_version}"
+ if git(repo, "rev-parse", "--verify", f"{tag}^{{commit}}").decode().strip() != revision:
+ raise ValueError("source revision does not match the exact Driver release tag")
+ payload = {name: committed_file(repo, revision, PLUGIN + name) for name in SOURCE_FILES}
+ payload["LICENSE.md"] = committed_file(repo, revision, "LICENSE.md")
+ payload["verify.py"] = committed_file(repo, revision, RELEASE + "verify.py")
+ version = re.search(rb"project\(cua_hyprland_plugin VERSION ([0-9.]+) LANGUAGES CXX\)", payload["CMakeLists.txt"])
+ if not version:
+ raise ValueError("cannot resolve committed plugin version")
+ metadata = {
+ "schema": 1,
+ "source_revision": revision,
+ "driver_version": driver_version,
+ "plugin_version": version[1].decode(),
+ "release_tag": f"cua-driver-rs-v{driver_version}",
+ "hyprland_version": "0.56.2",
+ "hyprland_package": "0.56.2-1",
+ "compiler_version": "16.1.1 20260728",
+ "compiler_comment": "GCC: (GNU) 16.1.1 20260728",
+ "architecture": "x86_64",
+ "native_certified": False,
+ "cmake_options": {"CUA_HYPRLAND_INPUT": "ON", "CUA_HYPRLAND_TEST_INPUT": "OFF", "CUA_HYPRLAND_INPUT_TRACE": "OFF"},
+ "files": {name: sha256(data) for name, data in sorted(payload.items())},
+ }
+ payload["SOURCE-PROVENANCE.json"] = json_bytes(metadata)
+ stem = f"cua-hyprland-plugin-{driver_version}-{revision}"
+ tarball = deterministic_archive({f"{stem}/{name}": data for name, data in payload.items()})
+ template = committed_file(repo, revision, RELEASE + "PKGBUILD.in").decode()
+ replacements = {
+ "DRIVER_VERSION": driver_version,
+ "REVISION": revision,
+ "STEM": stem,
+ "ARCHIVE_SHA256": sha256(tarball),
+ "MANIFEST_SHA256": sha256(payload["SOURCE-PROVENANCE.json"]),
+ }
+ for key, value in replacements.items():
+ template = template.replace(f"@{key}@", value)
+ if re.search(r"@[A-Z_]+@", template):
+ raise ValueError("unresolved recipe placeholder")
+ usage = committed_file(repo, revision, RELEASE + "USAGE.md")
+ files = {
+ f"{stem}.tar.gz": tarball,
+ "PKGBUILD": template.encode(),
+ "SOURCE-PROVENANCE.json": payload["SOURCE-PROVENANCE.json"],
+ "README.md": usage,
+ "lifecycle.py": committed_file(repo, revision, RELEASE + "lifecycle.py"),
+ }
+ files["SHA256SUMS"] = "".join(
+ f"{sha256(data)} {name}\n" for name, data in sorted(files.items())
+ ).encode()
+ if release_assets:
+ # Keep generic recipe/document/checksum names inside one namespaced kit.
+ # The source remains a separate asset at the URL pinned by PKGBUILD.
+ kit = {name: data for name, data in files.items() if name != f"{stem}.tar.gz"}
+ files = {
+ f"{stem}.tar.gz": tarball,
+ f"{stem}-build-kit.tar.gz": deterministic_archive(kit),
+ }
+ # Exclusive creation prevents replacing a previously reviewed release asset.
+ output.mkdir(parents=True, exist_ok=False)
+ for name, data in files.items():
+ (output / name).write_bytes(data)
+ return metadata
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=Path, required=True)
+ parser.add_argument("--revision", required=True)
+ parser.add_argument("--driver-version", required=True)
+ parser.add_argument("--output", type=Path, required=True, help="new directory; existing paths are refused")
+ parser.add_argument("--release-assets", action="store_true", help="require the exact component tag and emit source/build-kit release archives")
+ args = parser.parse_args()
+ try:
+ generate(args.repo.resolve(strict=True), args.revision, args.driver_version, args.output, release_assets=args.release_assets)
+ except (ValueError, OSError, subprocess.CalledProcessError) as error:
+ parser.exit(1, f"error: {error}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/lifecycle.py b/libs/cua-driver/hyprland-plugin/packaging/release/lifecycle.py
new file mode 100644
index 0000000000..edd821ca8c
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/lifecycle.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python3
+"""Build a standalone kit and qualify package transactions in fresh ALPM roots."""
+
+import argparse
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import shlex
+import subprocess
+import tarfile
+
+
+PACKAGE = "cua-hyprland-plugin"
+MODULE = "usr/lib/cua/hyprland/cua-hyprland-plugin.so"
+SOURCE = f"usr/share/{PACKAGE}/SOURCE-PROVENANCE.json"
+BUILD = f"usr/share/{PACKAGE}/BUILD-PROVENANCE.json"
+LICENSE = f"usr/share/licenses/{PACKAGE}/LICENSE"
+PAYLOAD = {MODULE, SOURCE, BUILD, LICENSE}
+
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def digest(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def run(command, *, cwd=None, env=None, check=True):
+ result = subprocess.run(command, cwd=cwd, env=env, capture_output=True,
+ text=True, errors="replace")
+ if check and result.returncode:
+ raise ValueError(f"{command[0]} failed ({result.returncode}):\n{result.stdout}\n{result.stderr}")
+ return result
+
+
+def verify_kit(kit, revision, driver_version):
+ require(re.fullmatch(r"[0-9a-f]{40}", revision), "requires a full source commit SHA")
+ require(re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", driver_version), "requires a stable Driver version")
+ stem = f"cua-hyprland-plugin-{driver_version}-{revision}"
+ expected = {"PKGBUILD", "README.md", "SOURCE-PROVENANCE.json", "lifecycle.py", f"{stem}.tar.gz"}
+ checksums = {}
+ for line in (kit / "SHA256SUMS").read_text().splitlines():
+ checksum, name = line.split(" ")
+ require(name in expected and name not in checksums, "unexpected or duplicate kit checksum entry")
+ require(re.fullmatch(r"[0-9a-f]{64}", checksum), "invalid kit checksum")
+ checksums[name] = checksum
+ require(set(checksums) == expected, "kit checksum inventory mismatch")
+ require({p.name for p in kit.iterdir()} == expected | {"SHA256SUMS"}, "use a fresh, unbuilt standalone kit")
+ for name, checksum in checksums.items():
+ path = kit / name
+ require(path.is_file() and not path.is_symlink(), "kit requires regular files")
+ require(digest(path.read_bytes()) == checksum, f"kit checksum mismatch: {name}")
+ require(digest(Path(__file__).read_bytes()) == checksums["lifecycle.py"], "runner differs from committed kit")
+ manifest = json.loads((kit / "SOURCE-PROVENANCE.json").read_text())
+ require(manifest["source_revision"] == revision and manifest["driver_version"] == driver_version,
+ "kit source revision/version mismatch")
+ return manifest, checksums
+
+
+def package_payload(package, manifest):
+ names = run(["bsdtar", "-tf", str(package)]).stdout.splitlines()
+ files = [name for name in names if not name.endswith("/")]
+ require(len(names) == len(set(names)), "duplicate package entries")
+ require(set(files) == PAYLOAD | {".PKGINFO", ".BUILDINFO", ".MTREE"}, "unexpected package payload or hooks")
+ directories = {str(parent) + "/" for name in PAYLOAD for parent in Path(name).parents if str(parent) != "."}
+ require(set(names) - set(files) <= directories, "unexpected package directory")
+ info = run(["bsdtar", "-xOf", str(package), ".PKGINFO"]).stdout.splitlines()
+ require(f"pkgname = {PACKAGE}" in info, "package name mismatch")
+ require(f"pkgver = {manifest['driver_version']}-1" in info, "package version mismatch")
+ require("arch = x86_64" in info, "package architecture mismatch")
+ require({line for line in info if line.startswith("depend = ")} ==
+ {"depend = hyprland=0.56.2-1", "depend = gcc-libs"}, "package dependency mismatch")
+ payload = {name: subprocess.check_output(["bsdtar", "-xOf", str(package), name]) for name in PAYLOAD}
+ require(json.loads(payload[SOURCE]) == manifest, "packaged source provenance mismatch")
+ require(digest(payload[LICENSE]) == manifest["files"]["LICENSE.md"], "packaged license provenance mismatch")
+ build = json.loads(payload[BUILD])
+ require(build["source"] == manifest, "packaged build source mismatch")
+ require(build["module_sha256"] == digest(payload[MODULE]), "packaged module hash mismatch")
+ require(build["module_runtime_sha256"] == build["compiler_runtime_sha256"] ==
+ build["compositor_runtime_sha256"], "packaged runtime provenance mismatch")
+ return {name: digest(data) for name, data in payload.items()}
+
+
+def dependency_fixture(destination, name, version):
+ # Metadata-only packages test ALPM's resolver, never native ABI compatibility.
+ data = (f"pkgname = {name}\npkgver = {version}\npkgdesc = Lifecycle dependency fixture\n"
+ "arch = x86_64\nsize = 0\n").encode()
+ with tarfile.open(destination, "w:gz") as archive:
+ info = tarfile.TarInfo(".PKGINFO")
+ info.size = len(data)
+ info.mode = 0o644
+ archive.addfile(info, io.BytesIO(data))
+
+
+def pacman_command(root, *arguments):
+ require(root.is_absolute() and (root / "lifecycle-root").is_file(), "uninitialized isolated ALPM root")
+ require(arguments and arguments[0] in ("-U", "-R", "-Q"), "unexpected ALPM operation")
+ # --noscriptlet is a transaction option, rejected by pacman's query mode.
+ transaction_options = ["--noscriptlet"] if arguments[0] in ("-U", "-R") else []
+ return ["sudo", "-n", "--", "pacman", "--root", str(root), "--dbpath", str(root / "var/lib/pacman"),
+ "--config", str(root / "pacman.conf"), "--hookdir", str(root / "empty-hooks"),
+ "--cachedir", str(root / "cache"), "--logfile", str(root / "pacman.log"),
+ *transaction_options, "--noconfirm", *arguments]
+
+
+def new_root(work, name):
+ root = work / name
+ root.mkdir()
+ for path in ("var/lib/pacman", "empty-hooks", "cache", "etc/hypr"):
+ (root / path).mkdir(parents=True)
+ (root / "lifecycle-root").write_text("Disposable ALPM lifecycle root\n")
+ (root / "pacman.conf").write_text("[options]\nArchitecture = x86_64\nSigLevel = Never\nLocalFileSigLevel = Never\n")
+ (root / "etc/hypr/hyprland.conf").write_text("# Operator configuration sentinel\n")
+ return root
+
+
+def assert_state(root, payload, installed):
+ require((root / "etc/hypr/hyprland.conf").read_text() == "# Operator configuration sentinel\n",
+ "operator configuration changed")
+ actual = {p.relative_to(root).as_posix() for p in (root / "usr").rglob("*") if not p.is_dir()}
+ require(actual == (set(payload) if installed else set()), "installed payload inventory mismatch")
+ for name, checksum in payload.items():
+ path = root / name
+ if installed:
+ require(path.is_file() and not path.is_symlink(), "installed payload is not a regular file")
+ require(digest(path.read_bytes()) == checksum, f"installed payload mismatch: {name}")
+ else:
+ require(not path.exists() and not path.is_symlink(), f"removed payload remains: {name}")
+
+
+def qualify(work, package, payload, manifest):
+ log = []
+
+ def transaction(root, *arguments, check=True):
+ result = run(pacman_command(root, *arguments), check=False,
+ env={**os.environ, "LC_ALL": "C"})
+ log.append({"root": root.name, "operation": arguments[0], "returncode": result.returncode,
+ "stdout": result.stdout, "stderr": result.stderr})
+ (work / "transactions.json").write_text(json.dumps(log, indent=2) + "\n")
+ require(not check or result.returncode == 0, "pacman failed; see retained transactions.json")
+ return result
+
+ gcc = work / "gcc-libs-fixture.pkg.tar.gz"
+ dependency_fixture(gcc, "gcc-libs", "1-1")
+ for label, version in (("matching", "0.56.2-1"), ("mismatched", "0.56.2-2")):
+ root = new_root(work, label)
+ hyprland = work / f"hyprland-{label}-fixture.pkg.tar.gz"
+ dependency_fixture(hyprland, "hyprland", version)
+ transaction(root, "-U", str(gcc), str(hyprland))
+ if label == "mismatched":
+ result = transaction(root, "-U", str(package), check=False)
+ diagnostic = result.stdout + result.stderr
+ require(result.returncode != 0 and 'unable to satisfy dependency' in diagnostic and
+ 'hyprland=0.56.2-1' in diagnostic, "missing specific Hyprland dependency refusal")
+ assert_state(root, payload, False)
+ require(transaction(root, "-Q", PACKAGE, check=False).returncode != 0,
+ "rejected package registered in ALPM")
+ continue
+ for stage in ("install", "remove", "reinstall"):
+ installed = stage != "remove"
+ transaction(root, "-U" if installed else "-R", str(package) if installed else PACKAGE)
+ assert_state(root, payload, installed)
+ result = transaction(root, "-Q", PACKAGE, check=False)
+ if installed:
+ require(result.returncode == 0 and result.stdout.strip() ==
+ f"{PACKAGE} {manifest['driver_version']}-1", "installed ALPM identity mismatch")
+ else:
+ require(result.returncode != 0, "removed package registered in ALPM")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--kit", type=Path, required=True, help="fresh standalone development or release kit")
+ parser.add_argument("--revision", required=True)
+ parser.add_argument("--driver-version", required=True)
+ parser.add_argument("--cxx", type=Path, default=Path("/usr/bin/g++"))
+ parser.add_argument("--output", type=Path, required=True, help="new retained evidence/build directory")
+ args = parser.parse_args()
+ try:
+ require(platform.system() == "Linux" and platform.machine() == "x86_64", "requires native Linux x86_64")
+ require(os.geteuid() != 0, "run as an ordinary build user; only isolated pacman uses sudo")
+ require(args.cxx.is_absolute() and args.cxx.is_file(), "requires an absolute compiler path")
+ kit = args.kit.resolve(strict=True)
+ manifest, checksums = verify_kit(kit, args.revision, args.driver_version)
+ work = args.output.absolute()
+ work.mkdir(parents=True, exist_ok=False)
+ work = work.resolve(strict=True)
+ build = work / "kit"
+ build.mkdir()
+ for name in (*checksums, "SHA256SUMS"):
+ (build / name).write_bytes((kit / name).read_bytes())
+ env = {**os.environ, "LC_ALL": "C", "CUA_RELEASE_CXX": str(args.cxx),
+ "PKGDEST": str(build), "SRCDEST": str(build), "BUILDDIR": str(build)}
+ config = work / "makepkg.conf"
+ config.write_text(Path("/etc/makepkg.conf").read_text() + "\n" +
+ "\n".join(f"{key}={shlex.quote(str(build))}"
+ for key in ("PKGDEST", "SRCDEST", "BUILDDIR", "LOGDEST", "SRCPKGDEST")) + "\n")
+ # No --syncdeps, --install, --skipinteg, --nocheck, or forced replacement.
+ result = run(["makepkg", "--config", str(config), "--noconfirm"], cwd=build, env=env, check=False)
+ (work / "makepkg.log").write_text(result.stdout + result.stderr)
+ require(result.returncode == 0, "makepkg failed; see retained makepkg.log")
+ packages = list(build.glob(f"{PACKAGE}-*.pkg.tar.*"))
+ packages = [p for p in packages if not p.name.endswith(".sig")]
+ require(len(packages) == 1, "expected one built plugin package")
+ package = packages[0]
+ payload = package_payload(package, manifest)
+ qualify(work, package, payload, manifest)
+ evidence = {"schema": 1, "result": "passed", "scope": "native build and isolated ALPM lifecycle",
+ "source_revision": args.revision, "driver_version": args.driver_version,
+ "plugin_version": manifest["plugin_version"], "kit_sha256": checksums,
+ "package_sha256": digest(package.read_bytes()), "payload_sha256": payload,
+ "dependency_fixtures": "metadata only; ABI verified by the native recipe",
+ "live_restart_verified": False, "live_rollback_verified": False,
+ "published_release_verified": False}
+ (work / "RESULT.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n")
+ print("Passed: native build and isolated ALPM install/remove/reinstall/dependency refusal.")
+ print("Live restart, rollback, and published release verification remain separate gates.")
+ except (ValueError, KeyError, OSError, subprocess.CalledProcessError) as error:
+ parser.exit(1, f"error: {error}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/test_lifecycle.py b/libs/cua-driver/hyprland-plugin/packaging/release/test_lifecycle.py
new file mode 100644
index 0000000000..a32834b76d
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/test_lifecycle.py
@@ -0,0 +1,217 @@
+"""Standalone lifecycle gate tests; native/ALPM commands use synthetic fixtures."""
+
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tarfile
+import tempfile
+import unittest
+from unittest import mock
+
+from test_release import load
+
+
+lifecycle = load("lifecycle")
+release_fixture = load("test_release")
+
+
+class KitTest(unittest.TestCase):
+ setUp = release_fixture.ReleaseTest.setUp
+ git = release_fixture.ReleaseTest.git
+ write = release_fixture.ReleaseTest.write
+ generate = release_fixture.ReleaseTest.generate
+
+ def test_lifecycle_kit_requires_exact_source_and_checksums(self):
+ kit = self.generate()
+ manifest, checksums = lifecycle.verify_kit(kit, self.revision, "1.2.3")
+ self.assertEqual(manifest["source_revision"], self.revision)
+ self.assertIn("lifecycle.py", checksums)
+ with self.assertRaises(ValueError):
+ lifecycle.verify_kit(kit, "0" * 40, "1.2.3")
+ (kit / "lifecycle.py").write_text("tampered runner")
+ with self.assertRaisesRegex(ValueError, "kit checksum mismatch"):
+ lifecycle.verify_kit(kit, self.revision, "1.2.3")
+
+ def test_existing_build_and_checksum_traversal_refused(self):
+ kit = self.generate()
+ (kit / "src").mkdir()
+ with self.assertRaisesRegex(ValueError, "fresh, unbuilt"):
+ lifecycle.verify_kit(kit, self.revision, "1.2.3")
+ (kit / "SHA256SUMS").write_text("0" * 64 + " ../PKGBUILD\n")
+ with self.assertRaisesRegex(ValueError, "unexpected or duplicate"):
+ lifecycle.verify_kit(kit, self.revision, "1.2.3")
+
+ def test_runner_copies_only_kit_files_and_marks_remaining_live_gates(self):
+ kit = self.generate()
+ output = kit / "evidence"
+ compiler = self.root / "g++"
+ compiler.write_text("synthetic compiler")
+ original_read = Path.read_text
+
+ def read_config(path, *args, **kwargs):
+ if path == Path("/etc/makepkg.conf"):
+ return "# synthetic makepkg configuration\n"
+ return original_read(path, *args, **kwargs)
+
+ def build(command, **kwargs):
+ self.assertEqual(command[0], "makepkg")
+ self.assertNotIn("--syncdeps", command)
+ self.assertNotIn("--install", command)
+ self.assertEqual(kwargs["env"]["CUA_RELEASE_CXX"], str(compiler))
+ (kwargs["cwd"] / "cua-hyprland-plugin-1.2.3-1-x86_64.pkg.tar.zst").write_bytes(b"synthetic package")
+ return subprocess.CompletedProcess(command, 0, "synthetic build", "")
+
+ arguments = ["lifecycle.py", "--kit", str(kit), "--revision", self.revision,
+ "--driver-version", "1.2.3", "--cxx", str(compiler), "--output", str(output)]
+ with mock.patch.object(sys, "argv", arguments), mock.patch.object(lifecycle.platform, "system", return_value="Linux"), \
+ mock.patch.object(lifecycle.platform, "machine", return_value="x86_64"), \
+ mock.patch.object(lifecycle.os, "geteuid", return_value=1000), \
+ mock.patch.object(Path, "read_text", read_config), mock.patch.object(lifecycle, "run", side_effect=build), \
+ mock.patch.object(lifecycle, "package_payload", return_value={}), \
+ mock.patch.object(lifecycle, "qualify") as qualify, mock.patch("builtins.print"):
+ lifecycle.main()
+ qualify.assert_called_once()
+ evidence = json.loads((output / "RESULT.json").read_text())
+ self.assertEqual(evidence["source_revision"], self.revision)
+ self.assertFalse(evidence["live_restart_verified"])
+ self.assertFalse(evidence["live_rollback_verified"])
+ self.assertFalse(evidence["published_release_verified"])
+
+
+class LifecycleTest(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory(prefix="cua-lifecycle-test-")
+ self.addCleanup(self.temporary.cleanup)
+ self.work = Path(self.temporary.name)
+ self.manifest = {"driver_version": "1.2.3", "source_revision": "a" * 40,
+ "files": {"LICENSE.md": lifecycle.digest(b"fixture license")}}
+ module = b"synthetic module"
+ build = {"source": self.manifest, "module_sha256": lifecycle.digest(module),
+ "module_runtime_sha256": "runtime", "compiler_runtime_sha256": "runtime",
+ "compositor_runtime_sha256": "runtime"}
+ self.data = {lifecycle.MODULE: module, lifecycle.SOURCE: json.dumps(self.manifest).encode(),
+ lifecycle.BUILD: json.dumps(build).encode(),
+ f"usr/share/licenses/{lifecycle.PACKAGE}/LICENSE": b"fixture license"}
+ self.payload = {name: lifecycle.digest(data) for name, data in self.data.items()}
+ self.package = self.work / "candidate.pkg.tar.zst"
+ self.package.write_text("synthetic package")
+ self.installed = set()
+ self.calls = []
+
+ def fake_pacman(self, command, **kwargs):
+ self.calls.append(command)
+ self.assertEqual(command[:4], ["sudo", "-n", "--", "pacman"])
+ root = Path(command[command.index("--root") + 1])
+ self.assertIn(root, (self.work / "matching", self.work / "mismatched"))
+ for option, suffix in (("--dbpath", "var/lib/pacman"), ("--config", "pacman.conf"),
+ ("--hookdir", "empty-hooks"), ("--cachedir", "cache"),
+ ("--logfile", "pacman.log")):
+ self.assertEqual(command[command.index(option) + 1], str(root / suffix))
+ self.assertNotIn("--nodeps", command)
+ operation = command[command.index("--noconfirm") + 1:]
+ self.assertEqual("--noscriptlet" in command, operation[0] in ("-U", "-R"))
+ code, out, err = 0, "", ""
+ if operation == ["-U", str(self.package)]:
+ if root.name == "mismatched":
+ code = 1
+ out = ":: unable to satisfy dependency 'hyprland=0.56.2-1' required by cua-hyprland-plugin"
+ err = "error: failed to prepare transaction (could not satisfy dependencies)"
+ else:
+ for name, data in self.data.items():
+ path = root / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ self.installed.add(root)
+ elif operation[0] == "-R":
+ for name in self.data:
+ (root / name).unlink()
+ self.installed.remove(root)
+ elif operation[0] == "-Q":
+ code = 0 if root in self.installed else 1
+ out = f"{lifecycle.PACKAGE} 1.2.3-1\n" if code == 0 else ""
+ return subprocess.CompletedProcess(command, code, out, err)
+
+ def test_install_remove_reinstall_and_paired_dependency_refusal(self):
+ with mock.patch.object(lifecycle, "run", side_effect=self.fake_pacman):
+ lifecycle.qualify(self.work, self.package, self.payload, self.manifest)
+ log = json.loads((self.work / "transactions.json").read_text())
+ self.assertEqual([entry["operation"] for entry in log if entry["root"] == "matching"],
+ ["-U", "-U", "-Q", "-R", "-Q", "-U", "-Q"])
+ self.assertEqual([entry["returncode"] for entry in log if entry["root"] == "mismatched"], [0, 1, 1])
+ lifecycle.assert_state(self.work / "matching", self.payload, True)
+ lifecycle.assert_state(self.work / "mismatched", self.payload, False)
+ with tarfile.open(self.work / "hyprland-mismatched-fixture.pkg.tar.gz") as archive:
+ self.assertEqual(archive.getnames(), [".PKGINFO"])
+ self.assertIn(b"pkgver = 0.56.2-2", archive.extractfile(".PKGINFO").read())
+
+ def test_generic_negative_control_failure_does_not_pass(self):
+ def fake(command, **kwargs):
+ result = self.fake_pacman(command, **kwargs)
+ if result.returncode and "-U" in command:
+ result.stdout = ""
+ result.stderr = "permission denied"
+ return result
+ with mock.patch.object(lifecycle, "run", side_effect=fake):
+ with self.assertRaisesRegex(ValueError, "specific Hyprland dependency refusal"):
+ lifecycle.qualify(self.work, self.package, self.payload, self.manifest)
+
+ def test_failed_positive_control_does_not_pass_and_retains_log(self):
+ with mock.patch.object(lifecycle, "run", return_value=subprocess.CompletedProcess([], 1, "", "failure")):
+ with self.assertRaisesRegex(ValueError, "pacman failed"):
+ lifecycle.qualify(self.work, self.package, self.payload, self.manifest)
+ self.assertEqual(json.loads((self.work / "transactions.json").read_text())[0]["returncode"], 1)
+
+ def test_config_and_payload_drift_fail(self):
+ root = lifecycle.new_root(self.work, "sentinel")
+ for name, data in self.data.items():
+ path = root / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ lifecycle.assert_state(root, self.payload, True)
+ (root / lifecycle.MODULE).write_text("modified")
+ with self.assertRaisesRegex(ValueError, "payload mismatch"):
+ lifecycle.assert_state(root, self.payload, True)
+ (root / "etc/hypr/hyprland.conf").write_text("changed config")
+ with self.assertRaisesRegex(ValueError, "configuration changed"):
+ lifecycle.assert_state(root, self.payload, True)
+
+ def test_uninitialized_root_refused(self):
+ with self.assertRaisesRegex(ValueError, "uninitialized"):
+ lifecycle.pacman_command(Path("/"), "-U", str(self.package))
+
+ def test_query_omits_transaction_only_option_without_weakening_mutations(self):
+ root = lifecycle.new_root(self.work, "query-options")
+ for operation in ("-U", "-R", "-Q"):
+ with self.subTest(operation=operation):
+ command = lifecycle.pacman_command(root, operation, lifecycle.PACKAGE)
+ self.assertEqual("--noscriptlet" in command, operation != "-Q")
+ self.assertIn("--noconfirm", command)
+ self.assertEqual(command[-2:], [operation, lifecycle.PACKAGE])
+ for arguments in ((), ("-Syu",), ("--query",)):
+ with self.subTest(arguments=arguments), self.assertRaisesRegex(ValueError, "unexpected ALPM"):
+ lifecycle.pacman_command(root, *arguments)
+
+ def test_package_provenance_and_unexpected_config_or_hook_payload(self):
+ names = list(self.payload) + [".PKGINFO", ".BUILDINFO", ".MTREE"]
+ info = ("pkgname = cua-hyprland-plugin\npkgver = 1.2.3-1\narch = x86_64\n"
+ "depend = hyprland=0.56.2-1\ndepend = gcc-libs\n")
+
+ def fake_run(command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, "\n".join(names) if "-tf" in command else info, "")
+
+ with mock.patch.object(lifecycle, "run", side_effect=fake_run), mock.patch.object(
+ lifecycle.subprocess, "check_output", side_effect=lambda command: self.data[command[-1]]):
+ self.assertEqual(lifecycle.package_payload(self.package, self.manifest), self.payload)
+ for extra in (".INSTALL", "etc/hypr/hyprland.conf", "../escape"):
+ names.append(extra)
+ with self.assertRaisesRegex(ValueError, "unexpected package payload"):
+ lifecycle.package_payload(self.package, self.manifest)
+ names.pop()
+ self.data[lifecycle.MODULE] = b"tampered module"
+ with self.assertRaisesRegex(ValueError, "module hash mismatch"):
+ lifecycle.package_payload(self.package, self.manifest)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/test_release.py b/libs/cua-driver/hyprland-plugin/packaging/release/test_release.py
new file mode 100644
index 0000000000..02a0fea3d9
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/test_release.py
@@ -0,0 +1,467 @@
+"""Source-release tests; native commands use synthetic contract fixtures."""
+
+import importlib.util
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import textwrap
+import unittest
+from unittest import mock
+
+
+HERE = Path(__file__).resolve().parent
+
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, HERE / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+bundle = load("bundle")
+verify = load("verify")
+
+
+class ReleaseTest(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory(prefix="cua-source-release-test-")
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.repo = self.root / "repo"
+ self.repo.mkdir()
+ self.git("init", "-q")
+ self.git("config", "user.email", "[email protected]")
+ self.git("config", "user.name", "Release Fixture")
+ # Synthetic source keeps this suite independent of uncommitted product work.
+ for name in bundle.SOURCE_FILES:
+ self.write(bundle.PLUGIN + name, "// synthetic public source\n")
+ self.write(bundle.PLUGIN + "CMakeLists.txt", "project(cua_hyprland_plugin VERSION 0.1.0 LANGUAGES CXX)\n")
+ self.write("libs/cua-driver/rust/Cargo.toml", '[workspace.package]\nversion = "1.2.3"\n')
+ self.write("LICENSE.md", "Synthetic fixture license\n")
+ for name in ("verify.py", "PKGBUILD.in", "USAGE.md", "lifecycle.py"):
+ self.write(bundle.RELEASE + name, (HERE / name).read_text())
+ self.write("private/secret.txt", "excluded sentinel\n")
+ self.write(bundle.PLUGIN + "tests/evidence/trace.json", "excluded sentinel\n")
+ self.write(bundle.PLUGIN + "src/private.hpp", "excluded sentinel\n")
+ self.git("add", ".")
+ self.git("commit", "-qm", "Synthetic release fixture")
+ self.revision = self.git("rev-parse", "HEAD")
+
+ def git(self, *args):
+ return subprocess.check_output(["git", "-C", str(self.repo), *args], stderr=subprocess.PIPE, text=True).strip()
+
+ def write(self, path, data):
+ destination = self.repo / path
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ destination.write_text(data)
+
+ def generate(self, name="release"):
+ output = self.root / name
+ bundle.generate(self.repo, self.revision, "1.2.3", output)
+ return output
+
+ def source(self):
+ output = self.generate()
+ tarball = next(output.glob("*.tar.gz"))
+ destination = self.root / "extracted"
+ with tarfile.open(tarball) as archive:
+ archive.extractall(destination, filter="data")
+ return next(destination.iterdir())
+
+ def test_deterministic_and_allowlisted_committed_source(self):
+ first = self.generate("first")
+ self.write(bundle.PLUGIN + "src/plugin.cpp", "dirty source must not ship\n")
+ self.write(bundle.PLUGIN + "src/untracked.hpp", "untracked must not ship\n")
+ self.write(bundle.RELEASE + "PKGBUILD.in", "dirty recipe must not ship\n")
+ second = self.generate("second")
+ self.assertEqual({p.name: p.read_bytes() for p in first.iterdir()}, {p.name: p.read_bytes() for p in second.iterdir()})
+ with tarfile.open(next(first.glob("*.tar.gz"))) as archive:
+ names = {"/".join(member.name.split("/")[1:]) for member in archive.getmembers()}
+ self.assertEqual(names, set(bundle.SOURCE_FILES) | {"LICENSE.md", "verify.py", "SOURCE-PROVENANCE.json"})
+ for member in archive.getmembers():
+ self.assertTrue(member.isfile())
+ self.assertEqual((member.uid, member.gid, member.mtime, member.mode), (0, 0, 0, 0o644))
+ self.assertNotIn(b"excluded sentinel", archive.extractfile(member).read())
+ self.assertEqual((first / "README.md").read_bytes(), (HERE / "USAGE.md").read_bytes())
+ subprocess.run(["bash", "-n", str(first / "PKGBUILD")], check=True)
+
+ @unittest.skipUnless(shutil.which("cmake"), "requires the portable plugin CMake toolchain")
+ def test_actual_allowlist_configures_and_builds_foreground_guard(self):
+ source = self.root / "allowlisted-source"
+ for relative in bundle.SOURCE_FILES:
+ destination = source / relative
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(HERE.parent.parent / relative, destination)
+ build = self.root / "portable-build"
+ configure = ["cmake", "-S", str(source), "-B", str(build), "-DCUA_HYPRLAND_BUILD_PLUGIN=OFF"]
+ compiler = os.environ.get("CXX") or shutil.which("clang++-18")
+ if compiler:
+ configure.append("-DCMAKE_CXX_COMPILER=" + compiler)
+ for command in (
+ configure,
+ ["cmake", "--build", str(build), "--target", "cua_hyprland_foreground_route_test"],
+ ):
+ result = subprocess.run(command, capture_output=True, text=True, timeout=120)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+ def test_refuses_revision_version_missing_source_and_existing_output(self):
+ for revision, version in (("HEAD", "1.2.3"), (self.revision, "1.2.4"), (self.revision, "1.2.3;false")):
+ with self.assertRaises(ValueError):
+ bundle.generate(self.repo, revision, version, self.root / "invalid")
+ output = self.generate()
+ with self.assertRaises(FileExistsError):
+ bundle.generate(self.repo, self.revision, "1.2.3", output)
+ self.git("rm", bundle.PLUGIN + "src/plugin.cpp")
+ self.git("commit", "-qm", "Missing required source")
+ with self.assertRaisesRegex(ValueError, "required committed regular file"):
+ bundle.generate(self.repo, self.git("rev-parse", "HEAD"), "1.2.3", self.root / "missing")
+
+ def test_release_archives_match_local_kit_and_are_deterministic(self):
+ self.git("tag", "-a", "cua-driver-rs-v1.2.3", "-m", "Synthetic component tag")
+ local = self.generate()
+ outputs = [self.root / name for name in ("assets-first", "assets-second")]
+ for output in outputs:
+ bundle.generate(self.repo, self.revision, "1.2.3", output, release_assets=True)
+ self.write(bundle.RELEASE + "USAGE.md", "dirty documentation must not ship")
+ self.assertEqual({p.name: p.read_bytes() for p in outputs[0].iterdir()},
+ {p.name: p.read_bytes() for p in outputs[1].iterdir()})
+ stem = f"cua-hyprland-plugin-1.2.3-{self.revision}"
+ self.assertEqual({p.name for p in outputs[0].iterdir()},
+ {f"{stem}.tar.gz", f"{stem}-build-kit.tar.gz"})
+ self.assertEqual((outputs[0] / f"{stem}.tar.gz").read_bytes(),
+ (local / f"{stem}.tar.gz").read_bytes())
+ with tarfile.open(outputs[0] / f"{stem}-build-kit.tar.gz") as archive:
+ self.assertEqual(archive.getnames(), sorted([
+ "PKGBUILD", "README.md", "SHA256SUMS", "SOURCE-PROVENANCE.json", "lifecycle.py",
+ ]))
+ kit = {member.name: archive.extractfile(member).read() for member in archive.getmembers()}
+ for member in archive.getmembers():
+ self.assertTrue(member.isfile())
+ self.assertEqual((member.uid, member.gid, member.mtime, member.mode), (0, 0, 0, 0o644))
+ self.assertEqual(kit[member.name], (local / member.name).read_bytes())
+ for line in kit["SHA256SUMS"].decode().splitlines():
+ digest, name = line.split(" ")
+ self.assertEqual(digest, bundle.sha256((local / name).read_bytes()))
+ self.assertFalse(json.loads(kit["SOURCE-PROVENANCE.json"])["native_certified"])
+ with self.assertRaises(FileExistsError):
+ bundle.generate(self.repo, self.revision, "1.2.3", outputs[0], release_assets=True)
+
+ def test_release_assets_require_exact_tag_and_committed_version(self):
+ output = self.root / "invalid-assets"
+ with self.assertRaises(subprocess.CalledProcessError):
+ bundle.generate(self.repo, self.revision, "1.2.3", output, release_assets=True)
+ self.git("tag", "cua-driver-rs-v1.2.3")
+ self.write("unrelated.txt", "another commit")
+ self.git("add", "unrelated.txt")
+ self.git("commit", "-qm", "Different source revision")
+ with self.assertRaisesRegex(ValueError, "exact Driver release tag"):
+ bundle.generate(self.repo, self.git("rev-parse", "HEAD"), "1.2.3", output, release_assets=True)
+ self.git("tag", "cua-driver-rs-v1.2.4", self.revision)
+ for version in ("1.2.4", "1.2.3-nightly.20260905"):
+ with self.assertRaises(ValueError):
+ bundle.generate(self.repo, self.revision, version, output, release_assets=True)
+ self.assertFalse(output.exists())
+
+ def workflow_generate(self, version="1.2.3"):
+ workflow = (HERE.parents[4] / ".github/workflows/cd-rust-cua-driver.yml").read_text()
+ job = workflow.split(" build-hyprland-plugin-source:\n", 1)[1]
+ script = textwrap.dedent(job.split(" run: |\n", 1)[1].split(
+ " - uses: actions/upload-artifact@v4", 1
+ )[0])
+ binaries = self.root / "bin"
+ binaries.mkdir(exist_ok=True)
+ python = binaries / "python3"
+ if not python.exists():
+ python.symlink_to(sys.executable)
+ return subprocess.run(["bash", "-e", "-c", script], cwd=self.repo,
+ env={**os.environ, "PATH": f"{binaries}:{os.environ['PATH']}",
+ "GITHUB_REF": "refs/heads/main", "REQUESTED_VERSION": version,
+ "GITHUB_OUTPUT": str(self.root / "step-output")},
+ capture_output=True, text=True)
+
+ def test_workflow_legacy_recovery_still_checks_source_and_version(self):
+ self.git("tag", "cua-driver-rs-v1.2.3")
+ legacy = self.workflow_generate()
+ self.assertEqual(legacy.returncode, 0, legacy.stderr)
+ self.assertIn("Legacy source has no plugin bundler", legacy.stdout)
+ self.assertFalse((self.root / "step-output").exists())
+ self.git("tag", "cua-driver-rs-v1.2.4")
+ self.assertNotEqual(self.workflow_generate("1.2.4").returncode, 0)
+ self.write("unrelated.txt", "different source")
+ self.git("add", "unrelated.txt")
+ self.git("commit", "-qm", "Different checkout")
+ self.assertNotEqual(self.workflow_generate().returncode, 0)
+
+ def test_workflow_existing_bundler_failure_is_not_a_legacy_skip(self):
+ self.write(bundle.RELEASE + "bundle.py", "raise SystemExit(17)\n")
+ self.git("add", bundle.RELEASE + "bundle.py")
+ self.git("commit", "-qm", "Existing incompatible bundler")
+ self.git("tag", "cua-driver-rs-v1.2.3")
+ result = self.workflow_generate()
+ self.assertEqual(result.returncode, 17, result.stderr)
+ self.assertNotIn("Legacy source", result.stdout)
+ self.assertFalse((self.root / "step-output").exists())
+
+ def test_workflow_generates_both_assets_from_the_tag(self):
+ self.write(bundle.RELEASE + "bundle.py", (HERE / "bundle.py").read_text())
+ self.git("add", bundle.RELEASE + "bundle.py")
+ self.git("commit", "-qm", "Release-capable bundler")
+ self.git("tag", "cua-driver-rs-v1.2.3")
+ result = self.workflow_generate()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual((self.root / "step-output").read_text(), "available=true\n")
+ stem = f"cua-hyprland-plugin-1.2.3-{self.git('rev-parse', 'HEAD')}"
+ self.assertEqual({p.name for p in (self.repo / "plugin-release-assets").iterdir()},
+ {f"{stem}.tar.gz", f"{stem}-build-kit.tar.gz"})
+
+ def prepare_staged_assets(self):
+ self.write(bundle.RELEASE + "bundle.py", (HERE / "bundle.py").read_text())
+ self.git("add", bundle.RELEASE + "bundle.py")
+ self.git("commit", "-qm", "Release-capable bundler")
+ self.revision = self.git("rev-parse", "HEAD")
+ self.git("tag", "cua-driver-rs-v1.2.3")
+ output = self.repo / "release-upload"
+ bundle.generate(self.repo, self.revision, "1.2.3", output, release_assets=True)
+ return sorted(output.iterdir())
+
+ def workflow_verify_staged_assets(self):
+ workflow = (HERE.parents[4] / ".github/workflows/cd-rust-cua-driver.yml").read_text()
+ step = workflow.split(" - name: Verify staged plugin source assets\n", 1)[1]
+ script = textwrap.dedent(step.split(" run: |\n", 1)[1].split(" - name:", 1)[0])
+ script = script.replace("${{ steps.version.outputs.version }}", "1.2.3").replace(
+ "${{ steps.version.outputs.sha }}", self.revision)
+ binaries = self.root / "bin"
+ binaries.mkdir(exist_ok=True)
+ (binaries / "python3").symlink_to(sys.executable)
+ return subprocess.run(["bash", "-e", "-c", script], cwd=self.repo,
+ env={**os.environ, "PATH": f"{binaries}:{os.environ['PATH']}"},
+ capture_output=True, text=True)
+
+ def test_staged_plugin_assets_match_exact_tag_bytes(self):
+ self.prepare_staged_assets()
+ result = self.workflow_verify_staged_assets()
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_staged_plugin_assets_refuse_missing_archive(self):
+ assets = self.prepare_staged_assets()
+ assets[0].rename(self.root / "withheld.tar.gz")
+ self.assertNotEqual(self.workflow_verify_staged_assets().returncode, 0)
+
+ def test_staged_plugin_assets_refuse_extra_archive(self):
+ self.prepare_staged_assets()
+ self.write("release-upload/cua-hyprland-plugin-unexpected.tar.gz", "unexpected")
+ self.assertNotEqual(self.workflow_verify_staged_assets().returncode, 0)
+
+ def test_staged_plugin_assets_refuse_wrong_revision_filename(self):
+ assets = self.prepare_staged_assets()
+ assets[0].rename(assets[0].with_name(assets[0].name.replace(self.revision, "0" * 40)))
+ self.assertNotEqual(self.workflow_verify_staged_assets().returncode, 0)
+
+ def test_staged_plugin_assets_refuse_changed_bytes(self):
+ assets = self.prepare_staged_assets()
+ assets[0].write_bytes(b"altered download")
+ self.assertNotEqual(self.workflow_verify_staged_assets().returncode, 0)
+
+ def test_staged_legacy_assets_need_no_plugin(self):
+ result = self.workflow_verify_staged_assets()
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_staged_legacy_assets_refuse_unexpected_plugin(self):
+ self.write("release-upload/cua-hyprland-plugin-unexpected.tar.gz", "unexpected")
+ self.assertNotEqual(self.workflow_verify_staged_assets().returncode, 0)
+
+ def test_source_tampering_and_provenance_mismatch(self):
+ source = self.source()
+ manifest = verify.verify_source(source, self.revision, "1.2.3")
+ self.assertFalse(manifest["native_certified"])
+ for revision, version in (("0" * 40, "1.2.3"), (self.revision, "1.2.4")):
+ with self.assertRaisesRegex(ValueError, "provenance mismatch"):
+ verify.verify_source(source, revision, version)
+ original = (source / "src/plugin.cpp").read_bytes()
+ (source / "src/plugin.cpp").write_text("tampered\n")
+ with self.assertRaisesRegex(ValueError, "checksum mismatch"):
+ verify.verify_source(source, self.revision, "1.2.3")
+ (source / "src/plugin.cpp").write_bytes(original)
+ (source / "extra.txt").write_text("unexpected\n")
+ with self.assertRaisesRegex(ValueError, "inventory mismatch"):
+ verify.verify_source(source, self.revision, "1.2.3")
+
+ def test_symlink_source_refused(self):
+ self.git("rm", bundle.PLUGIN + "src/plugin.cpp")
+ (self.repo / bundle.PLUGIN / "src/plugin.cpp").symlink_to("../CMakeLists.txt")
+ self.git("add", bundle.PLUGIN + "src/plugin.cpp")
+ self.git("commit", "-qm", "Symlink source fixture")
+ with self.assertRaisesRegex(ValueError, "required committed regular file"):
+ bundle.generate(self.repo, self.git("rev-parse", "HEAD"), "1.2.3", self.root / "symlink")
+
+ def test_archive_tampering_refused_before_verifier_execution(self):
+ output = self.generate()
+ tarball = next(output.glob("*.tar.gz"))
+ tarball.write_bytes(b"tampered archive")
+ result = subprocess.run(["bash", "-c", 'source "$1"; SRCDEST="$2"; srcdir="$2"; prepare', "test", str(output / "PKGBUILD"), str(output)], capture_output=True, text=True)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("FAILED", result.stdout)
+ self.assertNotIn("verify.py", result.stderr)
+
+ def test_recipe_installs_only_module_license_and_provenance(self):
+ output = self.generate()
+ srcdir = self.root / "src"
+ build = srcdir / "build"
+ build.mkdir(parents=True)
+ (build / "cua-hyprland-plugin.so").write_text("module fixture")
+ stem = next(output.glob("*.tar.gz")).name.removesuffix(".tar.gz")
+ source = srcdir / stem
+ source.mkdir()
+ (source / "LICENSE.md").write_text("license fixture")
+ (source / "SOURCE-PROVENANCE.json").write_text("{}")
+ (srcdir / "BUILD-PROVENANCE.json").write_text("{}")
+ pkgdir = self.root / "pkg"
+ script = '''source "$1"
+srcdir="$2"; pkgdir="$3"
+check() { :; }
+_verify() { :; }
+if command -v ginstall >/dev/null; then
+ install() { command ginstall "$@"; }
+fi
+package || exit 1
+[[ -z ${install:-} ]]
+'''
+ subprocess.run(["bash", "-c", script, "test", str(output / "PKGBUILD"), str(srcdir), str(pkgdir)], check=True)
+ self.assertEqual({str(p.relative_to(pkgdir)) for p in pkgdir.rglob("*") if p.is_file()}, {
+ "usr/lib/cua/hyprland/cua-hyprland-plugin.so",
+ "usr/share/licenses/cua-hyprland-plugin/LICENSE",
+ "usr/share/cua-hyprland-plugin/SOURCE-PROVENANCE.json",
+ "usr/share/cua-hyprland-plugin/BUILD-PROVENANCE.json",
+ })
+ text = (output / "PKGBUILD").read_text()
+ for forbidden in ("CUA_SOURCE_ROOT", "hyprctl", "systemctl", "hyprland.conf", "SKIP", "post_install", "post_upgrade"):
+ self.assertNotIn(forbidden, text)
+ failed = subprocess.run(["bash", "-c", 'source "$1"; check() { return 17; }; package', "test", str(output / "PKGBUILD")])
+ self.assertNotEqual(failed.returncode, 0)
+
+ def test_manifest_and_verifier_tampering_refused_before_execution(self):
+ source = self.source()
+ output = self.root / "release"
+ script = 'source "$1"; SRCDEST="$2"; srcdir="$3"; prepare'
+ for path in (source / "SOURCE-PROVENANCE.json", source / "verify.py"):
+ with self.subTest(path=path.name):
+ original = path.read_bytes()
+ path.write_text("tampered content\n")
+ result = subprocess.run(["bash", "-c", script, "test", str(output / "PKGBUILD"), str(output), str(source.parent)], capture_output=True, text=True)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("FAILED", result.stdout)
+ self.assertNotIn("SyntaxError", result.stderr)
+ path.write_bytes(original)
+
+ def test_mandatory_tests_drop_fakeroot_only_in_test_child(self):
+ output = self.generate()
+ binaries = self.root / 'test-bin'
+ binaries.mkdir()
+ ctest = binaries / 'ctest'
+ ctest.write_text('''#!/bin/sh
+test -z "${LD_PRELOAD+x}" && test -z "${FAKEROOTKEY+x}" && test -z "${FAKED_MODE+x}" || exit 91
+test "$1" = --test-dir && test "$3" = --output-on-failure && test "$4" = --no-tests=error || exit 92
+printf 'ctest-real-identity\\n'
+exit "${TEST_CTEST_EXIT:-0}"
+''')
+ ctest.chmod(0o755)
+ script = '''source "$1"
+srcdir="$2"; PATH="$3:$PATH"
+export LD_PRELOAD=synthetic-fakeroot.so FAKEROOTKEY=123 FAKED_MODE=unknown-is-real
+_verify() { [[ "$LD_PRELOAD" == synthetic-fakeroot.so && "$FAKEROOTKEY" == 123 ]]; }
+if [[ "$4" == check ]]; then
+ check; result=$?
+ [[ $result == 0 ]] || exit 93
+else
+ export TEST_CTEST_EXIT=17
+ package; result=$?
+ [[ $result != 0 ]] || exit 94
+fi
+[[ "$LD_PRELOAD" == synthetic-fakeroot.so && "$FAKEROOTKEY" == 123 && "$FAKED_MODE" == unknown-is-real ]]
+'''
+ for operation in ('check', 'package'):
+ with self.subTest(operation=operation):
+ result = subprocess.run(['bash', '-c', script, 'test', str(output / 'PKGBUILD'),
+ str(self.root / 'src'), str(binaries), operation],
+ capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, 'ctest-real-identity\n')
+
+
+class NativeContractTest(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory(prefix="cua-release-native-fixture-")
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.cxx = self.root / "g++"
+ self.cxx.write_text("compiler fixture")
+ self.runtime = self.root / "libstdc++.so.6.0.36"
+ self.runtime.write_text("runtime fixture")
+ self.package = "hyprland 0.56.2-1"
+ self.headers = "0.56.2"
+ self.compiler = verify.COMPILER_VERSION
+ self.comment = verify.COMPILER_COMMENT
+ self.probe_comment = verify.COMPILER_COMMENT
+
+ def fake_run(self, *args, input=None):
+ if args[:2] == ("pacman", "-Q"):
+ return self.package
+ if args[0] == "pkg-config":
+ return self.headers
+ if args[0] == "readelf":
+ comment = self.comment if args[-1] == "/usr/bin/Hyprland" else self.probe_comment
+ return f"String dump of section '.comment':\n [ 0] {comment}"
+ if args[0] == "ldd":
+ return f" libstdc++.so.6 => {self.runtime} (0x0000)"
+ if "-dM" in args:
+ return f'#define __VERSION__ "{self.compiler}"'
+ if "--print-file-name=libstdc++.so.6" in args:
+ return str(self.runtime)
+ return "synthetic compiler"
+
+ def native(self):
+ with mock.patch.object(verify.platform, "system", return_value="Linux"), mock.patch.object(verify.platform, "machine", return_value="x86_64"), mock.patch.object(verify, "run", side_effect=self.fake_run), mock.patch.object(verify, "digest", return_value="fixture-sha256"):
+ return verify.verify_native(self.cxx)
+
+ def test_exact_native_contract_and_mismatch_refusals(self):
+ self.assertEqual(self.native()["compiler_probe_comment"], verify.COMPILER_COMMENT)
+ for field, bad in (("package", "hyprland 0.56.2-2"), ("headers", "0.56.3"), ("compiler", "16.1.1 20260729"), ("comment", "GCC: (GNU) 16.1.1 20260729"), ("probe_comment", "GCC: (GNU) 16.1.1 20260729")):
+ with self.subTest(field=field):
+ original = getattr(self, field)
+ setattr(self, field, bad)
+ with self.assertRaises(ValueError):
+ self.native()
+ setattr(self, field, original)
+ self.runtime = self.root / "libstdc++.so.6.0.35"
+ self.runtime.write_text("old runtime")
+ with self.assertRaisesRegex(ValueError, "runtime mismatch"):
+ self.native()
+
+ def test_build_option_mismatch_refused(self):
+ build = self.root / "build"
+ build.mkdir()
+ (build / "CMakeCache.txt").write_text("CUA_HYPRLAND_INPUT:BOOL=OFF\n")
+ with self.assertRaisesRegex(ValueError, "build configuration mismatch: CUA_HYPRLAND_INPUT"):
+ verify.verify_build(build, self.root, self.cxx, "fixture-sha256")
+
+ def test_module_runtime_mismatch_refused(self):
+ build = self.root / "build"
+ build.mkdir()
+ cache = dict(verify.OPTIONS, BUILD_TESTING="ON", CUA_HYPRLAND_BUILD_PLUGIN="ON",
+ CUA_HYPRLAND_EXPECTED_VERSION="0.56.2", CMAKE_BUILD_TYPE="Release",
+ CUA_HYPRLAND_TEST_OPERATOR_KEY="", CMAKE_CXX_COMPILER=str(self.cxx),
+ CMAKE_HOME_DIRECTORY=str(self.root.resolve()))
+ (build / "CMakeCache.txt").write_text("".join(f"{key}:STRING={value}\n" for key, value in cache.items()))
+ with mock.patch.object(verify, "run", return_value="Shared library: [libstdc++.so.6]"), mock.patch.object(verify, "linked_runtime", return_value="different-runtime"):
+ with self.assertRaisesRegex(ValueError, "module and compiler shared runtimes differ"):
+ verify.verify_build(build, self.root, self.cxx, "fixture-sha256")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/test_workflow.py b/libs/cua-driver/hyprland-plugin/packaging/release/test_workflow.py
new file mode 100644
index 0000000000..ed5655ae2e
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/test_workflow.py
@@ -0,0 +1,66 @@
+"""Focused contract for stable plugin source assets in Driver releases."""
+
+from pathlib import Path
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[5]
+
+
+class WorkflowTest(unittest.TestCase):
+ def setUp(self):
+ self.workflow = (ROOT / ".github/workflows/cd-rust-cua-driver.yml").read_text()
+ self.job = self.workflow.split(" build-hyprland-plugin-source:\n", 1)[1].split(
+ " verify-release-artifacts:\n", 1
+ )[0]
+ self.release = self.workflow.split(" release:\n", 1)[1]
+
+ def test_stable_immutable_candidates_only_and_publication_dependency(self):
+ self.assertIn("needs: release-attribution-preflight", self.job)
+ self.assertIn(
+ " if: >-\n"
+ " inputs.channel != 'nightly' &&\n"
+ " (startsWith(github.ref, 'refs/tags/cua-driver-rs-v') ||\n"
+ " (github.event_name == 'workflow_dispatch' && inputs.publish == true))",
+ self.job,
+ )
+ # Every publishing dispatch runs the source job. Manual build-only and
+ # nightly invocations skip both publication and this stable source job.
+ needs, steps = self.release.split(" steps:\n", 1)
+ self.assertIn("build-hyprland-plugin-source]", needs)
+ self.assertIn("if: github.event_name == 'workflow_dispatch' && inputs.publish == true", needs)
+ self.assertNotIn("always()", needs)
+ self.assertIn('if [[ "$SHA" != "$TAG_SHA" ]]; then', steps)
+ self.assertIn("python3 .github/scripts/validate_release_versions.py --product driver", steps)
+
+ def test_source_override_is_checked_and_assets_remain_namespaced(self):
+ self.assertIn("fetch-depth: 0", self.job)
+ self.assertIn(
+ "ref: ${{ inputs.source_ref || github.event_name == 'workflow_dispatch' && "
+ "inputs.publish && format('refs/tags/cua-driver-rs-v{0}', inputs.version) || github.ref }}",
+ self.job,
+ )
+ self.assertIn('--repo . --revision "$(git rev-parse HEAD)"', self.job)
+ self.assertIn('--driver-version "$VERSION" --release-assets', self.job)
+ self.assertIn("path: plugin-release-assets/*.tar.gz", self.job)
+ self.assertIn("if-no-files-found: error", self.job)
+ self.assertIn("if: steps.source.outputs.available == 'true'", self.job)
+ self.assertLess(self.job.index('test "$SHA" = "$TAG_SHA"'), self.job.index("if ! git cat-file"))
+ self.assertLess(self.job.index('test "$VERSION" = "$SOURCE_VERSION"'), self.job.index("if ! git cat-file"))
+ self.assertNotIn("apply-version", self.job)
+ self.assertIn("cua-hyprland-plugin-*.tar.gz", self.release)
+ self.assertNotIn("--clobber", self.release)
+
+ def test_downloaded_plugin_assets_are_verified_before_checksums_and_publication(self):
+ verify = self.release.index("- name: Verify staged plugin source assets")
+ checksums = self.release.index("- name: Generate SHA256 checksums")
+ self.assertLess(self.release.index("- name: Download all artifacts"), verify)
+ self.assertLess(verify, checksums)
+ step = self.release[verify:checksums]
+ self.assertIn('test "${#PLUGIN_ASSETS[@]}" -eq 2', step)
+ self.assertIn('--release-assets --output plugin-release-expected', step)
+ self.assertIn('cmp "$EXPECTED" "release-upload/$(basename "$EXPECTED")"', step)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/packaging/release/verify.py b/libs/cua-driver/hyprland-plugin/packaging/release/verify.py
new file mode 100644
index 0000000000..cb170c8c7a
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/packaging/release/verify.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+"""Fail closed on source, Arch ABI, or compiler mismatches before packaging."""
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import subprocess
+import tempfile
+
+COMPILER_VERSION = "16.1.1 20260728"
+COMPILER_COMMENT = "GCC: (GNU) " + COMPILER_VERSION
+OPTIONS = {"CUA_HYPRLAND_INPUT": "ON", "CUA_HYPRLAND_TEST_INPUT": "OFF", "CUA_HYPRLAND_INPUT_TRACE": "OFF"}
+
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def digest(path):
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def run(*command, input=None):
+ return subprocess.check_output(command, input=input, text=True, stderr=subprocess.PIPE,
+ env={**os.environ, "LC_ALL": "C"}).strip()
+
+
+def linked_runtime(binary):
+ dependencies = run("ldd", str(binary))
+ matches = re.findall(r"^\s*libstdc\+\+\.so\.6 => (/\S+) \(", dependencies, re.MULTILINE)
+ require(len(matches) == 1, "cannot resolve shared libstdc++ for " + binary.name)
+ runtime = Path(matches[0]).resolve(strict=True)
+ require(runtime.name == "libstdc++.so.6.0.36", "loaded shared libstdc++ runtime mismatch")
+ return digest(runtime)
+
+
+def verify_source(source, revision, driver_version):
+ manifest = json.loads((source / "SOURCE-PROVENANCE.json").read_text())
+ expected = {
+ "schema": 1, "source_revision": revision, "driver_version": driver_version,
+ "release_tag": f"cua-driver-rs-v{driver_version}",
+ "hyprland_version": "0.56.2", "hyprland_package": "0.56.2-1",
+ "compiler_version": COMPILER_VERSION, "compiler_comment": COMPILER_COMMENT,
+ "architecture": "x86_64", "native_certified": False, "cmake_options": OPTIONS,
+ }
+ for key, value in expected.items():
+ require(manifest.get(key) == value, f"source provenance mismatch: {key}")
+ actual = set()
+ for path in source.rglob("*"):
+ require(not path.is_symlink(), f"source symlink refused: {path.name}")
+ if path.is_file():
+ actual.add(path.relative_to(source).as_posix())
+ require(actual == set(manifest["files"]) | {"SOURCE-PROVENANCE.json"}, "source file inventory mismatch")
+ for name, checksum in manifest["files"].items():
+ require(digest(source / name) == checksum, f"source checksum mismatch: {name}")
+ cmake = (source / "CMakeLists.txt").read_text()
+ require(f"project(cua_hyprland_plugin VERSION {manifest['plugin_version']} LANGUAGES CXX)" in cmake, "plugin version mismatch")
+ return manifest
+
+
+def verify_native(cxx):
+ require(platform.system() == "Linux" and platform.machine() == "x86_64", "requires Linux x86_64")
+ require(cxx.is_absolute() and cxx.is_file(), "C++ compiler must be an existing absolute path")
+ package = run("pacman", "-Q", "hyprland")
+ require(package == "hyprland 0.56.2-1", "Hyprland package mismatch")
+ require(run("pkg-config", "--modversion", "hyprland") == "0.56.2", "Hyprland header mismatch")
+ macros = run(str(cxx), "-dM", "-E", "-x", "c++", "-", input="")
+ require(f'#define __VERSION__ "{COMPILER_VERSION}"' in macros.splitlines(), "GCC version/date mismatch")
+ require("#define __clang__ " not in macros, "Clang is not the pinned GCC compiler")
+ comments = run("readelf", "-p", ".comment", "/usr/bin/Hyprland")
+ entries = [re.sub(r"^\s*\[[^]]+\]\s*", "", line).strip() for line in comments.splitlines()]
+ require(COMPILER_COMMENT in entries, "Hyprland compositor compiler mismatch")
+ # Check what the selected compiler emits, not only its self-reported version.
+ with tempfile.TemporaryDirectory(prefix="cua-compiler-probe-") as temporary:
+ probe = Path(temporary) / "probe.o"
+ run(str(cxx), "-x", "c++", "-c", "-o", str(probe), "-", input="int cua_compiler_probe;\n")
+ probe_comments = run("readelf", "-p", ".comment", str(probe))
+ probe_entries = [re.sub(r"^\s*\[[^]]+\]\s*", "", line).strip() for line in probe_comments.splitlines()]
+ require(COMPILER_COMMENT in probe_entries, "compiler probe does not match compositor compiler")
+ runtime = Path(run(str(cxx), "--print-file-name=libstdc++.so.6")).resolve(strict=True)
+ require(runtime.name == "libstdc++.so.6.0.36", "compiler shared libstdc++ runtime mismatch")
+ runtime_sha = digest(runtime)
+ require(linked_runtime(Path("/usr/bin/Hyprland")) == runtime_sha, "compositor and compiler shared runtimes differ")
+ return {
+ "hyprland_package": package,
+ "hyprland_header_version": "0.56.2",
+ "compositor_sha256": digest(Path("/usr/bin/Hyprland")),
+ "compositor_compiler": COMPILER_COMMENT,
+ "compiler_version": COMPILER_VERSION,
+ "compiler_banner": run(str(cxx), "--version"),
+ "compiler_sha256": digest(cxx),
+ "compiler_probe_comment": COMPILER_COMMENT,
+ "compiler_runtime": runtime.name,
+ "compiler_runtime_sha256": runtime_sha,
+ "compositor_runtime_sha256": runtime_sha,
+ }
+
+
+def verify_build(build, source, cxx, runtime_sha):
+ cache = {}
+ for line in (build / "CMakeCache.txt").read_text().splitlines():
+ match = re.match(r"([^:#/][^:]*):[^=]+=(.*)", line)
+ if match:
+ cache[match[1]] = match[2]
+ expected = dict(OPTIONS, BUILD_TESTING="ON", CUA_HYPRLAND_BUILD_PLUGIN="ON",
+ CUA_HYPRLAND_EXPECTED_VERSION="0.56.2", CMAKE_BUILD_TYPE="Release",
+ CUA_HYPRLAND_TEST_OPERATOR_KEY="", CMAKE_CXX_COMPILER=str(cxx),
+ CMAKE_HOME_DIRECTORY=str(source.resolve()))
+ for key, value in expected.items():
+ require(cache.get(key) == value, f"build configuration mismatch: {key}")
+ module = build / "cua-hyprland-plugin.so"
+ dynamic = run("readelf", "-d", str(module))
+ require("Shared library: [libstdc++.so.6]" in dynamic, "module must use shared libstdc++")
+ require("Shared library: [libc++.so" not in dynamic, "module uses incompatible libc++")
+ require(linked_runtime(module) == runtime_sha, "module and compiler shared runtimes differ")
+ return digest(module)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", required=True, type=Path)
+ parser.add_argument("--revision", required=True)
+ parser.add_argument("--driver-version", required=True)
+ parser.add_argument("--cxx", required=True, type=Path)
+ parser.add_argument("--build", type=Path)
+ parser.add_argument("--output", type=Path)
+ args = parser.parse_args()
+ try:
+ manifest = verify_source(args.source, args.revision, args.driver_version)
+ native = verify_native(args.cxx)
+ if args.build:
+ native["module_sha256"] = verify_build(args.build, args.source, args.cxx, native["compiler_runtime_sha256"])
+ native["module_runtime_sha256"] = native["compiler_runtime_sha256"]
+ if args.output:
+ require(args.build is not None, "build evidence is required for output")
+ native["source"] = manifest
+ args.output.write_text(json.dumps(native, indent=2, sort_keys=True) + "\n")
+ except (ValueError, KeyError, OSError, subprocess.CalledProcessError) as error:
+ parser.exit(1, f"error: {error}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md b/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md
new file mode 100644
index 0000000000..7c72cbc14a
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md
@@ -0,0 +1,255 @@
+# Local input protocol v3 candidate
+
+This opt-in candidate connects Driver's existing per-action admission to two
+independent compositor seats. The accepted extension adds a distinct exact-target
+primary-seat foreground route. It is not native certification or a release
+announcement. The default plugin build remains discovery-only, and discovery
+protocol v2 is unchanged.
+
+Driver completes common permission, resource, lifecycle, and application
+compatibility checks before each action. The plugin trusts the desktop account
+under a local trust model. Same-UID transport checks prevent accidental
+cross-account use; they do not authenticate human consent or contain hostile
+code running as that user. There is no external signer, `APPROVE` command,
+challenge, or separate per-window permission workflow in v3.
+
+## Transport and lane ownership
+
+The private Hyprland instance directory contains `cua-input-v3.sock` and
+`cua-input-v3-2.sock`. Each endpoint uses Linux `SOCK_SEQPACKET`, checks
+`SO_PEERCRED` for the compositor UID, and owns one lane. Socket permissions are
+`0600`; the instance directory must be owned by that user and private. Driver
+also verifies the peer against the selected compositor instance.
+
+Packets contain printable ASCII fields separated by exactly one space, with
+no newline. The maximum packet size is 2048 bytes. Responses are JSON packets.
+Unknown commands, extra fields, integer overflow, nonfinite coordinates, and
+out-of-range values refuse. Decimal integers are unsigned; the target address,
+epoch, and target token are hexadecimal. Epochs and tokens contain 32 lowercase
+hexadecimal characters.
+
+Each socket accepts at most eight connections. A connection must send `HELLO`
+within five seconds and must not remain idle for more than 60 seconds. A
+successful `CLAIM` reserves the endpoint for that connection until EOF,
+timeout, or a desktop/configuration lifecycle transition. Repeated `CLAIM` on
+the same connection is idempotent. Driver may try the second endpoint only
+after an explicit `lane_busy` reply, before target selection or dispatch.
+Connection failures and unknown delivery results do not permit retries.
+
+The v3 seats are `Cua-Agent` and `Cua-Agent-2`. Driver excludes these from its
+foreground virtual-input routes. Seat ownership does not come from public
+session labels. The signed experiment uses separate sockets, protocol 0, and
+its original seat names.
+
+## Requests and responses
+
+The request sequence for every Driver-admitted action is:
+
+1. Send `HELLO` once per connection. The response is
+ `{"ok":true,"protocol":3,"epoch":"<epoch>","foreground_target":true}`
+ for a production plugin implementing the foreground extension. Driver must
+ require that explicit capability before using the foreground route.
+2. Send `CLAIM`. The response is `{"ok":true,"lane":0}` or lane `1`.
+3. For background input, send `TARGET <pid> <hex-address> <capability>`.
+ For foreground input, send
+ `FOREGROUND_TARGET <pid> <hex-address> <capability>`. The capability is exactly
+ one of `1` (click), `2` (key), `4` (scroll), or `8` (drag); foreground selection
+ also permits `16` (activate). Combined masks refuse.
+ The response includes `ok`, `target`, `revision`, `width`, and `height`.
+4. Send the one matching bounded operation using that token and revision.
+ A subsequent action requires fresh route-specific target selection, even on
+ a cached connection. The binding fixes the route; an operation cannot turn
+ a background grant into a foreground grant.
+
+`TARGET` binds the exact live native top-level surface, generates a fresh token,
+and grants at most five seconds of steady-clock technical lifetime. It first
+retires any unused previous grant. It refuses unavailable desktops, primary
+focus on the target's Wayland client, another lane targeting that client, and
+unsupported keymaps. A discovered address is an input to attestation, not a
+surface lifetime token. Surface unmap, destruction, or replacement invalidates
+the binding. Geometry changes increment the revision and refuse stale actions.
+
+The complete operation requests are:
+
+| Request | Limits |
+| --- | --- |
+| `ACTIVATE <sequence> <target> <revision>` | Capability 16; foreground bindings only. |
+| `CLICK <sequence> <target> <revision> <x> <y> <button> <count>` | Evdev buttons 272–274; count 1–2. |
+| `KEY <sequence> <target> <revision> <key> <modifiers>` | Evdev key 1–247 except lock keys 58, 69, and 70. Modifier bits: shift=1, ctrl=2, alt=4, super=8. |
+| `SCROLL <sequence> <target> <revision> <x> <y> <axis> <value>` | Axis 0=vertical, 1=horizontal; nonzero value in [-1000,1000]. |
+| `DRAG <sequence> <target> <revision> <x1> <y1> <x2> <y2> <duration_ms>` | Left button; duration 50–2000 ms; the grant must cover the duration plus 50 ms. |
+
+Coordinates are finite logical surface-local values, with `0 <= x < width`
+and `0 <= y < height`. Subsurface hits refuse. Sequence numbers increase
+strictly across the connection, including fresh target selections. Repeated
+or lower sequences return `replay`; no operation is replayed automatically.
+
+The plugin repeats target, geometry, desktop, keymap, and conflict checks on
+the compositor thread at
+dispatch. It consumes the grant before the first synthetic focus/input event.
+Completed background operations release their held buttons, keys, keyboard focus, and
+remaining technical authority. A drag keeps its bounded lifetime while
+running; consuming its grant does not permit another action. A dispatch without
+fresh authority returns `action_not_admitted`. Malformed or refused requests
+never imply application rollback.
+
+Background pointer focus has a separate lifetime. After a successful background pointer operation,
+the lane keeps passive pointer focus on that exact live surface. This internal
+state is separate from the visible Driver overlay, whose idle fade and
+session-end removal remain unchanged. Fresh
+`TARGET` admission on the same surface and unchanged geometry preserves this
+focus while issuing a new token and one-operation grant. A key action releases
+its keyboard focus without removing a previously retained pointer focus.
+Retaining pointer focus prevents an unnecessary `wl_pointer.leave` directly
+after drag release; some clients coalesce motion and requeue the release.
+There is no fixed completion delay or trace-only timing behavior.
+
+Passive focus has no held input or authority, but still participates in
+primary-client and inter-lane conflicts. Owner cancellation, EOF, and the
+connection's idle timeout release held buttons and all keyboard state and
+revoke authority without requiring pointer leave. Passive target references
+are weak and independent of the transport owner; a disconnected owner retains
+no lane reservation. Fresh admission may reuse unchanged focus on the same
+live surface without inheriting old authority.
+
+Because Driver claims a free lane before selecting its target, fresh valid
+`TARGET` admission may retire matching hover on a different unreserved lane,
+or a lane whose new claimant has never successfully bound a target. A bare
+`CLAIM` reserves capacity; it does not adopt a previous owner's hover. This is
+allowed only when that peer has no lease, drag, held input, keyboard focus,
+capabilities, or remaining grant/expiry state. After a connection's first
+successful `TARGET`, its reservation protects its hover even after STOP,
+CANCEL, or target invalidation. Existing target owners and active peers still
+cause `agent_target_busy`; ordinary dispatch and conflict checks never evict
+them. This permits opposite-order reuse when both new connections reserve
+their lanes before either selects a target, without retrying any input.
+
+Target replacement, unmap, destruction, geometry change, primary-client
+conflict, and desktop/keymap/configuration transitions clear passive focus.
+The five-second action grant does not extend to passive focus. These boundaries
+may still end focus before a stalled client processes its events; dispatch
+acknowledgement is not an application-processing fence. Verify the application's
+effect independently.
+
+Successful background dispatch returns
+`{"ok":true,"effect":"unverifiable","route":"synthetic_events"}`. This
+acknowledges synthetic delivery, not an application outcome. A drag first
+returns `{"ok":true,"phase":"started"}` and later its final result. After
+that first acknowledgement, cancellation can leave partial application
+effects. EOF or a missing final acknowledgement means delivery is unknown;
+Driver must not report that nothing happened or replay the operation.
+
+Driver maps a refusal before an acknowledged start to `effect:refused`, with
+no delivery field. After a drag-start acknowledgement, an explicit cancellation
+maps to `effect:partial` with `delivery.mode:background` and
+`delivery.delivered_count:1`. This count measures acknowledged gesture phases
+(the start), not pointer events or application changes. A lost or malformed
+final reply preserves that count but sets `delivery.mode:unknown`; later input
+may have landed without acknowledgement. A missing initial reply has unknown
+delivery with no count. Neither case permits replay.
+
+Refusals use `{"ok":false,"code":"<code>","detail":"<code>"}`. Codes
+include `lane_busy`, `lane_not_claimed`, `stale_target`, `stale_geometry`,
+`session_unavailable`, `unsupported_layout`, `primary_target_busy`,
+`agent_target_busy`, `lease_expired`, `action_not_admitted`, `lease_busy`,
+`client_not_bound`, `replay`, `unsupported`, and `invalid_request`.
+
+## Exact-target foreground extension
+
+`FOREGROUND_TARGET` binds an ordinary live native top-level surface to
+`primary_foreground`. The plugin validates the exact PID, compositor address,
+surface lifetime, geometry revision, and route at admission and dispatch on the
+compositor thread. `ACTIVATE` intentionally activates that target. Foreground
+click, key, scroll, and drag use the same bounded operation shapes with a
+foreground binding; primary focus and cursor position may change. This route
+makes no promise to restore focus or cursor position after delivery.
+
+Before taking over primary input, the plugin must refuse held physical keys or
+buttons, active grabs, pointer constraints, and drag-and-drop. It requires a
+single primary seat binding, excluding its own agent seats by resource identity,
+and refuses binding or input-resource changes during dispatch. Keyboard delivery
+requires neutral primary modifiers and layout group zero; latched or locked
+modifiers refuse before activation. Foreground drag
+cancellation on primary-input and focus transitions remains subject to review
+and native verification; do not infer background isolation from this route.
+Foreground results use foreground delivery metadata. A drag cancellation after
+its start is partial, and a missing acknowledgement is unknown, under the same
+no-replay rules as background delivery.
+
+Discovery or activation read-back followed by global `wtype` input does not
+establish exact-target delivery and is not a fallback. Background refusal never
+escalates to foreground. Both routes use Driver's existing permission and
+lifecycle admission, without a separate approval UI.
+
+## Cancellation and recovery
+
+`CANCEL` and `STOP` both require the connection's lane claim. They revoke only
+that endpoint's pending/current action, invalidate its target, and release its
+synthetic held state. They preserve the reservation and other lane. A drag
+receives its cancellation result before the command acknowledgement. A new
+unclaimed control connection cannot cancel a runtime's lane. V3 has no global
+socket stop command; plugin disable or unload explicitly stops both lanes.
+
+These commands belong to the private plugin wire, not the public MCP tool
+surface. Likewise, EOF below means the owned plugin connection closes. Closing
+MCP stdin is not necessarily immediate plugin EOF: direct stdio finishes its
+current request before reading the next request or EOF. See the
+[Driver lifecycle boundary](host-authority-boundary.md#cancellation-and-recovery)
+for the separate cancellation paths and transport limits.
+
+EOF cancels only the departing connection's work and frees its reservation.
+Lock/unlock, DPMS, session activity, and monitor transitions revoke authority.
+Keymap/layout changes revoke authority, including synchronous layout and
+active-keyboard keymap notifications. For background bindings, changing primary
+focus to a target client cancels that lane synchronously. Dispatch and timer checks supplement
+these listeners. None of these paths wake the display or unlock the session.
+
+Config disable closes input transports but preserves client-owned seats and
+resources. Re-enable opens fresh transports with new epochs. Each later
+action must pass fresh Driver admission and target checks. Plugin replacement
+requires a desktop restart. The shared seat-lifetime marker rejects loading
+replacement modules in the same compositor instance. Unload retires globals
+and retains inert callbacks for late client cleanup.
+
+Cancellation releases synthetic state; it does not undo application effects.
+Cleanup depends on a responsive compositor event loop. A stall is not evidence
+of bounded cleanup latency.
+
+## Compatibility and build gates
+
+For background `TARGET`, Driver restricts app/package/version/operation
+eligibility before connecting. Its qualification scope remains native Calc and
+Inkscape. Foreground `FOREGROUND_TARGET` has no Calc/Inkscape package gate; its
+scope is ordinary native top-level surfaces. Native GTK3, Electron, and Tauri
+foreground coverage is planned and still requires certification. The plugin checks
+native surface identity, geometry, client conflicts, and exact compiled XKB
+content against the default `evdev`/`pc105`/`us` keymap. Variants, options,
+remaps, multiple groups, missing keyboards, XWayland, Unicode, IME input,
+arbitrary held-key streams, and modified pointer gestures are outside this
+candidate. Layout names alone never establish eligibility. Existing semantic
+Driver routes retain their own behavior.
+
+Driver expands bounded ASCII text into complete key operations under the exact
+US keymap. The protocol adds no text or IME stream. Background application
+qualification is unchanged by this foreground extension.
+
+Build against the exact Hyprland 0.56.2 ABI with `CUA_HYPRLAND_INPUT=ON`.
+This option defaults to `OFF` and is mutually exclusive with
+`CUA_HYPRLAND_TEST_INPUT`. The production build does not link an external
+signer or OpenSSL. `CUA_HYPRLAND_INPUT_TRACE=ON` adds test instrumentation for
+certification; it defaults to `OFF` and requires v3 input. Uninstrumented
+production does not expose `TRACE_START`, `TRACE_STOP`, or `TRACE_READ`.
+
+Portable grant, lifecycle, discovery, and transport tests do not prove native
+seat delivery or keymap qualification. Certification must build the actual
+native implementation and verify each supported app/operation, both lanes,
+independent primary interaction, stale/refusal paths, partial delivery,
+cleanup, and surviving-client recovery at the exact candidate SHA. Include
+both instrumented evidence and an uninstrumented production-package smoke.
+The foreground extension must also pass the existing complete canonical Linux
+Rust suite in native Hyprland at the candidate SHA, preserving its runner,
+required cells, assertions, and evidence checks. No foreground certification
+result is recorded here.
+
+The independent-seat design adapts Dillon DuPont's Hyprland prototype. Earlier
+signed-experiment results remain historical evidence for that source only.
diff --git a/libs/cua-driver/hyprland-plugin/protocol/host-authority-boundary.md b/libs/cua-driver/hyprland-plugin/protocol/host-authority-boundary.md
new file mode 100644
index 0000000000..ba28879a49
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/protocol/host-authority-boundary.md
@@ -0,0 +1,99 @@
+# Driver admission and compositor isolation
+
+This implementation note follows the scope correction in
+[RFC #3550](https://github.com/trycua/cua/issues/3550#issuecomment-5556178980).
+The v3 implementation is a candidate pending native certification and review,
+not a release announcement. The default plugin build remains discovery-only.
+
+## One permission system
+
+Driver's common tool registry admits every action before invoking the Linux
+adapter. Standard and explicitly acknowledged unrestricted mode without a
+manifest do not require per-window protected grants. Bounded mode requires an
+approved capability manifest. Manifests, managed policy, user policy, and
+shared hard invariants remain binding in every applicable mode.
+
+The plugin does not add an Omarchy-specific permission mode, approval panel,
+per-window prompt, indicator-owned authorization, or signing service. Existing
+Driver activity and lifecycle behavior still applies. A cached native
+connection, public session label, environment switch, or target token never
+bypasses the common registry on a later call.
+
+The earlier disconnected `isolated_input_authority` prototype has been removed.
+It required a separate trusted host but was not called by any runtime or
+adapter. The integrated boundary uses the existing dispatch, policy, and
+lifecycle paths instead.
+
+## Local trust and per-action binding
+
+An explicitly enabled plugin accepts the trusted desktop account over private
+same-UID sockets. Driver also attests the socket against its Wayland compositor
+connection. These checks prevent cross-account access and accidental routing
+to another compositor; they do not prove human consent or sandbox arbitrary
+native code running as the same user.
+
+The Linux adapter checks the qualified application package on every action
+before allocating or using a lane. Eligibility is a compatibility check, not
+an authorization boundary. The initial candidate scope is native Calc
+`libreoffice-fresh 26.2.5-3` and Inkscape `1.4.4-6`, subject to per-operation
+native qualification. Unknown packages refuse. The plugin separately checks
+the live native surface, geometry, primary/other-agent conflicts, desktop
+availability, and canonical US keymap.
+
+Production [input v3](cua-input-v3.md) has separate endpoints from discovery v2
+and signed experiment 0. Each private connection claims one compositor-owned
+lane. Every admitted action performs a fresh `TARGET` for one exact operation
+and a maximum five-second technical lifetime. Complete dispatch consumes that
+binding. Driver does not negotiate down to the experiment or primary seat.
+
+## Cancellation and recovery
+
+The registry supplies a runtime-private lifecycle identity. Independent Driver
+processes claim independent compositor lanes; matching public labels cannot
+transfer ownership. The current candidate supports at most two lanes.
+
+Session end signals interrupt in-flight adapter waits. Closing the owned
+connection cancels that lane and frees its reservation. Runtime teardown also
+cleans connections that never acquired an overlay. Plugin disable, session
+transitions, stale targets, keymap changes, and primary-target conflicts revoke
+affected work. Cleanup releases synthetic state only; it does not undo app
+effects. A stalled compositor cannot promise bounded cleanup latency.
+
+These are adapter lifecycle semantics, not an additional MCP cancellation
+feature. Direct stdio MCP processes one request at a time and ignores
+notifications, including `notifications/cancelled`. An `end_session` request or
+stdin EOF is handled after the current request returns; neither interrupts that
+request immediately. SDK invocation cancellation, runtime process termination,
+and plugin-socket EOF are distinct paths and need separate evidence. The
+process-termination proof does not certify MCP cancellation or session end.
+
+Do not replay canceled, partial, or unknown actions. A later new call may
+acquire a fresh target after common permission, lifecycle, identity, geometry,
+compatibility, and conflict checks. Config disable/re-enable preserves
+session-lifetime seats; replacing the plugin requires a desktop restart.
+
+## Evidence and remaining gates
+
+Focused common registry coverage is available from `libs/cua-driver/rust`:
+
+```bash
+cargo test -p cua-driver-core background_input_ --lib --locked
+```
+
+These tests exercise normal promptless modes and manifest allow/deny decisions
+on repeated calls before adapter invocation. They are not native delivery or
+continuous foreground-isolation evidence. The adapter tests additionally
+cover distinct protocol negotiation, exact operation binding, compositor lane
+allocation, and owned-session cleanup.
+
+The [production proof harness](../tests/production-proof.md) uses two direct
+Driver MCP processes with no signer. Native acceptance still requires saved
+application outputs, continuous primary-input and held-state oracles, a
+warp-and-return negative control, cancellation/fault coverage, and exact-source
+provenance. Test both an instrumented candidate and an uninstrumented package.
+Keep unproven and refused cells explicit.
+
+Review and merge the implementation chain, then publish and verify Driver and
+compatible plugin artifacts before building the final Fleet image. Source
+candidates can be tested in disposable Fleet instances before release; that is
+pre-release validation, not a final supported image.
diff --git a/libs/cua-driver/hyprland-plugin/protocol/input-experiment.md b/libs/cua-driver/hyprland-plugin/protocol/input-experiment.md
new file mode 100644
index 0000000000..0a285bed88
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/protocol/input-experiment.md
@@ -0,0 +1,166 @@
+# Isolated-input compatibility experiment
+
+This is a nonshipping implementation spike for [RFC #3550](https://github.com/trycua/cua/issues/3550),
+not its accepted production protocol. The normal build remains discovery-only.
+The [host authority implementation boundary](host-authority-boundary.md)
+records a disabled shared lifecycle primitive and the remaining production
+bridge requirements; it does not replace this experiment's signer.
+The experiment requires a separate compile-time opt-in and an Ed25519 public
+key selected by the operator. Never install this build on an unreviewed host.
+
+## Operator boundary
+
+The disposable-VM test operator holds the private signing key outside the VM.
+The agent has neither the key nor an approval tool. An operator signs a grant
+only after selecting the pending connection, exact target, capabilities, and
+expiry. A grant cannot be moved to another connection, target, or compositor
+epoch. Unauthenticated Stop can only revoke, not grant. This harness-specific
+boundary does not settle local production approval or defend against a
+compromised compositor, root, or an unrestricted hostile desktop user.
+
+## Transport under test
+
+Two additional sockets, `cua-input-test.sock` and `cua-input-test-2.sock`, in
+the private compositor instance directory use same-UID `SOCK_SEQPACKET`, bounded packets, nonblocking I/O, and
+event-loop dispatch. It does not change discovery protocol v2. Requests are
+ASCII fields separated by single spaces; responses are bounded JSON packets.
+Integers are decimal except address, nonce, epoch, target, and signature, which
+are hexadecimal. Unknown commands, extra fields, overflow, and nonfinite or
+out-of-bounds coordinates refuse without input. Each endpoint owns one seat,
+one active lease, and independent pointer, keyboard, XKB, and drag state.
+The compositor reserves each endpoint for one action connection. Driver tries
+the endpoints only during admission, before sending a target or action, and
+only an explicit `lane_busy` reply permits trying the second endpoint.
+Connection errors or unknown results do not trigger retries. This coordinates
+independent Driver processes without sharing seat state. The process-local
+registry still bounds and serializes private lifecycle owners; public session
+labels do not grant a lane or input authority.
+
+- `HELLO`: negotiate experimental protocol 0; return `epoch` and connection
+ `challenge`. A reconnect gets a new challenge.
+- `CLAIM`: reserve this endpoint for the connection, or return `lane_busy`.
+ A successful response includes `lane` (zero or one). Repeating a claim on the
+ same connection is idempotent. Target selection and input require a claim;
+ operator and trace connections do not claim a lane. Disconnect frees it.
+- `TARGET <pid> <address>`: attest a live native top-level and return `target`,
+ `revision`, logical `width` and `height`. The address is discovery input,
+ never a lifetime token. A recreated/unmapped surface invalidates its token.
+- `APPROVE <challenge> <target> <expires_unix_ms> <capabilities> <signature>`:
+ operator-only signed approval on a separate connection; lifetime at most
+ 60 seconds. Capability bits: click=1, key=2, scroll=4, drag=8.
+- `CLICK <sequence> <target> <revision> <x> <y> <button> <count>`: one complete
+ bounded click sequence. Buttons are evdev 272–274; count is one or two.
+- `KEY <sequence> <target> <revision> <key> <modifiers>`: complete evdev key
+ press/release with independent XKB state. Modifiers: shift=1, ctrl=2, alt=4,
+ super=8. No Unicode, IME, clipboard, or arbitrary held-key stream.
+- `SCROLL <sequence> <target> <revision> <x> <y> <axis> <value>`: one bounded
+ axis event; vertical=0, horizontal=1, logical value in [-1000,1000].
+- `DRAG <sequence> <target> <revision> <x1> <y1> <x2> <y2> <duration_ms>`:
+ one complete left-button drag, 50–2000 ms, scheduled in bounded steps. An
+ accepted drag first sends `{"ok":true,"phase":"started"}`, then its final
+ delivery result or cancellation refusal. Driver starts the visible drag
+ only after this acknowledgement; an animation is not delivery evidence.
+- `CANCEL`: revoke this endpoint's active and pending grants and release its
+ synthetic input state. Keep the lane reservation and control connections;
+ a new action needs a fresh target token and approval.
+- `STOP`: apply the same revocation to both endpoints. Previously signed but
+ unused grants and renewals also refuse. Release only synthetic-seat state;
+ operator and trace connections remain available.
+- `TRACE_START`, `TRACE_STOP`, `TRACE_READ <after>`: explicitly start, stop,
+ or page the test-only in-memory primary-input trace. Pages contain at most
+ eight events; collection must retain sequence numbers and completeness flags.
+
+The signed message is exactly the UTF-8 concatenation below, including the
+final newline. Hex fields use lowercase. The signature is Ed25519 over these
+bytes, represented as 128 hexadecimal digits.
+
+```text
+CUA_TEST_LEASE_1
+<epoch>
+<challenge>
+<target>
+<expires_unix_ms>
+<capabilities>
+```
+
+Sequence numbers increase strictly on the connection; duplicate or old
+sequences refuse instead of replaying an action. Dispatch acknowledgement is
+`effect: unverifiable`, `route: synthetic_events`; application success needs
+independent readback. Disconnect, expiry, Stop, lock, target loss, or plugin
+shutdown cancels delivery. Primary input aimed at the same target refuses.
+
+## Build and lifecycle limits
+
+Build with `CUA_HYPRLAND_TEST_INPUT=ON` and
+`CUA_HYPRLAND_TEST_OPERATOR_KEY=<64 lowercase hex characters>`, against
+Hyprland 0.56.2 and its matching compiler/runtime. Driver additionally requires
+`CUA_DRIVER_EXPERIMENTAL_HYPRLAND_INPUT=1`. The ordinary build and installer do
+not enable input. This experiment adds `Cua-Test-Agent` and `Cua-Test-Agent-2`;
+Driver excludes both from foreground virtual-pointer/keyboard routes.
+
+Disabling input revokes leases and closes input connections, but keeps both
+seat globals and client-owned resources. Re-enabling opens fresh transports
+with new epochs; existing applications keep their seats and need fresh input
+approval. Keymap replacement refreshes independent XKB state and keyboard
+resources, and revokes old authority without replacing the seats.
+
+Plugin replacement requires a desktop restart. Unload revokes input, disables
+seat capabilities, removes the globals, and retains inert protocol objects
+and `NODELETE` callbacks for late client cleanup. A marker in the private
+compositor-instance directory refuses replacement modules for that desktop
+lifetime, including a different module filename. It is a trusted-local
+lifecycle guard, not a boundary against a hostile same-user process. The old
+eight-reload workaround is no longer the upgrade contract. A new compositor
+instance gets its own directory and new seats.
+
+Synchronous lock/unlock, DPMS, session-active, and monitor-transition listeners
+revoke active and pending action connections even when a state returns to its
+original value between timer ticks. Operator and trace connections remain
+available. Dispatch-time state checks remain a second guard. These listeners
+cover stock Hyprland manager paths, not arbitrary third-party code bypassing
+them. Input socket cleanup preserves a replaced socket, file, or symlink and
+reports the cleanup outcome in lane status.
+
+The first input slice supports exact native top-level click, physical key and
+hotkey, scroll, and complete bounded drag. It refuses XWayland, child/subsurface
+targets, modified pointer gestures, and raw Unicode/text/IME. The existing
+AT-SPI text route is unchanged. A primary pointer or keyboard in the same
+Wayland client as the target revokes the lease, even for another window of
+that application. Concurrent leases aimed at the same Wayland client also
+refuse. Closing a Driver lifecycle closes only its owned input connection;
+public session labels do not let a new transport inherit an old lease.
+
+The passive trace hooks the exact Hyprland 0.56.2 cursor-update function and
+listens to primary focus signals and outbound pointer/keyboard event categories.
+It records coordinates, monotonic timestamps, actor numbers, and button/key
+state, but no keycodes, text, window names, or arbitrary protocol arguments.
+Capture stops after 60 seconds or 32,768 events. Missing instrumentation,
+overflow, sequence gaps, or timeout make evidence inconclusive. This observer
+is intrusive test instrumentation, not a proposed production API or a
+replacement for the existing cross-platform cursor observer. Calibrate it with
+the deliberate warp-and-return control before relying on preservation results.
+
+## Evidence required
+
+Test the exact source/module/Driver pair on the selected VM. Prove target
+effects through normal Driver MCP calls and independent application state,
+while observing primary pointer focus, keyboard focus, coordinates, and a
+foreground gesture. Exercise invalid grants, replay, expiry, disconnect,
+target loss, geometry changes, config-toggle recovery, and unload/replacement
+refusal. The historical unload/reload delivery test is not applicable to the
+restart-required candidate. GTK and Qt successes do not imply
+Chromium/Electron compatibility, Unicode support, physical-host acceptance,
+or production readiness.
+
+`tests/driver_input_live.py` runs the focused native GTK test through an actual
+Driver MCP process. It needs the two drawing-area fixtures from
+`tests/fixtures/apps/linux/isolated-input`, their journals and foreground wire
+log, and the compiled `tests/primary_grab.c` adversary. The operator signs its
+`grant-request.json` on a separate host and transfers only the public
+`grant.json`. It checks application event deltas, unchanged primary wire
+events, focus, workspace, cursor, a held foreground grab, and Stop refusal.
+It does not replace the canonical desktop E2E harness.
+
+The separate-seat design builds on Dillon DuPont's Hyprland prototype.
+Input-resource lifecycle and operator authorization are being adapted for a
+plugin; the prototype's earlier app results are not evidence for this build.
diff --git a/libs/cua-driver/hyprland-plugin/src/drag_geometry.hpp b/libs/cua-driver/hyprland-plugin/src/drag_geometry.hpp
new file mode 100644
index 0000000000..00c4c69306
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/drag_geometry.hpp
@@ -0,0 +1,16 @@
+#pragma once
+
+#include <cstdint>
+
+namespace cua::hyprland {
+// A drag is bound to the geometry accepted at dispatch. Other requests may
+// refresh the client's cached revision, but cannot rebase an in-flight drag.
+class DragGeometry {
+ public:
+ explicit constexpr DragGeometry(std::uint64_t revision) : accepted_(revision) {}
+ [[nodiscard]] constexpr bool matches(std::uint64_t current) const { return current == accepted_; }
+
+ private:
+ const std::uint64_t accepted_;
+};
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp b/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp
new file mode 100644
index 0000000000..0b675d335e
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp
@@ -0,0 +1,137 @@
+#pragma once
+
+#include <array>
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <string_view>
+
+namespace cua::hyprland {
+enum class InputRoute { unbound, independent, primary_foreground };
+
+enum class ForegroundFailureReason {
+ none, exact_root, primary_binding, peer_conflict, physical_keys, physical_buttons,
+ grab, dnd, constraint, keyboard_focus, pointer_focus, lease, client_dead,
+ session_unavailable, unsupported_layout, lease_expired, physical_keyboard,
+ keyboard_state, physical_pointer, pointer_target, seat_resource, pointer_resources,
+ keyboard_resources, keyboard_depressed, keyboard_latched, keyboard_locked, keyboard_group,
+};
+
+struct ForegroundFailure {
+ ForegroundFailureReason reason;
+
+ std::string_view detail() const {
+ switch (reason) {
+ case ForegroundFailureReason::none: return "foreground_none";
+ case ForegroundFailureReason::exact_root: return "foreground_exact_root";
+ case ForegroundFailureReason::primary_binding: return "foreground_primary_binding";
+ case ForegroundFailureReason::peer_conflict: return "foreground_peer_conflict";
+ case ForegroundFailureReason::physical_keys: return "foreground_physical_keys";
+ case ForegroundFailureReason::physical_buttons: return "foreground_physical_buttons";
+ case ForegroundFailureReason::grab: return "foreground_grab";
+ case ForegroundFailureReason::dnd: return "foreground_dnd";
+ case ForegroundFailureReason::constraint: return "foreground_constraint";
+ case ForegroundFailureReason::keyboard_focus: return "foreground_keyboard_focus";
+ case ForegroundFailureReason::pointer_focus: return "foreground_pointer_focus";
+ case ForegroundFailureReason::lease: return "foreground_lease";
+ case ForegroundFailureReason::client_dead: return "foreground_client_dead";
+ case ForegroundFailureReason::session_unavailable: return "foreground_session_unavailable";
+ case ForegroundFailureReason::unsupported_layout: return "foreground_unsupported_layout";
+ case ForegroundFailureReason::lease_expired: return "foreground_lease_expired";
+ case ForegroundFailureReason::physical_keyboard: return "foreground_physical_keyboard";
+ case ForegroundFailureReason::keyboard_state: return "foreground_keyboard_state";
+ case ForegroundFailureReason::physical_pointer: return "foreground_physical_pointer";
+ case ForegroundFailureReason::pointer_target: return "foreground_pointer_target";
+ case ForegroundFailureReason::seat_resource: return "foreground_seat_resource";
+ case ForegroundFailureReason::pointer_resources: return "foreground_pointer_resources";
+ case ForegroundFailureReason::keyboard_resources: return "foreground_keyboard_resources";
+ case ForegroundFailureReason::keyboard_depressed: return "foreground_keyboard_depressed";
+ case ForegroundFailureReason::keyboard_latched: return "foreground_keyboard_latched";
+ case ForegroundFailureReason::keyboard_locked: return "foreground_keyboard_locked";
+ case ForegroundFailureReason::keyboard_group: return "foreground_keyboard_group";
+ }
+ return "foreground_unknown";
+ }
+
+ static std::string_view code(bool attempted) {
+ return attempted ? "foreground_partial_unknown" : "primary_target_busy";
+ }
+};
+
+struct ForegroundSeatBindings {
+ unsigned primary_candidates = 0;
+
+ void observe(std::string_view resource_class, bool plugin_owned) {
+ if (resource_class == "wl_seat" && !plugin_owned && primary_candidates < 2)
+ ++primary_candidates;
+ }
+ bool unique() const { return primary_candidates == 1; }
+};
+
+inline ForegroundFailureReason foreground_key_modifier_failure(const std::array<std::uint32_t, 4>& modifiers) {
+ // The KEY mapping assumes a neutral US state, including layout group zero.
+ if (modifiers[0]) return ForegroundFailureReason::keyboard_depressed;
+ if (modifiers[1]) return ForegroundFailureReason::keyboard_latched;
+ if (modifiers[2]) return ForegroundFailureReason::keyboard_locked;
+ if (modifiers[3]) return ForegroundFailureReason::keyboard_group;
+ return ForegroundFailureReason::none;
+}
+
+inline bool foreground_key_modifiers_supported(const std::array<std::uint32_t, 4>& modifiers) {
+ return foreground_key_modifier_failure(modifiers) == ForegroundFailureReason::none;
+}
+
+template <typename Resources>
+bool foreground_resources_match(const Resources& current, const Resources& captured) {
+ std::size_t live = 0;
+ for (const auto& weak : current) {
+ const auto resource = weak.lock();
+ if (!resource || !resource->good()) continue;
+ ++live;
+ if (std::none_of(captured.begin(), captured.end(), [&](const auto& saved) {
+ return saved.lock() == resource;
+ })) return false;
+ }
+ return live == captured.size();
+}
+
+inline bool bind_input_route(InputRoute& bound, InputRoute requested) {
+ if (bound != InputRoute::unbound && bound != requested) return false;
+ bound = requested;
+ return true;
+}
+
+struct ForegroundGuard {
+ bool exact_root = false;
+ bool primary_binding = true;
+ bool peer_conflict = false;
+ bool physical_keys = false;
+ bool physical_buttons = false;
+ bool grab = false;
+ bool dnd = false;
+ bool constraint = false;
+ bool exact_keyboard_focus = false;
+ bool exact_pointer_focus = false;
+
+ ForegroundFailureReason activation_failure() const {
+ if (!exact_root) return ForegroundFailureReason::exact_root;
+ if (!primary_binding) return ForegroundFailureReason::primary_binding;
+ if (peer_conflict) return ForegroundFailureReason::peer_conflict;
+ if (physical_keys) return ForegroundFailureReason::physical_keys;
+ if (physical_buttons) return ForegroundFailureReason::physical_buttons;
+ if (grab) return ForegroundFailureReason::grab;
+ if (dnd) return ForegroundFailureReason::dnd;
+ if (constraint) return ForegroundFailureReason::constraint;
+ return ForegroundFailureReason::none;
+ }
+ ForegroundFailureReason dispatch_failure(bool needs_pointer = true) const {
+ const auto failure = activation_failure();
+ if (failure != ForegroundFailureReason::none) return failure;
+ if (!exact_keyboard_focus) return ForegroundFailureReason::keyboard_focus;
+ if (needs_pointer && !exact_pointer_focus) return ForegroundFailureReason::pointer_focus;
+ return ForegroundFailureReason::none;
+ }
+ bool can_activate() const { return activation_failure() == ForegroundFailureReason::none; }
+ bool can_dispatch(bool needs_pointer = true) const { return dispatch_failure(needs_pointer) == ForegroundFailureReason::none; }
+};
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/input_client_deadline.hpp b/libs/cua-driver/hyprland-plugin/src/input_client_deadline.hpp
new file mode 100644
index 0000000000..5964dbf977
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/input_client_deadline.hpp
@@ -0,0 +1,24 @@
+#pragma once
+
+#include <chrono>
+
+namespace cua::hyprland {
+// Pre-HELLO traffic cannot renew the acceptance deadline. Once initialized,
+// the connection retains the existing rolling idle timeout.
+class InputClientDeadline {
+ public:
+ using Clock = std::chrono::steady_clock;
+ explicit InputClientDeadline(Clock::time_point accepted = Clock::now())
+ : accepted_(accepted), activity_(accepted) {}
+
+ bool expired(bool initialized, Clock::time_point now) const {
+ return initialized ? now - activity_ >= std::chrono::seconds(60)
+ : now - accepted_ >= std::chrono::seconds(5);
+ }
+ void touch(Clock::time_point now) { activity_ = now; }
+
+ private:
+ const Clock::time_point accepted_;
+ Clock::time_point activity_;
+};
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp b/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp
new file mode 100644
index 0000000000..3f08ee198f
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp
@@ -0,0 +1,1394 @@
+// Independent-seat design adapted from Dillon DuPont's Hyprland prototype.
+// TARGET uses independent resources; FOREGROUND_TARGET explicitly uses the primary seat.
+#include "input_experiment.hpp"
+#include "drag_geometry.hpp"
+#include "input_grant.hpp"
+#include "input_client_deadline.hpp"
+#include "passive_pointer_target.hpp"
+#include "primary_trace.hpp"
+#include "seat_lifetime.hpp"
+#include "owned_socket_path.hpp"
+#include "foreground_route.hpp"
+
+#include <src/Compositor.hpp>
+#include <src/devices/IKeyboard.hpp>
+#include <src/event/EventBus.hpp>
+#include <src/managers/SeatManager.hpp>
+#include <src/output/Monitor.hpp>
+#include <src/protocols/core/Compositor.hpp>
+#include <src/state/MonitorState.hpp>
+#include <src/desktop/state/FocusState.hpp>
+#include <src/managers/input/InputManager.hpp>
+#include <src/pointer/PointerManager.hpp>
+#include <src/protocols/core/Seat.hpp>
+#include <src/protocols/core/DataDevice.hpp>
+#include <src/layout/LayoutManager.hpp>
+#include <linux/input-event-codes.h>
+#include <wayland.hpp>
+#include <wayland-server-core.h>
+
+#ifdef CUA_HYPRLAND_TEST_INPUT
+#include <openssl/evp.h>
+#endif
+#include <sys/random.h>
+#include <xkbcommon/xkbcommon.h>
+
+#include <algorithm>
+#include <array>
+#include <charconv>
+#include <cerrno>
+#include <chrono>
+#include <cmath>
+#include <cstring>
+#include <cstdlib>
+#include <filesystem>
+#include <fcntl.h>
+#include <format>
+#include <memory>
+#include <optional>
+#include <stdexcept>
+#include <string_view>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+#if defined(CUA_HYPRLAND_INPUT) == defined(CUA_HYPRLAND_TEST_INPUT)
+#error Select exactly one input admission mode
+#endif
+
+namespace cua::hyprland {
+namespace {
+using Clock = std::chrono::steady_clock;
+constexpr std::size_t kMaxPacket = 2048;
+constexpr std::size_t kMaxClients = 8;
+constexpr std::size_t kMaxResources = 512;
+#ifdef CUA_HYPRLAND_INPUT
+constexpr bool kProduction = true;
+#else
+constexpr bool kProduction = false;
+#endif
+
+#ifdef CUA_HYPRLAND_TEST_INPUT
+std::uint64_t unix_ms() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count();
+}
+#endif
+std::uint32_t event_ms() {
+ return static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
+ Clock::now().time_since_epoch()).count());
+}
+std::string nonce() {
+ std::array<unsigned char, 16> bytes{};
+ std::size_t offset = 0;
+ while (offset < bytes.size()) {
+ const auto n = getrandom(bytes.data() + offset, bytes.size() - offset, 0);
+ if (n < 0 && errno == EINTR) continue;
+ if (n <= 0) throw std::runtime_error("input entropy unavailable");
+ offset += static_cast<std::size_t>(n);
+ }
+ std::string result;
+ for (auto b : bytes)
+ result += std::format("{:02x}", b);
+ return result;
+}
+#ifdef CUA_HYPRLAND_TEST_INPUT
+std::vector<unsigned char> unhex(std::string_view value) {
+ if (value.size() % 2)
+ throw std::runtime_error("invalid hex");
+ std::vector<unsigned char> bytes;
+ for (std::size_t i = 0; i < value.size(); i += 2) {
+ unsigned int n = 0;
+ const auto [p, error] = std::from_chars(value.data() + i, value.data() + i + 2, n, 16);
+ if (error != std::errc{} || p != value.data() + i + 2)
+ throw std::runtime_error("invalid hex");
+ bytes.push_back(static_cast<unsigned char>(n));
+ }
+ return bytes;
+}
+#endif
+std::uint64_t number(std::string_view value, int base = 10) {
+ std::uint64_t n = 0;
+ const auto [p, error] = std::from_chars(value.data(), value.data() + value.size(), n, base);
+ if (value.empty() || error != std::errc{} || p != value.data() + value.size())
+ throw std::runtime_error("invalid integer");
+ return n;
+}
+double real(std::string_view value) {
+ double n = 0;
+ const auto [p, error] = std::from_chars(value.data(), value.data() + value.size(), n);
+ if (value.empty() || error != std::errc{} || p != value.data() + value.size() || !std::isfinite(n))
+ throw std::runtime_error("invalid coordinate");
+ return n;
+}
+std::vector<std::string> fields(std::string_view packet) {
+ if (packet.empty() || packet.front() == ' ' || packet.back() == ' ')
+ throw std::runtime_error("invalid packet");
+ std::vector<std::string> result;
+ std::size_t start = 0;
+ for (std::size_t i = 0; i <= packet.size(); ++i) {
+ if (i < packet.size() && (packet[i] < 32 || packet[i] > 126))
+ throw std::runtime_error("non-ASCII packet");
+ if (i != packet.size() && packet[i] != ' ')
+ continue;
+ if (i == start || result.size() >= 16)
+ throw std::runtime_error("invalid fields");
+ result.emplace_back(packet.substr(start, i - start));
+ start = i + 1;
+ }
+ return result;
+}
+std::string refusal(std::string_view code) {
+ // Only internal fixed identifiers enter JSON. No caller-provided strings.
+ return std::format(R"({{"ok":false,"code":"{}","detail":"{}"}})", code, code);
+}
+std::string refusal(std::string_view code, ForegroundFailure failure) {
+ return std::format(R"({{"ok":false,"code":"{}","detail":"{}"}})", code, failure.detail());
+}
+constexpr auto kDelivered = R"({"ok":true,"effect":"unverifiable","route":"synthetic_events"})";
+constexpr auto kForegroundDelivered = R"({"ok":true,"effect":"unverifiable","route":"primary_foreground"})";
+} // namespace
+
+struct InputExperiment::Impl {
+ struct Seat { SP<CWlSeat> wl; bool dead = false; };
+ struct Pointer { SP<CWlPointer> wl; bool dead = false; WP<CWLSurfaceResource> focus; };
+ struct Keyboard { SP<CWlKeyboard> wl; bool dead = false; WP<CWLSurfaceResource> focus; };
+ struct Touch { SP<CWlTouch> wl; bool dead = false; };
+ struct Client {
+ Impl* owner = nullptr;
+ int fd = -1;
+ wl_event_source* source = nullptr;
+ bool dead = false, hello = false;
+ // Sticky for this connection: a bare CLAIM does not own inherited
+ // hover. Never reset on STOP/CANCEL, repeated CLAIM, or invalidation.
+ bool has_bound_target = false;
+ InputRoute route = InputRoute::unbound;
+ bool foreground_attempted = false;
+ std::string challenge, token;
+ WP<Desktop::View::CWindow> window;
+ WP<CWLSurfaceResource> surface;
+ std::array<double, 6> geometry{};
+ std::uint64_t revision = 1, sequence = 0, approved_deadline = 0;
+ InputClientDeadline deadline;
+ CHyprSignalListener unmap, destroy;
+ ~Client() {
+ if (source) wl_event_source_remove(source);
+ if (fd >= 0) close(fd);
+ }
+ };
+ struct Drag {
+ Client* client;
+ double x1, y1, x2, y2;
+ Clock::time_point start;
+ unsigned duration;
+ DragGeometry geometry;
+ };
+ int listener = -1;
+ wl_event_source* listen_source = nullptr;
+ wl_event_source* timer = nullptr;
+ wl_global* global = nullptr;
+ OwnedSocketPath socket_path;
+ std::string_view socket_cleanup = "not_bound";
+ std::string path, epoch = nonce(), keymap_text;
+ std::vector<unsigned char> public_key;
+ std::vector<std::unique_ptr<Client>> clients;
+ std::vector<std::unique_ptr<Seat>> seats;
+ std::vector<std::unique_ptr<Pointer>> pointers;
+ std::vector<std::unique_ptr<Keyboard>> keyboards;
+ std::vector<std::unique_ptr<Touch>> touches;
+ Client* lease = nullptr;
+ // Pointer presence is not input authority. Keep the same live surface
+ // entered between actions, as a real pointer is, without retaining a grant.
+ PassivePointerTarget<WP<Desktop::View::CWindow>, WP<CWLSurfaceResource>> pointer_target;
+ CHyprSignalListener pointer_unmap, pointer_destroy;
+ Client* reservation = nullptr;
+ std::uint64_t desktop_generation = 1;
+ std::uint64_t capabilities = 0, dispatches = 0;
+ Clock::time_point expires{};
+ InputGrant grant;
+ std::optional<Drag> drag;
+ std::uint32_t held_button = 0;
+ std::vector<std::uint32_t> held_keys;
+ xkb_context* xkb_context_ = nullptr;
+ xkb_keymap* keymap = nullptr;
+ xkb_state* keyboard_state = nullptr;
+ int keymap_fd = -1;
+ bool retired = false, suspended = true, us_keymap = false, physical_keymap_present = false;
+ WP<IKeyboard> physical_keyboard;
+ CHyprSignalListener keymap_listener;
+ unsigned lane;
+ std::array<Impl*, 2> peers{};
+ PrimaryTrace* trace = nullptr;
+ bool foreground_started = false, foreground_activating = false;
+ bool foreground_keyboard_used = false;
+ bool foreground_needs_pointer = false;
+ WP<CWLSurfaceResource> foreground_surface;
+ WP<CWLSeatResource> foreground_seat;
+ std::vector<WP<CWLPointerResource>> foreground_pointers;
+ std::vector<WP<CWLKeyboardResource>> foreground_keyboards;
+ std::array<std::uint32_t, 4> foreground_modifiers{};
+
+ explicit Impl(const std::string& directory, unsigned index) : lane(index) {
+#ifdef CUA_HYPRLAND_TEST_INPUT
+ public_key = unhex(CUA_HYPRLAND_TEST_OPERATOR_KEY);
+ if (public_key.size() != 32)
+ throw std::runtime_error("invalid test operator public key");
+#endif
+ path = directory + (kProduction ?
+ (lane == 0 ? "/cua-input-v3.sock" : "/cua-input-v3-2.sock") :
+ (lane == 0 ? "/cua-input-test.sock" : "/cua-input-test-2.sock"));
+ if (path.size() >= sizeof(sockaddr_un::sun_path))
+ throw std::runtime_error("input socket path too long");
+ // No private key or input-enabled default exists in this component.
+ }
+
+ static bool canonical_us_keymap(xkb_context* context, xkb_keymap* map) {
+ // Compare canonical compiled content, not a layout display name. This
+ // deliberately excludes variants, options, remaps, and multiple groups.
+ const xkb_rule_names names{"evdev", "pc105", "us", "", ""};
+ auto* reference = xkb_keymap_new_from_names(context, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
+ if (!reference) return false;
+ char* actual = xkb_keymap_get_as_string(map, XKB_KEYMAP_FORMAT_TEXT_V1);
+ char* expected = xkb_keymap_get_as_string(reference, XKB_KEYMAP_FORMAT_TEXT_V1);
+ const bool matches = actual && expected && std::strcmp(actual, expected) == 0;
+ std::free(actual); std::free(expected); xkb_keymap_unref(reference);
+ return matches;
+ }
+ bool layout_qualified() const {
+ if (!kProduction) return true;
+ const auto keyboard = g_pSeatManager->m_keyboard.lock();
+ return physical_keymap_present && us_keymap && keyboard_state && keyboard &&
+ keyboard->m_xkbKeymapV1FD.get() >= 0 && keyboard->m_xkbKeymapV1String == keymap_text;
+ }
+ void sync_keymap() {
+ const auto keyboard = g_pSeatManager->m_keyboard.lock();
+ if (physical_keyboard != keyboard) {
+ if (physical_keymap_present) desktop_transition();
+ keymap_listener.reset();
+ physical_keyboard = keyboard;
+ if (keyboard && kProduction)
+ keymap_listener = keyboard->m_keyboardEvents.keymap.listen([this](IKeyboard::SKeymapEvent) {
+ desktop_transition();
+ });
+ }
+ if (!keyboard || keyboard->m_xkbKeymapV1FD.get() < 0 || keyboard->m_xkbKeymapV1String.empty()) {
+ if (physical_keymap_present) desktop_transition();
+ physical_keymap_present = false;
+ return;
+ }
+ physical_keymap_present = true;
+ if (keyboard_state && keymap_text == keyboard->m_xkbKeymapV1String) return;
+ // Prepare a complete replacement before retiring the old independent
+ // state. Keep our own fd: primary keyboard replacement must not leave
+ // later seat bindings referring to a closed compositor fd.
+ auto* context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
+ auto* map = context ? xkb_keymap_new_from_string(context, keyboard->m_xkbKeymapV1String.c_str(),
+ XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS) : nullptr;
+ auto* state = map ? xkb_state_new(map) : nullptr;
+ const auto fd = fcntl(keyboard->m_xkbKeymapV1FD.get(), F_DUPFD_CLOEXEC, 0);
+ if (!state || fd < 0) {
+ if (fd >= 0) close(fd);
+ if (state) xkb_state_unref(state);
+ if (map) xkb_keymap_unref(map);
+ if (context) xkb_context_unref(context);
+ throw std::runtime_error("independent XKB state unavailable");
+ }
+ desktop_transition();
+ if (keyboard_state) xkb_state_unref(keyboard_state);
+ if (keymap) xkb_keymap_unref(keymap);
+ if (xkb_context_) xkb_context_unref(xkb_context_);
+ if (keymap_fd >= 0) close(keymap_fd);
+ keyboard_state = state; keymap = map; xkb_context_ = context; keymap_fd = fd;
+ us_keymap = !kProduction || canonical_us_keymap(context, map);
+ keymap_text = keyboard->m_xkbKeymapV1String;
+ for (auto& k : keyboards)
+ if (!k->dead && k->wl->resource())
+ k->wl->sendKeymap(WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, keymap_fd, keymap_text.size() + 1);
+ for (auto& seat : seats)
+ if (!seat->dead && seat->wl->resource())
+ seat->wl->sendCapabilities(static_cast<wl_seat_capability>(WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD));
+ }
+ void start() {
+ sync_keymap();
+ timer = wl_event_loop_add_timer(g_pCompositor->m_wlEventLoop, tick, this);
+ if (!timer) throw std::runtime_error("input timer registration failed");
+ global = wl_global_create(g_pCompositor->m_wlDisplay, &wl_seat_interface, 9, this, bind_seat);
+ if (!global) throw std::runtime_error("synthetic seat unavailable");
+ wl_event_source_timer_update(timer, 16);
+ }
+ void resume() {
+ if (retired || desktop_generation == UINT64_MAX)
+ throw std::runtime_error("restart desktop before replacing input seats");
+ if (!suspended) return;
+ sync_keymap();
+ // Every new admission period has fresh identity and no inherited grant.
+ epoch = nonce();
+ listener = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+ if (listener < 0) throw std::runtime_error("input socket unavailable");
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ std::memcpy(address.sun_path, path.c_str(), path.size() + 1);
+ // Never unlink a pre-existing socket owned by another plugin instance.
+ if (bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0)
+ throw std::runtime_error("input socket bind refused");
+ if (!socket_path.capture(path))
+ throw std::runtime_error("input socket ownership unavailable");
+ socket_cleanup = "bound";
+ if (chmod(path.c_str(), 0600) != 0 || listen(listener, 8) != 0)
+ throw std::runtime_error("input socket setup failed");
+ listen_source = wl_event_loop_add_fd(g_pCompositor->m_wlEventLoop, listener, WL_EVENT_READABLE, accept_ready, this);
+ if (!listen_source) throw std::runtime_error("input event loop registration failed");
+ suspended = false;
+ }
+ void cleanup_socket() {
+ using Result = OwnedSocketPath::CleanupResult;
+ switch (socket_path.cleanup()) {
+ case Result::NotCaptured: break;
+ case Result::Removed: socket_cleanup = "removed"; break;
+ case Result::AlreadyAbsent: socket_cleanup = "absent"; break;
+ case Result::Replaced: socket_cleanup = "replacement_preserved"; break;
+ case Result::Failed: socket_cleanup = "failed"; break;
+ }
+ }
+ void suspend(std::string_view reason = "plugin_disabled") {
+ suspended = true;
+ revoke(reason);
+ reservation = nullptr;
+ if (listen_source) wl_event_source_remove(listen_source);
+ listen_source = nullptr;
+ clients.clear();
+ if (listener >= 0) close(listener);
+ listener = -1;
+ cleanup_socket();
+ // Keep the globals, capabilities, and client resources stable. Removing
+ // and recreating them makes existing apps lose their agent input path.
+ }
+ void retire() {
+ // wl_global removal does not revoke existing protocol objects. Destroying
+ // those objects immediately disconnects clients that still send release
+ // or cursor requests (observed with foot). Retain inert resources and
+ // callbacks until compositor exit; input-enabled modules are NODELETE.
+ suspend("plugin_shutdown");
+ keymap_listener.reset();
+ retired = true;
+ for (auto& seat : seats)
+ if (!seat->dead && seat->wl->resource())
+ seat->wl->sendCapabilities(static_cast<wl_seat_capability>(0));
+ if (global) wl_global_remove(global);
+ }
+ ~Impl() {
+ revoke("plugin_shutdown");
+ if (global) wl_global_destroy(global);
+ if (listen_source) wl_event_source_remove(listen_source);
+ if (timer) wl_event_source_remove(timer);
+ clients.clear();
+ // Destroy all plugin-owned resources before unloading code callbacks.
+ pointers.clear(); keyboards.clear(); touches.clear(); seats.clear();
+ if (listener >= 0) close(listener);
+ cleanup_socket();
+ if (keyboard_state) xkb_state_unref(keyboard_state);
+ if (keymap) xkb_keymap_unref(keymap);
+ if (xkb_context_) xkb_context_unref(xkb_context_);
+ if (keymap_fd >= 0) close(keymap_fd);
+ }
+ std::uint32_t serial() const { return wl_display_next_serial(g_pCompositor->m_wlDisplay); }
+ bool available() const {
+ return !retired && !suspended && g_pCompositor->m_sessionActive && g_pCompositor->m_dpmsStateOn &&
+ !g_pCompositor->m_isShuttingDown && !g_pSessionLockManager->isSessionLocked();
+ }
+ static void bind_seat(wl_client* client, void* data, std::uint32_t version, std::uint32_t id) {
+ auto& self = *static_cast<Impl*>(data);
+ if (self.seats.size() >= kMaxResources) { wl_client_post_no_memory(client); return; }
+ auto seat = std::make_unique<Seat>();
+ auto* entry = seat.get();
+ seat->wl = makeShared<CWlSeat>(client, std::min(version, 9u), id);
+ if (!seat->wl->resource()) { wl_client_post_no_memory(client); return; }
+ // Stock resource lookup casts CWlSeat::data to CWLSeatResource. Null is
+ // intentional: an agent serial must not authorize primary-seat WM grabs.
+ seat->wl->setData(nullptr);
+ seat->wl->setRelease([entry](CWlSeat*) { entry->dead = true; });
+ seat->wl->setOnDestroy([entry](CWlSeat*) { entry->dead = true; });
+ seat->wl->setGetPointer([&self](CWlSeat* r, std::uint32_t child) { self.add_pointer(r, child); });
+ seat->wl->setGetKeyboard([&self](CWlSeat* r, std::uint32_t child) { self.add_keyboard(r, child); });
+ seat->wl->setGetTouch([&self](CWlSeat* r, std::uint32_t child) { self.add_touch(r, child); });
+ if (version >= 2) seat->wl->sendName(kProduction ?
+ (self.lane == 0 ? "Cua-Agent" : "Cua-Agent-2") :
+ (self.lane == 0 ? "Cua-Test-Agent" : "Cua-Test-Agent-2"));
+ seat->wl->sendCapabilities(static_cast<wl_seat_capability>(self.retired ? 0 :
+ WL_SEAT_CAPABILITY_POINTER | (self.keyboard_state ? WL_SEAT_CAPABILITY_KEYBOARD : 0)));
+ self.seats.push_back(std::move(seat));
+ }
+ void add_pointer(CWlSeat* seat, std::uint32_t id) {
+ if (pointers.size() >= kMaxResources) { seat->noMemory(); return; }
+ auto p = std::make_unique<Pointer>(); auto* entry = p.get();
+ p->wl = makeShared<CWlPointer>(seat->client(), seat->version(), id);
+ if (!p->wl->resource()) { seat->noMemory(); return; }
+ p->wl->setData(nullptr);
+ p->wl->setRelease([entry](CWlPointer*) { entry->dead = true; });
+ p->wl->setOnDestroy([entry](CWlPointer*) { entry->dead = true; });
+ p->wl->setSetCursor([](CWlPointer*, std::uint32_t, wl_resource*, std::int32_t, std::int32_t) {});
+ pointers.push_back(std::move(p));
+ }
+ void add_keyboard(CWlSeat* seat, std::uint32_t id) {
+ if (!keyboard_state || keyboards.size() >= kMaxResources) { seat->noMemory(); return; }
+ auto k = std::make_unique<Keyboard>(); auto* entry = k.get();
+ k->wl = makeShared<CWlKeyboard>(seat->client(), seat->version(), id);
+ if (!k->wl->resource()) { seat->noMemory(); return; }
+ k->wl->setData(nullptr);
+ k->wl->setRelease([entry](CWlKeyboard*) { entry->dead = true; });
+ k->wl->setOnDestroy([entry](CWlKeyboard*) { entry->dead = true; });
+ k->wl->sendKeymap(WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, keymap_fd, keymap_text.size() + 1);
+ if (seat->version() >= 4) k->wl->sendRepeatInfo(0, 0);
+ keyboards.push_back(std::move(k));
+ }
+ void add_touch(CWlSeat* seat, std::uint32_t id) {
+ // Never advertised. A valid inert resource is safer than a dangling id.
+ if (touches.size() >= kMaxResources) { seat->noMemory(); return; }
+ auto t = std::make_unique<Touch>(); auto* entry = t.get();
+ t->wl = makeShared<CWlTouch>(seat->client(), seat->version(), id);
+ if (!t->wl->resource()) { seat->noMemory(); return; }
+ t->wl->setData(nullptr);
+ t->wl->setRelease([entry](CWlTouch*) { entry->dead = true; });
+ t->wl->setOnDestroy([entry](CWlTouch*) { entry->dead = true; });
+ touches.push_back(std::move(t));
+ }
+ static std::optional<std::array<double, 6>> target_geometry(
+ const PHLWINDOW& window, const SP<CWLSurfaceResource>& surface) {
+ if (!window || !surface || !window->m_isMapped || window->isHidden() ||
+ window->m_isX11 || window->resource() != surface || !surface->m_mapped || !surface->good()) return std::nullopt;
+ // Match Driver's captured client surface, not the decorated window box
+ // (which includes compositor borders and shifts clicks by their width).
+ const auto box = window->surfaceLogicalBox(); const auto surface_box = box;
+ if (!box || !surface_box || box->w <= 0 || box->h <= 0 || box->w > 32767 || box->h > 32767) return std::nullopt;
+ std::array<double, 6> geometry{box->x, box->y, box->w, box->h, surface_box->x, surface_box->y};
+ if (!std::ranges::all_of(geometry, [](double value) { return std::isfinite(value); })) return std::nullopt;
+ return geometry;
+ }
+ bool refresh(Client& c) {
+ const auto geometry = target_geometry(c.window.lock(), c.surface.lock());
+ if (!geometry) return false;
+ if (*geometry != c.geometry) {
+ if (c.revision == UINT64_MAX) return false;
+ c.geometry = *geometry; ++c.revision;
+ }
+ return true;
+ }
+ bool primary_conflict(const Client& c) const {
+ if (c.route == InputRoute::primary_foreground)
+ return foreground_started && !foreground_activating && !foreground_guard(c).can_dispatch(foreground_needs_pointer);
+ return primary_conflict(c.surface.lock());
+ }
+ bool primary_conflict(const SP<CWLSurfaceResource>& surface) const {
+ if (!surface) return true;
+ const auto pointer = g_pSeatManager->m_state.pointerFocus.lock();
+ const auto keyboard = g_pSeatManager->m_state.keyboardFocus.lock();
+ // Conservative per-client refusal avoids toolkit-global cross-window state.
+ return (pointer && pointer->client() == surface->client()) ||
+ (keyboard && keyboard->client() == surface->client());
+ }
+ bool agent_conflict(const Client& c) const {
+ if (c.route == InputRoute::primary_foreground)
+ for (const auto* peer : peers)
+ if (peer && peer != this && peer->lease && peer->lease->route == InputRoute::primary_foreground) return true;
+ return agent_conflict(c.surface.lock());
+ }
+ bool agent_conflict(const SP<CWLSurfaceResource>& surface) const {
+ if (!surface) return true;
+ for (const auto* peer : peers) {
+ if (!peer || peer == this) continue;
+ // Passive hover still participates after its transport owner dies.
+ if (peer->pointer_target.same_client(surface)) return true;
+ const auto other = peer->lease ? peer->lease->surface.lock() : nullptr;
+ if (other && other->client() == surface->client()) return true;
+ }
+ return false;
+ }
+ void retire_orphan_hover(const Client& c) {
+ for (auto* peer : peers) {
+ if (!peer || peer == this) continue;
+ const InputLaneActivity activity{
+ .reserved = peer->reservation != nullptr,
+ .leased = peer->lease != nullptr,
+ .dragging = peer->drag.has_value(),
+ .button = peer->held_button != 0,
+ .keys = !peer->held_keys.empty(),
+ .keyboard_focus = std::ranges::any_of(peer->keyboards, [](const auto& k) { return bool(k->focus); }),
+ .capabilities = peer->capabilities != 0,
+ .grant = peer->grant.deadline() != Clock::time_point{},
+ .expiry = peer->expires != Clock::time_point{},
+ .reservation_without_target = peer->reservation && !peer->reservation->has_bound_target,
+ };
+ // Driver claims the first free lane before TARGET. Retire only a
+ // matching, completely inert peer hover so opposite-order reuse
+ // cannot strand a target on another lane. A fresh claimant that
+ // has never bound a target does not adopt inherited hover; an
+ // existing target owner remains protected even after STOP.
+ if (peer->pointer_target.reclaimable_for(c.surface.lock(), activity)) peer->leave_pointer();
+ }
+ }
+ void invalidate(Client& c, bool clear_pointer = true) {
+ if (lease == &c || (clear_pointer && c.surface.lock() && pointer_target.surface() == c.surface.lock()))
+ revoke("stale_target", !clear_pointer);
+ c.token.clear(); c.window.reset(); c.surface.reset();
+ // Replay high-water belongs to the old target binding. A genuinely
+ // new token may receive a shorter grant after Stop or target change.
+ c.approved_deadline = 0;
+ }
+ void release_pointer_button() {
+ if (!held_button) return;
+ for (auto& p : pointers) {
+ const auto surface = p->focus.lock();
+ if (!p->dead && p->wl->resource() && surface && surface->good()) {
+ p->wl->sendButton(serial(), event_ms(), held_button, WL_POINTER_BUTTON_STATE_RELEASED);
+ // A complete release frame is delivery, not client processing proof.
+ if (p->wl->version() >= 5) p->wl->sendFrame();
+ }
+ }
+ held_button = 0;
+ }
+ void leave_pointer() {
+ release_pointer_button();
+ for (auto& p : pointers) {
+ const auto surface = p->focus.lock();
+ if (!p->dead && p->wl->resource() && surface && surface->good()) {
+ p->wl->sendLeave(serial(), surface->getResource().get());
+ if (p->wl->version() >= 5) p->wl->sendFrame();
+ }
+ p->focus.reset();
+ }
+ pointer_target.reset();
+ pointer_unmap.reset(); pointer_destroy.reset();
+ }
+ void leave_keyboard() {
+ for (auto& k : keyboards) {
+ const auto surface = k->focus.lock();
+ if (!k->dead && k->wl->resource() && surface && surface->good()) {
+ for (auto key : held_keys) k->wl->sendKey(serial(), event_ms(), key, WL_KEYBOARD_KEY_STATE_RELEASED);
+ k->wl->sendModifiers(serial(), 0, 0, 0, 0);
+ k->wl->sendLeave(serial(), surface->getResource().get());
+ }
+ k->focus.reset();
+ }
+ held_keys.clear();
+ if (keyboard_state) xkb_state_unref(keyboard_state);
+ keyboard_state = keymap ? xkb_state_new(keymap) : nullptr;
+ }
+ void retire_grant() {
+ lease = nullptr; capabilities = 0; grant.reset(); expires = {};
+ }
+ void complete_action() {
+ // All buttons/keys were released by the operation. Keyboard focus is
+ // action-scoped; passive pointer focus belongs only to its live target.
+ // Never send a gratuitous leave immediately after a drag's release:
+ // clients may requeue their release behind that leave while coalescing
+ // motion. This is not a client-processing acknowledgement.
+ finish_foreground();
+ leave_keyboard();
+ retire_grant();
+ }
+ void revoke(std::string_view reason, bool retain_pointer = false, ForegroundFailure failure = {ForegroundFailureReason::none}) {
+ if (lease && trace && reason != "completed") trace->mark("agent_cancel", lane + 1);
+ if (drag && drag->client && !drag->client->dead)
+ send(*drag->client, failure.reason == ForegroundFailureReason::none ?
+ refusal(foreground_started ? "foreground_partial_unknown" : reason) :
+ refusal(foreground_started ? "foreground_partial_unknown" : reason, failure));
+ drag.reset();
+ finish_foreground();
+ if (retain_pointer) release_pointer_button(); else leave_pointer();
+ leave_keyboard(); retire_grant();
+ }
+ void cancel_authority(std::string_view reason, bool retain_pointer = true) {
+ revoke(reason, retain_pointer);
+ // Invalidate pending authority as well as active work. This also makes
+ // unused signed renewals unusable in experimental builds. Keep the lane
+ // reservation; v3 requires fresh TARGET admission for the next action.
+ for (auto& c : clients) invalidate(*c, false);
+ }
+ void desktop_transition() {
+ // Signals can fire before Hyprland updates its aggregate state. Revoke
+ // unconditionally; an off/on pair between timer ticks must not revive
+ // authority. Kill pending connections as well as the active lease so
+ // a pre-transition signed grant cannot be approved after unlock.
+ revoke("desktop_changed");
+ for (auto& c : clients) {
+ // Observers and operator-control connections own no action target.
+ // Keep them alive so Stop/status/evidence survives a transition.
+ if (reservation != c.get() && c->token.empty()) continue;
+ c->dead = true;
+ if (c->source) wl_event_source_remove(c->source);
+ c->source = nullptr;
+ if (c->fd >= 0) close(c->fd);
+ c->fd = -1;
+ }
+ reservation = nullptr;
+ if (desktop_generation == UINT64_MAX)
+ suspended = true;
+ else
+ ++desktop_generation;
+ }
+ void send(Client& c, const std::string& packet) {
+ if (c.dead) return;
+ const auto n = ::send(c.fd, packet.data(), packet.size(), MSG_DONTWAIT | MSG_NOSIGNAL);
+ if (n < 0 || static_cast<std::size_t>(n) != packet.size()) c.dead = true;
+ }
+ static int accept_ready(int, std::uint32_t, void* data) {
+ auto& self = *static_cast<Impl*>(data);
+ for (unsigned i = 0; i < 8; ++i) {
+ const auto fd = accept4(self.listener, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
+ if (fd < 0) break;
+ ucred credentials{}; socklen_t size = sizeof(credentials);
+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &credentials, &size) != 0 ||
+ size != sizeof(credentials) || credentials.uid != getuid() || self.clients.size() >= kMaxClients) { close(fd); continue; }
+ bool owned = false;
+ try {
+ auto c = std::make_unique<Client>(); c->owner = &self; c->fd = fd; owned = true; c->challenge = nonce();
+ c->source = wl_event_loop_add_fd(g_pCompositor->m_wlEventLoop, fd, WL_EVENT_READABLE, client_ready, c.get());
+ if (!c->source) continue;
+ self.clients.push_back(std::move(c));
+ } catch (...) { if (!owned) close(fd); }
+ }
+ return 0;
+ }
+ static int client_ready(int fd, std::uint32_t mask, void* data) {
+ auto& c = *static_cast<Client*>(data); auto& self = *c.owner;
+ if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) c.dead = true;
+ for (unsigned i = 0; i < 8 && !c.dead; ++i) {
+ // Check before reading or changing HELLO state, even if the event
+ // loop's periodic expiry callback has not run yet.
+ if (c.deadline.expired(c.hello, Clock::now())) { c.dead = true; break; }
+ std::array<char, kMaxPacket> buffer{};
+ const auto n = recv(fd, buffer.data(), buffer.size(), MSG_DONTWAIT | MSG_TRUNC);
+ if (n < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) c.dead = true; break; }
+ if (!n) { c.dead = true; break; }
+ const auto received = Clock::now();
+ if (c.deadline.expired(c.hello, received)) { c.dead = true; break; }
+ c.deadline.touch(received);
+ if (static_cast<std::size_t>(n) > buffer.size()) { self.send(c, refusal("invalid_request")); continue; }
+ try { self.request(c, fields(std::string_view(buffer.data(), n))); }
+ catch (const ForegroundFailure& failure) {
+ const bool started = c.foreground_attempted;
+ const bool drag_reply = self.drag && self.drag->client == &c;
+ self.revoke("foreground_partial_unknown", false, failure);
+ if (!drag_reply) self.send(c, refusal(ForegroundFailure::code(started), failure));
+ }
+ catch (...) {
+ const bool foreground_partial = c.foreground_attempted;
+ const bool foreground_drag_reply = foreground_partial && self.drag && self.drag->client == &c;
+ if (kProduction && (self.lease == &c || self.reservation == &c)) self.revoke("invalid_request");
+ if (!foreground_drag_reply) self.send(c, refusal(foreground_partial ? "foreground_partial_unknown" : "invalid_request"));
+ }
+ }
+ if (c.dead) {
+ if (self.lease == &c) self.revoke("disconnected", true);
+ if (self.reservation == &c) self.reservation = nullptr;
+ }
+ return 0;
+ }
+#ifdef CUA_HYPRLAND_TEST_INPUT
+ bool valid_signature(const std::string& message, const std::string& signature) const {
+ if (signature.size() != 128) return false;
+ const auto bytes = unhex(signature);
+ auto* key = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key.data(), public_key.size());
+ auto* ctx = EVP_MD_CTX_new();
+ const bool ok = key && ctx && EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, key) == 1 &&
+ EVP_DigestVerify(ctx, bytes.data(), bytes.size(), reinterpret_cast<const unsigned char*>(message.data()), message.size()) == 1;
+ EVP_MD_CTX_free(ctx); EVP_PKEY_free(key); return ok;
+ }
+ void approve(Client& c, const std::vector<std::string>& f) {
+ if (f.size() != 6) { send(c, refusal("invalid_grant")); return; }
+ const auto deadline = number(f[3]); const auto caps = number(f[4]); const auto now = unix_ms();
+ if (deadline <= now || deadline - now > 60000 || caps == 0 || caps > 15) { send(c, refusal("invalid_grant")); return; }
+ const auto message = std::format("CUA_TEST_LEASE_1\n{}\n{}\n{}\n{}\n{}\n", epoch, f[1], f[2], deadline, caps);
+ if (!valid_signature(message, f[5])) { send(c, refusal("invalid_grant")); return; }
+ const auto found = std::ranges::find_if(clients, [&](auto& peer) {
+ return !peer->dead && peer->hello && peer->challenge == f[1] && peer->token == f[2] && !peer->token.empty();
+ });
+ if (found == clients.end() || !refresh(**found)) { send(c, refusal("stale_target")); return; }
+ if (reservation != found->get()) { send(c, refusal("lane_not_claimed")); return; }
+ if (lease) { send(c, refusal("lease_busy")); return; }
+ if (agent_conflict(**found)) { send(c, refusal("agent_target_busy")); return; }
+ if (deadline <= (*found)->approved_deadline) { send(c, refusal("invalid_grant")); return; }
+ if (!available()) { send(c, refusal("session_unavailable")); return; }
+ // Bind steady-clock lifetime once; a clock change cannot extend a lease.
+ lease = found->get(); capabilities = caps; expires = Clock::now() + std::chrono::milliseconds(deadline - now);
+ lease->approved_deadline = deadline;
+ // Approval begins the bounded active period. Time spent waiting for
+ // the external operator must not consume the input connection's idle
+ // budget while its newly approved lease is still valid.
+ lease->deadline.touch(Clock::now());
+ if (trace) trace->mark("agent_approved", lane + 1);
+ send(c, R"({"ok":true})");
+ }
+#endif
+ bool point(Client& c, double x, double y) const {
+ return std::isfinite(x) && std::isfinite(y) && x >= 0 && y >= 0 && x < c.geometry[2] && y < c.geometry[3];
+ }
+ bool unique_primary_seat(wl_client* client) const {
+ struct Scan {
+ const Impl* self;
+ ForegroundSeatBindings bindings;
+ } scan{this, {}};
+ // Hyprland's public lookup returns only the first primary binding.
+ // Count classes without casting arbitrary protocol user data. Agent
+ // seats are excluded only by exact resource identity, never by name.
+ wl_client_for_each_resource(client, [](wl_resource* resource, void* data) {
+ auto& scan = *static_cast<Scan*>(data);
+ const std::string_view resource_class = wl_resource_get_class(resource);
+ if (resource_class != "wl_seat") return WL_ITERATOR_CONTINUE;
+ bool owned = false;
+ for (const auto* peer : scan.self->peers) {
+ if (!peer) continue;
+ for (const auto& seat : peer->seats)
+ if (seat->wl->resource() == resource) { owned = true; break; }
+ if (owned) break;
+ }
+ scan.bindings.observe(resource_class, owned);
+ return WL_ITERATOR_CONTINUE;
+ }, &scan);
+ if (!scan.bindings.unique()) return false;
+ if (!foreground_started) return true;
+ // A release/rebind or new child resource during a drag must not leave
+ // our captured delivery set different from the primary seat's set.
+ const auto seat = g_pSeatManager->seatResourceForClient(client);
+ if (!seat || seat != foreground_seat.lock()) return false;
+ return foreground_resources_match(seat->m_pointers, foreground_pointers) &&
+ foreground_resources_match(seat->m_keyboards, foreground_keyboards);
+ }
+ ForegroundGuard foreground_guard(const Client& c) const {
+ const auto root = c.surface.lock();
+ const auto geometry = target_geometry(c.window.lock(), root);
+ bool pressed = !g_pInputManager->getKeysFromAllKBs().empty();
+ for (const auto& kb : g_pInputManager->m_keyboards) {
+ if (!kb->m_enabled || kb->isVirtual()) continue;
+ for (std::uint32_t code = 0; code <= KEY_MAX && !pressed; ++code) pressed = kb->getPressed(code);
+ }
+ const bool exact_root = geometry && *geometry == c.geometry;
+ return {
+ .exact_root = exact_root,
+ .primary_binding = !exact_root || unique_primary_seat(root->client()),
+ .peer_conflict = agent_conflict(c),
+ .physical_keys = pressed,
+ .physical_buttons = g_pInputManager->hasHeldButtons(),
+ .grab = bool(g_pSeatManager->m_seatGrab) || bool(g_layoutManager->dragController()->target()) ||
+ !g_pInputManager->m_exclusiveLSes.empty(),
+ .dnd = PROTO::data && PROTO::data->dndActive(),
+ .constraint = g_pInputManager->isConstrained(),
+ .exact_keyboard_focus = root && g_pSeatManager->m_state.keyboardFocus == root &&
+ Desktop::focusState()->window() == c.window.lock() && Desktop::focusState()->surface() == root,
+ .exact_pointer_focus = root && g_pSeatManager->m_state.pointerFocus == root,
+ };
+ }
+ void require_foreground(Client& c) {
+ if (lease != &c) throw ForegroundFailure{ForegroundFailureReason::lease};
+ if (c.dead) throw ForegroundFailure{ForegroundFailureReason::client_dead};
+ if (!available()) throw ForegroundFailure{ForegroundFailureReason::session_unavailable};
+ if (!layout_qualified()) throw ForegroundFailure{ForegroundFailureReason::unsupported_layout};
+ if (Clock::now() >= expires) throw ForegroundFailure{ForegroundFailureReason::lease_expired};
+ const auto failure = foreground_guard(c).dispatch_failure(foreground_needs_pointer);
+ if (failure != ForegroundFailureReason::none) throw ForegroundFailure{failure};
+ }
+ void finish_foreground() {
+ foreground_activating = false;
+ if (!foreground_started) return;
+ // Release only our own synthetic state, and only while these resources
+ // still address the original root. A focus loss must not send to its successor.
+ const auto root = foreground_surface.lock();
+ if (root && root->good() && g_pSeatManager->m_state.pointerFocus == root)
+ for (const auto& weak : foreground_pointers)
+ if (const auto p = weak.lock(); p && p->good() && held_button) {
+ p->sendButton(event_ms(), held_button, WL_POINTER_BUTTON_STATE_RELEASED);
+ p->sendFrame();
+ }
+ if (foreground_keyboard_used && root && root->good() && g_pSeatManager->m_state.keyboardFocus == root)
+ for (const auto& weak : foreground_keyboards)
+ if (const auto k = weak.lock(); k && k->good()) {
+ for (auto code : held_keys) k->sendKey(event_ms(), code, WL_KEYBOARD_KEY_STATE_RELEASED);
+ k->sendMods(foreground_modifiers[0], foreground_modifiers[1], foreground_modifiers[2], foreground_modifiers[3]);
+ }
+ held_button = 0; held_keys.clear();
+ foreground_pointers.clear(); foreground_keyboards.clear(); foreground_surface.reset(); foreground_seat.reset();
+ foreground_started = false;
+ foreground_keyboard_used = false;
+ }
+ void start_foreground(Client& c, double x, double y, bool needs_pointer, bool needs_keyboard) {
+ const auto root = c.surface.lock();
+ const auto physical = g_pSeatManager->m_keyboard.lock();
+ const auto failure = foreground_guard(c).activation_failure();
+ if (failure != ForegroundFailureReason::none) throw ForegroundFailure{failure};
+ if (!physical) throw ForegroundFailure{ForegroundFailureReason::physical_keyboard};
+ if (!keyboard_state) throw ForegroundFailure{ForegroundFailureReason::keyboard_state};
+ if (needs_pointer && !g_pSeatManager->m_mouse) throw ForegroundFailure{ForegroundFailureReason::physical_pointer};
+ const Vector2D local{x + c.geometry[0] - c.geometry[4], y + c.geometry[1] - c.geometry[5]};
+ if (needs_pointer && (!point(c, x, y) || root->at(local, true).first != root)) throw ForegroundFailure{ForegroundFailureReason::pointer_target};
+ const auto seat = g_pSeatManager->seatResourceForClient(root->client());
+ if (!seat || !seat->good()) throw ForegroundFailure{ForegroundFailureReason::seat_resource};
+ foreground_pointers.clear(); foreground_keyboards.clear();
+ for (const auto& p : seat->m_pointers) if (p && p->good()) foreground_pointers.push_back(p);
+ for (const auto& k : seat->m_keyboards) if (k && k->good()) foreground_keyboards.push_back(k);
+ if (needs_pointer && foreground_pointers.empty()) throw ForegroundFailure{ForegroundFailureReason::pointer_resources};
+ if (foreground_keyboards.empty()) throw ForegroundFailure{ForegroundFailureReason::keyboard_resources};
+ foreground_modifiers = {physical->m_modifiersState.depressed, physical->m_modifiersState.latched,
+ physical->m_modifiersState.locked, physical->m_modifiersState.group};
+ for (const auto& kb : g_pInputManager->m_keyboards) {
+ if (!kb->m_enabled || !kb->shareStates() || (kb->isVirtual() && g_pInputManager->shouldIgnoreVirtualKeyboard(kb))) continue;
+ foreground_modifiers[0] |= kb->m_modifiersState.depressed;
+ foreground_modifiers[1] |= kb->m_modifiersState.latched;
+ foreground_modifiers[2] |= kb->m_modifiersState.locked;
+ }
+ if (needs_keyboard) {
+ const auto modifier_failure = foreground_key_modifier_failure(foreground_modifiers);
+ if (modifier_failure != ForegroundFailureReason::none) throw ForegroundFailure{modifier_failure};
+ }
+ xkb_state_update_mask(keyboard_state, foreground_modifiers[0], foreground_modifiers[1], foreground_modifiers[2], 0, 0, foreground_modifiers[3]);
+ foreground_surface = root;
+ foreground_seat = seat;
+ foreground_needs_pointer = needs_pointer;
+ c.foreground_attempted = true;
+ foreground_started = true;
+ foreground_activating = true;
+ // Activation intentionally persists. Never save, borrow, or restore focus.
+ if (g_pSeatManager->m_state.keyboardFocus != root || Desktop::focusState()->window() != c.window.lock() ||
+ Desktop::focusState()->surface() != root)
+ Desktop::focusState()->fullWindowFocus(c.window.lock(), Desktop::FOCUS_REASON_OTHER, root);
+ foreground_activating = false;
+ if (lease != &c) throw ForegroundFailure{ForegroundFailureReason::lease};
+ const auto focus_failure = foreground_guard(c).dispatch_failure(false);
+ if (focus_failure != ForegroundFailureReason::none) throw ForegroundFailure{focus_failure};
+ if (!needs_pointer) { require_foreground(c); return; }
+ foreground_activating = true;
+ ::Pointer::mgr()->warpTo({x + c.geometry[0], y + c.geometry[1]});
+ if (lease != &c) throw ForegroundFailure{ForegroundFailureReason::lease};
+ const auto warp_failure = foreground_guard(c).dispatch_failure(false);
+ if (warp_failure != ForegroundFailureReason::none) throw ForegroundFailure{warp_failure};
+ g_pSeatManager->setPointerFocus(root, local);
+ foreground_activating = false;
+ require_foreground(c);
+ foreground_motion(c, x, y);
+ }
+ void foreground_motion(Client& c, double x, double y) {
+ require_foreground(c);
+ const Vector2D local{x + c.geometry[0] - c.geometry[4], y + c.geometry[1] - c.geometry[5]};
+ if (!point(c, x, y) || c.surface.lock()->at(local, true).first != c.surface.lock()) throw ForegroundFailure{ForegroundFailureReason::pointer_target};
+ ::Pointer::mgr()->warpTo({x + c.geometry[0], y + c.geometry[1]});
+ require_foreground(c);
+ for (const auto& weak : foreground_pointers) {
+ const auto p = weak.lock(); if (!p || !p->good()) throw ForegroundFailure{ForegroundFailureReason::pointer_resources};
+ p->sendMotion(event_ms(), local); p->sendFrame();
+ }
+ }
+ void foreground_button(Client& c, std::uint32_t code, bool pressed) {
+ require_foreground(c);
+ // Mark ownership before sending, so a later resource failure can unwind.
+ if (pressed) held_button = code;
+ for (const auto& weak : foreground_pointers) {
+ const auto p = weak.lock(); if (!p || !p->good()) throw ForegroundFailure{ForegroundFailureReason::pointer_resources};
+ p->sendButton(event_ms(), code, pressed ? WL_POINTER_BUTTON_STATE_PRESSED : WL_POINTER_BUTTON_STATE_RELEASED);
+ p->sendFrame();
+ }
+ held_button = pressed ? code : 0;
+ }
+ void foreground_key(Client& c, std::uint32_t code, bool pressed) {
+ require_foreground(c);
+ foreground_keyboard_used = true;
+ xkb_state_update_key(keyboard_state, code + 8, pressed ? XKB_KEY_DOWN : XKB_KEY_UP);
+ if (pressed) held_keys.push_back(code); else std::erase(held_keys, code);
+ for (const auto& weak : foreground_keyboards) {
+ const auto k = weak.lock(); if (!k || !k->good()) throw ForegroundFailure{ForegroundFailureReason::keyboard_resources};
+ k->sendKey(event_ms(), code, pressed ? WL_KEYBOARD_KEY_STATE_PRESSED : WL_KEYBOARD_KEY_STATE_RELEASED);
+ k->sendMods(xkb_state_serialize_mods(keyboard_state, XKB_STATE_MODS_DEPRESSED),
+ xkb_state_serialize_mods(keyboard_state, XKB_STATE_MODS_LATCHED),
+ xkb_state_serialize_mods(keyboard_state, XKB_STATE_MODS_LOCKED),
+ xkb_state_serialize_layout(keyboard_state, XKB_STATE_LAYOUT_EFFECTIVE));
+ }
+ }
+ bool pointer_enter(Client& c, double x, double y) {
+ const auto root = c.surface.lock(); if (!root) return false;
+ // Initial experiment refuses subsurface targets instead of misrouting.
+ const Vector2D local{x + c.geometry[0] - c.geometry[4], y + c.geometry[1] - c.geometry[5]};
+ const auto hit = root->at(local, true);
+ if (hit.first != root) return false;
+ unsigned count = 0;
+ for (auto& p : pointers) {
+ if (p->dead || !p->wl->resource() || p->wl->client() != root->client()) continue;
+ if (p->focus != root) {
+ if (const auto old = p->focus.lock(); old && old->good()) p->wl->sendLeave(serial(), old->getResource().get());
+ p->focus = root;
+ p->wl->sendEnter(serial(), root->getResource().get(), wl_fixed_from_double(local.x), wl_fixed_from_double(local.y));
+ }
+ p->wl->sendMotion(event_ms(), wl_fixed_from_double(local.x), wl_fixed_from_double(local.y));
+ if (p->wl->version() >= 5) p->wl->sendFrame();
+ ++count;
+ }
+ if (count && !pointer_target.matches(c.window.lock(), root, c.geometry)) {
+ pointer_unmap.reset(); pointer_destroy.reset();
+ pointer_target.capture(c.window.lock(), root, c.geometry);
+ // These listeners belong to the lane, never the socket Client.
+ const auto window = c.window.lock();
+ pointer_unmap = window->m_events.unmap.listen([this] { revoke("stale_target"); });
+ pointer_destroy = window->m_events.destroy.listen([this] { revoke("stale_target"); });
+ }
+ return count > 0;
+ }
+ void button(std::uint32_t value, bool pressed) {
+ for (auto& p : pointers) {
+ if (p->dead || !p->wl->resource() || !p->focus) continue;
+ p->wl->sendButton(serial(), event_ms(), value, pressed ? WL_POINTER_BUTTON_STATE_PRESSED : WL_POINTER_BUTTON_STATE_RELEASED);
+ if (p->wl->version() >= 5) p->wl->sendFrame();
+ }
+ held_button = pressed ? value : 0;
+ }
+ bool keyboard_enter(Client& c) {
+ const auto root = c.surface.lock(); const auto physical = g_pSeatManager->m_keyboard.lock();
+ if (!root || !physical || physical->m_xkbKeymapV1String != keymap_text || !keyboard_state) return false;
+ unsigned count = 0;
+ for (auto& k : keyboards) {
+ if (k->dead || !k->wl->resource() || k->wl->client() != root->client()) continue;
+ if (k->focus != root) {
+ if (const auto old = k->focus.lock(); old && old->good()) k->wl->sendLeave(serial(), old->getResource().get());
+ k->focus = root;
+ wl_array keys{};
+ k->wl->sendEnter(serial(), root->getResource().get(), &keys);
+ k->wl->sendModifiers(serial(), 0, 0, 0, 0);
+ }
+ ++count;
+ }
+ return count > 0;
+ }
+ void key(std::uint32_t code, bool pressed) {
+ xkb_state_update_key(keyboard_state, code + 8, pressed ? XKB_KEY_DOWN : XKB_KEY_UP);
+ if (pressed) held_keys.push_back(code); else std::erase(held_keys, code);
+ for (auto& k : keyboards) {
+ if (k->dead || !k->wl->resource() || !k->focus) continue;
+ k->wl->sendKey(serial(), event_ms(), code, pressed ? WL_KEYBOARD_KEY_STATE_PRESSED : WL_KEYBOARD_KEY_STATE_RELEASED);
+ k->wl->sendModifiers(serial(), xkb_state_serialize_mods(keyboard_state, XKB_STATE_MODS_DEPRESSED),
+ xkb_state_serialize_mods(keyboard_state, XKB_STATE_MODS_LATCHED),
+ xkb_state_serialize_mods(keyboard_state, XKB_STATE_MODS_LOCKED),
+ xkb_state_serialize_layout(keyboard_state, XKB_STATE_LAYOUT_EFFECTIVE));
+ }
+ }
+ void request(Client& c, const std::vector<std::string>& f) {
+ if (!foreground_started) c.foreground_attempted = false;
+ sync_keymap();
+ if (c.dead) return;
+ const auto& command = f[0];
+ if (command == "HELLO") {
+ if (f.size() != 1 || c.hello) { send(c, refusal("invalid_request")); return; }
+ c.hello = true;
+ if (kProduction)
+ send(c, std::format(R"({{"ok":true,"protocol":3,"epoch":"{}","foreground_target":true}})", epoch));
+ else
+ send(c, std::format(R"({{"ok":true,"protocol":0,"epoch":"{}","challenge":"{}"}})", epoch, c.challenge));
+ return;
+ }
+ if (!c.hello) { send(c, refusal("invalid_request")); return; }
+ if (command == "CLAIM" && f.size() == 1) {
+ if (reservation && reservation != &c) { send(c, refusal("lane_busy")); return; }
+ reservation = &c;
+ send(c, std::format(R"({{"ok":true,"lane":{}}})", lane)); return;
+ }
+ if (command == "STOP" && f.size() == 1) {
+ if (kProduction) {
+ if (reservation != &c) { send(c, refusal("lane_not_claimed")); return; }
+ cancel_authority("stopped");
+ } else {
+ for (auto* peer : peers) if (peer) peer->cancel_authority("stopped");
+ }
+ send(c, R"({"ok":true})"); return;
+ }
+ if (command == "CANCEL" && f.size() == 1) {
+ if (kProduction && reservation != &c) { send(c, refusal("lane_not_claimed")); return; }
+ cancel_authority("cancelled"); send(c, R"({"ok":true})"); return;
+ }
+ if (trace && ((command == "TRACE_START" || command == "TRACE_STOP") && f.size() == 1)) {
+ send(c, trace->request(command)); return;
+ }
+ if (trace && command == "TRACE_READ" && f.size() == 2) {
+ const auto after = number(f[1]);
+ if (after > 32768) { send(c, refusal("invalid_request")); return; }
+ send(c, trace->request(command, after)); return;
+ }
+#ifdef CUA_HYPRLAND_TEST_INPUT
+ if (command == "APPROVE") { approve(c, f); return; }
+#endif
+ if (reservation != &c) { send(c, refusal("lane_not_claimed")); return; }
+ if (command == "TARGET" || (kProduction && command == "FOREGROUND_TARGET")) {
+ if (drag) { send(c, refusal("invalid_request")); return; }
+ const auto route = command == "FOREGROUND_TARGET" ? InputRoute::primary_foreground : InputRoute::independent;
+ if (!bind_input_route(c.route, route)) { invalidate(c); send(c, refusal("route_mismatch")); return; }
+ if (f.size() != (kProduction ? 4u : 3u)) {
+ if (kProduction) invalidate(c);
+ send(c, refusal("invalid_request")); return;
+ }
+ // A new admission attempt always retires any unused old grant.
+ // Do not leave an unchanged surface merely to refresh authority.
+ if (kProduction) retire_grant();
+ const auto requested_cap = kProduction ? number(f[3]) : 0;
+ if (kProduction && (!InputGrant::single_operation(requested_cap) ||
+ (requested_cap == 16 && route != InputRoute::primary_foreground))) { invalidate(c); send(c, refusal("unsupported")); return; }
+ if (kProduction && !available()) { invalidate(c); send(c, refusal("session_unavailable")); return; }
+ if (!layout_qualified()) { invalidate(c); send(c, refusal("unsupported_layout")); return; }
+ const auto pid = number(f[1]); const auto address = number(f[2], 16);
+ PHLWINDOW window;
+ for (const auto& w : Desktop::windowState()->windows())
+ if (reinterpret_cast<std::uintptr_t>(w.get()) == address && static_cast<std::uint64_t>(w->getPID()) == pid) window = w;
+ if (!window || window->m_isX11 || !window->m_isMapped || window->isHidden() || !window->resource()) {
+ invalidate(c); send(c, refusal("stale_target")); return;
+ }
+ // Retire the old target before rebinding: even if the new target's
+ // geometry validation fails, a reserved lane must not strand it.
+ if (pointer_target.entered() && !pointer_target.same_target(window, window->resource()))
+ revoke("stale_target");
+ if (c.window != window || c.surface != window->resource() || c.token.empty()) {
+ // Rebinding authority (including a new socket owner) may reuse
+ // unchanged passive hover. Compare the actual target below.
+ invalidate(c, false); c.unmap.reset(); c.destroy.reset();
+ c.window = window; c.surface = window->resource(); c.token = nonce(); c.revision = 1;
+ c.unmap = window->m_events.unmap.listen([this, &c] { invalidate(c); });
+ c.destroy = window->m_events.destroy.listen([this, &c] { invalidate(c); });
+ }
+ if (!refresh(c)) { invalidate(c); send(c, refusal("stale_target")); return; }
+ if (pointer_target.entered() && !pointer_target.matches(window, c.surface.lock(), c.geometry))
+ revoke("stale_target");
+ // Only a valid fresh TARGET can retire an orphan on another lane.
+ // Dispatch/conflict checks never evict peer state or replay input.
+ if (available() && !primary_conflict(c)) retire_orphan_hover(c);
+ if (kProduction) {
+ if (primary_conflict(c)) { invalidate(c); send(c, refusal("primary_target_busy")); return; }
+ if (agent_conflict(c)) { invalidate(c); send(c, refusal("agent_target_busy")); return; }
+ if (route == InputRoute::primary_foreground) {
+ const auto failure = foreground_guard(c).activation_failure();
+ if (failure != ForegroundFailureReason::none) {
+ invalidate(c); send(c, refusal("primary_target_busy", ForegroundFailure{failure})); return;
+ }
+ }
+ if (route == InputRoute::primary_foreground) leave_pointer();
+ c.foreground_attempted = false;
+ c.token = nonce();
+ grant.arm(requested_cap, Clock::now());
+ lease = &c; capabilities = requested_cap; expires = grant.deadline();
+ if (trace) trace->mark("agent_admitted", lane + 1);
+ }
+ c.has_bound_target = true;
+ if (route == InputRoute::primary_foreground) {
+ send(c, std::format(R"({{"ok":true,"target":"{}","revision":{},"width":{},"height":{},"route":"primary_foreground"}})",
+ c.token, c.revision, c.geometry[2], c.geometry[3])); return;
+ }
+ send(c, std::format(R"({{"ok":true,"target":"{}","revision":{},"width":{},"height":{}}})", c.token, c.revision, c.geometry[2], c.geometry[3])); return;
+ }
+ const std::uint64_t cap = command == "CLICK" ? 1 : command == "KEY" ? 2 : command == "SCROLL" ? 4 : command == "DRAG" ? 8 :
+ command == "ACTIVATE" && kProduction && c.route == InputRoute::primary_foreground ? 16 : 0;
+ const std::size_t count = command == "CLICK" ? 8 : command == "KEY" ? 6 : command == "SCROLL" ? 8 : command == "ACTIVATE" ? 4 : 9;
+ if (!cap) { send(c, refusal("unsupported")); return; }
+ if (f.size() != count) { send(c, refusal("invalid_request")); return; }
+ const auto sequence = number(f[1]);
+ if (sequence <= c.sequence) { send(c, refusal("replay")); return; }
+ c.sequence = sequence;
+ if (c.token.empty() || f[2] != c.token || !refresh(c)) { send(c, refusal("stale_target")); return; }
+ if (number(f[3]) != c.revision) { if (kProduction) revoke("stale_geometry"); send(c, refusal("stale_geometry")); return; }
+ if (!available()) { revoke("session_unavailable"); send(c, refusal("session_unavailable")); return; }
+ if (!layout_qualified()) { revoke("unsupported_layout"); send(c, refusal("unsupported_layout")); return; }
+ if (lease && Clock::now() >= expires) revoke("lease_expired");
+ if (drag) { send(c, refusal("lease_busy")); return; }
+ if (lease != &c || !(capabilities & cap) || (kProduction && !grant.permits(cap, Clock::now()))) {
+ if (kProduction) {
+ revoke("action_not_admitted");
+ send(c, refusal("action_not_admitted"));
+ } else {
+ send(c, std::format(R"({{"ok":false,"code":"pending_operator_approval","detail":"external test operator approval required","epoch":"{}","challenge":"{}","target":"{}"}})", epoch, c.challenge, c.token));
+ }
+ return;
+ }
+ if (primary_conflict(c)) {
+ if (kProduction) revoke("primary_target_busy");
+ send(c, refusal("primary_target_busy")); return;
+ }
+ if (agent_conflict(c)) {
+ if (kProduction) revoke("agent_target_busy");
+ send(c, refusal("agent_target_busy")); return;
+ }
+ if (c.route == InputRoute::primary_foreground) {
+ foreground_request(c, f, cap);
+ return;
+ }
+ if (command == "KEY") {
+ const auto code = number(f[4]); const auto mods = number(f[5]);
+ if (code == 0 || code > 247 || mods > 15 || code == 58 || code == 69 || code == 70) { send(c, refusal("unsupported")); return; }
+ if (!consume_grant(c, cap)) return;
+ if (!keyboard_enter(c)) { send(c, refusal("client_not_bound")); return; }
+ const std::array<std::uint32_t, 4> keys{42, 29, 56, 125};
+ for (unsigned i = 0; i < 4; ++i) if ((mods & (1u << i)) && keys[i] != code) key(keys[i], true);
+ key(code, true); key(code, false);
+ for (int i = 3; i >= 0; --i) if ((mods & (1u << i)) && keys[i] != code) key(keys[i], false);
+ } else {
+ const auto x = real(f[4]), y = real(f[5]);
+ if (!point(c, x, y)) { send(c, refusal("invalid_request")); return; }
+ if (command == "CLICK") {
+ const auto btn = number(f[6]), clicks = number(f[7]);
+ if (btn < 272 || btn > 274 || clicks < 1 || clicks > 2) { send(c, refusal("invalid_request")); return; }
+ if (!consume_grant(c, cap)) return;
+ if (!pointer_enter(c, x, y)) { send(c, refusal("client_not_bound")); return; }
+ for (unsigned i = 0; i < clicks; ++i) { button(btn, true); button(btn, false); }
+ } else if (command == "SCROLL") {
+ const auto axis = number(f[6]); const auto value = real(f[7]);
+ if (axis > 1 || value == 0 || std::abs(value) > 1000) { send(c, refusal("invalid_request")); return; }
+ if (!consume_grant(c, cap)) return;
+ if (!pointer_enter(c, x, y)) { send(c, refusal("client_not_bound")); return; }
+ for (auto& p : pointers) {
+ if (p->dead || !p->wl->resource() || !p->focus) continue;
+ if (p->wl->version() >= 5) p->wl->sendAxisSource(WL_POINTER_AXIS_SOURCE_WHEEL);
+ p->wl->sendAxis(event_ms(), static_cast<wl_pointer_axis>(axis), wl_fixed_from_double(value));
+ if (p->wl->version() >= 5) p->wl->sendFrame();
+ }
+ } else {
+ const auto x2 = real(f[6]), y2 = real(f[7]); const auto duration = number(f[8]);
+ if (!point(c, x2, y2) || duration < 50 || duration > 2000) { send(c, refusal("invalid_request")); return; }
+ if (Clock::now() + std::chrono::milliseconds(duration + 50) >= expires) { send(c, refusal("lease_expired")); return; }
+ if (!consume_grant(c, cap)) return;
+ if (!pointer_enter(c, x, y)) { send(c, refusal("client_not_bound")); return; }
+ if (trace) trace->mark("agent_drag_start", lane + 1);
+ button(272, true);
+ drag.emplace(Drag{&c, x, y, x2, y2, Clock::now(), static_cast<unsigned>(duration), DragGeometry{c.revision}});
+ send(c, R"({"ok":true,"phase":"started"})"); return;
+ }
+ }
+ ++dispatches;
+ if (trace) trace->mark("agent_action_end", lane + 1);
+ if (kProduction) complete_action();
+ send(c, kDelivered);
+ }
+ void foreground_request(Client& c, const std::vector<std::string>& f, std::uint64_t cap) {
+ const auto& command = f[0];
+ double x = c.geometry[2] / 2, y = c.geometry[3] / 2, x2 = 0, y2 = 0, value = 0;
+ std::uint64_t code = 0, mods = 0, clicks = 0, axis = 0, duration = 0;
+ if (command == "KEY") {
+ code = number(f[4]); mods = number(f[5]);
+ if (code == 0 || code > 247 || mods > 15 || code == 58 || code == 69 || code == 70) {
+ send(c, refusal("unsupported")); return;
+ }
+ } else if (command != "ACTIVATE") {
+ x = real(f[4]); y = real(f[5]);
+ if (!point(c, x, y)) { send(c, refusal("invalid_request")); return; }
+ if (command == "CLICK") {
+ code = number(f[6]); clicks = number(f[7]);
+ if (code < 272 || code > 274 || clicks < 1 || clicks > 2) { send(c, refusal("invalid_request")); return; }
+ } else if (command == "SCROLL") {
+ axis = number(f[6]); value = real(f[7]);
+ if (axis > 1 || value == 0 || std::abs(value) > 1000) { send(c, refusal("invalid_request")); return; }
+ } else {
+ x2 = real(f[6]); y2 = real(f[7]); duration = number(f[8]);
+ if (!point(c, x2, y2) || duration < 50 || duration > 2000) { send(c, refusal("invalid_request")); return; }
+ if (Clock::now() + std::chrono::milliseconds(duration + 50) >= expires) { send(c, refusal("lease_expired")); return; }
+ }
+ }
+ if (!consume_grant(c, cap)) return;
+ start_foreground(c, x, y, command != "KEY" && command != "ACTIVATE", command == "KEY");
+ if (command == "KEY") {
+ const std::array<std::uint32_t, 4> keys{42, 29, 56, 125};
+ for (unsigned i = 0; i < 4; ++i) if ((mods & (1u << i)) && keys[i] != code) foreground_key(c, keys[i], true);
+ foreground_key(c, code, true); foreground_key(c, code, false);
+ for (int i = 3; i >= 0; --i) if ((mods & (1u << i)) && keys[i] != code) foreground_key(c, keys[i], false);
+ } else if (command == "CLICK") {
+ for (unsigned i = 0; i < clicks; ++i) { foreground_button(c, code, true); foreground_button(c, code, false); }
+ } else if (command == "SCROLL") {
+ require_foreground(c);
+ for (const auto& weak : foreground_pointers) {
+ const auto p = weak.lock(); if (!p || !p->good()) throw ForegroundFailure{ForegroundFailureReason::pointer_resources};
+ p->sendAxisSource(WL_POINTER_AXIS_SOURCE_WHEEL);
+ p->sendAxis(event_ms(), static_cast<wl_pointer_axis>(axis), value); p->sendFrame();
+ }
+ } else if (command == "DRAG") {
+ foreground_button(c, 272, true);
+ drag.emplace(Drag{&c, x, y, x2, y2, Clock::now(), static_cast<unsigned>(duration), DragGeometry{c.revision}});
+ send(c, R"({"ok":true,"phase":"started"})"); return;
+ }
+ require_foreground(c);
+ ++dispatches;
+ complete_action();
+ send(c, kForegroundDelivered);
+ }
+ bool consume_grant(Client& c, std::uint64_t capability) {
+ if (!kProduction) return true;
+ capabilities = 0;
+ if (grant.consume(capability, Clock::now())) return true;
+ revoke("action_not_admitted");
+ send(c, refusal("action_not_admitted"));
+ return false;
+ }
+ static int tick(void* data) {
+ auto& self = *static_cast<Impl*>(data);
+ try { self.step(); } catch (...) { self.revoke("internal_error"); }
+ wl_event_source_timer_update(self.timer, self.retired ? 500 : 16); return 0;
+ }
+ void step() {
+ if (!retired) sync_keymap();
+ for (auto& c : clients) if (c->deadline.expired(c->hello, Clock::now())) c->dead = true;
+ if (lease) {
+ if (lease->dead) revoke("disconnected", true);
+ else if (Clock::now() >= expires) revoke("lease_expired");
+ else if (!available() || !layout_qualified() || !refresh(*lease) || primary_conflict(*lease) || agent_conflict(*lease) ||
+ (drag && !drag->geometry.matches(lease->revision))) revoke("cancelled");
+ }
+ if (pointer_target.entered()) {
+ const auto surface = pointer_target.surface();
+ const auto geometry = target_geometry(pointer_target.window(), surface);
+ const bool bound = std::ranges::any_of(pointers, [&](const auto& p) {
+ return !p->dead && p->wl->resource() && surface && p->focus == surface;
+ });
+ if (!available() || !layout_qualified() || !geometry || *geometry != pointer_target.geometry() ||
+ !bound || primary_conflict(surface) || agent_conflict(surface)) revoke("cancelled");
+ }
+ if (drag) {
+ const auto d = *drag;
+ const auto elapsed = std::chrono::duration<double, std::milli>(Clock::now() - d.start).count();
+ const auto progress = std::min(elapsed / d.duration, 1.0);
+ if (d.client->route == InputRoute::primary_foreground) {
+ foreground_motion(*d.client, d.x1 + (d.x2 - d.x1) * progress, d.y1 + (d.y2 - d.y1) * progress);
+ if (progress >= 1) {
+ foreground_button(*d.client, 272, false); drag.reset(); ++dispatches;
+ complete_action(); send(*d.client, kForegroundDelivered);
+ }
+ } else if (!pointer_enter(*d.client, d.x1 + (d.x2 - d.x1) * progress, d.y1 + (d.y2 - d.y1) * progress)) revoke("client_not_bound");
+ else if (progress >= 1) {
+ button(272, false); drag.reset(); ++dispatches;
+ if (trace) trace->mark("agent_drag_end", lane + 1);
+ if (kProduction) complete_action();
+ send(*d.client, kDelivered);
+ }
+ }
+ if (lease && lease->dead) revoke("disconnected", true);
+ if (reservation && reservation->dead) reservation = nullptr;
+ std::erase_if(clients, [](auto& c) { return c->dead; });
+ std::erase_if(pointers, [](auto& p) { return p->dead; });
+ std::erase_if(keyboards, [](auto& k) { return k->dead; });
+ std::erase_if(touches, [](auto& t) { return t->dead; });
+ std::erase_if(seats, [](auto& s) { return s->dead; });
+ }
+};
+
+// Hyprland 0.56.2 signals run synchronously on the compositor thread. Keep
+// their ownership explicit and detach before retiring the seats. No polling
+// or aggregate-state comparison substitutes for this transition boundary.
+struct InputExperiment::DesktopListeners {
+ struct MonitorListeners {
+ PHLMONITORREF monitor;
+ CHyprSignalListener dpms, mode;
+ };
+ InputExperiment& owner;
+ std::vector<MonitorListeners> monitors;
+ CHyprSignalListener lock, unlock, active, layout, added, removed, destroyed;
+ CHyprSignalListener keyboard_layout, pointer_focus, keyboard_focus;
+ CHyprSignalListener mouse_move, mouse_button, mouse_axis, keyboard_key, touch_down, tablet_tip;
+
+ explicit DesktopListeners(InputExperiment& input) : owner(input) {
+ lock = g_pSessionLockManager->m_events.lock.listen([this] { changed(); });
+ unlock = g_pSessionLockManager->m_events.unlock.listen([this] { changed(); });
+ if (g_pCompositor->m_aqBackend->hasSession())
+ active = g_pCompositor->m_aqBackend->session->events.changeActive.listen([this] { changed(); });
+ layout = Event::bus()->m_events.monitor.layoutChanged.listen([this] { changed(); });
+ if (kProduction) {
+ keyboard_layout = Event::bus()->m_events.input.keyboard.layout.listen(
+ [this](SP<IKeyboard>, const std::string&) { changed(); });
+ pointer_focus = g_pSeatManager->m_events.pointerFocusChange.listen([this] { primary_changed(); });
+ keyboard_focus = g_pSeatManager->m_events.keyboardFocusChange.listen([this] { primary_changed(); });
+ // These notifications precede physical delivery. Retire our owned
+ // press before the user's event can become held on the same resource.
+ mouse_move = Event::bus()->m_events.input.mouse.move.listen([this](Vector2D, Event::SCallbackInfo&) { external_input(); });
+ mouse_button = Event::bus()->m_events.input.mouse.button.listen([this](IPointer::SButtonEvent, Event::SCallbackInfo&) { external_input(); });
+ mouse_axis = Event::bus()->m_events.input.mouse.axis.listen([this](IPointer::SAxisEvent, Event::SCallbackInfo&) { external_input(); });
+ keyboard_key = Event::bus()->m_events.input.keyboard.key.listen([this](IKeyboard::SKeyEvent, Event::SCallbackInfo&) { external_input(); });
+ touch_down = Event::bus()->m_events.input.touch.down.listen([this](ITouch::SDownEvent, Event::SCallbackInfo&) { external_input(); });
+ tablet_tip = Event::bus()->m_events.input.tablet.tip.listen([this](CTablet::STipEvent, Event::SCallbackInfo&) { external_input(); });
+ }
+ added = Event::bus()->m_events.monitor.preAdded.listen([this](PHLMONITOR monitor) {
+ changed(); watch(monitor);
+ });
+ removed = Event::bus()->m_events.monitor.preRemoved.listen([this](PHLMONITOR) { changed(); });
+ destroyed = Event::bus()->m_events.monitor.destroyMon.listen([this](PHLMONITOR monitor) {
+ changed();
+ std::erase_if(monitors, [&](const auto& entry) { return !entry.monitor || entry.monitor == monitor; });
+ });
+ for (const auto& monitor : State::monitorState()->allMonitors()) watch(monitor);
+ }
+ void changed() {
+ for (auto& lane : owner.lanes_) lane->desktop_transition();
+ }
+ void external_input() {
+ for (auto& lane : owner.lanes_)
+ if (lane->lease && lane->lease->route == InputRoute::primary_foreground)
+ lane->cancel_authority("foreground_interrupted", false);
+ }
+ void primary_changed() {
+ for (auto& lane : owner.lanes_) {
+ if ((lane->lease && lane->primary_conflict(*lane->lease)) ||
+ (lane->pointer_target.entered() && lane->primary_conflict(lane->pointer_target.surface())))
+ lane->cancel_authority("primary_target_busy", false);
+ }
+ }
+ void watch(PHLMONITOR monitor) {
+ if (!monitor || std::ranges::any_of(monitors, [&](const auto& entry) { return entry.monitor == monitor; })) return;
+ MonitorListeners listeners;
+ listeners.monitor = monitor;
+ listeners.dpms = monitor->m_events.dpmsChanged.listen([this] { changed(); });
+ listeners.mode = monitor->m_events.modeChanged.listen([this] { changed(); });
+ monitors.push_back(std::move(listeners));
+ }
+};
+
+InputExperiment::InputExperiment(const std::string& directory, void* plugin) {
+ SeatLifetime lifetime(directory);
+ for (unsigned i = 0; i < lanes_.size(); ++i) lanes_[i] = std::make_unique<Impl>(directory, i);
+ for (auto& lane : lanes_) { lane->peers = {lanes_[0].get(), lanes_[1].get()}; lane->start(); }
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT_TRACE)
+ trace_ = std::make_unique<PrimaryTrace>(plugin, [this](wl_resource* resource) {
+ for (unsigned i = 0; i < lanes_.size(); ++i) {
+ for (const auto& p : lanes_[i]->pointers) if (p->wl->resource() == resource) return i + 1;
+ for (const auto& k : lanes_[i]->keyboards) if (k->wl->resource() == resource) return i + 1;
+ }
+ return 0u;
+ });
+ for (auto& lane : lanes_) lane->trace = trace_.get();
+#else
+ (void)plugin;
+#endif
+ desktop_listeners_ = std::make_unique<DesktopListeners>(*this);
+ lifetime.publish();
+}
+InputExperiment::~InputExperiment() {
+ desktop_listeners_.reset();
+ for (auto& lane : lanes_) { lane->retire(); lane->trace = nullptr; lane->peers = {}; }
+ trace_.reset();
+ // Intentional process-lifetime ownership: callbacks, removed global, and
+ // remaining client-owned resources cannot outlive their Impl. The instance
+ // marker refuses replacement modules, so this retains at most two lanes.
+ for (auto& lane : lanes_) (void)lane.release();
+}
+void InputExperiment::suspend() {
+ for (auto& lane : lanes_) lane->suspend();
+}
+void InputExperiment::resume() {
+ try {
+ for (auto& lane : lanes_) lane->resume();
+ } catch (...) {
+ // Partial transport setup must not leave one admitted lane behind.
+ suspend();
+ throw;
+ }
+}
+std::string InputExperiment::status_json() const {
+ std::string states;
+ for (const auto& lane : lanes_) {
+ if (!states.empty()) states += ',';
+ const bool pointer_focus = std::ranges::any_of(lane->pointers, [](const auto& p) { return !p->dead && bool(p->focus); });
+ const bool keyboard_focus = std::ranges::any_of(lane->keyboards, [](const auto& k) { return !k->dead && bool(k->focus); });
+ states += std::format(R"({{"lane":{},"epoch":"{}","desktop_generation":{},"reserved":{},"socket_cleanup":"{}","lease_active":{},"seat_resources":{},"pointer_resources":{},"keyboard_resources":{},"dispatches":{},"held_button":{},"held_keys":{},"drag_active":{},"pointer_focus":{},"keyboard_focus":{}}})",
+ lane->lane, lane->epoch, lane->desktop_generation, lane->reservation != nullptr, lane->socket_cleanup, lane->lease != nullptr, lane->seats.size(), lane->pointers.size(), lane->keyboards.size(), lane->dispatches,
+ lane->held_button, lane->held_keys.size(), lane->drag.has_value(), pointer_focus, keyboard_focus);
+ }
+ // Aggregate legacy fields remain available to existing test probes.
+ return std::format(R"({{"protocol":{},"test_only":{},"seat_lifetime":"compositor","upgrade":"desktop_restart","transport_ready":{},"epoch":"{}","lease_active":{},"seat_resources":{},"pointer_resources":{},"keyboard_resources":{},"dispatches":{},"lanes":[{}]}})",
+ kProduction ? 3 : 0, !kProduction, !lanes_[0]->suspended && !lanes_[1]->suspended, lanes_[0]->epoch, lanes_[0]->lease != nullptr || lanes_[1]->lease != nullptr,
+ lanes_[0]->seats.size() + lanes_[1]->seats.size(), lanes_[0]->pointers.size() + lanes_[1]->pointers.size(),
+ lanes_[0]->keyboards.size() + lanes_[1]->keyboards.size(), lanes_[0]->dispatches + lanes_[1]->dispatches, states);
+}
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/input_experiment.hpp b/libs/cua-driver/hyprland-plugin/src/input_experiment.hpp
new file mode 100644
index 0000000000..d9e66cf367
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/input_experiment.hpp
@@ -0,0 +1,29 @@
+#pragma once
+
+#include <memory>
+#include <string>
+#include <array>
+
+namespace cua::hyprland {
+class PrimaryTrace;
+// Shared native seat/lifetime implementation. Build options select production
+// v3 admission or the historical signed experiment; never both.
+class InputExperiment {
+ public:
+ explicit InputExperiment(const std::string& instance_directory, void* plugin);
+ ~InputExperiment();
+ InputExperiment(const InputExperiment&) = delete;
+ InputExperiment& operator=(const InputExperiment&) = delete;
+ // Config toggles change admission, not client-owned Wayland resources.
+ void suspend();
+ void resume();
+ std::string status_json() const;
+
+ private:
+ struct Impl;
+ struct DesktopListeners;
+ std::array<std::unique_ptr<Impl>, 2> lanes_;
+ std::unique_ptr<PrimaryTrace> trace_;
+ std::unique_ptr<DesktopListeners> desktop_listeners_;
+};
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/input_grant.hpp b/libs/cua-driver/hyprland-plugin/src/input_grant.hpp
new file mode 100644
index 0000000000..9943d5e1c0
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/input_grant.hpp
@@ -0,0 +1,37 @@
+#pragma once
+
+#include <chrono>
+#include <cstdint>
+
+namespace cua::hyprland {
+// Technical per-dispatch lifetime, not an independent permission policy.
+class InputGrant {
+ public:
+ using Clock = std::chrono::steady_clock;
+ static constexpr auto lifetime = std::chrono::seconds(5);
+ static constexpr bool single_operation(std::uint64_t capability) {
+ return capability == 1 || capability == 2 || capability == 4 || capability == 8 || capability == 16;
+ }
+ bool arm(std::uint64_t capability, Clock::time_point now) {
+ reset();
+ if (!single_operation(capability)) return false;
+ capability_ = capability;
+ deadline_ = now + lifetime;
+ return true;
+ }
+ bool permits(std::uint64_t capability, Clock::time_point now) const {
+ return single_operation(capability) && capability_ == capability && now < deadline_;
+ }
+ bool consume(std::uint64_t capability, Clock::time_point now) {
+ const bool permitted = permits(capability, now);
+ // Even a mismatched or expired dispatch cannot retain authority.
+ reset();
+ return permitted;
+ }
+ void reset() { capability_ = 0; deadline_ = {}; }
+ Clock::time_point deadline() const { return deadline_; }
+ private:
+ std::uint64_t capability_ = 0;
+ Clock::time_point deadline_{};
+};
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/owned_socket_path.hpp b/libs/cua-driver/hyprland-plugin/src/owned_socket_path.hpp
new file mode 100644
index 0000000000..f0422b517a
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/owned_socket_path.hpp
@@ -0,0 +1,89 @@
+#pragma once
+
+#include <cerrno>
+#include <string>
+#include <sys/stat.h>
+#include <unistd.h>
+
+namespace cua::hyprland {
+namespace owned_socket_path_detail {
+
+inline bool is_owned_socket(const struct stat& metadata, uid_t owner) noexcept {
+ return S_ISSOCK(metadata.st_mode) && metadata.st_uid == owner;
+}
+
+inline bool matches_identity(const struct stat& current,
+ const struct stat& captured, uid_t owner) noexcept {
+ return is_owned_socket(current, owner) &&
+ current.st_uid == captured.st_uid &&
+ current.st_dev == captured.st_dev && current.st_ino == captured.st_ino;
+}
+
+} // namespace owned_socket_path_detail
+
+// Call capture immediately after a successful bind, in a private runtime
+// directory. Pathname inspection and unlink are not atomic: this guards normal
+// lifecycle replacement, not hostile races by another process with the same UID.
+// Cleanup is explicit so its outcome can be reported by the listener's owner.
+class OwnedSocketPath {
+ public:
+ enum class CleanupResult { NotCaptured, Removed, AlreadyAbsent, Replaced, Failed };
+
+ OwnedSocketPath() = default;
+ OwnedSocketPath(const OwnedSocketPath&) = delete;
+ OwnedSocketPath& operator=(const OwnedSocketPath&) = delete;
+
+ bool capture(const std::string& path) {
+ m_captured = false;
+ m_error = 0;
+ m_path = path;
+ if (lstat(m_path.c_str(), &m_metadata) != 0) {
+ m_error = errno;
+ return false;
+ }
+ if (!owned_socket_path_detail::is_owned_socket(m_metadata, getuid())) {
+ m_error = EPERM;
+ return false;
+ }
+ m_captured = true;
+ return true;
+ }
+
+ // Every attempt consumes ownership, including a failed or refused cleanup.
+ // A later retire/destructor must not retry against a newly installed path.
+ CleanupResult cleanup() noexcept {
+ m_error = 0;
+ if (!m_captured)
+ return CleanupResult::NotCaptured;
+ m_captured = false;
+
+ struct stat current{};
+ if (lstat(m_path.c_str(), &current) != 0) {
+ const int error = errno;
+ if (error == ENOENT)
+ return CleanupResult::AlreadyAbsent;
+ m_error = error;
+ return CleanupResult::Failed;
+ }
+ if (!owned_socket_path_detail::matches_identity(current, m_metadata, getuid()))
+ return CleanupResult::Replaced;
+ if (unlink(m_path.c_str()) != 0) {
+ const int error = errno;
+ if (error == ENOENT)
+ return CleanupResult::AlreadyAbsent;
+ m_error = error;
+ return CleanupResult::Failed;
+ }
+ return CleanupResult::Removed;
+ }
+
+ int error_number() const noexcept { return m_error; }
+
+ private:
+ std::string m_path;
+ struct stat m_metadata{};
+ bool m_captured = false;
+ int m_error = 0;
+};
+
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/passive_pointer_target.hpp b/libs/cua-driver/hyprland-plugin/src/passive_pointer_target.hpp
new file mode 100644
index 0000000000..cb9ee8d73d
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/passive_pointer_target.hpp
@@ -0,0 +1,71 @@
+#pragma once
+
+#include <array>
+
+namespace cua::hyprland {
+struct InputLaneActivity {
+ bool reserved = false, leased = false, dragging = false;
+ bool button = false, keys = false, keyboard_focus = false;
+ bool capabilities = false, grant = false, expiry = false;
+ // A new claimant does not adopt the previous owner's hover merely by
+ // reserving a lane. This exception ends after its first successful TARGET
+ // and must not be restored by STOP, CANCEL, or target invalidation.
+ bool reservation_without_target = false;
+
+ [[nodiscard]] bool inert() const {
+ return (!reserved || reservation_without_target) && !leased && !dragging && !button && !keys &&
+ !keyboard_focus && !capabilities && !grant && !expiry;
+ }
+};
+
+// Pointer presence outlives the transport owner, but never owns that owner,
+// its grant, or the target. Window/surface references must be weak references.
+template <typename WindowRef, typename SurfaceRef>
+class PassivePointerTarget {
+ public:
+ using Geometry = std::array<double, 6>;
+
+ template <typename Window, typename Surface>
+ void capture(const Window& window, const Surface& surface, const Geometry& geometry) {
+ window_ = window;
+ surface_ = surface;
+ geometry_ = geometry;
+ entered_ = true;
+ }
+ void reset() {
+ window_.reset();
+ surface_.reset();
+ geometry_ = {};
+ entered_ = false;
+ }
+ [[nodiscard]] bool entered() const { return entered_; }
+ [[nodiscard]] auto window() const { return window_.lock(); }
+ [[nodiscard]] auto surface() const { return surface_.lock(); }
+ [[nodiscard]] const Geometry& geometry() const { return geometry_; }
+
+ template <typename Window, typename Surface>
+ [[nodiscard]] bool same_target(const Window& window, const Surface& surface) const {
+ return entered_ && window && surface && window_.lock() == window &&
+ surface_.lock() == surface;
+ }
+ template <typename Window, typename Surface>
+ [[nodiscard]] bool matches(const Window& window, const Surface& surface, const Geometry& geometry) const {
+ return same_target(window, surface) && geometry_ == geometry;
+ }
+ template <typename Surface>
+ [[nodiscard]] bool same_client(const Surface& candidate) const {
+ const auto current = surface_.lock();
+ return entered_ && current && candidate && current->client() == candidate->client();
+ }
+ template <typename Surface>
+ [[nodiscard]] bool reclaimable_for(const Surface& candidate, const InputLaneActivity& activity) const {
+ return activity.inert() && same_client(candidate);
+ }
+
+ private:
+ WindowRef window_;
+ SurfaceRef surface_;
+ Geometry geometry_{};
+ bool entered_ = false;
+};
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/plugin.cpp b/libs/cua-driver/hyprland-plugin/src/plugin.cpp
index 6a676f6acf..88b99002e8 100644
--- a/libs/cua-driver/hyprland-plugin/src/plugin.cpp
+++ b/libs/cua-driver/hyprland-plugin/src/plugin.cpp
@@ -1,4 +1,7 @@
#include "inject_server.hpp"
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+#include "input_experiment.hpp"
+#endif
#include "cua_hyprland/protocol.hpp"
#include "cua_hyprland/status.hpp"
@@ -45,6 +48,10 @@ std::string g_runtime_abi_hash;
std::uint64_t g_epoch = 0;
std::string g_socket_path;
std::string g_reconcile_error;
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+std::unique_ptr<cua::hyprland::InputExperiment> g_experiment;
+HANDLE g_experiment_handle = nullptr;
+#endif
bool safe_instance_signature(const std::string& signature) {
if (signature.empty())
@@ -139,6 +146,10 @@ std::uint64_t make_epoch() {
}
std::string stop_server() {
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+ if (g_experiment)
+ g_experiment->suspend();
+#endif
if (!g_server)
return {};
g_server->stop();
@@ -171,8 +182,15 @@ void reconcile_server() {
.enabled_capabilities =
cua::hyprland::capability(cua::hyprland::Capability::discovery),
});
- if (server->start())
+ if (server->start()) {
g_epoch = epoch;
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+ if (!g_experiment)
+ g_experiment = std::make_unique<cua::hyprland::InputExperiment>(
+ std::filesystem::path{g_socket_path}.parent_path().string(), g_experiment_handle);
+ g_experiment->resume();
+#endif
+ }
g_server = std::move(server);
}
@@ -198,10 +216,40 @@ std::string status_output(bool json) {
.malformed_frames = snapshot.malformed_frames,
};
- if (json)
- return cua::hyprland::render_status_json(report);
+ if (json) {
+ auto result = cua::hyprland::render_status_json(report);
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+ if (g_experiment) {
+#ifdef CUA_HYPRLAND_INPUT
+ constexpr auto input_state = "\"state\":\"input_v3_candidate\"";
+ constexpr auto input_mutation = "trusted_local_per_action";
+ constexpr auto input_field = ",\"input\":";
+#else
+ constexpr auto input_state = "\"state\":\"input_experiment\"";
+ constexpr auto input_mutation = "separate_operator_gated_experiment";
+ constexpr auto input_field = ",\"experiment\":";
+#endif
+ const std::string old_state = "\"state\":\"discovery_only\"";
+ const auto state_at = result.find(old_state);
+ if (state_at != std::string::npos)
+ result.replace(state_at, old_state.size(), input_state);
+ const std::string old_mutation = "disabled_pending_rfc_and_agent_seat";
+ const auto mutation_at = result.find(old_mutation);
+ if (mutation_at != std::string::npos)
+ result.replace(mutation_at, old_mutation.size(), input_mutation);
+ result.pop_back();
+ result += input_field + g_experiment->status_json() + "}";
+ }
+#endif
+ return result;
+ }
- return cua::hyprland::render_status_text(report);
+ auto result = cua::hyprland::render_status_text(report);
+#ifdef CUA_HYPRLAND_INPUT
+ if (g_experiment)
+ result += "\nInput v3 candidate: trusted-local per-action admission; " + g_experiment->status_json();
+#endif
+ return result;
}
#if CUA_HYPRLAND_SOCKET1_API
@@ -242,6 +290,9 @@ APICALL EXPORT std::string PLUGIN_API_VERSION() {
}
APICALL EXPORT PLUGIN_DESCRIPTION_INFO PLUGIN_INIT(HANDLE handle) {
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+ g_experiment_handle = handle;
+#endif
// Hyprland skips PLUGIN_EXIT when initialization throws. Do not start any
// worker thread until all potentially throwing registration is complete.
const auto* runtime_abi_hash = __hyprland_api_get_hash();
@@ -256,7 +307,11 @@ APICALL EXPORT PLUGIN_DESCRIPTION_INFO PLUGIN_INIT(HANDLE handle) {
g_enabled = makeShared<Config::Values::CBoolValue>(
"plugin:cua:enabled",
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+ "Enable Cua's same-user local capability transport and the input mode selected at build time.",
+#else
"Enable Cua's same-user local capability transport. Background mutation remains disabled in this build.",
+#endif
false);
if (!HyprlandAPI::addConfigValueV2(handle, g_enabled))
throw std::runtime_error("failed to register plugin:cua:enabled");
@@ -284,6 +339,11 @@ APICALL EXPORT PLUGIN_DESCRIPTION_INFO PLUGIN_INIT(HANDLE handle) {
APICALL EXPORT void PLUGIN_EXIT() {
g_config_listener.reset();
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
+ // Retire input directly so an in-flight action receives plugin_shutdown,
+ // not the config-disable reason from stop_server()'s suspend path.
+ g_experiment.reset();
+#endif
static_cast<void>(stop_server());
g_status_command.reset();
g_enabled.reset();
diff --git a/libs/cua-driver/hyprland-plugin/src/primary_trace.cpp b/libs/cua-driver/hyprland-plugin/src/primary_trace.cpp
new file mode 100644
index 0000000000..39c9286c74
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/primary_trace.cpp
@@ -0,0 +1,123 @@
+#include "primary_trace.hpp"
+#include <src/Compositor.hpp>
+#include <src/managers/SeatManager.hpp>
+#include <src/pointer/PointerManager.hpp>
+#include <src/plugins/PluginAPI.hpp>
+#include <src/protocols/core/Compositor.hpp>
+#include <wayland-server-core.h>
+
+#include <array>
+#include <chrono>
+#include <cstring>
+#include <format>
+#include <stdexcept>
+
+namespace cua::hyprland {
+struct PrimaryTrace::Impl {
+ using Clock = std::chrono::steady_clock;
+ struct Event {
+ std::uint64_t ns = 0;
+ const char* kind = "";
+ double x = 0, y = 0;
+ unsigned actor = 0, state = 0;
+ bool surface_position = false;
+ double surface_x = 0, surface_y = 0;
+ };
+ static inline Impl* live = nullptr;
+ std::array<Event, 32768> events{};
+ std::size_t count = 0;
+ bool active = false, overflow = false, timed_out = false;
+ Clock::time_point started{};
+ void* plugin;
+ CFunctionHook* motion = nullptr;
+ wl_protocol_logger* logger = nullptr;
+ CHyprSignalListener pointer_focus, keyboard_focus;
+ std::function<unsigned(wl_resource*)> actor;
+
+ explicit Impl(void* handle, std::function<unsigned(wl_resource*)> classify)
+ : plugin(handle), actor(std::move(classify)) {}
+
+ void start() {
+ if (live) throw std::runtime_error("primary trace already installed");
+ const auto matches = HyprlandAPI::findFunctionsByName(plugin, "_ZN7Pointer15CPointerManager13onCursorMovedEv");
+ if (matches.size() != 1) throw std::runtime_error("exact primary cursor trace hook unavailable");
+ motion = HyprlandAPI::createFunctionHook(plugin, matches.front().address, reinterpret_cast<void*>(moved));
+ if (!motion || !motion->hook()) throw std::runtime_error("primary cursor trace hook refused");
+ live = this;
+ logger = wl_display_add_protocol_logger(g_pCompositor->m_wlDisplay, protocol, this);
+ if (!logger) throw std::runtime_error("primary protocol trace unavailable");
+ pointer_focus = g_pSeatManager->m_events.pointerFocusChange.listen([this] { record("pointer_focus", 0); });
+ keyboard_focus = g_pSeatManager->m_events.keyboardFocusChange.listen([this] { record("keyboard_focus", 0); });
+ }
+ ~Impl() {
+ active = false;
+ pointer_focus.reset(); keyboard_focus.reset();
+ if (logger) wl_protocol_logger_destroy(logger);
+ if (motion) HyprlandAPI::removeFunctionHook(plugin, motion);
+ if (live == this) live = nullptr;
+ }
+ void record(const char* kind, unsigned owner, unsigned state = 0,
+ bool surface_position = false, double surface_x = 0, double surface_y = 0) noexcept {
+ if (!active) return;
+ const auto now = Clock::now();
+ if (now - started > std::chrono::seconds(60)) { timed_out = true; active = false; return; }
+ if (count == events.size()) { overflow = true; active = false; return; }
+ const auto position = Pointer::mgr()->position();
+ events[count++] = Event{static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count()),
+ kind, position.x, position.y, owner, state, surface_position, surface_x, surface_y};
+ }
+ static void moved(void* pointer) {
+ auto* self = live;
+ // This hook records the compositor-owned position on *every* mutation,
+ // including two warps within one event-loop turn. It never changes it.
+ self->record("cursor", 0);
+ reinterpret_cast<void (*)(void*)>(self->motion->m_original)(pointer);
+ }
+ static void protocol(void* data, wl_protocol_logger_type direction, const wl_protocol_logger_message* message) {
+ auto& self = *static_cast<Impl*>(data);
+ if (!self.active || direction != WL_PROTOCOL_LOGGER_EVENT) return;
+ const auto* type = wl_resource_get_class(message->resource);
+ const auto* name = message->message->name;
+ const auto owner = self.actor(message->resource);
+ // Only event categories, button/key state, and synthetic pointer
+ // coordinates are retained, never keycodes, text, or window names.
+ if (!std::strcmp(type, "wl_pointer")) {
+ if (!std::strcmp(name, "motion")) self.record("pointer_motion", owner, 0, owner != 0,
+ wl_fixed_to_double(message->arguments[1].f), wl_fixed_to_double(message->arguments[2].f));
+ else if (!std::strcmp(name, "enter")) self.record("pointer_enter", owner, 0, owner != 0,
+ wl_fixed_to_double(message->arguments[2].f), wl_fixed_to_double(message->arguments[3].f));
+ else if (!std::strcmp(name, "leave")) self.record("pointer_leave", owner);
+ else if (!std::strcmp(name, "button")) self.record("pointer_button", owner, message->arguments[3].u);
+ else if (!std::strcmp(name, "axis")) self.record("pointer_axis", owner);
+ } else if (!std::strcmp(type, "wl_keyboard")) {
+ if (!std::strcmp(name, "enter")) self.record("keyboard_enter", owner);
+ else if (!std::strcmp(name, "leave")) self.record("keyboard_leave", owner);
+ else if (!std::strcmp(name, "key")) self.record("keyboard_key", owner, message->arguments[3].u);
+ }
+ }
+ std::string request(const std::string& command, unsigned after) {
+ if (command == "TRACE_START") {
+ count = 0; overflow = false; timed_out = false; started = Clock::now(); active = true;
+ record("start", 0);
+ } else if (command == "TRACE_STOP") {
+ record("stop", 0); active = false;
+ } else if (command != "TRACE_READ") {
+ return R"({"ok":false,"code":"invalid_request"})";
+ }
+ std::string rows;
+ for (std::size_t i = after; i < count && i < static_cast<std::size_t>(after) + 8; ++i) {
+ const auto& event = events[i];
+ if (!rows.empty()) rows += ',';
+ rows += std::format(R"([{}, {}, "{}", {}, {}, {}, {}{})", i + 1, event.ns, event.kind, event.x, event.y, event.actor, event.state,
+ event.surface_position ? std::format(", {}, {}]", event.surface_x, event.surface_y) : "]");
+ }
+ return std::format(R"({{"ok":true,"active":{},"overflow":{},"timed_out":{},"hook":true,"count":{},"events":[{}]}})",
+ active, overflow, timed_out, count, rows);
+ }
+};
+PrimaryTrace::PrimaryTrace(void* plugin, std::function<unsigned(wl_resource*)> actor)
+ : impl_(std::make_unique<Impl>(plugin, std::move(actor))) { impl_->start(); }
+PrimaryTrace::~PrimaryTrace() = default;
+std::string PrimaryTrace::request(const std::string& command, unsigned after) { return impl_->request(command, after); }
+void PrimaryTrace::mark(const char* kind, unsigned actor) { impl_->record(kind, actor); }
+}
diff --git a/libs/cua-driver/hyprland-plugin/src/primary_trace.hpp b/libs/cua-driver/hyprland-plugin/src/primary_trace.hpp
new file mode 100644
index 0000000000..6da2f56efd
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/primary_trace.hpp
@@ -0,0 +1,28 @@
+#pragma once
+
+#include <functional>
+#include <memory>
+#include <string>
+
+struct wl_resource;
+namespace cua::hyprland {
+// Test instrumentation, never part of the discovery-only production build.
+// No input is emitted. Capture is bounded, explicit, and kept in memory.
+class PrimaryTrace {
+ public:
+#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT_TRACE)
+ PrimaryTrace(void* plugin, std::function<unsigned(wl_resource*)> actor);
+ ~PrimaryTrace();
+ std::string request(const std::string& command, unsigned after = 0);
+ void mark(const char* kind, unsigned actor);
+ private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+#else
+ // Uninstrumented production has no hooks, trace buffer, or trace commands.
+ ~PrimaryTrace() = default;
+ std::string request(const std::string&, unsigned = 0) { return {}; }
+ void mark(const char*, unsigned) {}
+#endif
+};
+}
diff --git a/libs/cua-driver/hyprland-plugin/src/seat_lifetime.hpp b/libs/cua-driver/hyprland-plugin/src/seat_lifetime.hpp
new file mode 100644
index 0000000000..85792122db
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/seat_lifetime.hpp
@@ -0,0 +1,37 @@
+#pragma once
+
+#include <stdexcept>
+#include <string>
+#include <sys/stat.h>
+#include <unistd.h>
+
+namespace cua::hyprland {
+
+// The per-instance runtime directory is validated by the plugin entry point.
+// A successful initialization leaves a marker until the desktop ends. This
+// prevents even a different module filename/version from creating replacement
+// seats after unload. It is a trusted-local lifecycle guard, not protection
+// against another same-user process deleting the marker.
+class SeatLifetime {
+ public:
+ explicit SeatLifetime(const std::string& instance_directory)
+ : path_(instance_directory + "/cua-input-seat-lifetime") {
+ if (mkdir(path_.c_str(), 0700) != 0)
+ throw std::runtime_error("input seat lifetime unavailable; restart the desktop before loading a replacement plugin");
+ }
+ ~SeatLifetime() {
+ // Before publication there are no client-owned seat resources. Only
+ // remove our empty reservation after a failed initialization.
+ if (!published_)
+ static_cast<void>(rmdir(path_.c_str()));
+ }
+ SeatLifetime(const SeatLifetime&) = delete;
+ SeatLifetime& operator=(const SeatLifetime&) = delete;
+ void publish() noexcept { published_ = true; }
+
+ private:
+ std::string path_;
+ bool published_ = false;
+};
+
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/tests/README.md b/libs/cua-driver/hyprland-plugin/tests/README.md
index 7232c9537e..1aa3b64c0b 100644
--- a/libs/cua-driver/hyprland-plugin/tests/README.md
+++ b/libs/cua-driver/hyprland-plugin/tests/README.md
@@ -1,11 +1,17 @@
# Hyprland plugin test plan
-The plugin is optional, disabled by default, and discovery-only until the
-second-seat design is proven and its RFC is accepted. Tests must fail closed;
-they must not enable mutation merely to exercise a path.
+The normal plugin build is optional, disabled by default, and discovery-only.
+Tests of that build must fail closed; they must not enable mutation merely to
+exercise a path. The separately selected, nonshipping
+[input experiment](../protocol/input-experiment.md) has an explicit build flag
+and external test-operator grant. Its
+[VM validation record](input-validation.md) is not production acceptance.
+The [concurrent real-app follow-up](realapp-validation.md) records two-lane
+Calc/Inkscape tasks, moving-primary measurement, a warp-and-return negative
+control, per-lane Cancel, and global Stop on its exact tested candidate.
Neither stable Cua Driver `0.23.2` nor nightly provides isolated background
-input through this plugin. Discovery currently covers protocol negotiation,
+input through this plugin. Normal-build discovery covers protocol negotiation,
status, and liveness only; application target discovery and input mutation are
not enabled.
@@ -103,6 +109,228 @@ startup, arbitrary ABI combinations, or the complete driver desktop matrix.
Hosted CI tests the runner's cleanup/error paths with mocks; native results
require running it in the Fleet guest or another declared Wayland environment.
+## Held-input lifecycle faults
+
+The session-lifetime candidate replaces hot-reload recovery with config-toggle
+recovery. For that candidate, use `--case toggle --toggle-file PATH`, where
+`PATH` is a test-owned Lua include sourced by the disposable compositor config
+and contains exactly `hl.config({plugin = {cua = {enabled = true}}})` followed
+by a newline. The runner verifies disable and re-enable through plugin status,
+requires a new admission epoch and approval, and keeps the same applications
+running. It refuses the historical `reload` case before input or unload when
+status requires a desktop restart. Separate unload/replacement-refusal and
+fresh-desktop tests remain required; a config toggle does not prove them.
+The one-way retirement runner below covers the first of those gates when run
+natively. Adding the runner and passing its helper tests is not native evidence.
+
+The portable suite covers seat-owner reuse across 20 toggles, failed transport
+recovery, restart-required lifetime markers, and inode-aware socket cleanup.
+These mock/unit checks do not establish native seat delivery, keymap refresh,
+brief desktop-transition revocation, or real multi-process lane behavior.
+
+The [native reliability record](lifecycle-validation.md) identifies the tested
+source, measured results, recordings, setup failures, and remaining limits.
+
+Run `input_lifecycle_live.py` only in a disposable Fleet guest with the
+experimental build explicitly loaded, a source-built Driver service started
+with `--permission-mode unrestricted --dangerously-bypass-approvals`, and two
+native GTK fixtures. The normal build does not support this test.
+
+First observe both fixture windows through Driver. Supply a reviewed JSON plan
+containing `background` and `foreground` PID/window pairs, their matching
+`background_bounds` and `foreground_bounds`, two window-image points (`from`
+and `to`), and a window-local `foreground_point` for the independent primary
+grab. The runner rejects changed geometry and takes fresh Driver snapshots
+before and after application actions.
+
+Pass the exact paths through `--plan`, `--evidence`, `--driver`,
+`--driver-socket`, `--input-directory`, `--primary-grab`,
+`--background-journal`, `--foreground-journal`, and `--foreground-wire`.
+The journals and wire log belong to the existing isolated-input fixtures.
+Use `--record-video` for supporting Driver video evidence.
+
+The runner writes `request-initial.json` and waits up to 35 seconds. Review the
+exact pending target on the host and sign its epoch/challenge/target with
+`input_operator.py`. Grant only capabilities `10` (drag and the recovery key
+probe), with a bounded lifetime. Transfer only the signed grant as
+`grant-initial.json`; keep the private key outside the guest. The runner has
+no signing or implicit approval path.
+
+Choose one fault per run:
+
+- `--case stop` revokes input through the separate operator connection.
+- `--case disconnect` terminates the exact agent MCP proxy while its drag is
+ held. The observer remains connected independently.
+- `--case expiry --compositor-pid PID` deliberately stalls the explicitly
+ selected Hyprland process past lease expiry. Use a short grant, such as
+ 10 seconds. A separate PID-fd watchdog resumes that same process within
+ four seconds if the caller fails. When launching through systemd, use
+ `KillMode=process` so caller termination does not also kill the watchdog.
+- `--case toggle --toggle-file PATH` disables and re-enables admission while
+ preserving the seats and existing application processes.
+- Historical candidates only: `--case reload --reload-module PATH` tests
+ unload/reload recovery. The restart-required candidate refuses this case;
+ use the separate retirement runner instead.
+
+The application must receive a press before fault injection and a matching
+release within 750 ms. The fault lands early in a two-second drag, so natural
+completion cannot satisfy the Stop/disconnect/unload bound. For expiry, the
+bound starts at compositor resume, and a 500 ms drag must report
+`lease_expired`: the desktop is deliberately frozen during the stall. This
+case proves expiry cleanup after resumption, not uninterrupted
+foreground operation or cleanup while the compositor cannot run.
+
+The primary fixture must retain its grab, click count, and keyboard state.
+Its independent Wayland wire log must contain no pointer or keyboard input
+events during the fault window. Matching cursor endpoints alone cannot pass
+this check. Raw logs and grants remain private; publish only categorical
+results, timings, source and artifact digests, and stated limitations.
+
+Historical reload cleanup does not prove that surviving clients bind replacement
+seats or accept subsequent input. The session-lifetime candidate instead requires
+surviving-client recovery after config toggles and fresh-desktop recovery after
+replacement. Atomic key packets do not expose a held-key
+stream, so these cases make a held-pointer claim only. These focused tests
+supplement, rather than replace, the canonical desktop matrix and physical
+host validation.
+
+### Pending authority revocation
+
+`input_authority_live.py` tests Stop and Cancel before signed grants are
+redeemed. It does not dispatch input or establish application delivery.
+Run each command separately with `--command STOP` or `--command CANCEL`,
+`--input-directory`, `--plan`, `--evidence`, and `--disposable`.
+Both lanes must be idle and unclaimed. The plan is a JSON array of exactly
+two observed native disposable-fixture targets in separate processes, each
+with a positive `pid` and lowercase hexadecimal `address` without `0x`.
+
+The runner writes `request-before.json`. On the host, sign the named requests
+with `input_operator.py`, using only click capability `1`. Give `renewal-0`
+a later expiry than `active-0`, and transfer the public grants as
+`grants-before.json`, an object keyed by request name. The runner redeems
+`active-0`, but leaves the renewal and `pending-1` unused before revocation.
+Stop must reject both unused grants; per-lane Cancel must preserve the
+sibling's pending grant. Old grants must remain refused after target rebinding.
+
+Sign `request-after.json` into `grants-after.json` in the same format to prove
+fresh authorization still works. Lane 0's fresh grant must still be valid but
+expire before its revoked grant, as indicated by `expires_before_unix_ms`.
+This checks that an old target's replay high-water mark cannot reject a
+shorter grant for a new target binding. Allow time for both stages: for example,
+sign the initial grant for 50 seconds, its renewal for 60 seconds, and the
+fresh grant for 10 seconds, completing the second transfer before the initial
+deadline. Each transfer has a 40-second limit; grants
+must satisfy the protocol's 60-second ceiling and remain valid when submitted.
+The runner checks unchanged dispatch counters, no held/focused synthetic state,
+surviving operator connections, and final Stop cleanup. Keep grants and target
+identifiers in local evidence. `input_authority_test.py` tests the runner with
+scripted peers; those tests do not execute compositor code.
+
+### One-way seat retirement
+
+`input_retirement_live.py` unloads the plugin while a real Driver MCP drag is
+held, then checks that same-path and different-path replacement modules refuse
+until desktop restart. Use a fresh disposable session and a clean, committed
+candidate. Both native GTK fixtures must have Wayland wire logs from startup
+showing that they bound both synthetic seats. Start with both lanes idle.
+
+Supply the lifecycle runner's plan, journals, Driver and input socket paths,
+primary-grab binary, and evidence directory. Additionally supply both fixture
+wire logs, `--compositor-pid`, `--driver-service-pid`, `--source-sha`,
+`--module`, `--replacement-module`, their `--module-sha256` and
+`--replacement-module-sha256`, and `--driver-sha256`. The replacement must
+already be staged at a different canonical path and inode. A copy of the same
+build tests different-path refusal, not a different-build upgrade. The required
+`--disposable-session-restart-required` flag acknowledges the one-way transition.
+Use `--help` for exact argument names.
+
+The host signs `grant-request.json` into `grant.json` with capabilities `10`
+(drag and key probe), with 15–60 seconds remaining. The runner verifies a
+matching application press/release within the 750 ms cancellation bound,
+`plugin_shutdown`, closed old connections, removed sockets, both seat
+capabilities becoming zero, global removal, and unchanged primary input.
+Compositor and client identities, heartbeats, and fresh Driver snapshots must
+remain valid. Each replacement attempt must produce an explicit runtime
+restart refusal in enabled, ABI-matched plugin status; an absent plugin or
+failed ABI check cannot pass.
+
+The successful run leaves the plugin unloaded and its lifetime marker intact.
+Restart the disposable desktop before subsequent input tests. Fresh-desktop
+delivery and late-client cleanup still require separate native coverage.
+`retirement_evidence_test.py` checks the evidence oracles and preflight failures
+with synthetic data; it is not native retirement evidence.
+
+## Desktop-state fault controls
+
+The [native desktop-state validation record](desktop-state-validation.md)
+contains five matched fault/control pairs, artifact identities, measured
+cancellation and cleanup times, retained failures, and limits.
+
+`desktop_state_live.py` is a focused experimental safety test, not the canonical
+desktop matrix. It requires a disposable Fleet guest, the explicitly loaded
+input experiment, and a source-built Driver service with unrestricted
+permissions. Use native GTK raw-event fixtures and keep their journals and
+Wayland wire logs. The helper refuses an arbitrary process as its target.
+
+For each `--case destroy|move|resize|lock|dpms`, run `--mode control` before
+`--mode action --control PATH_TO_CONTROL_RESULT`. Use the same foreground
+fixture, geometry, source SHA, module digest, and selected fault in both runs.
+The identity also binds the Driver and adversary binaries and the harness files.
+The control measures the compositor effects of the fault without agent input.
+A lock can legitimately change focus; matching cursor endpoints alone does
+not prove that the agent added no interference. The comparison checks exact
+foreground state, ordered cursor movement, input events, and focus transitions.
+
+Use `--observer-driver-socket` to select a second Driver service built from the
+same source for observations and video. The action service must have no active
+recording. This separates input-response latency from synchronous post-action
+trajectory capture; both services still use real Driver MCP. A second MCP
+connection to the same service does not isolate that recording overhead.
+
+Pass the lifecycle runner's fixture paths, plus `--source-sha`, `--module`,
+`--compositor-pid`, `--compositor-exe`, `--instance`, and `--disposable`.
+Extend its plan with the exact `background_address` and a changed `move_to`
+or `resize_to` pair where applicable. Geometry faults require an already
+floating fixture. For destruction, capture `pre_target_resources` from both
+experimental lanes before launching the background fixture, after the other
+clients have settled. Resource counts must return to that baseline after
+destruction; expired weak focus references are not sufficient evidence.
+
+The action runner waits for the application's received button press before
+injecting the fault into a two-second drag. It requires a typed refusal and
+cleared authority, held input, and agent focus within 750 ms of fault dispatch,
+with enough time left that natural completion cannot satisfy the deadline.
+Surviving targets must receive a matching button release. A destroyed surface
+cannot acknowledge release, so that case uses disappearance and pruned
+resources instead. Unexpected keyboard or scroll input fails every drag case.
+
+The host operator reviews `request-initial.json` and `request-recovery.json`
+and supplies distinct signed grants with capabilities `10`. The runner waits
+35 seconds for each grant and never receives the signing key. After destruction,
+it also requests a separately launched replacement through `recovery-plan.json`.
+Recovery must refuse old authority, require a fresh grant, deliver exactly one
+Escape press/release pair, and preserve foreground input and compositor state.
+Before either approval, the foreground actor must already own primary focus.
+A newly launched target may take focus during setup; restore the foreground
+actor explicitly before measuring background delivery. Setup is not isolation
+evidence, and a grant revoked by a primary-target conflict is not a fault test.
+
+Build `session_lock_fixture.c` with the generated `ext-session-lock-v1`
+client protocol and pass it through `--lock-fixture`. It uses a real protocol
+lock, supplies opaque black surfaces on every advertised output, and waits for
+compositor acknowledgments. Without surfaces, Hyprland's missing-surface grace
+period delays acknowledgment. The fixture is not a production lock screen.
+Independent watchdogs restore DPMS or request graceful unlock. Never kill a
+lock client to unlock the session: a crashed client can leave it locked, in
+which case discard the disposable guest.
+
+Both modes require finalized Driver video. Preserve failed runs and cleanup
+results as well as passing evidence. Publish only sanitized outcomes, timings,
+versions, and digests. These cases test sustained lock or display-off states
+observed by the compositor loop; they do not prove that an off/on transition
+entirely between samples is latched. Atomic key packets provide recovery
+evidence, not an interrupted held-key-stream guarantee.
+
## Fleet packaging lane
Build an Omarchy/Arch Fleet image from the monorepo source using
diff --git a/libs/cua-driver/hyprland-plugin/tests/compositor_stall.py b/libs/cua-driver/hyprland-plugin/tests/compositor_stall.py
new file mode 100644
index 0000000000..c26dc3eb6f
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/compositor_stall.py
@@ -0,0 +1,53 @@
+"""Bounded fault injection for an explicitly selected disposable compositor.
+
+This intentionally freezes the desktop. It is not an uninterrupted-user test.
+An independent PID-fd watchdog resumes the exact process even if the caller dies.
+Never run against a user's working desktop.
+"""
+import os
+from pathlib import Path
+import select
+import signal
+import subprocess
+import sys
+import time
+
+
+def stall_past_expiry(pid, expires_unix_ms):
+ remaining = expires_unix_ms / 1000 - time.time()
+ if not 0 < remaining < 2.9:
+ raise ValueError('expiry must be within the bounded compositor stall')
+ expected = Path('/usr/bin/Hyprland').resolve(strict=True)
+ if Path(f'/proc/{pid}/exe').resolve(strict=True) != expected:
+ raise ValueError('fault target is not the installed Hyprland executable')
+ if Path(f'/proc/{pid}').stat().st_uid != os.getuid():
+ raise ValueError('fault target is not owned by the test user')
+ fd = os.pidfd_open(pid)
+ watchdog = None
+ try:
+ watchdog = subprocess.Popen([
+ sys.executable, '-c',
+ 'import signal,sys,time; print("ARMED",flush=True); time.sleep(4); '
+ 'signal.pidfd_send_signal(int(sys.argv[1]),signal.SIGCONT)', str(fd)],
+ pass_fds=(fd,), stdout=subprocess.PIPE, text=True)
+ if not select.select([watchdog.stdout], [], [], 2)[0] or watchdog.stdout.readline().strip() != 'ARMED':
+ raise RuntimeError('compositor resume watchdog did not arm')
+ started = time.monotonic_ns()
+ signal.pidfd_send_signal(fd, signal.SIGSTOP)
+ try:
+ # Use one monotonic deadline; clock adjustments cannot extend the stall.
+ deadline = time.monotonic() + max(0, expires_unix_ms / 1000 - time.time()) + 0.05
+ time.sleep(max(0, deadline - time.monotonic()))
+ finally:
+ resumed = time.monotonic_ns()
+ signal.pidfd_send_signal(fd, signal.SIGCONT)
+ return {'resume_ns': resumed, 'stall_ms': (resumed - started) / 1_000_000}
+ finally:
+ # Also covers exceptions after SIGSTOP and before entering its try block.
+ signal.pidfd_send_signal(fd, signal.SIGCONT)
+ if watchdog is not None:
+ if watchdog.poll() is None:
+ watchdog.terminate()
+ watchdog.wait(timeout=5)
+ watchdog.stdout.close()
+ os.close(fd)
diff --git a/libs/cua-driver/hyprland-plugin/tests/compositor_stall_test.py b/libs/cua-driver/hyprland-plugin/tests/compositor_stall_test.py
new file mode 100644
index 0000000000..2c01e18753
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/compositor_stall_test.py
@@ -0,0 +1,47 @@
+from contextlib import ExitStack
+from pathlib import Path
+import signal
+import unittest
+from unittest.mock import Mock, patch
+
+from compositor_stall import stall_past_expiry
+
+
+class CompositorStallTest(unittest.TestCase):
+ def test_invalid_deadline_never_touches_a_process(self):
+ with patch('compositor_stall.time.time', return_value=10), \
+ patch('compositor_stall.os.pidfd_open', create=True) as opened:
+ for expiry in (9000, 10000, 14000):
+ with self.assertRaises(ValueError):
+ stall_past_expiry(7, expiry)
+ opened.assert_not_called()
+
+ def test_resume_runs_even_when_fault_wait_fails(self):
+ calls = []
+ watchdog = Mock()
+ watchdog.stdout.readline.return_value = 'ARMED\n'
+ watchdog.poll.return_value = None
+ with ExitStack() as stack:
+ stack.enter_context(patch('compositor_stall.time.time', return_value=10))
+ stack.enter_context(patch('compositor_stall.time.sleep', side_effect=RuntimeError('fault wait')))
+ stack.enter_context(patch('compositor_stall.Path.resolve', return_value=Path('/usr/bin/Hyprland')))
+ stack.enter_context(patch('compositor_stall.Path.stat', return_value=Mock(st_uid=1000)))
+ stack.enter_context(patch('compositor_stall.os.getuid', return_value=1000))
+ opened = stack.enter_context(patch('compositor_stall.os.pidfd_open', return_value=9, create=True))
+ closed = stack.enter_context(patch('compositor_stall.os.close'))
+ stack.enter_context(patch('compositor_stall.signal.pidfd_send_signal',
+ side_effect=lambda fd, sig: calls.append((fd, sig)), create=True))
+ spawned = stack.enter_context(patch('compositor_stall.subprocess.Popen', return_value=watchdog))
+ stack.enter_context(patch('compositor_stall.select.select', return_value=([watchdog.stdout], [], [])))
+ with self.assertRaisesRegex(RuntimeError, 'fault wait'):
+ stall_past_expiry(7, 11000)
+ opened.assert_called_once_with(7)
+ self.assertEqual(calls, [(9, signal.SIGSTOP), (9, signal.SIGCONT), (9, signal.SIGCONT)])
+ self.assertEqual(spawned.call_args.kwargs['pass_fds'], (9,))
+ watchdog.terminate.assert_called_once()
+ watchdog.wait.assert_called_once_with(timeout=5)
+ closed.assert_called_once_with(9)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/desktop-state-validation.md b/libs/cua-driver/hyprland-plugin/tests/desktop-state-validation.md
new file mode 100644
index 0000000000..7a18104103
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/desktop-state-validation.md
@@ -0,0 +1,179 @@
+# Desktop-state safety validation
+
+On 2026-09-05, five matched fault-only controls and five Driver MCP background
+drag episodes passed in a disposable Omarchy Cua Fleet VM. Moving, resizing,
+locking, turning the display off, or destroying the target cancelled the
+background action within the 750 ms test bound. Agent input state and authority
+cleared, old grants were refused, and freshly approved recovery succeeded.
+
+Each action produced no additional foreground effects compared with its
+fault-only control. This does **not** mean every fault leaves the foreground
+unchanged: the real session lock itself released the foreground grab and changed
+focus. The action and control had the same measured effects.
+
+This is focused evidence for [draft #3572](https://github.com/trycua/cua/pull/3572),
+not a supported release or production certification. The normal plugin build
+remains discovery-only. The [earlier real-app](realapp-validation.md) and
+[held-input lifecycle](lifecycle-validation.md) results retain their own source
+identities; this pass does not recertify them.
+
+## Exact artifacts
+
+All ten final episodes used the same native binaries and final executable test
+helpers. Changes after the native source SHA were confined to tests and
+documentation. The commits adding this report change documentation only.
+
+| Component | Tested identity |
+| --- | --- |
+| Native Driver and plugin source | `fc225fef9bbaa07c9953e1d80cf6fd82d66bd4fd` |
+| Final executable test-helper source | `9b1c71c67145173d902c6638805afb355b8eb305` |
+| Omarchy | `4.0.1-1`, disposable KVM Fleet VM |
+| Hyprland | `0.56.2-1`, commit `efb50993780079460b0cbed1363e2166a2de1d9f` |
+| Portal | `xdg-desktop-portal-hyprland 1.4.1-1` |
+| Driver source and installed version | `0.23.2`, custom task-local source build, not the stock release |
+| Plugin | `0.1.0`, explicitly enabled input experiment |
+| Toolchain | GCC `16.1.1`, CMake `4.4.3`, Rust `1.97.1` |
+| Display | One 1920 × 1080 output, scale 1 |
+
+The SHA-256 artifact digests are:
+
+- Native source archive: `7b7643136e80e67422fa7f37104aeed15c022529b2fd9d24ba86c4f073ffc3b4`.
+- Driver: `57b1de8296cc41e6e8121b181056bcb1c1f20cc9d531becbf0f3221c96992b1b`.
+- Plugin: `7e105e0701fe0d1104f7389e654dff59c7d7503e4e380ced1638e8295ed20358`.
+- Primary-pointer fixture: `32e52f55ac1be4261ba32b9328264c04e28a2f8da464f4d1f1c4a50550751cdf`.
+- Session-lock fixture: `237b694749137a518f47eb73691719d2c183ebc7649a16935e071b6aba11b856`.
+- Final test-helper archive: `d63a18294b40194cab5b7255eb51386a9636583666156d70f046d38d394750e1`.
+- Retained evidence archive: `9e40e9136310b77798c23d91de628a196fedf15d72405f24391616cade2c44be`.
+
+The installed Driver and both running service executables had matching digests.
+One service performed actions; a separate service from the same binary recorded
+video and observed state. The action service had recording disabled. Separate
+connections to one service would not isolate synchronous recording overhead.
+The ordinary Driver installation was preserved. No host installation or Fleet
+image publication occurred.
+
+## Geometry regression
+
+The previous drag check compared against mutable cached target geometry. An
+intervening target request or approval refresh could update that cache before
+the timer compared revisions, masking movement during an active drag.
+
+The experiment now pins each drag to the geometry revision accepted at its
+start. The regression test refreshes the target cache before checking the active
+drag and requires cancellation. Its assertions remain active in Release builds
+with `NDEBUG` defined.
+
+## Method and foreground comparison
+
+[`desktop_state_live.py`](desktop_state_live.py) drives native GTK raw-event
+fixtures through real Driver MCP `drag` and `press_key` calls. The Fleet SDK
+provides VM transport and setup, not the background input path. An independent
+virtual primary pointer holds a real Wayland grab in the foreground fixture.
+It is not physical mouse input.
+
+Each control/action pair binds the same fault, foreground identity and geometry,
+native source, module and Driver digests, adversary binaries, test-helper bytes,
+and observer-service arrangement. Background targets are verified from fresh
+Driver snapshots. The operator signs short-lived target/connection/epoch-bound
+test grants outside the guest.
+
+The action episode waits for the application's received button press before
+injecting a fault into a two-second drag. Both the typed refusal and observed
+cleared state must arrive within 750 ms of fault dispatch, early enough that
+natural completion cannot pass. Cleared state means no lease, active drag,
+held button or keys, or agent pointer/keyboard focus. Surviving targets must also
+journal a matching button release. Unexpected keys or scroll events fail the
+drag episode.
+
+The comparison uses foreground application deltas, Wayland wire events,
+compositor input/focus traces, the ordered cursor path, and exact active-window,
+workspace, and cursor readback. Matching endpoints alone cannot pass. For lock,
+the control captures the compositor's own release and focus changes; the action
+must not add effects beyond those.
+
+Destruction requires independently observed target disappearance. Both lanes'
+seat, pointer, and keyboard resource counts must return to a baseline measured
+before launching the target. A destroyed surface cannot acknowledge release, so
+this case does not claim an application-received release. Recovery uses a new
+process identity even if Hyprland reuses the old window address.
+
+Every action refuses the old grant, refuses unapproved recovery input, requires
+a distinct fresh grant, and then delivers exactly one Escape press/release pair.
+The recovery checks also require unchanged foreground application and compositor
+state and no foreground wire-input leakage. See the
+[runner instructions](README.md#desktop-state-fault-controls) for setup and
+watchdog requirements.
+
+## Recorded results
+
+All five controls and all five action episodes passed with no cleanup errors.
+The following times are individual observations measured from fault dispatch,
+not a latency distribution or performance guarantee. Observed cleared-state
+time includes the status-query delay; it is not the exact native cleanup instant.
+
+| Fault | MCP refusal | Cleared state observed | App received release | Result |
+| --- | ---: | ---: | ---: | --- |
+| Move | 241.08 ms | 439.13 ms | 242.88 ms | `cancelled` |
+| Resize | 189.02 ms | 354.70 ms | 188.64 ms | `cancelled` |
+| Real session lock | 60.96 ms | 130.60 ms | 76.52 ms | `cancelled` |
+| DPMS off | 64.40 ms | 263.39 ms | 66.47 ms | `cancelled` |
+| Target destruction | 7.03 ms | 299.71 ms | Not receivable | `stale_target` |
+
+All ten results were recomputed offline from the raw application journals,
+action responses, status records, primary traces, and window-manager snapshots.
+The ten original recordings fully decoded. Uniform video samples and selected
+fault/recovery frames were visually inspected, including target movement,
+resizing, disappearance, black lock/display-off intervals, and recovery.
+
+Video is supporting evidence, not the timing oracle. The recordings are not
+frame-exactly synchronized with the event journals. An attempted cross-clock
+conversion produced invalid sample positions; visual inspection instead used
+video-local timestamps without altering the original recordings. Event latency
+comes from the monotonic test journals, not the video timeline.
+
+The private evidence bundle retains original videos, per-file digests, passing
+and failed episodes, and setup/build records. Operational logs, grants, and
+machine-specific evidence are not committed to the public repository.
+
+## Supporting checks and retained failures
+
+- All 79 Python helper tests passed on the host and Fleet guest.
+- All seven portable CTests passed on the native guest and in a host Release
+ build, including the cached-geometry regression with `NDEBUG` enabled.
+- Two initial move episodes exceeded the 750 ms MCP-response bound at roughly
+ 865 ms and 985 ms while synchronous action recording was enabled. Native
+ release was prompt, but those episodes failed and remain retained. The final
+ matrix uses an independent observer service and keeps the same 750 ms bound.
+ It makes no passing recording-inclusive action-service latency claim.
+- A lock fixture without surfaces encountered Hyprland's missing-surface grace
+ period and exceeded its acknowledgment deadline. The final fixture supplies
+ opaque black shared-memory surfaces for every advertised output and waits for
+ real protocol lock/unlock acknowledgments. Recovery was graceful; the lock
+ client was not killed to unlock the session.
+- Newly launched targets could take primary focus during setup. The plugin
+ correctly revoked grants for that primary-client conflict. Setup now restores
+ and asserts the exact foreground actor before initial or recovery approval.
+ Driver exact-window foreground activation explicitly refuses on Hyprland;
+ the independent primary-seat fixture performed this authorized setup, bracketed
+ by Driver observations. Setup is not background-isolation evidence.
+
+Ordinary hosted CI supplements these focused native results. It does not certify
+compositor behavior or replace the canonical desktop matrix.
+
+## Remaining gates
+
+This pass covers native GTK fixtures, not a new real-app or physical-host
+certification. It does not establish Chromium/Ozone, Electron, GTK4, Qt6,
+XWayland, subsurface, fractional-scaling, multi-monitor, or broad input-method
+compatibility. Actions exercised one lane per episode; destruction inspected
+both lanes' resource counts, not concurrent two-lane fault delivery.
+
+Lock and DPMS are sampled states. An off/on transition entirely between samples
+is not proven to revoke authority. Escape recovery uses an atomic key packet,
+not interruption of a held-key stream. These remain separate test and design
+gates, along with the complete canonical desktop matrix at the final candidate.
+
+Production authorization UX, resource lifetime and hot-reload behavior,
+capability-aware observation, and the protocol/RFC decision remain open. Keep
+the PR draft. This evidence does not authorize merge, release, image publication,
+or production rollout.
diff --git a/libs/cua-driver/hyprland-plugin/tests/desktop_faults.py b/libs/cua-driver/hyprland-plugin/tests/desktop_faults.py
new file mode 100644
index 0000000000..0412969c69
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/desktop_faults.py
@@ -0,0 +1,370 @@
+"""External adversaries for a selected disposable Hyprland VM, never agent input.
+
+Native agent actions belong to Cua Driver. Run a separate fault-only episode to
+measure legitimate lock/DPMS primary-seat changes. No control claims that those
+changes are uninterrupted-user behavior. Lock-client failure can leave Wayland
+locked by design: discard the disposable guest if graceful recovery fails.
+"""
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import select
+import signal
+import subprocess
+import sys
+import time
+
+
+def _identity(pid):
+ if type(pid) is not int or pid <= 1:
+ raise ValueError('an exact non-init PID is required')
+ root = Path(f'/proc/{pid}')
+ fields = (root / 'stat').read_text().rsplit(')', 1)[1].split()
+ return {'pid': pid, 'starttime': fields[19], 'uid': root.stat().st_uid,
+ 'exe': str((root / 'exe').resolve(strict=True))}
+
+
+def _hypr(instance, *args):
+ return subprocess.check_output(['hyprctl', '-i', instance, *args],
+ text=True, timeout=2).strip()
+
+
+def _dpms_dispatch(value):
+ if value not in ('on', 'off'):
+ raise ValueError('explicit DPMS state required')
+ action = 'enable' if value == 'on' else 'disable'
+ return 'hl.dsp.dpms({ action = "' + action + '" })'
+
+
+def _same_compositor(identity, instance):
+ if _identity(identity['pid']) != identity:
+ raise RuntimeError('selected compositor identity changed')
+ instances = json.loads(subprocess.check_output(['hyprctl', '-j', 'instances'],
+ text=True, timeout=2))
+ if len([row for row in instances if row.get('instance') == instance and
+ row.get('pid') == identity['pid']]) != 1:
+ raise RuntimeError('selected compositor instance no longer matches PID')
+
+
+def _wait(predicate, timeout=3):
+ deadline = time.monotonic() + timeout
+ while True:
+ value = predicate()
+ if value:
+ return value
+ if time.monotonic() >= deadline:
+ raise TimeoutError('fault state was not acknowledged')
+ time.sleep(.02)
+
+
+def _watchdog(config, cancel_fd, target_fd):
+ """Private fixed-operation child; EOF also recovers after controller death."""
+ print('ARMED', flush=True)
+ readable = select.select([cancel_fd], [], [], config['seconds'])[0]
+ if readable and os.read(cancel_fd, 1) == b'C':
+ return
+ record = {'started_ns': time.monotonic_ns(), 'restored': False}
+ try:
+ _same_compositor(config['compositor'], config['instance'])
+ if config['kind'] == 'lock':
+ # Killing a lock client would leave an orphaned lock. Request its
+ # protocol unlock; the client also has its own monotonic deadline.
+ signal.pidfd_send_signal(target_fd, signal.SIGUSR1)
+ record['unlock_requested'] = True
+ else:
+ if _hypr(config['instance'], 'dispatch', _dpms_dispatch('on')) != 'ok':
+ raise RuntimeError('DPMS recovery dispatcher refused')
+ def recovered():
+ _same_compositor(config['compositor'], config['instance'])
+ rows = json.loads(_hypr(config['instance'], '-j', 'monitors', 'all'))
+ return rows and all(row.get('dpmsStatus') is True for row in rows)
+ _wait(recovered)
+ record['restored'] = True
+ except Exception as error:
+ record['error'] = str(error)
+ finally:
+ record['observed_ns'] = time.monotonic_ns()
+ Path(config['record']).write_text(json.dumps(record))
+
+
+class FaultController:
+ def __init__(self, *, compositor_pid, instance, target, disposable, evidence,
+ lock_fixture=None, move_to=None, resize_to=None, hold_seconds=12,
+ compositor_exe=Path('/usr/bin/Hyprland')):
+ if disposable is not True or platform.system() != 'Linux':
+ raise ValueError('faults require explicit disposable Linux guest confirmation')
+ if subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode:
+ raise ValueError('faults require a detected disposable virtual machine')
+ if not isinstance(instance, str) or not re.fullmatch(r'[A-Za-z0-9_.-]+', instance):
+ raise ValueError('invalid explicit compositor instance')
+ if os.environ.get('HYPRLAND_INSTANCE_SIGNATURE') != instance:
+ raise ValueError('selected compositor differs from the test session')
+ if type(hold_seconds) is not int or not 2 <= hold_seconds <= 20:
+ raise ValueError('fault recovery deadline must be 2..20 seconds')
+ if not re.fullmatch(r'0x[0-9a-fA-F]+', target.get('address', '')):
+ raise ValueError('exact hexadecimal fixture address required')
+ self.instance, self.target = instance, dict(target)
+ self.compositor = _identity(compositor_pid)
+ if (self.compositor['exe'] != str(Path(compositor_exe).resolve(strict=True)) or
+ Path(self.compositor['exe']).name != 'Hyprland' or
+ self.compositor['uid'] != os.getuid()):
+ raise ValueError('selected compositor executable or owner mismatch')
+ _same_compositor(self.compositor, instance)
+ self.fixture = _identity(target['pid'])
+ self.fixture_fd = os.pidfd_open(target['pid'])
+ try:
+ self._validate_fixture()
+ except BaseException:
+ os.close(self.fixture_fd)
+ raise
+ self.evidence = Path(evidence)
+ self.evidence.mkdir(parents=True, exist_ok=True)
+ if any((self.evidence / name).exists() for name in ('fault.json', 'restoration.json', 'watchdog.json')):
+ os.close(self.fixture_fd)
+ raise ValueError('fault evidence must not overwrite an existing episode')
+ self.lock_fixture = Path(lock_fixture) if lock_fixture else None
+ self.move_to, self.resize_to = move_to, resize_to
+ self.hold_seconds = hold_seconds
+ self.kind = self.before = self.lock_process = self.watchdog = None
+ self.lock_state = 'unknown'
+ self.cancel_fd = self.lock_fd = None
+ self.restoration = None
+ self.mutated = False
+ self.lock_buffer = b''
+ self.lock_events = []
+ self.lock_ack_ns = None
+
+ def _validate_fixture(self):
+ if select.select([self.fixture_fd], [], [], 0)[0] or _identity(self.target['pid']) != self.fixture:
+ raise ValueError('selected fixture PID exited or changed')
+ if self.fixture['uid'] != os.getuid():
+ raise ValueError('fixture is not owned by the test user')
+ cmd = Path(f'/proc/{self.target["pid"]}/cmdline').read_bytes().split(b'\0')
+ argv = [item.decode() for item in cmd if item]
+ fixture = Path(__file__).resolve().parents[2] / 'tests/fixtures/apps/linux/isolated-input/main.py'
+ # Explicit interpreter + canonical repository fixture; arbitrary process
+ # names, title matches, and user-supplied executable commands are refused.
+ if (len(argv) < 6 or Path(argv[1]).resolve() != fixture or
+ argv.count('--actor') != 1 or argv[argv.index('--actor') + 1] != 'Background' or
+ '--journal' not in argv):
+ raise ValueError('target is not the exact synthetic Background fixture')
+
+ def snapshot(self):
+ _same_compositor(self.compositor, self.instance)
+ if self.lock_process:
+ while True:
+ event = self._read_lock_event()
+ if event is None:
+ break
+ self.lock_events.append(event)
+ clients = json.loads(_hypr(self.instance, '-j', 'clients'))
+ selected = [row for row in clients if row.get('address') == self.target['address']]
+ if len(selected) > 1 or (selected and selected[0].get('pid') != self.target['pid']):
+ raise RuntimeError('fixture address changed ownership')
+ state = {'target': selected[0] if selected else None,
+ 'monitors': json.loads(_hypr(self.instance, '-j', 'monitors', 'all')),
+ 'activewindow': json.loads(_hypr(self.instance, '-j', 'activewindow')),
+ 'cursor': json.loads(_hypr(self.instance, '-j', 'cursorpos')),
+ 'lock': self.lock_state, 'lock_ack_ns': self.lock_ack_ns}
+ state['observed_ns'] = time.monotonic_ns()
+ return state
+
+ def _dispatch(self, command, value):
+ if not ((command == 'dpms' and value in ('on', 'off')) or
+ (command in ('movewindowpixel', 'resizewindowpixel') and
+ re.fullmatch(r'exact -?\d+ -?\d+,address:' + re.escape(self.target['address']), value))):
+ raise ValueError('unsupported fault dispatch')
+ _same_compositor(self.compositor, self.instance)
+ if command != 'dpms':
+ self._validate_fixture()
+ if self.snapshot()['target'] is None:
+ raise RuntimeError('fixture disappeared before dispatch')
+ if command == 'dpms':
+ dispatch = _dpms_dispatch(value)
+ else:
+ x, y = value.split(',')[0].split()[1:]
+ operation = 'move' if command == 'movewindowpixel' else 'resize'
+ dispatch = ('hl.dsp.window.' + operation + '({ window = "address:' +
+ self.target['address'] + '", x = ' + x + ', y = ' + y + ' })')
+ if _hypr(self.instance, 'dispatch', dispatch) != 'ok':
+ raise RuntimeError('fault dispatcher did not acknowledge request')
+
+ def _arm(self, kind):
+ reader, self.cancel_fd = os.pipe()
+ config = {'kind': kind, 'seconds': self.hold_seconds, 'compositor': self.compositor,
+ 'instance': self.instance, 'record': str(self.evidence / 'watchdog.json')}
+ passed = (reader,) + ((self.lock_fd,) if self.lock_fd is not None else ())
+ try:
+ self.watchdog = subprocess.Popen([sys.executable, str(Path(__file__).resolve()),
+ '--watchdog', json.dumps(config), str(reader), str(self.lock_fd or -1)],
+ pass_fds=passed, stdout=subprocess.PIPE, text=True, start_new_session=True)
+ if (not select.select([self.watchdog.stdout], [], [], 2)[0] or
+ self.watchdog.stdout.readline().strip() != 'ARMED'):
+ raise RuntimeError('fault recovery watchdog did not arm')
+ finally:
+ os.close(reader)
+
+ def _read_lock_event(self):
+ if b'\n' not in self.lock_buffer:
+ if not select.select([self.lock_process.stdout], [], [], 0)[0]:
+ return None
+ chunk = os.read(self.lock_process.stdout.fileno(), 4096)
+ if not chunk:
+ if self.lock_state == 'unlocked':
+ return None
+ raise RuntimeError('lock fixture exited before acknowledged recovery')
+ self.lock_buffer += chunk
+ if len(self.lock_buffer) > 16384:
+ raise RuntimeError('oversized lock fixture response')
+ if b'\n' not in self.lock_buffer:
+ return None
+ line, self.lock_buffer = self.lock_buffer.split(b'\n', 1)
+ event = json.loads(line)
+ self.lock_state, self.lock_ack_ns = event['event'], event['observed_ns']
+ return event
+
+ def _lock_event(self, expected):
+ event = self.lock_events.pop(0) if self.lock_events else _wait(self._read_lock_event)
+ if event['event'] != expected:
+ raise RuntimeError(f'unexpected lock protocol event: {event}')
+ return event
+
+ def apply(self, kind):
+ if self.kind is not None or kind not in ('destroy', 'move', 'resize', 'lock', 'dpms'):
+ raise ValueError('one supported fault per controller')
+ self._validate_fixture()
+ self.before = self.snapshot()
+ if self.before['target'] is None:
+ raise ValueError('selected fixture is not mapped')
+ self.kind = kind
+ record = {'kind': kind, 'before': self.before, 'fault_ns': None, 'acknowledged': False}
+ try:
+ if kind in ('move', 'resize'):
+ target = self.before['target']
+ if target.get('floating') is not True or target.get('fullscreen', 0):
+ raise ValueError('geometry faults require an already-floating synthetic fixture')
+ key, command = ('at', 'movewindowpixel') if kind == 'move' else ('size', 'resizewindowpixel')
+ values = self.move_to if kind == 'move' else self.resize_to
+ if (not isinstance(values, (tuple, list)) or len(values) != 2 or
+ any(type(v) is not int or abs(v) > 16384 for v in values) or
+ (kind == 'resize' and min(values) < 1) or list(values) == target[key]):
+ raise ValueError('explicit changed bounded geometry required')
+ record['fault_ns'] = time.monotonic_ns()
+ self.mutated = True
+ self._dispatch(command, f'exact {values[0]} {values[1]},address:{self.target["address"]}')
+ _wait(lambda: (self.snapshot()['target'] or {}).get(key) == list(values))
+ elif kind == 'destroy':
+ record['fault_ns'] = time.monotonic_ns()
+ self.mutated = True
+ signal.pidfd_send_signal(self.fixture_fd, signal.SIGTERM)
+ _wait(lambda: select.select([self.fixture_fd], [], [], 0)[0] and self.snapshot()['target'] is None)
+ elif kind == 'dpms':
+ if not self.before['monitors'] or not all(row.get('dpmsStatus') is True for row in self.before['monitors']):
+ raise ValueError('DPMS fault requires all existing monitors acknowledged on')
+ self._arm(kind)
+ record['fault_ns'] = time.monotonic_ns()
+ self.mutated = True
+ self._dispatch('dpms', 'off')
+ _wait(lambda: self._dpms(False))
+ else:
+ if not self.lock_fixture or self.lock_fixture.name != 'session_lock_fixture':
+ raise ValueError('owned session_lock_fixture binary required')
+ # The helper connects to the selected compositor using its
+ # inherited Wayland display; SO_PEERCRED validation is in C.
+ self.lock_process = subprocess.Popen([str(self.lock_fixture.resolve(strict=True)),
+ str(self.hold_seconds * 1000), str(self.compositor['pid'])],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, start_new_session=True)
+ self.lock_fd = os.pidfd_open(self.lock_process.pid)
+ self._lock_event('ready')
+ self._arm(kind)
+ record['fault_ns'] = time.monotonic_ns()
+ self.mutated = True
+ self.lock_process.stdin.write('LOCK\n')
+ self.lock_process.stdin.flush()
+ record['protocol'] = self._lock_event('locked')
+ after = self.snapshot()
+ if kind == 'lock' and after['lock'] != 'locked':
+ raise RuntimeError('session lock ended before fault acknowledgment')
+ if kind == 'dpms' and not all(row.get('dpmsStatus') is False for row in after['monitors']):
+ raise RuntimeError('DPMS fault ended before acknowledgment')
+ record.update(acknowledged=True, after=after, observed_ns=time.monotonic_ns())
+ return record
+ except BaseException as error:
+ record.update(error=str(error), observed_ns=time.monotonic_ns())
+ raise
+ finally:
+ (self.evidence / 'fault.json').write_text(json.dumps(record))
+
+ def _dpms(self, value):
+ rows = self.snapshot()['monitors']
+ expected = {row['name'] for row in self.before['monitors']}
+ return {row['name'] for row in rows} == expected and all(row.get('dpmsStatus') is value for row in rows)
+
+ def rollback(self):
+ if self.restoration is not None:
+ return self.restoration
+ record = {'kind': self.kind, 'restored': False, 'started_ns': time.monotonic_ns()}
+ try:
+ if self.mutated and self.kind in ('move', 'resize'):
+ key, command = ('at', 'movewindowpixel') if self.kind == 'move' else ('size', 'resizewindowpixel')
+ values = self.before['target'][key]
+ self._dispatch(command, f'exact {values[0]} {values[1]},address:{self.target["address"]}')
+ _wait(lambda: (self.snapshot()['target'] or {}).get(key) == values)
+ elif self.mutated and self.kind == 'dpms':
+ self._dispatch('dpms', 'on')
+ _wait(lambda: self._dpms(True))
+ elif self.mutated and self.kind == 'lock' and self.lock_process:
+ # Safe even if the controller lost its stdin channel. Never
+ # SIGKILL/SIGTERM a client that might own a protocol lock.
+ if self.lock_process.poll() is None:
+ signal.pidfd_send_signal(self.lock_fd, signal.SIGUSR1)
+ record['protocol'] = self._lock_event('unlocked')
+ if self.lock_process.wait(timeout=3) != 0:
+ raise RuntimeError('lock fixture reported failed recovery')
+ record.update(restored=True, after=self.snapshot(),
+ target_recreated=False if self.kind == 'destroy' else None)
+ if self.cancel_fd is not None:
+ try:
+ os.write(self.cancel_fd, b'C')
+ except BrokenPipeError:
+ pass # Timed recovery may already have completed.
+ self.restoration = record
+ return record
+ except BaseException as error:
+ record['error'] = str(error)
+ raise
+ finally:
+ record['observed_ns'] = time.monotonic_ns()
+ (self.evidence / 'restoration.json').write_text(json.dumps(record))
+
+ def close(self):
+ try:
+ self.rollback()
+ finally:
+ # EOF asks the independent watchdog to restore on any failure.
+ for name in ('cancel_fd', 'fixture_fd', 'lock_fd'):
+ fd = getattr(self, name)
+ if fd is not None:
+ os.close(fd)
+ setattr(self, name, None)
+ for process in (self.lock_process, self.watchdog):
+ if process:
+ if process.stdin:
+ process.stdin.close()
+ if process.poll() is not None and process.stdout:
+ process.wait(timeout=1)
+ process.stdout.close()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_):
+ self.close()
+
+
+if __name__ == '__main__':
+ if len(sys.argv) != 5 or sys.argv[1] != '--watchdog':
+ raise SystemExit('Private watchdog entry only; use FaultController from the harness')
+ _watchdog(json.loads(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
diff --git a/libs/cua-driver/hyprland-plugin/tests/desktop_faults_test.py b/libs/cua-driver/hyprland-plugin/tests/desktop_faults_test.py
new file mode 100644
index 0000000000..648dcb28b6
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/desktop_faults_test.py
@@ -0,0 +1,261 @@
+"""Safety/recovery contracts; no compositor or host desktop is touched."""
+import json
+from pathlib import Path
+import signal
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+
+import desktop_faults as faults
+
+
+class DesktopFaultTest(unittest.TestCase):
+ def controller(self, directory):
+ value = faults.FaultController.__new__(faults.FaultController)
+ value.instance = 'selected-instance'
+ value.target = {'pid': 42, 'address': '0xab'}
+ value.compositor = {'pid': 10, 'starttime': '77', 'uid': 1000, 'exe': '/usr/bin/Hyprland'}
+ value.fixture = {'pid': 42, 'starttime': '88', 'uid': 1000, 'exe': '/usr/bin/python3'}
+ value.fixture_fd = 7
+ value.evidence = Path(directory)
+ value.move_to, value.resize_to = (110, 130), (680, 560)
+ value.hold_seconds = 12
+ value.kind = value.before = value.lock_process = value.watchdog = None
+ value.cancel_fd = value.lock_fd = value.restoration = None
+ value.lock_state, value.lock_buffer = 'unknown', b''
+ value.lock_events, value.lock_ack_ns = [], None
+ value.mutated = False
+ return value
+
+ def state(self, **target):
+ return {'target': {'pid': 42, 'address': '0xab', 'at': [70, 100],
+ 'size': [600, 500], 'floating': True, **target},
+ 'monitors': [{'name': 'virtual-1', 'dpmsStatus': True}],
+ 'lock': 'unknown', 'observed_ns': 1}
+
+ def test_host_and_missing_confirmation_rejected_before_commands(self):
+ with patch('desktop_faults.platform.system', return_value='Darwin'), \
+ patch('desktop_faults.subprocess.run') as run:
+ for disposable in (False, True):
+ with self.assertRaises(ValueError):
+ faults.FaultController(compositor_pid=10, instance='test', target={},
+ disposable=disposable, evidence=Path('/unused'))
+ run.assert_not_called()
+
+ def test_bare_metal_rejected_before_process_lookup(self):
+ with patch('desktop_faults.platform.system', return_value='Linux'), \
+ patch('desktop_faults.subprocess.run', return_value=Mock(returncode=1)), \
+ patch('desktop_faults._identity') as identity:
+ with self.assertRaisesRegex(ValueError, 'virtual machine'):
+ faults.FaultController(compositor_pid=10, instance='test', target={},
+ disposable=True, evidence=Path('/unused'))
+ identity.assert_not_called()
+
+ def test_stale_compositor_identity_rejected_before_hyprctl(self):
+ with patch('desktop_faults._identity', return_value={'starttime': 'replacement'}), \
+ patch('desktop_faults.subprocess.check_output') as command:
+ with self.assertRaisesRegex(RuntimeError, 'identity changed'):
+ faults._same_compositor({'pid': 10, 'starttime': 'original'}, 'instance')
+ command.assert_not_called()
+
+ def test_instance_must_match_pid(self):
+ original = {'pid': 10, 'starttime': '77'}
+ with patch('desktop_faults._identity', return_value=original), \
+ patch('desktop_faults.subprocess.check_output', return_value='[{"instance":"other","pid":10}]'):
+ with self.assertRaisesRegex(RuntimeError, 'instance'):
+ faults._same_compositor(original, 'selected')
+
+ def test_address_reuse_fails_closed(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ with patch('desktop_faults._same_compositor'), \
+ patch('desktop_faults._hypr', return_value='[{"address":"0xab","pid":43}]'):
+ with self.assertRaisesRegex(RuntimeError, 'ownership'):
+ value.snapshot()
+
+ def test_fixture_pidfd_exit_prevents_retargeting(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ with patch('desktop_faults.select.select', return_value=([7], [], [])), \
+ patch('desktop_faults._identity') as identity:
+ with self.assertRaisesRegex(ValueError, 'exited'):
+ value._validate_fixture()
+ identity.assert_not_called()
+
+ def test_foreground_fixture_is_not_a_fault_target(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ fixture = Path(faults.__file__).resolve().parents[2] / 'tests/fixtures/apps/linux/isolated-input/main.py'
+ argv = f'python3\0{fixture}\0--actor\0Foreground\0--journal\0test.json\0'.encode()
+ with patch('desktop_faults.select.select', return_value=([], [], [])), \
+ patch('desktop_faults._identity', return_value=value.fixture), \
+ patch('desktop_faults.os.getuid', return_value=1000), \
+ patch('desktop_faults.Path.read_bytes', return_value=argv):
+ with self.assertRaisesRegex(ValueError, 'Background'):
+ value._validate_fixture()
+
+ def test_destroy_signals_only_bound_pidfd_and_records_disappearance(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ absent = {**self.state(), 'target': None}
+ with patch.object(value, '_validate_fixture'), \
+ patch.object(value, 'snapshot', side_effect=[self.state(), absent, absent]), \
+ patch('desktop_faults.select.select', return_value=([7], [], [])), \
+ patch('desktop_faults.signal.pidfd_send_signal', create=True) as send:
+ record = value.apply('destroy')
+ send.assert_called_once_with(7, signal.SIGTERM)
+ self.assertTrue(record['acknowledged'])
+ self.assertIsNone(record['after']['target'])
+ self.assertLessEqual(record['fault_ns'], record['observed_ns'])
+ self.assertEqual(json.loads((Path(directory) / 'fault.json').read_text()), record)
+
+ def test_move_requires_nontrivial_floating_target(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ with patch.object(value, '_validate_fixture'), \
+ patch.object(value, 'snapshot', return_value=self.state(floating=False)), \
+ patch.object(value, '_dispatch') as dispatch:
+ with self.assertRaisesRegex(ValueError, 'already-floating'):
+ value.apply('move')
+ value.rollback()
+ dispatch.assert_not_called()
+
+ def test_move_ack_and_restore_exact_selected_address(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ original, moved = self.state(), self.state(at=[110, 130])
+ with patch.object(value, '_validate_fixture'), \
+ patch.object(value, 'snapshot', side_effect=[original, moved, moved, original, original]), \
+ patch.object(value, '_dispatch') as dispatch:
+ value.apply('move')
+ restored = value.rollback()
+ self.assertIs(value.rollback(), restored)
+ self.assertEqual(dispatch.call_args_list[0].args,
+ ('movewindowpixel', 'exact 110 130,address:0xab'))
+ self.assertEqual(dispatch.call_args_list[1].args,
+ ('movewindowpixel', 'exact 70 100,address:0xab'))
+ self.assertTrue(restored['restored'])
+
+ def test_dpms_rejects_initial_off_without_forcing_on_in_cleanup(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ state = self.state()
+ state['monitors'][0]['dpmsStatus'] = False
+ with patch.object(value, '_validate_fixture'), \
+ patch.object(value, 'snapshot', return_value=state), \
+ patch.object(value, '_dispatch') as dispatch, \
+ patch.object(value, '_arm') as arm:
+ with self.assertRaisesRegex(ValueError, 'acknowledged on'):
+ value.apply('dpms')
+ value.rollback()
+ arm.assert_not_called()
+ dispatch.assert_not_called()
+
+ def test_dpms_watchdog_arms_before_mutation_and_survives_failed_ack(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ order = []
+ with patch.object(value, '_validate_fixture'), \
+ patch.object(value, 'snapshot', return_value=self.state()), \
+ patch.object(value, '_arm', side_effect=lambda kind: order.append('armed')), \
+ patch.object(value, '_dispatch', side_effect=lambda *args: order.append(args)), \
+ patch('desktop_faults._wait', side_effect=TimeoutError('no ack')):
+ with self.assertRaises(TimeoutError):
+ value.apply('dpms')
+ self.assertEqual(order, ['armed', ('dpms', 'off')])
+ self.assertTrue(value.mutated)
+ record = json.loads((Path(directory) / 'fault.json').read_text())
+ self.assertFalse(record['acknowledged'])
+ self.assertEqual(record['error'], 'no ack')
+
+ def test_failed_restoration_never_cancels_watchdog(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ value.kind, value.mutated, value.cancel_fd = 'dpms', True, 8
+ with patch.object(value, '_dispatch', side_effect=RuntimeError('unavailable')), \
+ patch('desktop_faults.os.write') as write:
+ with self.assertRaises(RuntimeError):
+ value.rollback()
+ write.assert_not_called()
+ self.assertIsNone(value.restoration)
+ self.assertFalse(json.loads((Path(directory) / 'restoration.json').read_text())['restored'])
+
+ def test_lock_recovery_uses_graceful_signal_not_termination(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ value.kind, value.mutated, value.lock_fd = 'lock', True, 9
+ value.lock_process = Mock()
+ value.lock_process.poll.return_value = None
+ value.lock_process.wait.return_value = 0
+ with patch.object(value, '_lock_event', return_value={'event': 'unlocked'}) as acknowledgment, \
+ patch.object(value, 'snapshot', return_value=self.state()), \
+ patch('desktop_faults.signal.pidfd_send_signal', create=True) as send:
+ self.assertTrue(value.rollback()['restored'])
+ send.assert_called_once_with(9, signal.SIGUSR1)
+ acknowledgment.assert_called_once_with('unlocked')
+ value.lock_process.terminate.assert_not_called()
+ value.lock_process.kill.assert_not_called()
+
+ def test_watchdog_controller_death_restores_dpms_with_readback(self):
+ with tempfile.TemporaryDirectory() as directory:
+ config = {'kind': 'dpms', 'seconds': 12, 'compositor': {'pid': 10},
+ 'instance': 'selected', 'record': str(Path(directory) / 'watchdog.json')}
+ with patch('desktop_faults.select.select', return_value=([8], [], [])), \
+ patch('desktop_faults.os.read', return_value=b''), \
+ patch('desktop_faults._same_compositor'), \
+ patch('desktop_faults._hypr', side_effect=['ok', '[{"dpmsStatus":true}]']) as hypr:
+ faults._watchdog(config, 8, -1)
+ self.assertEqual(hypr.call_args_list[0].args, ('selected', 'dispatch', 'hl.dsp.dpms({ action = "enable" })'))
+ self.assertTrue(json.loads(Path(config['record']).read_text())['restored'])
+
+ def test_watchdog_cancel_does_not_mutate_desktop(self):
+ with patch('desktop_faults.select.select', return_value=([8], [], [])), \
+ patch('desktop_faults.os.read', return_value=b'C'), \
+ patch('desktop_faults._same_compositor') as verify:
+ faults._watchdog({'seconds': 12}, 8, -1)
+ verify.assert_not_called()
+
+ def test_dpms_monitor_set_change_is_not_restoration(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ value.before = self.state()
+ changed = self.state()
+ changed['monitors'][0]['name'] = 'replacement'
+ with patch.object(value, 'snapshot', return_value=changed):
+ self.assertFalse(value._dpms(True))
+
+ def test_arbitrary_dispatch_is_rejected_before_compositor_access(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ with patch('desktop_faults._same_compositor') as identity:
+ for command, argument in [('exec', 'anything'), ('dpms', 'toggle'),
+ ('movewindowpixel', 'exact 1 2,address:0xcd')]:
+ with self.assertRaises(ValueError):
+ value._dispatch(command, argument)
+ identity.assert_not_called()
+
+ def test_buffered_unlock_acknowledgment_is_not_lost(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ value.lock_process = Mock()
+ value.lock_buffer = (b'{"event":"locked","observed_ns":12}\n'
+ b'{"event":"unlocked","observed_ns":15}\n')
+ self.assertEqual(value._lock_event('locked')['observed_ns'], 12)
+ self.assertEqual(value._lock_event('unlocked')['observed_ns'], 15)
+ self.assertEqual(value.lock_state, 'unlocked')
+
+ def test_resize_restores_exact_size(self):
+ with tempfile.TemporaryDirectory() as directory:
+ value = self.controller(directory)
+ original, resized = self.state(), self.state(size=[680, 560])
+ with patch.object(value, '_validate_fixture'), \
+ patch.object(value, 'snapshot', side_effect=[original, resized, resized, original, original]), \
+ patch.object(value, '_dispatch') as dispatch:
+ value.apply('resize')
+ self.assertTrue(value.rollback()['restored'])
+ self.assertEqual(dispatch.call_args_list[1].args,
+ ('resizewindowpixel', 'exact 600 500,address:0xab'))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/desktop_state_evidence.py b/libs/cua-driver/hyprland-plugin/tests/desktop_state_evidence.py
new file mode 100644
index 0000000000..26da6def86
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/desktop_state_evidence.py
@@ -0,0 +1,156 @@
+"""Fail-closed evidence for native desktop-state faults, separate from dispatch.
+
+Destroyed surfaces cannot acknowledge release. Their case instead requires a
+prompt typed refusal, compositor-confirmed disappearance, and cleared agent
+state. Surviving surfaces must additionally journal a matching release.
+"""
+from collections import Counter
+import math
+
+from lifecycle_evidence import held_release, primary_wire_events
+from primary_trace import analyze
+
+
+CASES = ("destroy", "move", "resize", "lock", "dpms")
+REFUSALS = {
+ "destroy": {"cancelled", "stale_target"},
+ "move": {"cancelled", "stale_target"},
+ "resize": {"cancelled", "stale_target"},
+ "lock": {"cancelled", "background_unavailable", "desktop_changed"},
+ "dpms": {"cancelled", "background_unavailable", "desktop_changed"},
+}
+PRIMARY_FIELDS = {"application_delta", "wire_inputs", "wire_focus", "compositor_inputs",
+ "compositor_focus", "max_cursor_displacement", "cursor_path", "wm_before", "wm_after"}
+
+
+def focus_transitions(events):
+ streams = {"pointer": [], "keyboard": []}
+ for event in events:
+ family = "pointer" if "pointer" in event else "keyboard"
+ if not streams[family] or streams[family][-1] != event:
+ streams[family].append(event)
+ return streams
+
+
+def agent_cleared(status, lane):
+ matches = [row for row in status["experiment"]["lanes"] if row["lane"] == lane]
+ assert len(matches) == 1, "missing exact agent lane"
+ state = matches[0]
+ for name in ("lease_active", "drag_active", "pointer_focus", "keyboard_focus"):
+ assert state.get(name) is False, "agent state not cleared: " + name
+ for name in ("held_button", "held_keys"):
+ assert type(state.get(name)) is int and state[name] == 0, "held agent state: " + name
+ return {"agent_authority_cleared": True, "agent_input_state_cleared": True}
+
+
+def resource_counts(status):
+ lanes = status["experiment"]["lanes"]
+ assert {row["lane"] for row in lanes} == {0, 1} and len(lanes) == 2
+ result = []
+ for row in sorted(lanes, key=lambda item: item["lane"]):
+ counts = {name: row[name] for name in ("seat_resources", "pointer_resources", "keyboard_resources")}
+ assert all(type(value) is int and value >= 0 for value in counts.values())
+ result.append({"lane": row["lane"], **counts})
+ return result
+
+
+def destroyed_resources_pruned(baseline, before, after):
+ # The host captures this baseline before launching the exact target client,
+ # after the observer, foreground fixture, and overlay have settled.
+ assert baseline == resource_counts({"experiment": {"lanes": baseline}})
+ initial, final = resource_counts(before), resource_counts(after)
+ for base, live in zip(baseline, initial):
+ for name in ("seat_resources", "pointer_resources", "keyboard_resources"):
+ assert live[name] > base[name], "target resources were not observed before destruction"
+ assert final == baseline, "destroyed client resources were not pruned to pre-target baseline"
+ return {"destroyed_client_resources_pruned": True}
+
+
+def cancellation(case, rows, *, fault_ns, observed_ns, response_ns, response,
+ status_ns, status, lane, duration_ms=2000, maximum_latency_ms=750,
+ target_destroyed=False):
+ assert case in CASES
+ stamps = (fault_ns, observed_ns, response_ns, status_ns)
+ assert all(type(value) is int and value > 0 for value in stamps)
+ presses = [row for row in rows if row["kind"] == "button-press"]
+ assert len(presses) == 1, "need exactly one received press"
+ press = presses[0]["time"]
+ assert type(press) is int and press < fault_ns <= observed_ns, "fault must follow received press"
+ normal_end = press + duration_ms * 1_000_000
+ deadline = fault_ns + maximum_latency_ms * 1_000_000
+ assert deadline < normal_end, "natural completion could satisfy cancellation deadline"
+ assert fault_ns <= response_ns <= deadline, "typed cancellation was not prompt"
+ assert fault_ns <= status_ns <= deadline, "agent cleanup was not observed promptly"
+ assert response.get("isError") is True, "normal drag success is not cancellation"
+ reason = response.get("structuredContent", {}).get("reason")
+ assert reason in REFUSALS[case], "missing case-specific structured refusal"
+ result = agent_cleared(status, lane)
+ assert not any(row["kind"] in ("key-press", "key-release", "scroll") for row in rows), "unexpected non-drag input delivery"
+ if case == "destroy":
+ assert target_destroyed is True, "target disappearance not independently observed"
+ result["release_oracle"] = "destroyed_surface_not_receivable"
+ else:
+ result.update(held_release(rows, fault_ns=fault_ns, maximum_latency_ms=maximum_latency_ms))
+ result["release_oracle"] = "application_journal"
+ return {**result, "action_refusal": reason,
+ "refusal_latency_ms": (response_ns - fault_ns) / 1_000_000,
+ "cleanup_latency_ms": (status_ns - fault_ns) / 1_000_000}
+
+
+def recovery_input(rows, status, lane):
+ keys = [row for row in rows if row["kind"] in ("key-press", "key-release")]
+ assert [row["kind"] for row in keys] == ["key-press", "key-release"], "recovery key pair missing or duplicated"
+ assert all(row.get("key") == "Escape" for row in keys), "unexpected recovery key"
+ assert keys[0]["time"] <= keys[1]["time"], "unordered recovery keys"
+ assert not any(row["kind"] in ("button-press", "button-release", "scroll") for row in rows), "unexpected recovery pointer input"
+ selected = [row for row in status["experiment"]["lanes"] if row["lane"] == lane]
+ assert len(selected) == 1 and selected[0].get("held_keys") == 0 and selected[0].get("held_button") == 0
+ return {"freshly_approved_recovery_received": True, "recovery_key_balanced": True}
+
+
+def primary_effect(before, after, wire, trace, wm_before, wm_after):
+ """Summarize measured effects, without assuming locks preserve focus/grabs.
+
+ Focus transition categories ignore duplicate compositor bookkeeping. Input
+ event counts and press/release states remain exact, so normalization cannot
+ erase a transient injected click or warp-and-return.
+ """
+ report = analyze(trace)
+ assert report.get("telemetry_complete") is True, "missing complete compositor trace"
+ assert before.get("held") is True, "primary grab not established"
+ for item in (before, after):
+ assert all(key in item for key in ("clicks", "keys", "held", "scroll", "motion"))
+ assert after["keys"].startswith(before["keys"]), "foreground key history was replaced"
+ primary = [row for row in trace["events"] if row[5] == 0]
+ inputs = Counter((row[2], row[6]) for row in primary
+ if row[2] in ("pointer_button", "pointer_axis", "keyboard_key"))
+ focus = focus_transitions(row[2] for row in primary if "focus" in row[2]
+ or row[2] in ("pointer_enter", "pointer_leave", "keyboard_enter", "keyboard_leave"))
+ events = primary_wire_events(wire)
+ wire_inputs = Counter(event for event in events
+ if event.rsplit(".", 1)[1] not in ("enter", "leave"))
+ delta = {key: after[key] - before[key] for key in ("clicks", "scroll", "motion")}
+ assert all(type(value) is int and value >= 0 for value in delta.values())
+ return {"application_delta": {**delta, "keys": after["keys"][len(before["keys"]):],
+ "held": after["held"]},
+ "wire_inputs": sorted([key, value] for key, value in wire_inputs.items()),
+ "wire_focus": focus_transitions(event for event in events if event not in wire_inputs),
+ "compositor_inputs": sorted([kind, state, count] for (kind, state), count in inputs.items()),
+ "compositor_focus": focus,
+ "max_cursor_displacement": report["max_primary_displacement_px"],
+ "cursor_path": [row[3:5] for row in primary if row[2] == "cursor"],
+ "wm_before": wm_before, "wm_after": wm_after}
+
+
+def compare_control(control, actual, identity):
+ assert control.get("result") == "passed" and control.get("mode") == "control", "unproven control"
+ assert control.get("identity") == identity, "control belongs to another fixture, fault, or candidate"
+ expected = control["primary_effect"]
+ assert set(expected) == PRIMARY_FIELDS and set(actual) == PRIMARY_FIELDS, "incomplete foreground evidence"
+ for key in expected:
+ assert key in actual, "missing independent evidence: " + key
+ if key == "max_cursor_displacement":
+ assert math.isfinite(actual[key]) and abs(actual[key] - expected[key]) <= 0.01, "extra primary cursor displacement"
+ else:
+ assert actual[key] == expected[key], "agent added foreground effects: " + key
+ return {"fault_only_control_matched": True, "no_extra_foreground_effects": True}
diff --git a/libs/cua-driver/hyprland-plugin/tests/desktop_state_evidence_test.py b/libs/cua-driver/hyprland-plugin/tests/desktop_state_evidence_test.py
new file mode 100644
index 0000000000..dfb795bc6a
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/desktop_state_evidence_test.py
@@ -0,0 +1,252 @@
+"""Adversarial evidence checks; no desktop or plugin required."""
+from copy import deepcopy
+from contextlib import redirect_stdout
+import io
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import MagicMock, patch
+
+from desktop_state_evidence import agent_cleared, cancellation, compare_control, primary_effect, destroyed_resources_pruned, recovery_input
+
+
+def status():
+ return {"experiment": {"lanes": [{"lane": 0, "lease_active": False,
+ "drag_active": False, "pointer_focus": False, "keyboard_focus": False,
+ "held_button": 0, "held_keys": 0}]}}
+
+
+def trace(events=()):
+ kinds = [("start", 0, 0, 0, 0), *events, ("stop", 0, 0, 0, 0)]
+ rows = [[index, index * 1_000_000, kind, x, y, actor, state]
+ for index, (kind, x, y, actor, state) in enumerate(kinds, 1)]
+ return {"hook": True, "active": False, "overflow": False, "timed_out": False,
+ "count": len(rows), "events": rows}
+
+
+class CancellationTest(unittest.TestCase):
+ def test_destroyed_resources_require_real_pre_target_baseline_and_pruning(self):
+ baseline = [{"lane": lane, "seat_resources": 2, "pointer_resources": 2, "keyboard_resources": 2}
+ for lane in (0, 1)]
+ before = {"experiment": {"lanes": [{**row, "seat_resources": 3, "pointer_resources": 3, "keyboard_resources": 3}
+ for row in baseline]}}
+ after = {"experiment": {"lanes": baseline}}
+ self.assertTrue(destroyed_resources_pruned(baseline, before, after)["destroyed_client_resources_pruned"])
+ for initial, final in ((after, after), (before, before)):
+ with self.assertRaises(AssertionError):
+ destroyed_resources_pruned(baseline, initial, final)
+
+ def arguments(self):
+ return {"fault_ns": 1_100_000_000, "observed_ns": 1_110_000_000,
+ "response_ns": 1_120_000_000, "status_ns": 1_130_000_000,
+ "response": {"isError": True, "structuredContent": {"reason": "cancelled"}},
+ "status": status(), "lane": 0}
+
+ def rows(self):
+ return [{"kind": "button-press", "button": 1, "time": 1_000_000_000},
+ {"kind": "button-release", "button": 1, "time": 1_150_000_000}]
+
+ def test_surviving_target_requires_all_independent_evidence(self):
+ for case in ("move", "resize", "lock", "dpms"):
+ result = cancellation(case, self.rows(), **self.arguments())
+ self.assertEqual(result["release_latency_ms"], 50)
+ self.assertTrue(result["agent_authority_cleared"])
+
+ def test_drag_cannot_hide_other_input(self):
+ for kind in ("key-press", "key-release", "scroll"):
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ cancellation("move", self.rows() + [{"kind": kind, "time": 1_200_000_000}], **self.arguments())
+
+ def test_recovery_requires_exact_pair_before_cleanup(self):
+ pair = [{"kind": "key-press", "key": "Escape", "time": 1},
+ {"kind": "key-release", "key": "Escape", "time": 2}]
+ self.assertTrue(recovery_input(pair, status(), 0)["recovery_key_balanced"])
+ for bad in (pair[:1], pair * 2, pair + [{"kind": "scroll"}],
+ [{**row, "key": "a"} for row in pair]):
+ with self.subTest(rows=bad), self.assertRaises(AssertionError):
+ recovery_input(bad, status(), 0)
+ held = status()
+ held["experiment"]["lanes"][0]["held_keys"] = 1
+ with self.assertRaises(AssertionError):
+ recovery_input(pair, held, 0)
+
+ def test_destroyed_target_does_not_require_impossible_release(self):
+ result = cancellation("destroy", self.rows()[:1], **self.arguments(), target_destroyed=True)
+ self.assertEqual(result["release_oracle"], "destroyed_surface_not_receivable")
+ with self.assertRaises(AssertionError):
+ cancellation("destroy", self.rows()[:1], **self.arguments())
+
+ def test_missing_release_or_pre_fault_release_fails(self):
+ for rows in (self.rows()[:1], [], [{**row, "time": row["time"] - 100_000_000} for row in self.rows()]):
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ cancellation("move", rows, **self.arguments())
+
+ def test_late_or_naturally_completed_drag_cannot_pass(self):
+ for update in ({"response_ns": 3_000_000_000}, {"status_ns": 3_000_000_000},
+ {"duration_ms": 800}, {"fault_ns": 900_000_000},
+ {"response": {"structuredContent": {"effect": "unverifiable"}}},
+ {"response": {"isError": True, "structuredContent": {"reason": "lease_expired"}}}):
+ with self.subTest(update=update), self.assertRaises(AssertionError):
+ cancellation("move", self.rows(), **{**self.arguments(), **update})
+
+ def test_cleanup_requires_every_owned_state_field(self):
+ for name in ("lease_active", "drag_active", "pointer_focus", "keyboard_focus", "held_button", "held_keys"):
+ for missing in (False, True):
+ data = status()
+ if missing:
+ del data["experiment"]["lanes"][0][name]
+ else:
+ data["experiment"]["lanes"][0][name] = 1
+ with self.subTest(name=name, missing=missing), self.assertRaises(AssertionError):
+ agent_cleared(data, 0)
+ with self.assertRaises(AssertionError):
+ agent_cleared(status(), 1)
+
+
+class ControlTest(unittest.TestCase):
+ def setUp(self):
+ self.before = {"held": True, "clicks": 1, "keys": "", "scroll": 0, "motion": 0}
+ self.wm = {"pid": 123, "address": "0x123", "cursor": {"x": 0, "y": 0}, "workspace": 1}
+ self.identity = {"case": "lock", "source_sha": "a" * 40}
+
+ def effect(self, after=None, events=(), wire="", wm_after=None):
+ return primary_effect(self.before, after or self.before, wire, trace(events),
+ self.wm, wm_after or self.wm)
+
+ def control(self, effect):
+ return {"result": "passed", "mode": "control", "identity": self.identity,
+ "primary_effect": effect}
+
+ def test_legitimate_lock_focus_changes_match_control(self):
+ events = [("pointer_leave", 0, 0, 0, 0), ("keyboard_leave", 0, 0, 0, 0)]
+ expected = self.effect(events=events, wire="wl_pointer#2.leave(5, wl_surface#1)")
+ actual = self.effect(events=events + [events[0]], wire="wl_pointer#7.leave(6, wl_surface#8)")
+ self.assertTrue(compare_control(self.control(expected), actual, self.identity)["fault_only_control_matched"])
+
+ def test_extra_input_or_transient_warp_is_not_hidden_by_matching_endpoints(self):
+ expected = self.effect()
+ actuals = [self.effect(events=[("cursor", 100, 50, 0, 0), ("cursor", 0, 0, 0, 0)]),
+ self.effect(events=[("pointer_button", 0, 0, 0, 1), ("pointer_button", 0, 0, 0, 0)]),
+ self.effect(wire="wl_keyboard#2.key(5, 123, 30, 1)"),
+ self.effect(after={**self.before, "keys": "x"})]
+ for actual in actuals:
+ with self.subTest(actual=actual), self.assertRaises(AssertionError):
+ compare_control(self.control(expected), actual, self.identity)
+
+ def test_same_maximum_cannot_hide_extra_cursor_path(self):
+ control_events = [("cursor", 100, 0, 0, 0), ("cursor", 0, 0, 0, 0)]
+ expected = self.effect(events=control_events)
+ actual = self.effect(events=control_events + [("cursor", 10, 0, 0, 0), ("cursor", 0, 0, 0, 0)])
+ self.assertEqual(expected["max_cursor_displacement"], actual["max_cursor_displacement"])
+ with self.assertRaises(AssertionError):
+ compare_control(self.control(expected), actual, self.identity)
+
+ def test_changed_boolean_cannot_hide_wrong_foreground_identity(self):
+ expected = self.effect(wm_after={**self.wm, "pid": 456, "address": "0x456"})
+ actual = self.effect(wm_after={**self.wm, "pid": 789, "address": "0x789"})
+ with self.assertRaises(AssertionError):
+ compare_control(self.control(expected), actual, self.identity)
+
+ def test_extra_focus_round_trip_is_not_hidden_by_control_categories(self):
+ events = [("pointer_leave", 0, 0, 0, 0), ("pointer_enter", 0, 0, 0, 0)]
+ expected = self.effect(events=events)
+ actual = self.effect(events=events + events)
+ with self.assertRaises(AssertionError):
+ compare_control(self.control(expected), actual, self.identity)
+
+ def test_missing_or_wrong_control_and_incomplete_trace_fail_closed(self):
+ expected = self.effect()
+ control = self.control(expected)
+ for update in ({"result": "failed"}, {"mode": "action"}, {"identity": {}}):
+ with self.assertRaises(AssertionError):
+ compare_control({**control, **update}, expected, self.identity)
+ for field in ("overflow", "timed_out", "active"):
+ incomplete = trace()
+ incomplete[field] = True
+ with self.assertRaises(AssertionError):
+ primary_effect(self.before, self.before, "", incomplete, self.wm, self.wm)
+ missing = deepcopy(expected)
+ del missing["wire_inputs"]
+ with self.assertRaises(AssertionError):
+ compare_control(control, missing, self.identity)
+
+
+class CleanupTest(unittest.TestCase):
+ def test_fault_and_video_failure_still_close_all_owned_resources_and_retain_failure(self):
+ from desktop_state_live import run
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bounds = {"x": 0, "y": 0, "width": 600, "height": 500}
+ plan = {"background": {"pid": 101, "window_id": "a"},
+ "foreground": {"pid": 102, "window_id": "b"},
+ "background_bounds": bounds, "foreground_bounds": bounds,
+ "background_address": "0xabc", "from": [100, 100], "to": [200, 200],
+ "foreground_point": [300, 300], "move_to": [20, 20]}
+ plan_path = root / "plan.json"
+ plan_path.write_text(json.dumps(plan))
+ module = root / "module.so"
+ module.write_bytes(b"synthetic module")
+ (root / "driver").write_bytes(b"synthetic driver")
+ (root / "grab").write_bytes(b"synthetic primary helper")
+ wire = root / "wire.log"
+ wire.write_text("wl_pointer#2.button(5, 123, 272, 1)\n")
+ args = SimpleNamespace(evidence=root / "attempt", plan=plan_path, mode="control", case="move",
+ source_sha="a" * 40, module=module, control=None, driver=root / "driver",
+ driver_socket=root / "driver.sock", observer_driver_socket=root / "observer.sock",
+ compositor_pid=100, instance="synthetic",
+ disposable=True, lock_fixture=None, compositor_exe=root / "Hyprland",
+ primary_grab=root / "grab", input_directory=root,
+ background_journal=root / "bg.jsonl", foreground_journal=root / "fg.jsonl",
+ foreground_wire=wire)
+ observer, client = MagicMock(), MagicMock()
+ def tool(name, _arguments):
+ if name == "stop_recording":
+ raise RuntimeError("synthetic video finalization failure")
+ data = {"window_bounds": bounds, "screenshot_width": 600, "screenshot_height": 500,
+ "screen_width": 1024, "screen_height": 768, "video_active": True}
+ return {"structuredContent": data}
+ observer.tool.side_effect = client.tool.side_effect = tool
+ fault = MagicMock()
+ fault.snapshot.return_value = {}
+ fault.rollback.return_value = {"restored": True}
+ fault.apply.side_effect = RuntimeError("synthetic fault failure")
+ grab = MagicMock()
+ grab.poll.return_value = None
+ grab.stdout.readline.return_value = "HELD\n"
+ tracer = MagicMock()
+ tracer.collect.return_value = trace()
+ initial = status()
+ initial["experiment"]["lease_active"] = False
+ primary = {"held": True, "clicks": 0, "keys": "", "scroll": 0, "motion": 0}
+ with patch("desktop_faults.FaultController", return_value=fault), \
+ patch("desktop_state_live.MCP", side_effect=[observer, client]) as connections, \
+ patch("desktop_state_live.Trace", return_value=tracer), \
+ patch("desktop_state_live.subprocess.check_output", return_value=json.dumps(initial)), \
+ patch("desktop_state_live.subprocess.Popen", return_value=grab), \
+ patch("desktop_state_live.select.select", return_value=([grab.stdout], [], [])), \
+ patch("desktop_state_live.state", return_value=primary), \
+ patch("desktop_state_live.journal", return_value=[]), \
+ patch("desktop_state_live.wm", return_value={"pid": 102}), \
+ redirect_stdout(io.StringIO()), self.assertRaises(AssertionError):
+ run(args)
+ fault.rollback.assert_called_once()
+ fault.close.assert_called_once()
+ grab.terminate.assert_called_once()
+ client.close.assert_called_once()
+ observer.close.assert_called_once()
+ self.assertEqual(connections.call_args_list[0].args[0].driver_socket, args.observer_driver_socket)
+ self.assertEqual(connections.call_args_list[1].args[0].driver_socket, args.driver_socket)
+ tracer.close.assert_called_once()
+ result = json.loads((args.evidence / "result.json").read_text())
+ self.assertEqual(result["result"], "failed")
+ self.assertEqual(result["error"], "synthetic fault failure")
+ self.assertTrue(result["cleanup_errors"])
+ self.assertTrue(result["identity"]["separate_observer_runtime"])
+ self.assertTrue((args.evidence / "foreground-wire-final.log").is_file())
+ self.assertTrue((args.evidence / "failed-primary-trace.json").is_file())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/desktop_state_live.py b/libs/cua-driver/hyprland-plugin/tests/desktop_state_live.py
new file mode 100644
index 0000000000..74cb5ca7c6
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/desktop_state_live.py
@@ -0,0 +1,401 @@
+"""Native desktop-state cancellation proof in an explicitly disposable guest.
+
+Run each --case once with --mode control, then --mode action --control RESULT.
+Both runs require already selected native fixtures and finalized Driver video.
+The plan extends input_lifecycle_live's plan with background_address; move_to
+or resize_to must choose the exact geometry for those cases. --source-sha names
+the independently verified candidate. This is focused evidence, not the desktop
+matrix or a physical-hardware claim.
+
+The action run emits GRANT_REQUIRED and waits for grant-initial.json, then
+grant-recovery.json in its exclusive evidence directory. Only the external host
+operator signs grants (capabilities 10). For destroy it first emits
+REPLACEMENT_REQUIRED and waits for recovery-plan.json containing target
+{pid,window_id}, bounds, and journal for an explicitly created replacement.
+No fixture is automatically relaunched and no signing key enters this process.
+Raw journals, traces, grants, wire logs, and video are private evidence.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+from pathlib import Path
+import re
+import select
+import subprocess
+import time
+from types import SimpleNamespace
+
+from desktop_state_evidence import agent_cleared, cancellation, compare_control, primary_effect, destroyed_resources_pruned, recovery_input, CASES
+from driver_input_live import MCP, journal, state, wait_for, wm
+from input_lifecycle_live import validate_plan
+from input_transport_test import connect, exchange, refused
+from lifecycle_evidence import primary_wire_events
+from primary_trace import Trace
+from realapp_proof import cleanup_all
+
+
+def save(path, value):
+ path.write_text(json.dumps(value, indent=2))
+
+
+def run(args):
+ from desktop_faults import FaultController
+
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ result = {"result": "failed", "case": args.case, "mode": args.mode,
+ "full_desktop_matrix": False, "physical_hardware": False}
+ client = observer = operator = controller = grab = trace = executor = None
+ recording = trace_active = False
+ bg_offset = fg_offset = wire_offset = None
+ label = "desktop-state-" + args.evidence.name
+ try:
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ assert re.fullmatch(r"[0-9a-f]{40}", args.source_sha), "require exact verified candidate SHA"
+ assert args.module.is_file(), "require exact loaded module artifact"
+ save(args.evidence / "plan.json", plan)
+ target, foreground = plan["background"], plan["foreground"]
+ result["identity"] = {"case": args.case, "source_sha": args.source_sha,
+ "module_sha256": hashlib.sha256(args.module.read_bytes()).hexdigest(),
+ "driver_sha256": hashlib.sha256(args.driver.read_bytes()).hexdigest(),
+ "primary_grab_sha256": hashlib.sha256(args.primary_grab.read_bytes()).hexdigest(),
+ "lock_fixture_sha256": hashlib.sha256(args.lock_fixture.read_bytes()).hexdigest() if args.lock_fixture else None,
+ "separate_observer_runtime": args.observer_driver_socket is not None,
+ "harness_sha256": {name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest()
+ for name in ("desktop_state_live.py", "desktop_state_evidence.py", "desktop_faults.py",
+ "driver_input_live.py", "input_lifecycle_live.py", "lifecycle_evidence.py",
+ "primary_trace.py", "input_transport_test.py", "realapp_proof.py")},
+ "foreground": foreground, "foreground_bounds": plan["foreground_bounds"],
+ "background_bounds": plan["background_bounds"],
+ "foreground_point": plan["foreground_point"],
+ "move_to": plan.get("move_to"), "resize_to": plan.get("resize_to")}
+ control = None
+ if args.mode == "action":
+ assert args.control, "action requires a separately retained fault-only control"
+ control = json.loads(args.control.read_text())
+ assert control.get("identity") == result["identity"], "control candidate/fixture mismatch"
+ assert control.get("result") == "passed" and control.get("mode") == "control"
+ result["control_sha256"] = hashlib.sha256(args.control.read_bytes()).hexdigest()
+
+ def new_client(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ endpoint = args.observer_driver_socket if name == "observer" and args.observer_driver_socket else args.driver_socket
+ return MCP(SimpleNamespace(evidence=directory, driver=args.driver,
+ driver_socket=endpoint))
+
+ def snapshot(mcp, selection):
+ response = mcp.tool("get_window_state", {**selection, "max_elements": 80})
+ assert not response.get("isError"), response
+ data = response["structuredContent"]
+ assert data.get("screenshot_width", 0) > 0 and data.get("screenshot_height", 0) > 0
+ return data
+
+ def status():
+ return json.loads(subprocess.check_output(["hyprctl", "-j", "cua:status"], timeout=2))
+
+ def probe_pending(selection, suffix):
+ assert not (args.evidence / ("grant-" + suffix + ".json")).exists(), "grant predates fresh request"
+ snapshot(client, selection)
+ response = client.tool("press_key", {**selection, "session": label,
+ "delivery_mode": "background", "key": "Escape"})
+ snapshot(observer, selection)
+ pending = response.get("structuredContent", {})
+ assert response.get("isError") is True and pending.get("reason") == "pending_operator_approval", response
+ save(args.evidence / ("request-" + suffix + ".json"), pending)
+ return pending
+
+ def receive_grant(pending, suffix):
+ path = args.evidence / ("grant-" + suffix + ".json")
+ print(json.dumps({"event": "GRANT_REQUIRED", "phase": suffix,
+ "request": str(args.evidence / ("request-" + suffix + ".json"))}), flush=True)
+ wait_for(path.exists, 35)
+ grant = json.loads(path.read_text())
+ assert all(grant[key] == pending[key] for key in ("epoch", "challenge", "target"))
+ assert grant["capabilities"] == 10, "only drag and recovery-key authority permitted"
+ assert grant["expires_unix_ms"] / 1000 - time.time() > 5, "insufficient remaining lease"
+ return grant
+
+ observer, client = new_client("observer"), new_client("agent")
+ initial_status = status()
+ assert initial_status["experiment"]["lease_active"] is False, "another experiment owns input authority"
+ save(args.evidence / "initial-status.json", initial_status)
+ if args.case == "destroy":
+ assert isinstance(plan.get("pre_target_resources"), list), "destruction requires pre-target resource baseline"
+ bg, fg = snapshot(client, target), snapshot(observer, foreground)
+ assert bg["window_bounds"] == plan["background_bounds"], "stale background geometry"
+ assert fg["window_bounds"] == plan["foreground_bounds"], "stale foreground geometry"
+ for point in (plan["from"], plan["to"]):
+ assert point[0] < bg["screenshot_width"] and point[1] < bg["screenshot_height"]
+ controller = FaultController(compositor_pid=args.compositor_pid, instance=args.instance,
+ target={"pid": target["pid"], "address": plan["background_address"]},
+ disposable=args.disposable, evidence=args.evidence / "fault", lock_fixture=args.lock_fixture,
+ move_to=plan.get("move_to"), resize_to=plan.get("resize_to"), hold_seconds=12,
+ compositor_exe=args.compositor_exe)
+ save(args.evidence / "compositor-before.json", controller.snapshot())
+ response = observer.tool("start_recording", {"output_dir": str(args.evidence / "recording"),
+ "record_video": True})
+ # Stop even if startup reports an incomplete recording.
+ recording = not response.get("isError")
+ assert recording and response.get("structuredContent", {}).get("video_active") is True, "video not active"
+ result["video_active"] = True
+ if args.mode == "action":
+ unapproved_offset = len(journal(args.background_journal))
+ pending = probe_pending(target, "initial")
+ assert not any(row["kind"] in ("button-press", "button-release", "key-press", "key-release", "scroll")
+ for row in journal(args.background_journal)[unapproved_offset:]), "initial unapproved input delivered"
+ grant = receive_grant(pending, "initial")
+ lane = pending["lane"]
+ assert lane in (0, 1), "unknown experimental lane"
+ input_path = args.input_directory / ("cua-input-test.sock" if lane == 0 else "cua-input-test-2.sock")
+ operator, _ = connect(input_path)
+ assert wm()["pid"] == foreground["pid"], "set up the exact foreground actor before approval"
+ assert exchange(operator, grant["packet"])["ok"] is True
+
+ desktop = observer.tool("get_desktop_state", {})["structuredContent"]
+ point, box = plan["foreground_point"], fg["window_bounds"]
+ grab = subprocess.Popen([str(args.primary_grab), str(box["x"] + point[0]),
+ str(box["y"] + point[1]), str(desktop["screen_width"]), str(desktop["screen_height"]),
+ "60000"], stdout=subprocess.PIPE, text=True)
+ wait_for(lambda: select.select([grab.stdout], [], [], 0)[0])
+ assert grab.stdout.readline().strip() == "HELD"
+ wait_for(lambda: state(args.foreground_journal)["held"])
+ snapshot(observer, foreground)
+ before_wm = wm()
+ assert before_wm["pid"] == foreground["pid"]
+ assert "wl_pointer.button" in primary_wire_events(args.foreground_wire.read_text()), "wire oracle inactive"
+ before_primary = state(args.foreground_journal)
+ bg_offset = len(journal(args.background_journal))
+ fg_offset = len(journal(args.foreground_journal))
+ wire_offset = args.foreground_wire.stat().st_size
+ trace = Trace(args.input_directory / "cua-input-test.sock")
+ trace.exchange("TRACE_START")
+ trace_active = True
+ future = None
+ if args.mode == "action":
+ snapshot(client, target)
+ executor = ThreadPoolExecutor(max_workers=1)
+ def drag():
+ response = client.tool("drag", {**target, "session": label, "delivery_mode": "background",
+ "from_x": plan["from"][0], "from_y": plan["from"][1],
+ "to_x": plan["to"][0], "to_y": plan["to"][1], "duration_ms": 2000})
+ return response, time.monotonic_ns()
+ future = executor.submit(drag)
+ press = wait_for(lambda: next((row for row in journal(args.background_journal)[bg_offset:]
+ if row["kind"] == "button-press"), None), 5)
+ assert time.monotonic_ns() - press["time"] < 900_000_000, "fault injection too late"
+
+ fault = controller.apply(args.case)
+ save(args.evidence / "fault-observed.json", fault)
+ result["fault"] = fault
+ if args.case == "destroy":
+ def pruned():
+ current = status()
+ try:
+ proof = destroyed_resources_pruned(plan["pre_target_resources"], initial_status, current)
+ except AssertionError:
+ return None
+ save(args.evidence / "pruned-status.json", current)
+ return proof
+ result.update(wait_for(pruned, .5))
+ if args.mode == "action":
+ def cleared():
+ sample = status()
+ stamp = time.monotonic_ns()
+ save(args.evidence / "agent-status-last.json", {"time": stamp, "status": sample})
+ try:
+ agent_cleared(sample, lane)
+ except AssertionError:
+ return None
+ return sample, stamp
+ cleaned_status, status_ns = wait_for(cleared, 2)
+ response, response_ns = future.result(timeout=5)
+ save(args.evidence / "action-response.json", {"time": response_ns, "response": response})
+ if args.case != "destroy":
+ wait_for(lambda: any(row["kind"] == "button-release"
+ for row in journal(args.background_journal)[bg_offset:]), 2)
+ result.update(cancellation(args.case, journal(args.background_journal)[bg_offset:],
+ fault_ns=fault["fault_ns"], observed_ns=fault["observed_ns"],
+ response_ns=response_ns, response=response, status_ns=status_ns, status=cleaned_status,
+ lane=lane, target_destroyed=fault["after"]["target"] is None))
+
+ # Give the independently logged GTK state one heartbeat after the fault.
+ # This observation window is identical for control and action and is
+ # not the cancellation latency oracle.
+ wait_for(lambda: state(args.foreground_journal)["time"] > fault["observed_ns"] + 250_000_000, 2)
+ after_primary, after_wm = state(args.foreground_journal), wm()
+ trace.exchange("TRACE_STOP")
+ trace_active = False
+ captured_trace = trace.collect()
+ save(args.evidence / "primary-trace.json", captured_trace)
+ with args.foreground_wire.open("rb") as stream:
+ stream.seek(wire_offset)
+ wire = stream.read().decode("utf-8")
+ (args.evidence / "foreground-wire.log").write_text(wire)
+ save(args.evidence / "foreground-journal.json", journal(args.foreground_journal)[fg_offset:])
+ save(args.evidence / "background-journal.json", journal(args.background_journal)[bg_offset:])
+ save(args.evidence / "primary-state.json", {"before": before_primary, "after": after_primary,
+ "wm_before": before_wm, "wm_after": after_wm})
+ result["primary_effect"] = primary_effect(before_primary, after_primary, wire,
+ captured_trace, before_wm, after_wm)
+ if args.mode == "control":
+ assert not any(row["kind"] in ("button-press", "key-press")
+ for row in journal(args.background_journal)[bg_offset:]), "control received agent input"
+ assert not any(row[2].startswith("agent_") for row in captured_trace["events"]), "control had active agent"
+ if control:
+ result.update(compare_control(control, result["primary_effect"], result["identity"]))
+ save(args.evidence / "rollback.json", controller.rollback())
+ snapshot(observer, foreground)
+ if args.case != "destroy":
+ snapshot(observer, target)
+ else:
+ windows = observer.tool("list_windows", {"pid": target["pid"]})
+ assert not windows.get("isError"), windows
+ assert not any(row.get("window_id") == target["window_id"]
+ for row in windows["structuredContent"]["windows"]), "destroyed window remains mapped"
+ # End the owned primary adversary before another external approval wait.
+ grab.terminate()
+ grab.wait(timeout=5)
+ wait_for(lambda: not state(args.foreground_journal)["held"])
+
+ if args.mode == "action":
+ stale = exchange(operator, grant["packet"])
+ save(args.evidence / "stale-grant-response.json", stale)
+ refused(stale, "invalid_grant", "stale_target")
+ result["old_grant_refused"] = True
+ recovery_target, recovery_journal = target, args.background_journal
+ if args.case == "destroy":
+ replacement = args.evidence / "recovery-plan.json"
+ assert not replacement.exists(), "replacement must be selected after destruction"
+ print(json.dumps({"event": "REPLACEMENT_REQUIRED", "path": str(replacement)}), flush=True)
+ wait_for(replacement.exists, 35)
+ selected = json.loads(replacement.read_text())
+ recovery_target, recovery_journal = selected["target"], Path(selected["journal"])
+ assert set(recovery_target) == {"pid", "window_id"}
+ assert recovery_target["pid"] not in (target["pid"], foreground["pid"])
+ assert snapshot(client, recovery_target)["window_bounds"] == selected["bounds"]
+ recovery_offset = len(journal(recovery_journal))
+ fresh = probe_pending(recovery_target, "recovery")
+ assert not any(row["kind"] in ("key-press", "button-press")
+ for row in journal(recovery_journal)[recovery_offset:]), "unapproved recovery input delivered"
+ result["fresh_approval_required"] = True
+ fresh_grant = receive_grant(fresh, "recovery")
+ assert fresh_grant["packet"] != grant["packet"], "recovery reused revoked approval"
+ assert wm()["pid"] == foreground["pid"], "restore the foreground actor before recovery approval"
+ assert exchange(operator, fresh_grant["packet"])["ok"] is True
+ snapshot(client, recovery_target)
+ recovery_offset = len(journal(recovery_journal))
+ recovery_primary = state(args.foreground_journal)
+ recovery_wm = wm()
+ recovery_wire_offset = args.foreground_wire.stat().st_size
+ response = client.tool("press_key", {**recovery_target, "session": label,
+ "delivery_mode": "background", "key": "Escape"})
+ snapshot(observer, recovery_target)
+ assert not response.get("isError") and response["structuredContent"].get("route") == "synthetic_events", response
+ received = wait_for(lambda: next((row for row in journal(recovery_journal)[recovery_offset:]
+ if row["kind"] == "key-release" and row.get("key") == "Escape"), None), 3)
+ recovery_status = status()
+ save(args.evidence / "recovery-status-before-cleanup.json", recovery_status)
+ result.update(recovery_input(journal(recovery_journal)[recovery_offset:], recovery_status, lane))
+ snapshot(observer, foreground)
+ wait_for(lambda: state(args.foreground_journal)["time"] > received["time"], 2)
+ for key in ("clicks", "keys", "held", "scroll", "motion"):
+ assert state(args.foreground_journal)[key] == recovery_primary[key], "recovery reached foreground"
+ assert wm() == recovery_wm, "recovery changed primary compositor state"
+ with args.foreground_wire.open("rb") as stream:
+ stream.seek(recovery_wire_offset)
+ recovery_wire = stream.read().decode("utf-8")
+ (args.evidence / "recovery-foreground-wire.log").write_text(recovery_wire)
+ assert not primary_wire_events(recovery_wire), "recovery leaked primary input"
+ save(args.evidence / "recovery-journal.json", journal(recovery_journal)[recovery_offset:])
+ result["freshly_approved_recovery_received"] = bool(received)
+ result["result"] = "passed"
+ except BaseException as error:
+ result.update(error_type=type(error).__name__, error=str(error))
+ raise
+ finally:
+ def retain_failed_oracles():
+ for path, offset, name in ((args.background_journal, bg_offset, "background-journal-final.json"),
+ (args.foreground_journal, fg_offset, "foreground-journal-final.json")):
+ if offset is not None:
+ save(args.evidence / name, journal(path)[offset:])
+ if wire_offset is not None:
+ with args.foreground_wire.open("rb") as stream:
+ stream.seek(wire_offset)
+ (args.evidence / "foreground-wire-final.log").write_bytes(stream.read())
+ def revoke():
+ if operator:
+ try:
+ assert exchange(operator, "CANCEL")["ok"] is True
+ save(args.evidence / "final-agent-status.json", status())
+ agent_cleared(status(), lane)
+ finally:
+ operator.close()
+ def release_primary():
+ if grab and grab.poll() is None:
+ grab.terminate()
+ grab.wait(timeout=5)
+ def finish_trace():
+ if trace:
+ try:
+ if trace_active:
+ trace.exchange("TRACE_STOP")
+ save(args.evidence / "failed-primary-trace.json", trace.collect())
+ finally:
+ trace.close()
+ def finish_video():
+ if recording:
+ response = observer.tool("stop_recording", {})
+ assert not response.get("isError"), response
+ video = response.get("structuredContent", {}).get("last_video_path")
+ assert video and Path(video).is_file() and Path(video).stat().st_size > 0, "missing finalized video"
+ probe = json.loads(subprocess.check_output(["ffprobe", "-v", "error", "-show_streams",
+ "-show_format", "-of", "json", video], timeout=10))
+ assert any(row.get("codec_type") == "video" for row in probe["streams"])
+ assert float(probe["format"]["duration"]) > 0, "empty finalized video"
+ result.update(video_finalized=True, video_file=str(Path(video).relative_to(args.evidence)))
+ save(args.evidence / "video-probe.json", probe)
+ operations = [("cancel_agent", revoke), ("finish_trace", finish_trace),
+ ("retain_oracles", retain_failed_oracles)]
+ if controller:
+ operations.append(("owned_fault_rollback", lambda: save(args.evidence / "cleanup-rollback.json", controller.rollback())))
+ operations.append(("close_fault_controller", controller.close))
+ operations.append(("release_primary", release_primary))
+ operations.append(("finalize_video", finish_video))
+ if executor:
+ operations.append(("join_action", lambda: executor.shutdown(wait=True, cancel_futures=True)))
+ if client:
+ operations.append(("close_agent", client.close))
+ if observer:
+ operations.append(("close_observer", observer.close))
+ errors = cleanup_all(operations)
+ result["cleanup_errors"] = errors
+ if errors or not result.get("video_finalized"):
+ result["result"] = "failed"
+ save(args.evidence / "result.json", result)
+ print(json.dumps(result), flush=True)
+ if errors:
+ raise AssertionError("desktop-state cleanup failed: " + str(errors))
+ return result
+
+
+if __name__ == "__main__":
+ if not __debug__:
+ raise RuntimeError("assertions must remain enabled")
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--case", choices=CASES, required=True)
+ parser.add_argument("--mode", choices=("control", "action"), required=True)
+ for name in ("plan", "evidence", "driver", "driver-socket", "input-directory", "module",
+ "primary-grab", "background-journal", "foreground-journal", "foreground-wire"):
+ parser.add_argument("--" + name, type=Path, required=True)
+ parser.add_argument("--control", type=Path)
+ parser.add_argument("--observer-driver-socket", type=Path,
+ help="independent Driver runtime for video and observations; excludes synchronous action-recording capture from cancellation timing")
+ parser.add_argument("--lock-fixture", type=Path)
+ parser.add_argument("--source-sha", required=True)
+ parser.add_argument("--compositor-pid", type=int, required=True)
+ parser.add_argument("--compositor-exe", type=Path, required=True)
+ parser.add_argument("--instance", required=True)
+ parser.add_argument("--disposable", action="store_true")
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/drag_geometry_test.cpp b/libs/cua-driver/hyprland-plugin/tests/drag_geometry_test.cpp
new file mode 100644
index 0000000000..e0ce272c87
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/drag_geometry_test.cpp
@@ -0,0 +1,37 @@
+#include "drag_geometry.hpp"
+
+#include <array>
+#include <cstdlib>
+#include <cstdint>
+
+namespace {
+void check(bool condition) { if (!condition) std::abort(); }
+}
+
+int main() {
+ using cua::hyprland::DragGeometry;
+ std::array<int, 4> cached{10, 10, 640, 480};
+ std::uint64_t revision = 2;
+ const auto refresh = [&](const std::array<int, 4>& actual) {
+ if (actual != cached) { cached = actual; ++revision; }
+ };
+ const DragGeometry drag{revision};
+ check(drag.matches(revision));
+
+ // Simulate a resize consumed by request()/approve() before their busy
+ // refusal. The timer refresh sees no new change; the drag must still fail.
+ const std::array<int, 4> resized{10, 10, 800, 600};
+ refresh(resized);
+ const auto before_tick = revision;
+ refresh(resized);
+ check(before_tick == revision);
+ check(!drag.matches(revision));
+
+ // Moving back cannot revive old coordinates or old authority.
+ refresh({10, 10, 640, 480});
+ check(!drag.matches(revision));
+ const DragGeometry newly_authorized{revision};
+ check(newly_authorized.matches(revision));
+ refresh({20, 30, 640, 480});
+ check(!newly_authorized.matches(revision));
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/driver_input_live.py b/libs/cua-driver/hyprland-plugin/tests/driver_input_live.py
new file mode 100644
index 0000000000..169c47cbd1
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/driver_input_live.py
@@ -0,0 +1,225 @@
+"""Opt-in native GTK fixture proof through the real Driver MCP transport.
+
+Run only in a disposable Hyprland session with the two isolated-input GTK
+fixtures already mapped. An external operator must sign grant-request.json
+and place ONLY the public grant in grant.json. This process cannot sign.
+This focused gate supplements, rather than replaces, the desktop matrix.
+"""
+import argparse
+import base64
+import json
+import os
+from pathlib import Path
+import select
+import socket
+import subprocess
+import time
+
+
+def wait_for(check, timeout=10):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ value = check()
+ if value:
+ return value
+ time.sleep(0.05)
+ raise AssertionError("bounded evidence wait expired")
+
+
+def journal(path):
+ # Ignore an in-progress final line, never manufacture missing evidence.
+ return [json.loads(line) for line in path.read_text().splitlines()
+ if line.endswith("}")]
+
+
+def state(path):
+ return next(row for row in reversed(journal(path)) if row["kind"] == "state")
+
+
+def wm():
+ def query(name):
+ return json.loads(subprocess.check_output(["hyprctl", "-j", name], timeout=5))
+ active = query("activewindow")
+ return {"pid": active.get("pid"), "address": active.get("address"),
+ "cursor": query("cursorpos"), "workspace": query("activeworkspace")["id"]}
+
+
+class MCP:
+ def __init__(self, args):
+ self.directory = args.evidence
+ self.log = (self.directory / "mcp.stderr").open("w")
+ self.process = subprocess.Popen(
+ # The service must already be started with unrestricted permission
+ # mode and --dangerously-bypass-approvals; the MCP proxy cannot set it.
+ [str(args.driver), "mcp", "--socket", str(args.driver_socket)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log,
+ text=True, bufsize=1)
+ self.counter = 0
+ self.rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
+ "clientInfo": {"name": "isolated-input-fixture", "version": "1"}})
+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
+ self.process.stdin.flush()
+
+ def rpc(self, method, params):
+ self.counter += 1
+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": self.counter,
+ "method": method, "params": params}) + "\n")
+ self.process.stdin.flush()
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline:
+ if not select.select([self.process.stdout], [], [], 1)[0]:
+ continue
+ line = self.process.stdout.readline()
+ if not line:
+ raise RuntimeError("MCP closed before response")
+ response = json.loads(line)
+ if response.get("id") != self.counter:
+ continue
+ if "error" in response:
+ raise RuntimeError(response["error"])
+ result = response["result"]
+ for index, content in enumerate(result.get("content", [])):
+ if content.get("type") == "image":
+ image = self.directory / f"{self.counter:03d}-{index}.png"
+ image.write_bytes(base64.b64decode(content.pop("data")))
+ content["image_file"] = image.name
+ (self.directory / f"{self.counter:03d}.json").write_text(json.dumps(result, indent=2))
+ return result
+ raise TimeoutError("MCP response timeout; never replay the action")
+
+ def tool(self, name, arguments):
+ return self.rpc("tools/call", {"name": name, "arguments": arguments})
+
+ def close(self):
+ self.process.stdin.close()
+ try:
+ self.process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ self.process.terminate()
+ self.process.wait(timeout=5)
+ self.log.close()
+
+
+def run(args):
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ mcp, grab, operator = MCP(args), None, None
+ try:
+ windows = mcp.tool("list_windows", {})["structuredContent"]["windows"]
+ def fixture(name):
+ matches = [w for w in windows if w["title"] == "Cua Isolated Input " + name]
+ assert len(matches) == 1, "need one exact synthetic fixture per actor"
+ return {key: matches[0][key] for key in ("pid", "window_id")}
+ background, foreground = fixture("Background"), fixture("Foreground")
+ assert background["pid"] != foreground["pid"]
+ def snapshot(target):
+ result = mcp.tool("get_window_state", target)
+ assert not result.get("isError"), result
+ return result["structuredContent"]
+ bg_before = snapshot(background)
+ fg_before = snapshot(foreground)
+ assert bg_before["screenshot_width"] > 400 and bg_before["screenshot_height"] > 300
+ pending = mcp.tool("click", {**background, "x": 200, "y": 300, "delivery_mode": "background"})
+ snapshot(background)
+ grant_request = pending.get("structuredContent", {})
+ assert pending.get("isError") and grant_request.get("reason") == "pending_operator_approval", pending
+ (args.evidence / "grant-request.json").write_text(json.dumps(grant_request))
+ print(json.dumps({"event": "grant_required", **grant_request}), flush=True)
+ grant_path = args.evidence / "grant.json"
+ wait_for(grant_path.exists, 120)
+ grant = json.loads(grant_path.read_text())
+ for key in ("epoch", "challenge", "target"):
+ assert grant[key] == grant_request[key], "grant belongs to another pending request"
+ operator = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+ operator.settimeout(5)
+ operator.connect(str(args.input_socket))
+ def exchange(packet):
+ operator.sendall(packet.encode("ascii"))
+ return json.loads(operator.recv(2048))
+ assert exchange("HELLO")["ok"]
+ assert exchange(grant["packet"])["ok"], "operator approval failed"
+ fg_box = fg_before["window_bounds"]
+ desktop = mcp.tool("get_desktop_state", {})["structuredContent"]
+ # Fixture-only adversary, not the background action actuator.
+ grab = subprocess.Popen([str(args.primary_grab), str(fg_box["x"] + 300),
+ str(fg_box["y"] + 300), str(desktop["screen_width"]),
+ str(desktop["screen_height"]), "60000"], stdout=subprocess.PIPE, text=True)
+ assert wait_for(lambda: select.select([grab.stdout], [], [], 0)[0])
+ assert grab.stdout.readline().strip() == "HELD"
+ wait_for(lambda: state(args.foreground_journal)["held"])
+ snapshot(foreground)
+ primary_before = wm()
+ assert primary_before["pid"] == foreground["pid"]
+ foreground_baseline = state(args.foreground_journal)
+ background_baseline = state(args.background_journal)
+ background_offset = len(journal(args.background_journal))
+ wire_offset = args.foreground_wire.stat().st_size
+ actions = [
+ ("click", {"x": 200, "y": 300}),
+ ("press_key", {"key": "a"}),
+ ("hotkey", {"keys": ["shift", "b"]}),
+ ("scroll", {"x": 200, "y": 300, "direction": "down", "amount": 3}),
+ ("drag", {"from_x": 200, "from_y": 300, "to_x": 350, "to_y": 320, "duration_ms": 500}),
+ ]
+ for name, parameters in actions:
+ snapshot(background)
+ result = mcp.tool(name, {**background, **parameters, "delivery_mode": "background"})
+ snapshot(background)
+ snapshot(foreground)
+ assert not result.get("isError"), (name, result)
+ assert result["structuredContent"]["route"] == "synthetic_events", (name, result)
+ assert result["structuredContent"]["effect"] == "unverifiable", (name, result)
+ assert wm() == primary_before, "foreground focus, workspace, or cursor changed"
+ current = state(args.foreground_journal)
+ for key in ("clicks", "keys", "held"):
+ assert current[key] == foreground_baseline[key], (key, current)
+ final = wait_for(lambda: state(args.background_journal)
+ if state(args.background_journal)["clicks"] >= background_baseline["clicks"] + 2 else None)
+ assert "a" in final["keys"] and "B" in final["keys"], final
+ assert final["scroll"] > background_baseline["scroll"] and not final["held"], final
+ assert final["motion"] > background_baseline["motion"] + 2, final
+ presses = [row for row in journal(args.background_journal)[background_offset:]
+ if row["kind"] == "button-press"]
+ assert presses, "missing raw pointer coordinate evidence"
+ scale_x = bg_before["window_bounds"]["width"] / bg_before["screenshot_width"]
+ scale_y = bg_before["window_bounds"]["height"] / bg_before["screenshot_height"]
+ assert abs(presses[0]["x"] - 200 * scale_x) < 1, presses[0]
+ assert abs(presses[0]["y"] - 300 * scale_y) < 1, presses[0]
+ with args.foreground_wire.open("rb") as stream:
+ stream.seek(wire_offset)
+ wire = stream.read().decode()
+ assert not any("wl_pointer#" in line and any(event in line for event in (".leave(", ".enter(", ".button("))
+ for line in wire.splitlines()), "primary pointer changed during background actions"
+ assert not any("wl_keyboard#" in line and any(event in line for event in (".leave(", ".enter(", ".key("))
+ for line in wire.splitlines()), "primary keyboard changed during background actions"
+ assert exchange("STOP")["ok"]
+ snapshot(background)
+ stopped = mcp.tool("click", {**background, "x": 200, "y": 300, "delivery_mode": "background"})
+ snapshot(background)
+ assert stopped.get("isError") and stopped["structuredContent"]["reason"] == "pending_operator_approval"
+ result = {"result": "passed", "actions": [a[0] for a in actions],
+ "foreground_grab_preserved": True, "primary_wire_unchanged": True,
+ "foreground_focus_cursor_workspace_preserved": True, "stop_revoked": True,
+ "background_before": background_baseline, "background_after": final,
+ "full_desktop_matrix": False}
+ (args.evidence / "result.json").write_text(json.dumps(result, indent=2))
+ print(json.dumps(result), flush=True)
+ finally:
+ if operator:
+ try:
+ operator.send(b"STOP")
+ operator.recv(2048)
+ except OSError:
+ pass
+ operator.close()
+ if grab and grab.poll() is None:
+ grab.terminate()
+ grab.wait(timeout=5)
+ mcp.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ("driver", "driver-socket", "input-socket", "evidence", "primary-grab",
+ "background-journal", "foreground-journal", "foreground-wire"):
+ parser.add_argument("--" + name, type=Path, required=True)
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp b/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp
new file mode 100644
index 0000000000..bdac3d3740
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp
@@ -0,0 +1,146 @@
+#include "foreground_route.hpp"
+#include <cstdlib>
+#include <initializer_list>
+#include <memory>
+#include <vector>
+
+using namespace cua::hyprland;
+void check(bool value) { if (!value) std::abort(); }
+int main() {
+ constexpr std::array labels{
+ "foreground_none", "foreground_exact_root", "foreground_primary_binding", "foreground_peer_conflict",
+ "foreground_physical_keys", "foreground_physical_buttons", "foreground_grab", "foreground_dnd",
+ "foreground_constraint", "foreground_keyboard_focus", "foreground_pointer_focus", "foreground_lease",
+ "foreground_client_dead", "foreground_session_unavailable", "foreground_unsupported_layout",
+ "foreground_lease_expired", "foreground_physical_keyboard", "foreground_keyboard_state",
+ "foreground_physical_pointer", "foreground_pointer_target", "foreground_seat_resource",
+ "foreground_pointer_resources", "foreground_keyboard_resources", "foreground_keyboard_depressed",
+ "foreground_keyboard_latched", "foreground_keyboard_locked", "foreground_keyboard_group",
+ };
+ static_assert(labels.size() == static_cast<unsigned>(ForegroundFailureReason::keyboard_group) + 1);
+ for (unsigned i = 0; i < labels.size(); ++i)
+ check(ForegroundFailure{static_cast<ForegroundFailureReason>(i)}.detail() == labels[i]);
+ check(ForegroundFailure::code(false) == "primary_target_busy");
+ check(ForegroundFailure::code(true) == "foreground_partial_unknown");
+
+ // Exhaust every guard combination against the original admission predicates.
+ for (unsigned bits = 0; bits < 1024; ++bits) {
+ const ForegroundGuard candidate{
+ .exact_root = bool(bits & 1), .primary_binding = bool(bits & 2),
+ .peer_conflict = bool(bits & 4), .physical_keys = bool(bits & 8),
+ .physical_buttons = bool(bits & 16), .grab = bool(bits & 32),
+ .dnd = bool(bits & 64), .constraint = bool(bits & 128),
+ .exact_keyboard_focus = bool(bits & 256), .exact_pointer_focus = bool(bits & 512),
+ };
+ const bool activate = candidate.exact_root && candidate.primary_binding && !candidate.peer_conflict &&
+ !candidate.physical_keys && !candidate.physical_buttons && !candidate.grab && !candidate.dnd && !candidate.constraint;
+ check(candidate.can_activate() == activate);
+ check(candidate.can_dispatch(false) == (activate && candidate.exact_keyboard_focus));
+ check(candidate.can_dispatch(true) == (activate && candidate.exact_keyboard_focus && candidate.exact_pointer_focus));
+ const auto expected = !candidate.exact_root ? ForegroundFailureReason::exact_root :
+ !candidate.primary_binding ? ForegroundFailureReason::primary_binding :
+ candidate.peer_conflict ? ForegroundFailureReason::peer_conflict :
+ candidate.physical_keys ? ForegroundFailureReason::physical_keys :
+ candidate.physical_buttons ? ForegroundFailureReason::physical_buttons :
+ candidate.grab ? ForegroundFailureReason::grab : candidate.dnd ? ForegroundFailureReason::dnd :
+ candidate.constraint ? ForegroundFailureReason::constraint : ForegroundFailureReason::none;
+ check(candidate.activation_failure() == expected);
+ for (const bool needs_pointer : {false, true}) {
+ const auto dispatch = expected != ForegroundFailureReason::none ? expected :
+ !candidate.exact_keyboard_focus ? ForegroundFailureReason::keyboard_focus :
+ needs_pointer && !candidate.exact_pointer_focus ? ForegroundFailureReason::pointer_focus : ForegroundFailureReason::none;
+ check(candidate.dispatch_failure(needs_pointer) == dispatch);
+ }
+ }
+ struct Resource {
+ bool valid = true;
+ bool good() const { return valid; }
+ };
+ auto first = std::make_shared<Resource>();
+ auto second = std::make_shared<Resource>();
+ std::vector<std::weak_ptr<Resource>> current{first}, captured{first};
+ check(foreground_resources_match(current, captured));
+ current.push_back(second);
+ check(!foreground_resources_match(current, captured));
+ current = {second};
+ check(!foreground_resources_match(current, captured));
+ current = {first};
+ first->valid = false;
+ check(!foreground_resources_match(current, captured));
+ first.reset();
+ check(!foreground_resources_match(current, captured));
+ current = {second};
+ captured = current;
+ check(foreground_resources_match(current, captured));
+ current.clear();
+ check(!foreground_resources_match(current, captured));
+
+ ForegroundSeatBindings bindings;
+ bindings.observe("wl_surface", false);
+ bindings.observe("wl_keyboard", false);
+ bindings.observe("wl_seat", true); // Cua-Agent
+ bindings.observe("wl_seat", true); // Cua-Agent-2
+ check(!bindings.unique());
+ bindings.observe("wl_seat", false); // Primary binding
+ check(bindings.unique());
+ // A second binding, including one created during a drag, must refuse.
+ bindings.observe("wl_seat", false);
+ check(!bindings.unique());
+ bindings.observe("wl_seat", true);
+ check(!bindings.unique());
+ // Saturation cannot make an arbitrarily large resource count unique.
+ for (unsigned i = 0; i < 1000; ++i) bindings.observe("wl_seat", false);
+ check(!bindings.unique());
+
+ std::array<std::uint32_t, 4> modifiers{};
+ constexpr std::array modifier_reasons{ForegroundFailureReason::keyboard_depressed,
+ ForegroundFailureReason::keyboard_latched, ForegroundFailureReason::keyboard_locked, ForegroundFailureReason::keyboard_group};
+ check(foreground_key_modifiers_supported(modifiers));
+ check(foreground_key_modifier_failure(modifiers) == ForegroundFailureReason::none);
+ for (unsigned i = 0; i < modifiers.size(); ++i) {
+ // Depressed, latched, locked, and nonzero layout group each refuse.
+ modifiers[i] = 1;
+ check(!foreground_key_modifiers_supported(modifiers));
+ check(foreground_key_modifier_failure(modifiers) == modifier_reasons[i]);
+ modifiers[i] = 0x80000000u;
+ check(!foreground_key_modifiers_supported(modifiers));
+ check(foreground_key_modifier_failure(modifiers) == modifier_reasons[i]);
+ modifiers[i] = 0;
+ }
+ check(foreground_key_modifiers_supported(modifiers));
+
+ InputRoute route = InputRoute::unbound;
+ check(bind_input_route(route, InputRoute::primary_foreground));
+ check(bind_input_route(route, InputRoute::primary_foreground));
+ check(!bind_input_route(route, InputRoute::independent));
+ check(route == InputRoute::primary_foreground);
+ route = InputRoute::independent;
+ check(!bind_input_route(route, InputRoute::primary_foreground));
+
+ ForegroundGuard guard{.exact_root = true};
+ check(guard.can_activate());
+ check(!guard.can_dispatch());
+ guard.exact_keyboard_focus = true;
+ check(!guard.can_dispatch());
+ check(guard.can_dispatch(false));
+ guard.exact_pointer_focus = true;
+ check(guard.can_dispatch());
+ for (auto member : {&ForegroundGuard::peer_conflict, &ForegroundGuard::physical_keys,
+ &ForegroundGuard::physical_buttons, &ForegroundGuard::grab,
+ &ForegroundGuard::dnd, &ForegroundGuard::constraint}) {
+ guard.*member = true;
+ check(!guard.can_activate());
+ check(!guard.can_dispatch());
+ guard.*member = false;
+ }
+ guard.exact_root = false;
+ check(!guard.can_activate());
+ check(!guard.can_dispatch());
+ guard.exact_root = true;
+ guard.exact_pointer_focus = false;
+ check(!guard.can_dispatch());
+ guard.exact_pointer_focus = true;
+ guard.exact_keyboard_focus = false;
+ check(!guard.can_dispatch());
+ check(!guard.can_dispatch(false));
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/foreground_siblings.py b/libs/cua-driver/hyprland-plugin/tests/foreground_siblings.py
new file mode 100644
index 0000000000..11fd09d5ef
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/foreground_siblings.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+"""Supplemental foreground safety fixture: two windows, one Wayland client.
+
+Each drawing area records its own raw events and live counters. Focus changes
+are performed independently by the Rust test through compositor IPC.
+"""
+
+import argparse
+import json
+import os
+import time
+from pathlib import Path
+
+import gi
+
+gi.require_version("Gtk", "3.0")
+gi.require_version("Gdk", "3.0")
+from gi.repository import Gdk, GLib, GObject, Gtk
+
+
+class Actor:
+ def __init__(self, name, directory):
+ self.name = name
+ self.journal = (directory / (name + ".jsonl")).open("x", buffering=1)
+ self.state = {"clicks": 0, "keys": "", "held": False, "motion": 0}
+ self.window = Gtk.Window(title="Cua Foreground " + name)
+ self.window.set_default_size(600, 500)
+ self.canvas = Gtk.DrawingArea()
+ self.canvas.set_can_focus(True)
+ self.canvas.add_events(Gdk.EventMask.ALL_EVENTS_MASK)
+ self.window.add(self.canvas)
+ self.canvas.connect("draw", self.draw)
+ self.canvas.connect("event", self.event)
+ self.window.connect("destroy", Gtk.main_quit)
+ self.window.show_all()
+ self.canvas.grab_focus()
+ GLib.timeout_add(100, self.heartbeat)
+
+ def record(self, kind, **values):
+ self.journal.write(json.dumps({"kind": kind, "time": time.monotonic_ns(),
+ "actor": self.name, **values}) + "\n")
+
+ def draw(self, widget, cr):
+ cr.set_source_rgb(0.08, 0.13, 0.18)
+ cr.paint()
+ cr.set_source_rgb(0.75, 0.9, 0.75)
+ cr.select_font_face("sans-serif", 0, 0)
+ cr.set_font_size(26)
+ for index, line in enumerate([self.name, *[
+ str(key) + "=" + str(value) for key, value in self.state.items()]]):
+ cr.move_to(25, 55 + index * 48)
+ cr.show_text(line[-60:])
+ return False
+
+ def event(self, widget, event):
+ data = {}
+ if event.type in (Gdk.EventType.BUTTON_PRESS, Gdk.EventType.BUTTON_RELEASE,
+ Gdk.EventType.MOTION_NOTIFY, Gdk.EventType.SCROLL):
+ data.update(x=event.x, y=event.y)
+ if event.type in (Gdk.EventType.BUTTON_PRESS, Gdk.EventType.BUTTON_RELEASE):
+ self.state["held"] = event.type == Gdk.EventType.BUTTON_PRESS
+ if not self.state["held"]:
+ self.state["clicks"] += 1
+ _, button = event.get_button()
+ data["button"] = int(button)
+ self.canvas.grab_focus()
+ elif event.type == Gdk.EventType.MOTION_NOTIFY:
+ self.state["motion"] += 1
+ elif event.type in (Gdk.EventType.KEY_PRESS, Gdk.EventType.KEY_RELEASE):
+ key = Gdk.keyval_name(event.keyval) or "unknown"
+ data.update(key=key, modifiers=int(event.state))
+ if event.type == Gdk.EventType.KEY_PRESS:
+ self.state["keys"] += key
+ if event.type not in (Gdk.EventType.EXPOSE, Gdk.EventType.CONFIGURE):
+ self.record(event.type.value_nick, **data)
+ self.canvas.queue_draw()
+ return False
+
+ def heartbeat(self):
+ self.record("state", **self.state)
+ return True
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--journal-dir", type=Path, required=True)
+ args = parser.parse_args()
+ display = Gdk.Display.get_default()
+ # The runtime backend type is available even without the GdkWayland typelib.
+ if display is None or GObject.type_name(display.__gtype__) != "GdkWaylandDisplay":
+ raise RuntimeError("native Wayland required")
+ actors = [Actor(name, args.journal_dir) for name in ("Target", "Sibling")]
+ for actor in actors:
+ if actor.window.get_display() != display:
+ raise RuntimeError("siblings must share one Gdk.Display")
+ for actor in actors:
+ actor.record("ready", pid=os.getpid(), same_display=True, native_wayland=True)
+ Gtk.main()
+ for actor in actors:
+ actor.journal.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/foreground_siblings_test.py b/libs/cua-driver/hyprland-plugin/tests/foreground_siblings_test.py
new file mode 100644
index 0000000000..995426dfb4
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/foreground_siblings_test.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+"""Backend and sibling-client checks without GTK or an optional backend typelib."""
+
+import importlib.util
+from pathlib import Path
+import sys
+from types import ModuleType, SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+
+class ForegroundSiblingsTest(unittest.TestCase):
+ def setUp(self):
+ gi = ModuleType("gi")
+ gi.require_version = Mock()
+ repository = ModuleType("gi.repository")
+ self.display = SimpleNamespace(__gtype__="GdkWaylandDisplay")
+ repository.Gdk = SimpleNamespace(Display=SimpleNamespace(
+ get_default=Mock(return_value=self.display)))
+ repository.GObject = SimpleNamespace(type_name=Mock(side_effect=lambda value: value))
+ repository.GLib = SimpleNamespace()
+ repository.Gtk = SimpleNamespace(main=Mock())
+ spec = importlib.util.spec_from_file_location(
+ "foreground_siblings", Path(__file__).with_name("foreground_siblings.py"))
+ self.fixture = importlib.util.module_from_spec(spec)
+ with patch.dict(sys.modules, {"gi": gi, "gi.repository": repository}):
+ spec.loader.exec_module(self.fixture)
+ self.assertEqual(gi.require_version.call_args_list,
+ [unittest.mock.call("Gtk", "3.0"),
+ unittest.mock.call("Gdk", "3.0")])
+ self.actors = []
+
+ def actor(self, name, directory):
+ actor = SimpleNamespace(name=name, window=Mock(), record=Mock(), journal=Mock())
+ actor.window.get_display.return_value = self.display
+ self.actors.append(actor)
+ return actor
+
+ def run_fixture(self, actor_factory=None):
+ with patch.object(sys, "argv", ["foreground_siblings", "--journal-dir", "."]), \
+ patch.object(self.fixture, "Actor", side_effect=actor_factory or self.actor), \
+ patch.object(self.fixture.os, "getpid", return_value=1234):
+ self.fixture.main()
+
+ def test_wayland_siblings_share_actual_display_and_pid(self):
+ self.run_fixture()
+ self.assertEqual([actor.name for actor in self.actors], ["Target", "Sibling"])
+ for actor in self.actors:
+ actor.window.get_display.assert_called_once_with()
+ actor.record.assert_called_once_with(
+ "ready", pid=1234, same_display=True, native_wayland=True)
+ actor.journal.close.assert_called_once_with()
+ self.fixture.Gtk.main.assert_called_once_with()
+
+ def test_rejects_x11_even_with_wayland_environment(self):
+ self.display.__gtype__ = "GdkX11Display"
+ with patch.dict(self.fixture.os.environ, {"GDK_BACKEND": "wayland"}), \
+ self.assertRaisesRegex(RuntimeError, "native Wayland required"):
+ self.run_fixture()
+ self.assertEqual(self.actors, [])
+ self.fixture.Gtk.main.assert_not_called()
+
+ def test_rejects_no_display(self):
+ self.fixture.Gdk.Display.get_default.return_value = None
+ with self.assertRaisesRegex(RuntimeError, "native Wayland required"):
+ self.run_fixture()
+ self.fixture.GObject.type_name.assert_not_called()
+ self.assertEqual(self.actors, [])
+
+ def test_rejects_inexact_backend_type(self):
+ self.display.__gtype__ = "OtherWaylandDisplay"
+ with self.assertRaisesRegex(RuntimeError, "native Wayland required"):
+ self.run_fixture()
+ self.assertEqual(self.actors, [])
+
+ def test_rejects_sibling_on_another_wayland_display(self):
+ def different_display(name, directory):
+ actor = self.actor(name, directory)
+ if name == "Sibling":
+ actor.window.get_display.return_value = Mock(__gtype__="GdkWaylandDisplay")
+ return actor
+
+ with self.assertRaisesRegex(RuntimeError, "siblings must share one Gdk.Display"):
+ self.run_fixture(different_display)
+ for actor in self.actors:
+ actor.record.assert_not_called()
+ self.fixture.Gtk.main.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/input-validation.md b/libs/cua-driver/hyprland-plugin/tests/input-validation.md
new file mode 100644
index 0000000000..93f25cf744
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input-validation.md
@@ -0,0 +1,160 @@
+# Isolated-input VM validation
+
+This is the historical single-seat record. The later
+[concurrent real-app validation](realapp-validation.md) covers two independent
+lanes, Calc and Inkscape, moving-primary measurement, Cancel, and Stop on a
+different explicitly identified candidate.
+
+On 2026-09-05, the nonshipping input experiment passed a focused native GTK3
+test in an existing Omarchy Fleet VM. Real Driver MCP calls delivered click,
+key, hotkey, scroll, and drag events to a background application while a
+different application retained its primary-seat pointer grab.
+
+This is evidence for one experimental configuration, not a supported release,
+a complete desktop E2E result, or acceptance of [RFC #3550](https://github.com/trycua/cua/issues/3550).
+The normal plugin build remains discovery-only. The implementation is in
+[draft #3572](https://github.com/trycua/cua/pull/3572), with the discovery
+foundation [#3547](https://github.com/trycua/cua/pull/3547) and native observation
+[#3557](https://github.com/trycua/cua/pull/3557) as dependencies.
+
+## Tested artifacts
+
+The executable and module were built from an archive of the same committed
+source, not from an uncommitted working tree.
+
+| Component | Tested identity |
+| --- | --- |
+| Source commit | `e61413a053a6f44c09cac2b263fd9e76410b43d8` |
+| Omarchy package | `4.0.1-1` |
+| Hyprland package | `0.56.2-1` |
+| Hyprland commit | `efb50993780079460b0cbed1363e2166a2de1d9f` |
+| Portal package | `xdg-desktop-portal-hyprland 1.4.1-1` |
+| Plugin version | `0.1.0`, experimental input build |
+| Driver source and installed version | `0.23.2`, source build, not the published binary |
+| Plugin compiler | GCC `16.1.1`, matching the compositor |
+| Rust compiler | `1.97.1` |
+
+The full Hyprland ABI fingerprint was
+`efb50993780079460b0cbed1363e2166a2de1d9f_aq_0.14_hu_0.14_hg_0.5_hc_0.1_hlg_0.6`.
+The build linked the compositor's shared C++ runtime, not a static copy.
+The source archive SHA-256 was
+`64d9f26f32c4c51ecaf1d81d49f249cf5bca2e13a20b5b886672d3997c1b0e03`.
+
+Artifact SHA-256 values were:
+
+- Plugin: `c011f16d1ea6f121bd9088a7b5031e56124f3f633913306b30bdf8d8759cdca3`.
+- Installed Driver: `ffe064d7b175df3293fd13b488ab63c6056cb833b1adbe7a9b837bd11ae18274`.
+
+The repository's `install-local.sh` installed the Driver into a task-local
+guest directory. Its source SHA, resolved executable, version, digest, and
+running service executable were checked. The pre-existing local and published
+Driver binaries were preserved. No Fleet image was published.
+
+Commit `5d4c2f7432cd6a1f7c3d8de0f6f6c0937bad3687` changes only Rust formatting
+and module declaration order after this tested source. Subsequent validation
+notes and the supplemental lease probe do not change either executable.
+
+## Application and isolation evidence
+
+[`driver_input_live.py`](driver_input_live.py) connected through a real Driver
+MCP process to an unrestricted test service. Both
+[GTK3 drawing-area fixtures](../../tests/fixtures/apps/linux/isolated-input/main.py)
+had empty actionable accessibility trees; AT-SPI actions could not substitute
+for the raw input under test. PyGObject `3.58.0` and pycairo `1.29.1` ran the
+fixtures.
+
+Each action had a fresh Cua window snapshot before and after. Independent
+application event journals and Wayland wire logs supplied the behavior oracle.
+The primary-seat adversary was [`primary_grab.c`](primary_grab.c), which held
+the foreground left button through a virtual pointer. It was not a physical
+mouse test. Background delivery used only the Driver MCP input route.
+
+| Observation | Result |
+| --- | --- |
+| Background click | Raw button press arrived at `(200, 300)`, matching the window screenshot coordinates |
+| Background key and hotkey | Application received `a` and `Shift+B` with the independent keymap |
+| Background scroll | Application scroll counter increased from zero to one |
+| Background drag | Motion events and a complete press/release arrived; no button remained held |
+| Background aggregate | Click/release counter increased from zero to two; motion counter from zero to 14 |
+| Foreground grab | Remained held during all five actions; the harness released it afterward |
+| Primary pointer wire | No enter, leave, or button events during background delivery |
+| Primary keyboard wire | No enter, leave, or key events during background delivery |
+| Compositor state | Foreground identity, cursor position, and workspace stayed unchanged |
+| Stop | Revoked the lease; a subsequent Driver click required new operator approval |
+
+Driver correctly reported `route: synthetic_events` and `effect: unverifiable`.
+The test's application evidence established delivery; the transport response
+did not claim application success. The host signed a target/connection-bound
+test grant, and only the public grant entered the guest.
+
+## Other checks
+
+- Six native CTests passed: protocol, status, Linux transport, two mocked API
+ variants, and the CMake API probe. These are not six input application tests.
+- Focused Rust tests passed: six `hyprland_input`, three `experimental_`, two
+ `primary_seat`, and 23 shared `action_record` tests.
+- All 24 Python operator, transport, and nested-lifecycle helper tests passed
+ on the host with the optional cryptography dependency available.
+- [`input_transport_test.py`](input_transport_test.py) passed against the final
+ module: missing, malformed, and forged grants; replayed grants before and
+ after Stop; replayed action sequences; NaN, infinity, negative, and
+ out-of-bounds coordinates. Exactly one valid fixture click was dispatched.
+- [`input_lease_live.py`](input_lease_live.py) separately proved that expiry
+ refused further input and reconnect produced a fresh challenge, rejected
+ the old connection's grant, and required fresh approval. These probes did
+ not exercise cancellation while input was held.
+- The exact module passed the two-owned-nested-compositor lifecycle runner:
+ old sockets/connections closed, restart produced a fresh epoch and socket,
+ the sibling remained responsive, and both owned compositors exited cleanly.
+- A disposable foot client and both GTK fixtures survived unloading and
+ reloading the final module in the parent session. Fresh Cua snapshots and
+ unchanged process/window identities verified survival.
+- After reload, Driver's first call reported its broken connection without
+ replaying input. Following a fresh snapshot, a separately requested call
+ reconnected and required approval in the new epoch. Fixture counters did
+ not change on either refused call.
+
+The supplemental lease probe's tested SHA-256 is
+`42c623def921c4f359e7b8d2c2660951901372fc36a934ff4a5c53e6749d574c`.
+Use a new evidence directory for each run. For `--case expiry`, sign its
+`request.json` with click capability `1` and a short lifetime such as 15 seconds,
+then promptly transfer only the public `grant.json`. For `--case disconnect`,
+use a lifetime of at most 60 seconds. It must run alone: cleanup sends Stop.
+
+## Failures corrected during the experiment
+
+- Destroying seat resources immediately on unload disconnected a live foot
+ client. The final experiment retains inert handlers and marks its ELF module
+ `NODELETE`; the disposable-client regression then passed. This is a bounded
+ test workaround, not safe production hot-unload support.
+- Hidden symbol visibility created private copies of compositor globals.
+ The experimental build uses the compositor-compatible visibility settings.
+- Advertising seat version 8 prevented the nested compositor from binding;
+ the experiment now advertises version 9.
+- The Driver initially delivered input but rejected its missing execution
+ record as `action_outcome_mismatch`. The isolated transport now records the
+ shared synthetic-event action outcome.
+- Decorated window bounds shifted pointer coordinates by four pixels. Using
+ client-surface bounds fixed the final coordinate assertion.
+- The fixture's button-event serialization initially raised an exception.
+ Its corrected raw journal recorded both final button presses at `(200, 300)`.
+
+## Remaining acceptance gates
+
+This result does not cover GTK4, Qt6, LibreOffice, Chromium/Ozone, Electron,
+XWayland, subsurfaces, Unicode/IME, raw text, modified pointer gestures,
+fractional scaling, multiple monitors, multi-agent concurrency, or physical
+Omarchy hardware. Earlier prototype results do not certify this plugin build.
+
+Further native tests must exercise target loss, geometry changes during
+delivery, lock/DPMS transitions, primary input entering a target or sibling
+window, and held-state cleanup during expiry/disconnect/unload. The experiment
+allows one short-lived lease and conservatively refuses a target when primary
+input is in the same Wayland client. Normal permission UX, a stable protocol,
+production resource lifetime, and the RFC decision remain open.
+
+The complete canonical desktop matrix has not run for this candidate. The
+Hyprland foreground-activation adapter and capability-aware observation hints
+also remain separate Driver work: a successful isolated-input fixture does
+not establish foreground parity or remove the stock Wayland fallback hints.
+Keep this PR draft until its review and broader acceptance scope are decided.
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_authority_live.py b/libs/cua-driver/hyprland-plugin/tests/input_authority_live.py
new file mode 100644
index 0000000000..3674f7b34d
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_authority_live.py
@@ -0,0 +1,174 @@
+"""Opt-in Stop/Cancel grant-boundary probe in a disposable Hyprland session.
+
+No input action is dispatched. The operator signs grants outside the guest;
+this probe tests pending/active authority, not application delivery. Use the
+held-input Driver harness separately for release and primary-input evidence.
+"""
+
+import argparse
+from contextlib import ExitStack
+import json
+from pathlib import Path
+import re
+import subprocess
+import time
+
+from input_transport_test import approved_packet, connect, exchange, refused
+
+
+def lane_state(status):
+ experiment = status.get("experiment", {})
+ assert experiment.get("protocol") == 0 and experiment.get("test_only") is True
+ assert experiment.get("transport_ready") is True
+ lanes = experiment.get("lanes", [])
+ assert len(lanes) == 2 and [lane["lane"] for lane in lanes] == [0, 1]
+ for lane in lanes:
+ assert type(lane.get("lease_active")) is bool
+ assert type(lane.get("dispatches")) is int and lane["dispatches"] >= 0
+ assert lane.get("held_button") == 0 and lane.get("held_keys") == 0
+ assert lane.get("drag_active") is False
+ assert lane.get("pointer_focus") is False and lane.get("keyboard_focus") is False
+ return lanes
+
+
+def exercise(command, clients, hellos, operators, targets, obtain_grants, read_status, send=exchange):
+ """Exercise real transport by default; injected seams test the runner only."""
+ assert command in ("STOP", "CANCEL")
+ before = lane_state(read_status())
+ assert not any(lane["lease_active"] for lane in before), "test requires idle input lanes"
+ baseline = [lane["dispatches"] for lane in before]
+ selected = [send(clients[i], f"TARGET {target['pid']} {target['address']}")
+ for i, target in enumerate(targets)]
+ assert all(item.get("ok") is True for item in selected)
+
+ def request(name, lane, target):
+ return {"name": name, "lane": lane, "capabilities": 1,
+ "epoch": hellos[lane]["epoch"], "challenge": hellos[lane]["challenge"],
+ "target": target["target"]}
+
+ requests = [request("active-0", 0, selected[0]), request("renewal-0", 0, selected[0]),
+ request("pending-1", 1, selected[1])]
+ grants = obtain_grants("before", requests)
+ packets = {row["name"]: approved_packet(grants[row["name"]], hellos[row["lane"]], selected[row["lane"]])
+ for row in requests}
+ assert int(packets["renewal-0"].split()[3]) > int(packets["active-0"].split()[3]), "renewal must have a later deadline"
+ assert send(operators[0], packets["active-0"]).get("ok") is True, "initial positive-control grant refused"
+ assert [lane["lease_active"] for lane in lane_state(read_status())] == [True, False]
+
+ # Only the first grant has been redeemed. A high-water deadline check alone
+ # cannot reject either the unused renewal or the other lane's pending grant.
+ assert send(operators[0], command).get("ok") is True
+ assert not any(lane["lease_active"] for lane in lane_state(read_status()))
+ refused(send(operators[0], packets["active-0"]), "stale_target")
+ refused(send(operators[0], packets["renewal-0"]), "stale_target")
+ if command == "STOP":
+ refused(send(operators[1], packets["pending-1"]), "stale_target")
+ affected = [0, 1]
+ else:
+ assert send(operators[1], packets["pending-1"]).get("ok") is True, "Cancel invalidated the sibling lane"
+ affected = [0]
+
+ fresh = {}
+ for lane in affected:
+ target = targets[lane]
+ fresh[lane] = send(clients[lane], f"TARGET {target['pid']} {target['address']}")
+ assert fresh[lane].get("ok") is True
+ assert fresh[lane]["target"] != selected[lane]["target"], "revocation retained target binding"
+ # Rebinding on the same action connections must not revive old signatures.
+ refused(send(operators[0], packets["renewal-0"]), "stale_target")
+ if command == "STOP":
+ refused(send(operators[1], packets["pending-1"]), "stale_target")
+ requests = [request(f"fresh-{lane}", lane, fresh[lane]) for lane in affected]
+ accepted_deadline = int(packets["active-0"].split()[3])
+ requests[0]["expires_before_unix_ms"] = accepted_deadline
+ grants = obtain_grants("after", requests)
+ for row in requests:
+ lane = row["lane"]
+ packet = approved_packet(grants[row["name"]], hellos[lane], fresh[lane])
+ if lane == 0:
+ assert int(packet.split()[3]) < accepted_deadline, "fresh lane-0 grant must expire before the revoked grant"
+ assert send(operators[lane], packet).get("ok") is True, "fresh positive-control grant refused"
+ after = lane_state(read_status())
+ assert all(lane["lease_active"] for lane in after)
+ assert [lane["dispatches"] for lane in after] == baseline, "authority probe unexpectedly dispatched input"
+ return {"result": "passed", "command": command, "unused_renewal_refused": True,
+ "pending_sibling": "revoked" if command == "STOP" else "preserved",
+ "fresh_grants_accepted": True, "shorter_fresh_grant_accepted": True,
+ "control_connections_preserved": True,
+ "input_dispatched": False, "held_input_cleanup_tested": False,
+ "application_delivery_tested": False, "full_desktop_matrix": False}
+
+
+def validate_targets(targets):
+ if not isinstance(targets, list) or len(targets) != 2:
+ raise ValueError("plan must name exactly two native disposable fixture targets")
+ for target in targets:
+ if (not isinstance(target, dict) or set(target) != {"pid", "address"}
+ or type(target["pid"]) is not int or not 0 < target["pid"] < (1 << 31)
+ or not isinstance(target["address"], str)
+ or re.fullmatch(r"[0-9a-f]{1,16}", target["address"]) is None
+ or int(target["address"], 16) == 0):
+ raise ValueError("target needs a positive PID and lowercase hex address without 0x")
+ if targets[0]["pid"] == targets[1]["pid"]:
+ raise ValueError("targets must be separate application processes")
+
+
+def run(args):
+ if not args.disposable:
+ raise ValueError("requires an explicitly selected disposable session")
+ targets = json.loads(args.plan.read_text())
+ validate_targets(targets)
+ args.evidence.mkdir(parents=True, exist_ok=False)
+
+ def read_status():
+ return json.loads(subprocess.check_output(["hyprctl", "-j", "cua:status"], timeout=5))
+
+ def obtain_grants(stage, requests):
+ (args.evidence / f"request-{stage}.json").write_text(json.dumps(requests, indent=2))
+ path = args.evidence / f"grants-{stage}.json"
+ assert not path.exists(), "do not prepopulate grants for unobserved targets"
+ print(f"GRANTS_REQUIRED {stage}", flush=True)
+ deadline = time.monotonic() + 40
+ while not path.exists():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("external operator grants did not arrive")
+ time.sleep(0.05)
+ value = json.loads(path.read_text())
+ assert isinstance(value, dict) and set(value) == {row["name"] for row in requests}
+ return value
+
+ result = {"result": "failed", "command": args.command}
+ try:
+ initial = lane_state(read_status())
+ assert not any(lane["lease_active"] or lane.get("reserved") is not False for lane in initial), "test requires unowned idle lanes"
+ with ExitStack() as stack:
+ clients, hellos, operators = [], [], []
+ for name in ("cua-input-test.sock", "cua-input-test-2.sock"):
+ client, hello = connect(args.input_directory / name, claim=True)
+ clients.append(stack.enter_context(client))
+ hellos.append(hello)
+ operator, _ = connect(args.input_directory / name)
+ operators.append(stack.enter_context(operator))
+ # Registered after the socket, so Stop runs before it closes,
+ # including partial setup or a failed assertion/grant transfer.
+ stack.callback(exchange, operator, "STOP")
+ result = exercise(args.command, clients, hellos, operators, targets, obtain_grants, read_status)
+ assert not any(lane["lease_active"] for lane in lane_state(read_status())), "cleanup left active authority"
+ result["cleanup_verified"] = True
+ except Exception as error:
+ result = {"result": "failed", "command": args.command, "error_type": type(error).__name__}
+ raise
+ finally:
+ (args.evidence / "result.json").write_text(json.dumps(result, indent=2))
+
+
+if __name__ == "__main__":
+ if not __debug__:
+ raise RuntimeError("assertions must be enabled")
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--command", choices=["STOP", "CANCEL"], required=True)
+ parser.add_argument("--input-directory", type=Path, required=True)
+ parser.add_argument("--plan", type=Path, required=True)
+ parser.add_argument("--evidence", type=Path, required=True)
+ parser.add_argument("--disposable", action="store_true")
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_authority_test.py b/libs/cua-driver/hyprland-plugin/tests/input_authority_test.py
new file mode 100644
index 0000000000..cd83e82341
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_authority_test.py
@@ -0,0 +1,126 @@
+"""Runner checks only; these mocks do not compile or validate the compositor."""
+
+import unittest
+
+from input_authority_live import exercise, lane_state, validate_targets
+
+
+class ScriptedPeer:
+ def __init__(self, fault=None):
+ self.fault = fault
+ self.tokens = [None, None]
+ self.leases = [False, False]
+ self.deadlines = [0, 0]
+ self.serial = 0
+ self.revoked = False
+ self.calls = []
+ self.hellos = [{"epoch": "a" * 32, "challenge": char * 32} for char in ("b", "c")]
+
+ def status(self):
+ return {"experiment": {"protocol": 0, "test_only": True, "transport_ready": True,
+ "lanes": [{"lane": i, "lease_active": self.leases[i], "dispatches": 0,
+ "held_button": 0, "held_keys": 0, "drag_active": False,
+ "pointer_focus": False, "keyboard_focus": False} for i in range(2)]}}
+
+ def grants(self, stage, requests):
+ grants = {}
+ for row in requests:
+ expiry = 1700000001000 if row["name"] == "active-0" else 1700000002000
+ if stage == "after" and row["lane"] == 0:
+ expiry = row["expires_before_unix_ms"] - 100
+ grants[row["name"]] = {"epoch": row["epoch"],
+ "packet": f"APPROVE {row['challenge']} {row['target']} {expiry} 1 {'d' * 128}"}
+ if stage == "before" and self.fault == "invalid_renewal":
+ grants["renewal-0"] = dict(grants["active-0"])
+ return grants
+
+ def send(self, connection, packet):
+ lane = int(connection[-1])
+ self.calls.append((connection, packet))
+ fields = packet.split()
+ if fields[0] == "TARGET":
+ if self.tokens[lane] is None:
+ self.serial += 1
+ self.tokens[lane] = f"{self.serial:032x}"
+ return {"ok": True, "target": self.tokens[lane], "revision": 1}
+ if fields[0] in ("STOP", "CANCEL"):
+ self.revoked = True
+ affected = [0, 1] if fields[0] == "STOP" or self.fault == "cancel_sibling" else [lane]
+ for index in affected:
+ self.leases[index] = False
+ if self.fault != "retain_highwater":
+ self.deadlines[index] = 0
+ if self.fault != "retain_tokens":
+ self.tokens[index] = None
+ return {"ok": True}
+ if fields[0] == "APPROVE":
+ stale = fields[2] != self.tokens[lane]
+ if stale and not (self.revoked and ((self.fault == "accept_renewal" and lane == 0
+ and fields[3] == "1700000002000")
+ or (self.fault == "accept_pending" and lane == 1))):
+ return {"ok": False, "code": "stale_target", "detail": "stale_target"}
+ if self.fault == "refuse_fresh" and self.revoked:
+ return {"ok": False, "code": "invalid_grant", "detail": "invalid_grant"}
+ if int(fields[3]) <= self.deadlines[lane]:
+ return {"ok": False, "code": "invalid_grant", "detail": "invalid_grant"}
+ self.deadlines[lane] = int(fields[3])
+ self.leases[lane] = True
+ return {"ok": True}
+ raise AssertionError("authority probe must not send input")
+
+
+class AuthorityProbeTest(unittest.TestCase):
+ def probe(self, command="STOP", fault=None):
+ peer = ScriptedPeer(fault)
+ result = exercise(command, ["client0", "client1"], peer.hellos, ["operator0", "operator1"],
+ [{"pid": 10, "address": "abc"}, {"pid": 11, "address": "def"}],
+ peer.grants, peer.status, peer.send)
+ return result, peer
+
+ def test_stop_checks_unused_renewal_and_pending_other_lane(self):
+ result, peer = self.probe()
+ self.assertEqual(result["result"], "passed")
+ self.assertEqual(result["pending_sibling"], "revoked")
+ self.assertTrue(result["fresh_grants_accepted"])
+ self.assertTrue(result["shorter_fresh_grant_accepted"])
+ self.assertFalse(result["input_dispatched"])
+ self.assertTrue(all(packet.split()[0] in ("TARGET", "APPROVE", "STOP") for _, packet in peer.calls))
+
+ def test_cancel_preserves_the_pending_sibling_grant(self):
+ result, _ = self.probe("CANCEL")
+ self.assertEqual(result["pending_sibling"], "preserved")
+
+ def test_regressions_cannot_report_pass(self):
+ for fault in ("accept_renewal", "accept_pending", "retain_tokens", "refuse_fresh", "invalid_renewal", "retain_highwater"):
+ with self.subTest(fault=fault), self.assertRaises(AssertionError):
+ self.probe(fault=fault)
+ with self.assertRaises(AssertionError):
+ self.probe("CANCEL", "cancel_sibling")
+ with self.assertRaises(AssertionError):
+ self.probe("CANCEL", "retain_highwater")
+
+ def test_status_requires_explicit_no_input_evidence(self):
+ status = ScriptedPeer().status()
+ for field, value in (("held_button", 272), ("held_keys", 1), ("drag_active", True),
+ ("pointer_focus", True), ("keyboard_focus", True), ("dispatches", "0")):
+ with self.subTest(field=field):
+ invalid = ScriptedPeer().status()
+ invalid["experiment"]["lanes"][0][field] = value
+ with self.assertRaises(AssertionError):
+ lane_state(invalid)
+ del status["experiment"]["lanes"][0]["lease_active"]
+ with self.assertRaises(AssertionError):
+ lane_state(status)
+
+ def test_plan_refuses_unbounded_or_shared_targets(self):
+ valid = [{"pid": 10, "address": "abc"}, {"pid": 11, "address": "def"}]
+ validate_targets(valid)
+ for invalid in ([], [valid[0], valid[0]], [valid[0], {"pid": True, "address": "def"}],
+ [valid[0], {"pid": 11, "address": "0xdef"}],
+ [valid[0], {"pid": 11, "address": "0"}]):
+ with self.subTest(invalid=invalid), self.assertRaises(ValueError):
+ validate_targets(invalid)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_client_deadline_test.cpp b/libs/cua-driver/hyprland-plugin/tests/input_client_deadline_test.cpp
new file mode 100644
index 0000000000..794e382bfb
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_client_deadline_test.cpp
@@ -0,0 +1,50 @@
+#include "input_client_deadline.hpp"
+
+#include <array>
+#include <cstdlib>
+#include <iostream>
+
+using cua::hyprland::InputClientDeadline;
+using namespace std::chrono_literals;
+
+namespace {
+void check(bool condition, const char* message) {
+ if (!condition) {
+ std::cerr << "FAIL: " << message << '\n';
+ std::exit(1);
+ }
+}
+}
+
+int main() {
+ const auto start = InputClientDeadline::Clock::time_point{} + 1h;
+ InputClientDeadline deadline(start);
+ check(!deadline.expired(false, start + 4999ms), "HELLO allowed before acceptance deadline");
+ for (auto elapsed = 1s; elapsed < 5s; elapsed += 1s) {
+ deadline.touch(start + elapsed);
+ check(!deadline.expired(false, start + elapsed), "pre-HELLO traffic is initially tolerated");
+ }
+ check(deadline.expired(false, start + 5s), "traffic cannot extend the hard HELLO deadline");
+ check(deadline.expired(false, start + 6s), "late HELLO must be refused before handling it");
+ deadline.touch(start + 6s);
+ check(deadline.expired(false, start + 6s), "even late activity cannot revive an uninitialized client");
+
+ InputClientDeadline initialized(start);
+ initialized.touch(start + 4s); // successful HELLO
+ check(!initialized.expired(true, start + 63999ms), "HELLO begins rolling idle time");
+ check(initialized.expired(true, start + 64s), "initialized idle deadline is sixty seconds");
+ initialized.touch(start + 63s);
+ check(!initialized.expired(true, start + 122999ms), "initialized traffic renews idle time");
+ check(initialized.expired(true, start + 123s), "renewed idle deadline remains bounded");
+
+ std::array<InputClientDeadline, 8> clients{
+ InputClientDeadline(start), InputClientDeadline(start),
+ InputClientDeadline(start), InputClientDeadline(start),
+ InputClientDeadline(start), InputClientDeadline(start),
+ InputClientDeadline(start), InputClientDeadline(start)};
+ for (auto& client : clients) {
+ client.touch(start + 4999ms);
+ check(client.expired(false, start + 5s), "every pre-HELLO slot becomes reclaimable");
+ }
+ std::cout << "input client deadline tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_config_toggle.py b/libs/cua-driver/hyprland-plugin/tests/input_config_toggle.py
new file mode 100644
index 0000000000..b37dbb6f56
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_config_toggle.py
@@ -0,0 +1,40 @@
+"""Config-toggle fault for an explicitly test-owned, sourced Lua file.
+
+The caller must create this exact one-line file in its disposable compositor
+config and pass it explicitly. This helper does not modify arbitrary user
+configuration or unload a session-lifetime input plugin.
+"""
+import json
+from pathlib import Path
+import subprocess
+
+ENABLED = "hl.config({plugin = {cua = {enabled = true}}})\n"
+DISABLED = "hl.config({plugin = {cua = {enabled = false}}})\n"
+
+
+class InputConfigToggle:
+ def __init__(self, path):
+ self.path = Path(path)
+ if self.path.is_symlink() or self.path.read_text() != ENABLED:
+ raise ValueError("require the exact test-owned enabled Lua include")
+ self.changed = False
+
+ def _set(self, enabled):
+ expected = DISABLED if self.changed else ENABLED
+ if self.path.is_symlink() or self.path.read_text() != expected:
+ raise RuntimeError("test-owned toggle file changed unexpectedly")
+ self.path.write_text(ENABLED if enabled else DISABLED)
+ self.changed = not enabled
+ output = subprocess.check_output(["hyprctl", "reload"], text=True, timeout=5)
+ if output.strip() != "ok":
+ raise RuntimeError("config reload did not acknowledge toggle")
+ status = json.loads(subprocess.check_output(["hyprctl", "-j", "cua:status"], timeout=5))
+ if status.get("configured") is not enabled or status.get("experiment", {}).get("transport_ready") is not enabled:
+ raise RuntimeError("plugin did not observe the sourced toggle file")
+
+ def disable(self):
+ self._set(False)
+
+ def restore(self):
+ if self.changed:
+ self._set(True)
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_config_toggle_test.py b/libs/cua-driver/hyprland-plugin/tests/input_config_toggle_test.py
new file mode 100644
index 0000000000..7cb994743e
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_config_toggle_test.py
@@ -0,0 +1,49 @@
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+from input_config_toggle import DISABLED, ENABLED, InputConfigToggle
+
+
+class InputConfigToggleTest(unittest.TestCase):
+ def test_toggle_and_restore_verify_compositor_state(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "input.lua"
+ path.write_text(ENABLED)
+ toggle = InputConfigToggle(path)
+ replies = ["ok", json.dumps({"configured": False, "experiment": {"transport_ready": False}}),
+ "ok", json.dumps({"configured": True, "experiment": {"transport_ready": True}})]
+ with patch("input_config_toggle.subprocess.check_output", side_effect=replies) as ctl:
+ toggle.disable()
+ self.assertEqual(path.read_text(), DISABLED)
+ toggle.restore()
+ self.assertEqual(path.read_text(), ENABLED)
+ toggle.restore()
+ self.assertEqual(ctl.call_count, 4)
+
+ def test_unsourced_or_changed_include_cannot_pass(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "input.lua"
+ path.write_text("unrelated configuration")
+ with self.assertRaises(ValueError):
+ InputConfigToggle(path)
+ path.write_text(ENABLED)
+ toggle = InputConfigToggle(path)
+ with patch("input_config_toggle.subprocess.check_output", side_effect=["ok", "{}"]):
+ with self.assertRaises(RuntimeError):
+ toggle.disable()
+ self.assertTrue(toggle.changed)
+ path.write_text("unexpected edit")
+ with self.assertRaises(RuntimeError):
+ toggle.restore()
+
+ def test_symlink_is_not_a_test_owned_include(self):
+ with tempfile.TemporaryDirectory() as directory:
+ target = Path(directory) / "target.lua"
+ target.write_text(ENABLED)
+ link = Path(directory) / "input.lua"
+ link.symlink_to(target)
+ with self.assertRaises(ValueError):
+ InputConfigToggle(link)
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_grant_test.cpp b/libs/cua-driver/hyprland-plugin/tests/input_grant_test.cpp
new file mode 100644
index 0000000000..dccd240015
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_grant_test.cpp
@@ -0,0 +1,48 @@
+#include "input_grant.hpp"
+
+#include <cstdlib>
+#include <iostream>
+#include <limits>
+
+using cua::hyprland::InputGrant;
+using namespace std::chrono_literals;
+
+namespace {
+void check(bool condition, const char* message) {
+ if (!condition) {
+ std::cerr << "FAIL: " << message << '\n';
+ std::exit(1);
+ }
+}
+}
+
+int main() {
+ const auto now = InputGrant::Clock::time_point{} + 1h;
+ InputGrant first, second;
+ check(!first.permits(1, now), "fresh connection has no input authority");
+ for (const auto cap : {1u, 2u, 4u, 8u, 16u}) {
+ check(first.arm(cap, now), "each bounded operation can be admitted");
+ check(first.permits(cap, now + 4999ms), "admission lasts less than five seconds");
+ check(!first.permits(cap, now + 5s), "deadline is exclusive");
+ check(!first.consume(cap, now + 5s), "expired authority cannot dispatch");
+ check(first.arm(cap, now), "fresh TARGET can reacquire");
+ check(first.consume(cap, now + 1s), "first dispatch consumes the grant");
+ check(!first.consume(cap, now + 1s), "a second dispatch cannot reuse authority");
+ }
+ for (const auto cap : {0ull, 3ull, 5ull, 7ull, 15ull, 17ull,
+ std::numeric_limits<unsigned long long>::max()}) {
+ check(first.arm(1, now), "seed valid authority");
+ check(!first.arm(cap, now), "zero, combined and unknown capability masks refuse");
+ check(!first.permits(1, now), "invalid fresh admission retires old authority");
+ }
+ check(first.arm(1, now) && second.arm(8, now), "two independent lanes admit different operations");
+ check(!first.consume(2, now), "one capability never grants another operation");
+ check(!first.permits(1, now), "wrong dispatch cannot retain the previous capability");
+ check(second.permits(8, now), "one lane's refusal preserves the other lane");
+ first.reset();
+ check(second.consume(8, now + 2s), "other lane remains usable after cancellation");
+ check(first.arm(2, now), "new admission after cancellation succeeds");
+ first.reset();
+ check(!first.consume(2, now), "revocation invalidates a pending operation");
+ std::cout << "bounded input grant tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_lease_live.py b/libs/cua-driver/hyprland-plugin/tests/input_lease_live.py
new file mode 100644
index 0000000000..546148dc18
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_lease_live.py
@@ -0,0 +1,71 @@
+"""Opt-in expiry/disconnect checks against the disposable-VM input socket.
+
+The operator signs request.json outside the guest and supplies only grant.json.
+No input should be delivered: every attempted click must refuse. This probes
+lease invalidation, not held-input cleanup or application compatibility.
+"""
+import argparse
+import json
+from pathlib import Path
+import time
+
+from input_transport_test import connect, exchange, refused, approved_packet
+
+
+def run(args):
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ client, hello = connect(args.socket, claim=True)
+ operator, _ = connect(args.socket)
+ try:
+ target = exchange(client, f"TARGET {args.pid} {args.address}")
+ assert target.get("ok"), target
+ request = {**hello, **target, "capabilities": 1}
+ (args.evidence / "request.json").write_text(json.dumps(request))
+ print(json.dumps({"event": "grant_required", **request}), flush=True)
+ path = args.evidence / "grant.json"
+ deadline = time.monotonic() + 120
+ while not path.exists():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("public operator grant did not arrive")
+ time.sleep(0.05)
+ grant = json.loads(path.read_text())
+ packet = approved_packet(grant, hello, target)
+ assert exchange(operator, packet).get("ok"), "approval failed"
+ if args.case == "expiry":
+ remaining = int(packet.split()[3]) / 1000 - time.time()
+ if not 0 < remaining <= 20:
+ raise ValueError("expiry probe needs a grant with at most 20 seconds remaining")
+ time.sleep(remaining + 0.2)
+ else:
+ client.close()
+ time.sleep(0.1)
+ client, fresh = connect(args.socket, claim=True)
+ assert fresh["challenge"] != hello["challenge"]
+ assert fresh["epoch"] == hello["epoch"]
+ target = exchange(client, f"TARGET {args.pid} {args.address}")
+ assert target.get("ok"), target
+ refused(exchange(operator, packet), "stale_target")
+ response = exchange(client, f"CLICK 1 {target['target']} {target['revision']} 200 300 272 1")
+ refused(response, "pending_operator_approval")
+ result = {"result": "passed", "case": args.case, "input_refused": True,
+ "held_state_cleanup_tested": False}
+ (args.evidence / "result.json").write_text(json.dumps(result))
+ print(json.dumps(result), flush=True)
+ finally:
+ try:
+ exchange(operator, "STOP")
+ finally:
+ operator.close()
+ client.close()
+
+
+if __name__ == "__main__":
+ if not __debug__:
+ raise RuntimeError("assertions must be enabled")
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--case", choices=["expiry", "disconnect"], required=True)
+ parser.add_argument("--socket", type=Path, required=True)
+ parser.add_argument("--pid", type=int, required=True)
+ parser.add_argument("--address", required=True)
+ parser.add_argument("--evidence", type=Path, required=True)
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_lifecycle_live.py b/libs/cua-driver/hyprland-plugin/tests/input_lifecycle_live.py
new file mode 100644
index 0000000000..5385b16991
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_lifecycle_live.py
@@ -0,0 +1,306 @@
+"""Held-input failure proof through Driver MCP in a disposable Hyprland VM.
+
+The reviewed plan binds two already-observed native fixtures and canvas points.
+Only the host operator signs grants. Raw wire logs stay local; public results
+contain categorical outcomes and timing. This supplements the desktop matrix.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import json
+from pathlib import Path
+import select
+import subprocess
+import time
+from types import SimpleNamespace
+
+from driver_input_live import MCP, journal, state, wait_for, wm
+from input_transport_test import connect, exchange, refused
+from lifecycle_evidence import held_release, primary_wire_events, unchanged_primary
+from realapp_proof import cleanup_all
+from compositor_stall import stall_past_expiry
+from input_config_toggle import InputConfigToggle
+
+
+def validate_plan(plan):
+ targets = [plan[name] for name in ('background', 'foreground')]
+ assert all(set(target) == {'pid', 'window_id'} for target in targets)
+ assert all(type(target['pid']) is int and target['pid'] > 0 for target in targets)
+ assert targets[0]['pid'] != targets[1]['pid'], 'primary and agent must use separate fixture processes'
+ for name in ('background', 'foreground'):
+ bounds = plan[name + '_bounds']
+ assert all(type(bounds[key]) in (int, float) for key in ('x', 'y', 'width', 'height'))
+ assert bounds['width'] > 0 and bounds['height'] > 0
+ for name in ('from', 'to'):
+ point = plan[name]
+ assert len(point) == 2 and all(type(value) in (int, float) and value >= 0 for value in point)
+ # Driver uses snapshot pixels; exact point-to-image bounds are checked
+ # again against the fresh grounding response in run().
+ point = plan['foreground_point']
+ bounds = plan['foreground_bounds']
+ assert len(point) == 2 and 0 < point[0] < bounds['width'] and 0 < point[1] < bounds['height']
+
+
+def run(args):
+ # Refuse the historical hot-reload test before starting input or unloading
+ # a restart-required module. Its replacement is config-toggle recovery.
+ status = json.loads(subprocess.check_output(['hyprctl', '-j', 'cua:status'], timeout=5))
+ if args.case == 'reload' and status.get('experiment', {}).get('upgrade') == 'desktop_restart':
+ raise ValueError('use the toggle case; plugin replacement requires a desktop restart')
+ if args.case == 'toggle' and not args.toggle_file:
+ raise ValueError('toggle case requires an explicit test-owned Lua include')
+ toggle = InputConfigToggle(args.toggle_file) if args.case == 'toggle' else None
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ target, foreground = plan['background'], plan['foreground']
+ label = 'lifecycle-' + args.evidence.name
+ client = observer = grab = operator = executor = None
+ recording = False
+ unloaded = False
+ result = {'result': 'failed', 'case': args.case, 'full_desktop_matrix': False}
+
+ def new_client(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ return MCP(SimpleNamespace(evidence=directory, driver=args.driver, driver_socket=args.driver_socket))
+
+ def snapshot(mcp, selection):
+ value = mcp.tool('get_window_state', {**selection, 'max_elements': 80})
+ assert not value.get('isError'), value
+ data = value['structuredContent']
+ assert data.get('screenshot_width', 0) > 0, 'missing grounding screenshot'
+ return data
+
+ def input_args():
+ return {**target, 'session': label, 'delivery_mode': 'background'}
+
+ def request_grant(mcp, suffix):
+ snapshot(mcp, target)
+ response = mcp.tool('press_key', {**input_args(), 'key': 'Escape'})
+ snapshot(observer, target)
+ pending = response.get('structuredContent', {})
+ assert response.get('isError') and pending.get('reason') == 'pending_operator_approval', response
+ (args.evidence / f'request-{suffix}.json').write_text(json.dumps(pending))
+ return pending
+
+ def read_new_wire(offset):
+ with args.foreground_wire.open('rb') as stream:
+ stream.seek(offset)
+ return stream.read().decode('utf-8')
+
+ try:
+ observer, client = new_client('observer'), new_client('agent')
+ bg = snapshot(client, target)
+ fg = snapshot(observer, foreground)
+ assert bg['window_bounds'] == plan['background_bounds'], 'stale target geometry'
+ assert fg['window_bounds'] == plan['foreground_bounds'], 'stale foreground geometry'
+ for point in (plan['from'], plan['to']):
+ assert point[0] < bg['screenshot_width'] and point[1] < bg['screenshot_height']
+ desktop = observer.tool('get_desktop_state', {})['structuredContent']
+ point = plan['foreground_point']
+ box = fg['window_bounds']
+ grab = subprocess.Popen([str(args.primary_grab), str(box['x'] + point[0]),
+ str(box['y'] + point[1]), str(desktop['screen_width']),
+ str(desktop['screen_height']), '60000'],
+ stdout=subprocess.PIPE, text=True)
+ wait_for(lambda: select.select([grab.stdout], [], [], 0)[0])
+ assert grab.stdout.readline().strip() == 'HELD'
+ wait_for(lambda: state(args.foreground_journal)['held'])
+ snapshot(observer, foreground)
+ primary = wm()
+ assert primary['pid'] == foreground['pid']
+ before_primary = state(args.foreground_journal)
+ # A missing or disabled wire logger must not turn into an empty pass.
+ assert 'wl_pointer.button' in primary_wire_events(args.foreground_wire.read_text())
+ pending = request_grant(client, 'initial')
+ grant_path = args.evidence / 'grant-initial.json'
+ print('GRANT_REQUIRED', flush=True)
+ wait_for(grant_path.exists, 35) # Primary adversary has a 60-second ceiling.
+ grant = json.loads(grant_path.read_text())
+ assert all(grant[key] == pending[key] for key in ('epoch', 'challenge', 'target'))
+ assert grant['capabilities'] == 10, 'grant must cover only drag and recovery key probe'
+ lane = pending['lane']
+ input_path = args.input_directory / ('cua-input-test.sock' if lane == 0 else 'cua-input-test-2.sock')
+ operator, _ = connect(input_path)
+ assert exchange(operator, grant['packet'])['ok']
+ # Native recording is supporting evidence, never the cleanup oracle.
+ if args.record_video:
+ response = observer.tool('start_recording', {'output_dir': str(args.evidence / 'recording'),
+ 'record_video': True})
+ assert not response.get('isError'), response
+ assert response.get('structuredContent', {}).get('video_active') is True, 'video did not start'
+ recording = True
+ if args.case == 'expiry':
+ assert args.compositor_pid, 'expiry fault requires an explicitly selected disposable compositor'
+ wait_for(lambda: grant['expires_unix_ms'] / 1000 - time.time() <= 2.9, 60)
+ snapshot(client, target)
+ background_offset = len(journal(args.background_journal))
+ wire_offset = args.foreground_wire.stat().st_size
+ executor = ThreadPoolExecutor(max_workers=1)
+ started_ns = time.monotonic_ns()
+ future = executor.submit(client.tool, 'drag', {**input_args(),
+ 'from_x': plan['from'][0], 'from_y': plan['from'][1],
+ 'to_x': plan['to'][0], 'to_y': plan['to'][1],
+ # Leave room for a fresh snapshot before the expiry admission
+ # check. The expiry response, not natural drag completion, must
+ # explain the eventual release after the compositor resumes.
+ 'duration_ms': 500 if args.case == 'expiry' else 2000})
+ press = wait_for(lambda: next((row for row in journal(args.background_journal)[background_offset:]
+ if row['kind'] == 'button-press'), None), 5)
+ fault_ns = time.monotonic_ns()
+ # Driver may record pre-action screenshots before delivering input.
+ # Only the app's actual press starts the held interval, not RPC entry.
+ limit_ns = 200_000_000 if args.case == 'expiry' else 900_000_000
+ assert fault_ns - press['time'] < limit_ns, 'too late to distinguish cancellation from completion'
+ result['dispatch_to_press_ms'] = (press['time'] - started_ns) / 1_000_000
+ if args.case == 'disconnect':
+ client.process.terminate()
+ client.process.wait(timeout=3)
+ elif args.case == 'stop':
+ assert exchange(operator, 'STOP')['ok']
+ elif args.case == 'expiry':
+ stall = stall_past_expiry(args.compositor_pid, grant['expires_unix_ms'])
+ fault_ns = stall['resume_ns']
+ result.update(compositor_stall_ms=stall['stall_ms'], release_bound_origin='compositor_resume',
+ uninterrupted_desktop=False)
+ elif args.case == 'toggle':
+ toggle.disable()
+ operator.close()
+ operator = None
+ elif args.case == 'reload':
+ assert args.reload_module and args.reload_module.is_file()
+ output = subprocess.check_output(['hyprctl', 'plugin', 'unload', str(args.reload_module)], text=True, timeout=5)
+ assert output.strip() == 'ok', output
+ unloaded = True
+ operator.close()
+ operator = None
+ else:
+ raise ValueError('unsupported fault')
+ wait_for(lambda: any(row['kind'] == 'button-release' for row in journal(args.background_journal)[background_offset:]), 3)
+ try:
+ response = future.result(timeout=5)
+ result['action_refusal'] = response.get('structuredContent', {}).get('reason')
+ if args.case == 'stop':
+ assert response.get('isError') and result['action_refusal'] == 'stopped', response
+ if args.case == 'expiry':
+ assert response.get('isError') and result['action_refusal'] == 'lease_expired', response
+ if args.case in ('reload', 'toggle'):
+ assert response.get('isError'), response
+ except (RuntimeError, OSError, ValueError) as error:
+ if args.case != 'disconnect':
+ raise
+ result['action_transport_closed'] = type(error).__name__
+ snapshot(observer, target)
+ snapshot(observer, foreground)
+ assert wm() == primary, 'primary compositor state changed'
+ result.update(unchanged_primary(before_primary, state(args.foreground_journal), read_new_wire(wire_offset)))
+ rows = journal(args.background_journal)[background_offset:]
+ (args.evidence / 'release-evidence.json').write_text(json.dumps({'fault_ns': fault_ns, 'rows': rows}))
+ result.update(held_release(rows, fault_ns=fault_ns, maximum_latency_ms=5000))
+ assert result['release_latency_ms'] <= 750, 'held input was not released within the cancellation bound'
+ assert not state(args.background_journal)['held'], 'application still holds synthetic button'
+ result['observed_release'] = True
+ if args.case == 'toggle':
+ toggle.restore()
+ operator, hello = connect(input_path)
+ assert hello['epoch'] != pending['epoch'], 'toggle retained old admission epoch'
+ result['new_epoch'] = True
+ result['same_application_processes'] = True
+ if args.case == 'reload':
+ output = subprocess.check_output(['hyprctl', 'plugin', 'load', str(args.reload_module)], text=True, timeout=5)
+ assert output.strip() == 'ok', output
+ unloaded = False
+ # The disposable config already explicitly enables the experiment.
+ assert subprocess.check_output(['hyprctl', 'reload'], text=True, timeout=5).strip() == 'ok'
+ snapshot(observer, target)
+ snapshot(observer, foreground)
+ assert wm() == primary, 'reload changed primary compositor state'
+ result.update(unchanged_primary(before_primary, state(args.foreground_journal), read_new_wire(wire_offset)))
+ operator, hello = connect(input_path)
+ assert hello['epoch'] != pending['epoch'], 'reload retained the old epoch'
+ result['new_epoch'] = True
+ if args.case in ('disconnect', 'reload'):
+ client.close()
+ client = new_client('reconnected')
+ snapshot(client, target)
+ ended = client.tool('press_key', {**input_args(), 'key': 'Escape'})
+ snapshot(observer, target)
+ assert ended.get('isError') and any('has ended' in item.get('text', '')
+ for item in ended.get('content', [])), ended
+ result['ended_label_refused'] = True
+ # A new transport cannot revive the old lifecycle by guessing its
+ # public label. Use a genuinely new episode and obtain a new grant.
+ label += '-new'
+ fresh = request_grant(client, 'recovery')
+ if args.case in ('disconnect', 'reload', 'toggle'):
+ assert fresh['challenge'] != pending['challenge'], 'reconnect inherited old authority'
+ refused(exchange(operator, grant['packet']), 'stale_target', 'invalid_grant')
+ elif args.case == 'stop':
+ assert fresh['target'] != pending['target'], 'Stop retained the old target binding'
+ refused(exchange(operator, grant['packet']), 'stale_target')
+ else:
+ refused(exchange(operator, grant['packet']), 'invalid_grant')
+ result.update(result='passed', fresh_approval_required=True, old_grant_refused=True)
+ except Exception as error:
+ result['error_type'] = type(error).__name__
+ result['error'] = str(error)
+ raise
+ finally:
+ def restore_module():
+ if toggle:
+ toggle.restore()
+ if unloaded:
+ output = subprocess.check_output(['hyprctl', 'plugin', 'load', str(args.reload_module)], text=True, timeout=5)
+ assert output.strip() == 'ok', output
+ assert subprocess.check_output(['hyprctl', 'reload'], text=True, timeout=5).strip() == 'ok'
+ def stop_operator():
+ if operator:
+ try:
+ exchange(operator, 'STOP')
+ finally:
+ operator.close()
+ def release_primary():
+ if grab and grab.poll() is None:
+ grab.terminate()
+ grab.wait(timeout=5)
+ wait_for(lambda: not state(args.foreground_journal)['held'])
+ def stop_recording():
+ if recording:
+ response = observer.tool('stop_recording', {})
+ assert not response.get('isError'), response
+ video = response.get('structuredContent', {}).get('last_video_path')
+ assert video and Path(video).is_file() and Path(video).stat().st_size > 0, 'video missing after stop'
+ result['video_file'] = Path(video).name
+ operations = [('operator_stop', stop_operator), ('primary_release', release_primary),
+ ('recording_stop', stop_recording), ('restore_module', restore_module)]
+ if executor:
+ operations.append(('action_thread', lambda: executor.shutdown(wait=True, cancel_futures=True)))
+ if client:
+ operations.append(('client_close', client.close))
+ if observer:
+ operations.append(('observer_close', observer.close))
+ errors = cleanup_all(operations)
+ result['cleanup_errors'] = errors
+ if errors:
+ result['result'] = 'failed'
+ (args.evidence / 'result.json').write_text(json.dumps(result, indent=2))
+ print(json.dumps(result), flush=True)
+ if errors:
+ raise AssertionError('lifecycle cleanup failed')
+ return result
+
+
+if __name__ == '__main__':
+ if not __debug__:
+ raise RuntimeError('assertions must remain enabled')
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--case', choices=('disconnect', 'stop', 'expiry', 'reload', 'toggle'), required=True)
+ for name in ('plan', 'evidence', 'driver', 'driver-socket', 'input-directory',
+ 'primary-grab', 'background-journal', 'foreground-journal', 'foreground-wire'):
+ parser.add_argument('--' + name, type=Path, required=True)
+ parser.add_argument('--record-video', action='store_true')
+ parser.add_argument('--compositor-pid', type=int)
+ parser.add_argument('--reload-module', type=Path)
+ parser.add_argument('--toggle-file', type=Path,
+ help='Explicit test-owned Lua include for config-toggle recovery')
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_operator.py b/libs/cua-driver/hyprland-plugin/tests/input_operator.py
new file mode 100644
index 0000000000..64398d8544
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_operator.py
@@ -0,0 +1,165 @@
+r"""Host-only operator for the nonshipping isolated-input experiment.
+
+Requires the optional Python ``cryptography`` package for key operations.
+Keep the private key outside the VM and outside any agent/MCP-accessible path.
+Transfer only the public key and the JSON output of ``sign`` to the guest.
+This helper has no network or compositor access and never approves implicitly.
+
+Usage (operator shell on the host):
+ python3 input_operator.py keygen --key /operator/private/input.pem
+ python3 input_operator.py public-key --key /operator/private/input.pem
+ python3 input_operator.py sign --key /operator/private/input.pem \
+ --epoch HEX --challenge HEX --target HEX --capabilities 1 --ttl-ms 30000
+"""
+
+import argparse
+import json
+import os
+import re
+import stat
+import sys
+import time
+from pathlib import Path
+
+MAX_UINT64 = (1 << 64) - 1
+MAX_LEASE_MS = 60_000
+
+
+def hex_token(value):
+ if not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{32}", value) is None:
+ raise ValueError("token must be exactly 32 lowercase hexadecimal digits")
+ return value
+
+
+def unsigned(value, maximum=MAX_UINT64):
+ if type(value) is int:
+ number = value
+ elif isinstance(value, str) and re.fullmatch(r"0|[1-9][0-9]*", value):
+ if len(value) > 20:
+ raise ValueError("integer is out of range")
+ number = int(value)
+ else:
+ raise ValueError("integer must be canonical unsigned decimal")
+ if number < 0 or number > maximum:
+ raise ValueError("integer is out of range")
+ return number
+
+
+def canonical_message(epoch, challenge, target, expires_unix_ms, capabilities):
+ tokens = [hex_token(value) for value in (epoch, challenge, target)]
+ expiry = unsigned(expires_unix_ms)
+ caps = unsigned(capabilities, 15)
+ if not caps:
+ raise ValueError("at least one capability is required")
+ return ("CUA_TEST_LEASE_1\n" + "\n".join(tokens + [str(expiry), str(caps)]) + "\n").encode("ascii")
+
+
+def validate_expiry(expires_unix_ms, now_ms):
+ expiry, now = unsigned(expires_unix_ms), unsigned(now_ms)
+ if not now < expiry <= now + MAX_LEASE_MS:
+ raise ValueError("grant must expire in the next 1 to 60000 milliseconds")
+ return expiry
+
+
+def crypto():
+ try:
+ from cryptography.hazmat.primitives import serialization
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+ except ImportError:
+ raise RuntimeError("key operations require the optional cryptography package") from None
+ return serialization, Ed25519PrivateKey
+
+
+def public_key_hex(key):
+ serialization, _ = crypto()
+ return key.public_key().public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ ).hex()
+
+
+def keygen(path):
+ serialization, key_type = crypto()
+ key = key_type.generate()
+ pem = key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ )
+ # Exclusive creation prevents overwriting a key or following a symlink.
+ with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as stream:
+ stream.write(pem)
+ return public_key_hex(key)
+
+
+def load_key(path):
+ serialization, key_type = crypto()
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW), "rb") as stream:
+ metadata = os.fstat(stream.fileno())
+ if (not stat.S_ISREG(metadata.st_mode) or metadata.st_mode & 0o077
+ or metadata.st_uid != os.getuid()):
+ raise ValueError("private key must be an owner-only regular file")
+ pem = stream.read(4097)
+ if len(pem) > 4096:
+ raise ValueError("invalid private key file")
+ try:
+ key = serialization.load_pem_private_key(pem, password=None)
+ except (ValueError, TypeError):
+ raise ValueError("invalid private key file") from None
+ if not isinstance(key, key_type):
+ raise ValueError("private key must be Ed25519")
+ return key
+
+
+def sign_grant(key, epoch, challenge, target, expires_unix_ms, capabilities, now_ms):
+ expiry = validate_expiry(expires_unix_ms, now_ms)
+ message = canonical_message(epoch, challenge, target, expiry, capabilities)
+ caps = unsigned(capabilities, 15)
+ signature = key.sign(message).hex()
+ return {
+ "epoch": epoch,
+ "challenge": challenge,
+ "target": target,
+ "expires_unix_ms": expiry,
+ "capabilities": caps,
+ "packet": f"APPROVE {challenge} {target} {expiry} {caps} {signature}",
+ }
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ commands = parser.add_subparsers(dest="command", required=True)
+ for command in ("keygen", "public-key", "sign"):
+ subparser = commands.add_parser(command)
+ subparser.add_argument("--key", type=Path, required=True)
+ if command == "sign":
+ for name in ("epoch", "challenge", "target", "capabilities"):
+ subparser.add_argument("--" + name, required=True)
+ expiry = subparser.add_mutually_exclusive_group()
+ expiry.add_argument("--expires-unix-ms")
+ expiry.add_argument("--ttl-ms", default="30000")
+ args = parser.parse_args(argv)
+ try:
+ if args.command == "keygen":
+ output = {"public_key": keygen(args.key)}
+ elif args.command == "public-key":
+ output = {"public_key": public_key_hex(load_key(args.key))}
+ else:
+ now = time.time_ns() // 1_000_000
+ expiry = args.expires_unix_ms
+ if expiry is None:
+ expiry = now + unsigned(args.ttl_ms, MAX_LEASE_MS)
+ # Validate all public input before opening the private key.
+ validate_expiry(expiry, now)
+ canonical_message(args.epoch, args.challenge, args.target, expiry, args.capabilities)
+ output = sign_grant(load_key(args.key), args.epoch, args.challenge,
+ args.target, expiry, args.capabilities, now)
+ except (OSError, ValueError, RuntimeError):
+ # Neither exception text nor private-key paths/content belong in logs.
+ print("operator failed: check public arguments, owner-only key file, and cryptography dependency", file=sys.stderr)
+ return 1
+ print(json.dumps(output, separators=(",", ":")))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_operator_test.py b/libs/cua-driver/hyprland-plugin/tests/input_operator_test.py
new file mode 100644
index 0000000000..8893f04c07
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_operator_test.py
@@ -0,0 +1,145 @@
+"""Host-only signing tests. Every private key here is a disposable test key."""
+
+import contextlib
+import io
+import json
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import input_operator as operator
+
+
+EPOCH, CHALLENGE, TARGET = "a" * 32, "b" * 32, "c" * 32
+
+
+class CanonicalTest(unittest.TestCase):
+ def test_exact_bytes_and_final_newline(self):
+ self.assertEqual(
+ operator.canonical_message(EPOCH, CHALLENGE, TARGET, "1700000000123", "15"),
+ b"CUA_TEST_LEASE_1\n" + b"a" * 32 + b"\n" + b"b" * 32
+ + b"\n" + b"c" * 32 + b"\n1700000000123\n15\n",
+ )
+
+ def test_malformed_hex(self):
+ for value in ("a" * 31, "a" * 33, "A" * 32, "g" * 32, "0x" + EPOCH, EPOCH + "\n", None, 1):
+ for index in range(3):
+ tokens = [EPOCH, CHALLENGE, TARGET]
+ tokens[index] = value
+ with self.subTest(value=value, index=index), self.assertRaises(ValueError):
+ operator.canonical_message(*tokens, 1000, 1)
+
+ def test_malformed_numbers(self):
+ for value in (-1, True, 1.0, "01", "+1", " 1", "1\n", "1.0", "nan", "inf", "1e3", str(1 << 64), "9" * 100):
+ with self.subTest(value=value), self.assertRaises(ValueError):
+ operator.canonical_message(EPOCH, CHALLENGE, TARGET, value, 1)
+ for value in (0, 16, -1, True, "01", "1.0"):
+ with self.subTest(caps=value), self.assertRaises(ValueError):
+ operator.canonical_message(EPOCH, CHALLENGE, TARGET, 1000, value)
+
+ def test_expiry_is_future_and_at_most_sixty_seconds(self):
+ self.assertEqual(operator.validate_expiry(60_001, 1), 60_001)
+ self.assertEqual(operator.validate_expiry(2, 1), 2)
+ for expiry in (0, 1, 60_002):
+ with self.subTest(expiry=expiry), self.assertRaises(ValueError):
+ operator.validate_expiry(expiry, 1)
+
+ def test_invalid_arguments_do_not_open_key_or_echo_content(self):
+ out, err = io.StringIO(), io.StringIO()
+ with patch.object(operator, "load_key") as load, contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ result = operator.main(["sign", "--key", "/private/sensitive-path", "--epoch", "sensitive-invalid-value",
+ "--challenge", CHALLENGE, "--target", TARGET, "--capabilities", "1"])
+ self.assertEqual(result, 1)
+ load.assert_not_called()
+ self.assertEqual(out.getvalue(), "")
+ self.assertNotIn("sensitive", err.getvalue())
+
+
+try:
+ operator.crypto()
+ HAS_CRYPTO = True
+except RuntimeError:
+ HAS_CRYPTO = False
+
+
[email protected](HAS_CRYPTO, "optional cryptography package is unavailable")
+class KeyTest(unittest.TestCase):
+ def test_exclusive_owner_only_key_and_public_output(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / "test.pem"
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out):
+ self.assertEqual(operator.main(["keygen", "--key", str(path)]), 0)
+ output = json.loads(out.getvalue())
+ self.assertEqual(set(output), {"public_key"})
+ self.assertRegex(output["public_key"], r"^[0-9a-f]{64}$")
+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)
+ original = path.read_bytes()
+ with self.assertRaises(FileExistsError):
+ operator.keygen(path)
+ self.assertEqual(path.read_bytes(), original)
+ self.assertEqual(operator.public_key_hex(operator.load_key(path)), output["public_key"])
+ self.assertNotIn("PRIVATE", out.getvalue())
+
+ def test_signed_packet_verifies_and_is_bound_to_fields(self):
+ _, key_type = operator.crypto()
+ key = key_type.generate()
+ grant = operator.sign_grant(key, EPOCH, CHALLENGE, TARGET, 60_001, 15, 1)
+ packet = grant["packet"].split(" ")
+ self.assertEqual(packet[:5], ["APPROVE", CHALLENGE, TARGET, "60001", "15"])
+ signature = bytes.fromhex(packet[5])
+ self.assertEqual(len(signature), 64)
+ key.public_key().verify(signature, operator.canonical_message(EPOCH, CHALLENGE, TARGET, 60_001, 15))
+ from cryptography.exceptions import InvalidSignature
+ for tokens in (("d" * 32, CHALLENGE, TARGET, 60_001, 15),
+ (EPOCH, "d" * 32, TARGET, 60_001, 15),
+ (EPOCH, CHALLENGE, "d" * 32, 60_001, 15),
+ (EPOCH, CHALLENGE, TARGET, 60_000, 15),
+ (EPOCH, CHALLENGE, TARGET, 60_001, 1)):
+ with self.subTest(tokens=tokens), self.assertRaises(InvalidSignature):
+ key.public_key().verify(signature, operator.canonical_message(*tokens))
+ self.assertNotIn("private", json.dumps(grant).lower())
+
+ def test_expired_or_overlong_grants_are_never_signed(self):
+ from unittest.mock import Mock
+ key = Mock()
+ for expiry in (1000, 61_001):
+ with self.assertRaises(ValueError):
+ operator.sign_grant(key, EPOCH, CHALLENGE, TARGET, expiry, 1, 1000)
+ key.sign.assert_not_called()
+
+ def test_key_permissions_symlinks_and_parse_errors(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / "test.pem"
+ operator.keygen(path)
+ os.chmod(path, 0o644)
+ with self.assertRaises(ValueError):
+ operator.load_key(path)
+ os.chmod(path, 0o600)
+ link = Path(root) / "link.pem"
+ link.symlink_to(path)
+ with self.assertRaises(OSError):
+ operator.load_key(link)
+ with patch.object(operator.os, "getuid", return_value=-1):
+ with self.assertRaises(ValueError):
+ operator.load_key(path)
+
+ def test_sign_cli_only_emits_public_grant(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / "test.pem"
+ operator.keygen(path)
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out), patch.object(operator.time, "time_ns", return_value=1_000_000_000):
+ self.assertEqual(operator.main(["sign", "--key", str(path), "--epoch", EPOCH,
+ "--challenge", CHALLENGE, "--target", TARGET,
+ "--capabilities", "1", "--ttl-ms", "60000"]), 0)
+ grant = json.loads(out.getvalue())
+ self.assertEqual(grant["expires_unix_ms"], 61_000)
+ self.assertNotIn(str(path), out.getvalue())
+ self.assertNotIn("PRIVATE", out.getvalue())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_retirement_live.py b/libs/cua-driver/hyprland-plugin/tests/input_retirement_live.py
new file mode 100644
index 0000000000..a936aac27f
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_retirement_live.py
@@ -0,0 +1,331 @@
+"""Opt-in irreversible seat retirement in an explicitly disposable desktop.
+
+Requires the existing two GTK fixtures, their journals and WAYLAND_DEBUG logs,
+a reviewed input_lifecycle_live.py plan, an enabled matching experiment, and
+an already running unrestricted Driver service. The operator signs only the
+public grant-request.json (capabilities 10) outside the guest, then transfers
+grant.json. No private key, automatic grant, install, or compositor restart.
+
+Both module paths must already exist and have different canonical paths and
+inodes; the replacement may be an independently staged copy of the same build.
+Unload permanently retires seats for this desktop. The runner intentionally
+leaves the module unloaded and the lifetime marker intact, even on failure.
+Restart the disposable desktop before any further input test. This focused
+native gate does not prove fresh-desktop recovery or the full desktop matrix.
+Raw evidence is private and can contain paths, input, and public grants.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import select
+import stat
+import subprocess
+import sys
+import time
+from types import SimpleNamespace
+
+from driver_input_live import MCP, journal, state, wait_for, wm
+from input_lifecycle_live import validate_plan
+from input_transport_test import connect, exchange
+from lifecycle_evidence import held_release, primary_wire_events, unchanged_primary
+from live_discovery import connect as discovery_connect
+from realapp_proof import cleanup_all
+from retirement_evidence import active_experiment, bound_seats, replacement_refusal, retired_seats, service_owns_socket, socket_closed
+
+
+def ctl(*arguments):
+ return subprocess.check_output(["hyprctl", *arguments], text=True, timeout=5).strip()
+
+
+def status():
+ value = json.loads(ctl("-j", "cua:status"))
+ if not isinstance(value, dict):
+ raise AssertionError("plugin status is not an object")
+ return value
+
+
+def process_identity(pid):
+ directory = Path(f"/proc/{pid}")
+ if directory.stat().st_uid != os.getuid():
+ raise ValueError("selected process does not belong to test user")
+ fields = (directory / "stat").read_text().rsplit(") ", 1)[1].split()
+ if fields[0] in ("Z", "X"):
+ raise AssertionError("selected process is not alive")
+ return (str((directory / "exe").resolve(strict=True)), fields[19])
+
+
+def digest(path):
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def preflight(args):
+ if not __debug__ or sys.platform != "linux" or not args.disposable_session_restart_required:
+ raise ValueError("requires Linux, assertions, and explicit disposable-session-restart-required opt-in")
+ if args.compositor_pid <= 0:
+ raise ValueError("select the exact disposable compositor PID")
+ instance = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "")
+ if not re.fullmatch(r"[a-zA-Z0-9_.-]+", instance) or instance in (".", ".."):
+ raise ValueError("missing safe compositor instance signature")
+ matches = [row for row in json.loads(ctl("-j", "instances")) if row.get("instance") == instance]
+ if len(matches) != 1 or matches[0].get("pid") != args.compositor_pid:
+ raise ValueError("ambient hyprctl instance is not the selected disposable compositor")
+ runtime = Path(os.environ["XDG_RUNTIME_DIR"])
+ expected = runtime / "hypr" / instance
+ for directory in (runtime, runtime / "hypr", expected):
+ metadata = directory.lstat()
+ if (not directory.is_absolute() or not stat.S_ISDIR(metadata.st_mode)
+ or metadata.st_uid != os.getuid() or metadata.st_mode & 0o077):
+ raise ValueError("require private same-user runtime directories without symlinks")
+ if args.input_directory != expected:
+ raise ValueError("input directory must match the exact ambient compositor instance")
+ initial = status()
+ active_experiment(initial)
+ compositor = process_identity(args.compositor_pid)
+ if Path(compositor[0]).name != "Hyprland":
+ raise ValueError("selected process is not Hyprland")
+ for path in (args.module, args.replacement_module, args.driver):
+ if not path.is_absolute() or path.is_symlink() or not path.is_file():
+ raise ValueError("require explicit absolute regular artifact paths")
+ if args.module.resolve() == args.replacement_module.resolve() or args.module.samefile(args.replacement_module):
+ raise ValueError("replacement requires a different canonical path and inode")
+ mapped = {row.split(maxsplit=5)[5] for row in Path(f"/proc/{args.compositor_pid}/maps").read_text().splitlines()
+ if len(row.split(maxsplit=5)) == 6}
+ if str(args.module.resolve()) not in mapped or str(args.replacement_module.resolve()) in mapped:
+ raise ValueError("initial module must be mapped; replacement must not already be mapped")
+ artifacts = {name: digest(getattr(args, name)) for name in ("module", "replacement_module", "driver")}
+ for name, actual in artifacts.items():
+ if actual != getattr(args, name + "_sha256"):
+ raise ValueError("artifact digest does not match selected candidate: " + name)
+ root = Path(__file__).resolve().parents[4]
+ head = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip()
+ if head != args.source_sha:
+ raise ValueError("harness checkout differs from selected source SHA")
+ dirty = subprocess.check_output(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=normal",
+ "--", "libs/cua-driver"], text=True)
+ if dirty:
+ raise ValueError("commit the candidate Driver/plugin/harness changes before native certification")
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ service = process_identity(args.driver_service_pid)
+ if service[0] != str(args.driver.resolve()):
+ raise ValueError("Driver service executable does not match the selected artifact")
+ socket_metadata = args.driver_socket.lstat()
+ if (not args.driver_socket.is_absolute() or not stat.S_ISSOCK(socket_metadata.st_mode)
+ or socket_metadata.st_uid != os.getuid()):
+ raise ValueError("Driver socket must be an absolute same-user socket without a symlink")
+ service_owns_socket(Path("/proc/net/unix").read_text(),
+ [os.readlink(path) for path in Path(f"/proc/{args.driver_service_pid}/fd").iterdir()], args.driver_socket)
+ service_environment = dict(item.split(b"=", 1) for item in
+ Path(f"/proc/{args.driver_service_pid}/environ").read_bytes().split(b"\0") if b"=" in item)
+ if (service_environment.get(b"HYPRLAND_INSTANCE_SIGNATURE") != instance.encode()
+ or service_environment.get(b"CUA_DRIVER_EXPERIMENTAL_HYPRLAND_INPUT") != b"1"):
+ raise ValueError("Driver service must enable input in this exact compositor instance")
+ identities = {args.compositor_pid: compositor, args.driver_service_pid: service}
+ seats = {}
+ for actor in ("background", "foreground"):
+ pid = plan[actor]["pid"]
+ identities[pid] = process_identity(pid)
+ command = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
+ if not any(item.endswith(b"/isolated-input/main.py") for item in command):
+ raise ValueError("selected client must be the disposable isolated-input GTK fixture")
+ log = getattr(args, actor + "_journal")
+ heartbeat = state(log)
+ if heartbeat["held"] or not 0 <= time.monotonic_ns() - heartbeat["time"] <= 2_000_000_000:
+ raise ValueError("fixture must have a fresh idle heartbeat")
+ seats[actor] = bound_seats(getattr(args, actor + "_wire").read_text())
+ marker = expected / "cua-input-seat-lifetime"
+ metadata = marker.lstat()
+ if not stat.S_ISDIR(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o700 or metadata.st_uid != os.getuid():
+ raise ValueError("missing private seat-lifetime marker")
+ paths = [expected / name for name in ("cua-input-test.sock", "cua-input-test-2.sock")]
+ discovery = Path(initial["transport"]["socket"])
+ if discovery.parent != expected:
+ raise ValueError("discovery socket belongs to another instance")
+ return initial, plan, identities, seats, paths + [discovery], (metadata.st_dev, metadata.st_ino), artifacts
+
+
+def run(args):
+ initial, plan, identities, seats, paths, marker_identity, artifacts = preflight(args)
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ result = {"result": "failed", "native_run": True, "source_sha": args.source_sha,
+ "artifact_sha256": artifacts, "full_desktop_matrix": False,
+ "fresh_desktop_recovery_tested": False, "desktop_restart_required": True}
+ clients, sockets = [], []
+ grab = executor = None
+ loaded = args.module
+ unload_attempted = False
+ marker = args.input_directory / "cua-input-seat-lifetime"
+
+ def snapshot(client, actor):
+ response = client.tool("get_window_state", {**plan[actor], "max_elements": 80})
+ assert not response.get("isError"), response
+ value = response["structuredContent"]
+ assert value.get("screenshot_width", 0) > 0 and value.get("screenshot_height", 0) > 0
+ assert value["window_bounds"] == plan[actor + "_bounds"], "fixture geometry changed"
+ return value
+
+ def alive():
+ stamp = time.monotonic_ns()
+ for pid, identity in identities.items():
+ assert process_identity(pid) == identity, "process exited or was replaced"
+ assert json.loads(ctl("-j", "version")), "compositor did not answer"
+ for actor in ("background", "foreground"):
+ wait_for(lambda: state(getattr(args, actor + "_journal"))["time"] > stamp, 2)
+ snapshot(observer, actor)
+
+ def no_transports():
+ assert all(not os.path.lexists(path) for path in paths), "retired transport path remains"
+ metadata = marker.lstat()
+ assert (metadata.st_dev, metadata.st_ino) == marker_identity, "lifetime marker changed"
+
+ try:
+ (args.evidence / "preflight.json").write_text(json.dumps({"status": initial, "identities": identities,
+ "version": json.loads(ctl("-j", "version")), "artifact_sha256": artifacts}, indent=2))
+ for name in ("agent", "observer"):
+ directory = args.evidence / name
+ directory.mkdir()
+ clients.append(MCP(SimpleNamespace(evidence=directory, driver=args.driver, driver_socket=args.driver_socket)))
+ agent, observer = clients
+ bg = snapshot(agent, "background")
+ snapshot(observer, "foreground")
+ for point in (plan["from"], plan["to"]):
+ assert point[0] < bg["screenshot_width"] and point[1] < bg["screenshot_height"]
+ arguments = {**plan["background"], "session": "retirement-" + args.evidence.name, "delivery_mode": "background"}
+ response = agent.tool("press_key", {**arguments, "key": "Escape"})
+ snapshot(observer, "background")
+ pending = response.get("structuredContent", {})
+ assert response.get("isError") and pending.get("reason") == "pending_operator_approval", response
+ (args.evidence / "grant-request.json").write_text(json.dumps(pending))
+ print("GRANT_REQUIRED capabilities=10", flush=True)
+ wait_for((args.evidence / "grant.json").exists, 120)
+ grant = json.loads((args.evidence / "grant.json").read_text())
+ assert all(grant[key] == pending[key] for key in ("epoch", "challenge", "target"))
+ assert grant["capabilities"] == 10 and grant["packet"].split()[4] == "10"
+ assert int(grant["packet"].split()[3]) == grant["expires_unix_ms"]
+ assert 15_000 < grant["expires_unix_ms"] - time.time_ns() // 1_000_000 <= 60_000, "need lease time for setup and fault"
+ for path in paths[:2]:
+ connection, _ = connect(path)
+ sockets.append(connection)
+ sockets.append(discovery_connect(initial))
+ assert type(pending["lane"]) is int and pending["lane"] in (0, 1)
+ operator = sockets[pending["lane"]]
+ assert exchange(operator, grant["packet"])["ok"]
+ desktop = observer.tool("get_desktop_state", {})["structuredContent"]
+ box, point = plan["foreground_bounds"], plan["foreground_point"]
+ grab = subprocess.Popen([str(args.primary_grab), str(box["x"] + point[0]), str(box["y"] + point[1]),
+ str(desktop["screen_width"]), str(desktop["screen_height"]), "60000"], stdout=subprocess.PIPE, text=True)
+ wait_for(lambda: select.select([grab.stdout], [], [], 0)[0])
+ assert grab.stdout.readline().strip() == "HELD"
+ wait_for(lambda: state(args.foreground_journal)["held"])
+ snapshot(observer, "foreground")
+ primary, before = wm(), state(args.foreground_journal)
+ assert primary["pid"] == plan["foreground"]["pid"]
+ assert "wl_pointer.button" in primary_wire_events(args.foreground_wire.read_text())
+ snapshot(agent, "background")
+ assert digest(args.module) == artifacts["module"], "loaded artifact changed after preflight"
+ offsets = {actor: getattr(args, actor + "_wire").stat().st_size for actor in seats}
+ offset = len(journal(args.background_journal))
+ executor = ThreadPoolExecutor(max_workers=1)
+ future = executor.submit(agent.tool, "drag", {**arguments, "from_x": plan["from"][0],
+ "from_y": plan["from"][1], "to_x": plan["to"][0], "to_y": plan["to"][1], "duration_ms": 2000})
+ press = wait_for(lambda: next((row for row in journal(args.background_journal)[offset:]
+ if row["kind"] == "button-press"), None), 5)
+ fault_ns = time.monotonic_ns()
+ assert 0 <= fault_ns - press["time"] < 900_000_000, "fault too late to rule out natural completion"
+ unload_attempted = True
+ assert ctl("plugin", "unload", str(loaded)) == "ok"
+ loaded = None
+ wait_for(lambda: any(row["kind"] == "button-release" for row in journal(args.background_journal)[offset:]), 3)
+ rows = journal(args.background_journal)[offset:]
+ (args.evidence / "release-evidence.json").write_text(json.dumps({"fault_ns": fault_ns, "rows": rows}))
+ result.update(held_release(rows, fault_ns=fault_ns))
+ response = future.result(timeout=5)
+ assert response.get("isError") and response.get("structuredContent", {}).get("reason") == "plugin_shutdown", response
+ for connection in sockets:
+ socket_closed(connection)
+ result["old_connections_closed"] = len(sockets)
+ no_transports()
+ alive()
+ assert not state(args.background_journal)["held"]
+
+ def verify_retirement():
+ alive()
+ assert grab.poll() is None and wm() == primary, "primary grab or compositor state changed"
+ for actor in seats:
+ with getattr(args, actor + "_wire").open("rb") as stream:
+ stream.seek(offsets[actor])
+ wire = stream.read().decode("utf-8")
+ result[actor + "_retirement"] = retired_seats(seats[actor], wire)
+ if actor == "foreground":
+ result.update(unchanged_primary(before, state(args.foreground_journal), wire))
+ no_transports()
+
+ verify_retirement()
+ result["replacement_attempts"] = []
+ for label, module in (("same_path", args.module), ("different_path", args.replacement_module)):
+ assert digest(module) == artifacts["module" if label == "same_path" else "replacement_module"]
+ loaded = module # Cleanup also covers ambiguous load outcomes.
+ assert ctl("plugin", "load", str(module)) == "ok", "replacement registration failed before runtime refusal"
+ assert ctl("reload") == "ok"
+ refusal = status() # Absent/invalid status is a failure, never refusal proof.
+ result["replacement_attempts"].append({"case": label, **replacement_refusal(refusal)})
+ (args.evidence / (label + "-status.json")).write_text(json.dumps(refusal, indent=2))
+ verify_retirement()
+ assert ctl("plugin", "unload", str(module)) == "ok"
+ loaded = None
+ verify_retirement()
+ result.update(result="passed", same_client_processes_alive=True, compositor_alive=True)
+ except Exception as error:
+ result.update(error_type=type(error).__name__, error=str(error))
+ raise
+ finally:
+ def stop_input():
+ if not unload_attempted:
+ for connection in sockets[:2]:
+ exchange(connection, "STOP")
+
+ def release_primary():
+ if grab and grab.poll() is None:
+ grab.terminate()
+ grab.wait(timeout=5)
+ wait_for(lambda: not state(args.foreground_journal)["held"], 3)
+
+ def unload_remaining():
+ assert ctl("plugin", "unload", str(loaded)) == "ok", "cleanup unload was not acknowledged"
+
+ operations = [("stop_input", stop_input)]
+ if unload_attempted and loaded:
+ operations.append(("unload_remaining_module", unload_remaining))
+ operations += [("primary_release", release_primary)]
+ operations += [("socket_close", connection.close) for connection in sockets]
+ if executor:
+ operations.append(("action_thread", lambda: executor.shutdown(wait=True, cancel_futures=True)))
+ operations += [("mcp_close", client.close) for client in clients]
+ errors = cleanup_all(operations)
+ result["cleanup_errors"] = errors
+ if errors:
+ result["result"] = "failed"
+ (args.evidence / "result.json").write_text(json.dumps(result, indent=2))
+ print(json.dumps(result), flush=True)
+ if errors:
+ raise AssertionError("retirement harness cleanup failed")
+ return result
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--disposable-session-restart-required", action="store_true")
+ parser.add_argument("--compositor-pid", type=int, required=True)
+ parser.add_argument("--driver-service-pid", type=int, required=True)
+ parser.add_argument("--source-sha", required=True)
+ for name in ("plan", "evidence", "driver", "driver-socket", "input-directory", "primary-grab",
+ "background-journal", "foreground-journal", "background-wire", "foreground-wire",
+ "module", "replacement-module"):
+ parser.add_argument("--" + name, type=Path, required=True)
+ for name in ("module", "replacement-module", "driver"):
+ parser.add_argument("--" + name + "-sha256", required=True)
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/input_transport_test.py b/libs/cua-driver/hyprland-plugin/tests/input_transport_test.py
new file mode 100644
index 0000000000..a18da5f8b5
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/input_transport_test.py
@@ -0,0 +1,274 @@
+r"""Transport unit checks and an opt-in disposable-guest input refusal suite.
+
+Unit checks: python3 -m unittest input_transport_test
+Live suite: python3 input_transport_test.py --socket PATH --pid PID \
+ --address HEX --click-x X --click-y Y
+
+The live suite prints a JSON grant request, keeps that client open, and reads
+one already-signed grant JSON line from stdin. Sign its epoch/challenge/target
+on the host with input_operator.py (click capability=1), then transfer only
+the JSON grant through the trusted operator channel. No key or signing code
+is loaded in the guest. The supplied coordinates must belong to a disposable
+fixture: exactly one accepted synthetic click is attempted. Application
+effects and primary-seat isolation require independent GUI fixture evidence.
+"""
+
+import argparse
+import io
+import json
+import math
+import re
+import socket
+import stat
+import sys
+import time
+import unittest
+from pathlib import Path
+from unittest.mock import MagicMock, Mock, patch
+
+MAX_PACKET = 2048
+
+
+def exchange(client, packet):
+ encoded = packet.encode("ascii")
+ if not encoded or len(encoded) > MAX_PACKET:
+ raise ValueError("request packet is empty or too large")
+ if client.send(encoded) != len(encoded):
+ raise RuntimeError("partial packet send")
+ raw, _ancillary, flags, _address = client.recvmsg(MAX_PACKET + 1)
+ if flags & socket.MSG_TRUNC or not raw or len(raw) > MAX_PACKET:
+ raise RuntimeError("response is empty or too large")
+ value = json.loads(raw)
+ if not isinstance(value, dict) or type(value.get("ok")) is not bool:
+ raise ValueError("invalid response envelope")
+ return value
+
+
+def connect(path, *, claim=False):
+ metadata = Path(path).stat()
+ if not stat.S_ISSOCK(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o600:
+ raise ValueError("expected a mode-0600 experiment socket")
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+ try:
+ client.settimeout(5)
+ client.connect(str(path))
+ hello = exchange(client, "HELLO")
+ if hello.get("ok") is not True or hello.get("protocol") != 0:
+ raise ValueError("experiment HELLO failed")
+ for name in ("epoch", "challenge"):
+ if re.fullmatch(r"[0-9a-f]{32}", hello.get(name, "")) is None:
+ raise ValueError("invalid HELLO token")
+ if claim:
+ claimed = exchange(client, "CLAIM")
+ if claimed.get("ok") is not True or type(claimed.get("lane")) is not int or claimed["lane"] not in (0, 1):
+ raise ValueError("input lane claim failed")
+ return client, hello
+ except BaseException:
+ client.close()
+ raise
+
+
+def refused(response, *codes):
+ if response.get("ok") is not False or response.get("code") not in codes or not isinstance(response.get("detail"), str):
+ raise AssertionError(f"expected refusal {codes}, received {response}")
+
+
+def accepted(response):
+ if response != {"ok": True, "effect": "unverifiable", "route": "synthetic_events"}:
+ raise AssertionError(f"expected synthetic dispatch acknowledgement, received {response}")
+
+
+def approved_packet(grant, hello, target):
+ """Reject misplaced fixture grants; signature verification stays server-side."""
+ packet = grant.get("packet") if isinstance(grant, dict) else None
+ if not isinstance(packet, str) or re.fullmatch(
+ r"APPROVE [0-9a-f]{32} [0-9a-f]{32} [1-9][0-9]{0,19} [1-9][0-9]? [0-9a-f]{128}", packet
+ ) is None:
+ raise ValueError("expected a signed APPROVE packet")
+ _, challenge, token, expiry, caps, _signature = packet.split(" ")
+ if challenge != hello["challenge"] or token != target["target"]:
+ raise ValueError("grant does not match pending connection and target")
+ if grant.get("epoch") != hello["epoch"]:
+ raise ValueError("grant does not match compositor epoch")
+ if int(expiry) > (1 << 64) - 1 or not 1 <= int(caps) <= 15 or not int(caps) & 1:
+ raise ValueError("grant must include click capability and bounded fields")
+ return packet
+
+
+def run_live(path, pid, address, x, y, grant_input=sys.stdin, output=sys.stdout):
+ if pid <= 0 or pid > (1 << 31) - 1 or re.fullmatch(r"[0-9a-f]{1,16}", address) is None:
+ raise ValueError("expected a positive PID and a lowercase hexadecimal address without 0x")
+ if not math.isfinite(x) or not math.isfinite(y) or x < 0 or y < 0:
+ raise ValueError("click coordinates must be finite and nonnegative")
+ client, hello = connect(path, claim=True)
+ with client:
+ target = exchange(client, f"TARGET {pid} {address}")
+ if target.get("ok") is not True or re.fullmatch(r"[0-9a-f]{32}", target.get("target", "")) is None:
+ raise AssertionError(f"TARGET failed: {target}")
+ revision = target["revision"]
+ if type(revision) is not int or revision < 1 or not (x < target["width"] and y < target["height"]):
+ raise ValueError("invalid target geometry or fixture coordinates")
+ token = target["target"]
+ refused(exchange(client, f"CLICK 1 {token} {revision} {x} {y} 272 1"), "pending_operator_approval")
+ click = f"CLICK 7 {token} {revision} {x} {y} 272 1"
+ # An operator connection has its own HELLO and cannot mint authority.
+ operator_client, operator_hello = connect(path)
+ with operator_client:
+ if operator_hello["challenge"] == hello["challenge"] or operator_hello["epoch"] != hello["epoch"]:
+ raise AssertionError("operator HELLO did not isolate the connection")
+ refused(exchange(operator_client, "APPROVE malformed"), "invalid_request", "invalid_grant")
+ expiry = time.time_ns() // 1_000_000 + 30_000
+ forged = f"APPROVE {hello['challenge']} {token} {expiry} 1 {'0' * 128}"
+ refused(exchange(operator_client, forged), "invalid_grant")
+ print(json.dumps({"event": "grant_required", "epoch": hello["epoch"],
+ "challenge": hello["challenge"], "target": token,
+ "revision": revision, "width": target["width"], "height": target["height"],
+ "capabilities": 1, "max_lifetime_ms": 60_000}), file=output, flush=True)
+ line = grant_input.readline(MAX_PACKET + 1)
+ if not line or len(line) > MAX_PACKET:
+ raise ValueError("signed grant JSON missing or too large")
+ packet = approved_packet(json.loads(line), hello, target)
+ approval = exchange(operator_client, packet)
+ if approval.get("ok") is not True:
+ raise AssertionError(f"operator approval failed: {approval}")
+ try:
+ refused(exchange(operator_client, packet), "invalid_grant", "lease_busy", "replay")
+ for bad in (
+ f"CLICK 2 {token} {revision} nan {y} 272 1",
+ f"CLICK 3 {token} {revision} {x} inf 272 1",
+ f"CLICK 4 {token} {revision} -1 {y} 272 1",
+ f"CLICK 5 {token} {revision} {target['width']} {y} 272 1",
+ f"CLICK 6 {token} {revision} {x} {target['height']} 272 1",
+ ):
+ refused(exchange(client, bad), "invalid_request")
+ accepted(exchange(client, click))
+ refused(exchange(client, click), "replay")
+ finally:
+ stopped = exchange(operator_client, "STOP")
+ if stopped.get("ok") is not True:
+ raise AssertionError(f"STOP failed: {stopped}")
+ refused(exchange(operator_client, packet), "stale_target")
+ refused(exchange(client, f"CLICK 8 {token} {revision} {x} {y} 272 1"), "stale_target")
+ fresh = exchange(client, f"TARGET {pid} {address}")
+ if fresh.get("ok") is not True or fresh.get("target") == token:
+ raise AssertionError("Stop must require a fresh target binding")
+ refused(exchange(operator_client, packet), "stale_target")
+ refused(exchange(client, f"CLICK 9 {fresh['target']} {fresh['revision']} {x} {y} 272 1"), "pending_operator_approval")
+ print(json.dumps({"result": "passed", "missing_grant": "refused", "malformed_grant": "refused",
+ "forged_grant": "refused", "grant_replay": "refused", "grant_replay_after_stop": "refused", "sequence_replay": "refused",
+ "invalid_coordinates": "refused", "stop": "revoked", "accepted_clicks": 1,
+ "effect": "unverifiable", "route": "synthetic_events"}), file=output, flush=True)
+
+
+class TransportTest(unittest.TestCase):
+ def run_scripted_live(self, fail_click=False):
+ hello = {"epoch": "a" * 32, "challenge": "b" * 32}
+ target = {"ok": True, "target": "c" * 32, "revision": 1, "width": 100, "height": 100}
+ grant = {"epoch": hello["epoch"],
+ "packet": f"APPROVE {hello['challenge']} {target['target']} 1700000000000 1 {'d' * 128}"}
+ refusal = lambda code: {"ok": False, "code": code, "detail": "synthetic refusal"}
+ responses = [target, refusal("pending_operator_approval"), refusal("invalid_request"),
+ refusal("invalid_grant"), {"ok": True}, refusal("lease_busy")]
+ responses += [refusal("invalid_request")] * 5
+ if fail_click:
+ responses += [refusal("primary_target_busy"), {"ok": True}]
+ else:
+ responses += [{"ok": True, "effect": "unverifiable", "route": "synthetic_events"},
+ refusal("replay"), {"ok": True}, refusal("stale_target"), refusal("stale_target"),
+ {**target, "target": "f" * 32}, refusal("stale_target"), refusal("pending_operator_approval")]
+ connections = [(MagicMock(), hello), (MagicMock(), {**hello, "challenge": "e" * 32})]
+ output = io.StringIO()
+ with patch(__name__ + ".connect", side_effect=connections), patch(__name__ + ".exchange", side_effect=responses) as send:
+ if fail_click:
+ with self.assertRaises(AssertionError):
+ run_live(Path("synthetic.sock"), 123, "abc", 5, 5, io.StringIO(json.dumps(grant) + "\n"), output)
+ self.assertEqual(send.call_args.args[1], "STOP")
+ self.assertNotIn('"result": "passed"', output.getvalue())
+ else:
+ run_live(Path("synthetic.sock"), 123, "abc", 5, 5, io.StringIO(json.dumps(grant) + "\n"), output)
+ records = [json.loads(line) for line in output.getvalue().splitlines()]
+ self.assertEqual(records[0]["event"], "grant_required")
+ self.assertEqual(records[1]["accepted_clicks"], 1)
+ self.assertEqual(send.call_count, len(responses))
+
+ def test_live_sequence_with_already_signed_fixture(self):
+ self.run_scripted_live()
+
+ def test_live_failure_still_revokes_grant(self):
+ self.run_scripted_live(fail_click=True)
+
+ def test_packet_framing(self):
+ client = Mock()
+ client.send.return_value = 5
+ client.recvmsg.return_value = (b'{"ok":true}', [], 0, None)
+ self.assertEqual(exchange(client, "HELLO"), {"ok": True})
+ client.send.assert_called_once_with(b"HELLO")
+
+ def test_truncated_or_invalid_responses(self):
+ for raw, flags in ((b"", 0), (b"x" * (MAX_PACKET + 1), 0),
+ (b'{"ok":true}', socket.MSG_TRUNC), (b"[]", 0),
+ (b'{"ok":1}', 0), (b"not-json", 0)):
+ client = Mock()
+ client.send.return_value = 5
+ client.recvmsg.return_value = (raw, [], flags, None)
+ with self.subTest(raw=raw[:30], flags=flags), self.assertRaises((ValueError, RuntimeError)):
+ exchange(client, "HELLO")
+
+ def test_partial_send_and_packet_limits(self):
+ client = Mock()
+ client.send.return_value = 1
+ with self.assertRaises(RuntimeError):
+ exchange(client, "HELLO")
+ for packet in ("", "x" * (MAX_PACKET + 1), "é"):
+ with self.assertRaises(ValueError):
+ exchange(client, packet)
+
+ def test_refusals_require_structured_expected_code(self):
+ refused({"ok": False, "code": "replay", "detail": "old sequence"}, "replay")
+ for response in ({"ok": True}, {"ok": False, "code": "replay"},
+ {"ok": False, "code": "invalid_request", "detail": "bad"}):
+ with self.assertRaises(AssertionError):
+ refused(response, "replay")
+
+ def test_signed_fixture_matches_pending_connection(self):
+ hello = {"epoch": "a" * 32, "challenge": "b" * 32}
+ target = {"target": "c" * 32}
+ packet = f"APPROVE {hello['challenge']} {target['target']} 1700000000000 1 {'d' * 128}"
+ grant = {"epoch": hello["epoch"], "packet": packet}
+ self.assertEqual(approved_packet(grant, hello, target), packet)
+ for invalid in ({**grant, "epoch": "e" * 32}, {**grant, "packet": packet + " extra"},
+ {**grant, "packet": packet.replace("b" * 32, "e" * 32)},
+ {**grant, "packet": packet.replace("c" * 32, "e" * 32)},
+ {**grant, "packet": packet.replace(" 1 ", " 2 ")},
+ {**grant, "packet": packet.replace("1700000000000", str(1 << 64))}):
+ with self.subTest(invalid=invalid), self.assertRaises(ValueError):
+ approved_packet(invalid, hello, target)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--socket", type=Path, required=True)
+ parser.add_argument("--pid", type=int, required=True)
+ parser.add_argument("--address", required=True)
+ parser.add_argument("--click-x", type=float, required=True)
+ parser.add_argument("--click-y", type=float, required=True)
+ parser.add_argument("--grant-file", type=Path,
+ help="Read a public operator grant from a new file instead of stdin")
+ args = parser.parse_args()
+ class GrantFile:
+ def readline(self, maximum):
+ deadline = time.monotonic() + 45
+ while not args.grant_file.exists():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("external operator grant did not arrive")
+ time.sleep(0.1)
+ with args.grant_file.open() as stream:
+ return stream.readline(maximum)
+ if args.grant_file and args.grant_file.exists():
+ raise ValueError("grant file must not exist before the pending challenge")
+ run_live(args.socket, args.pid, args.address, args.click_x, args.click_y,
+ GrantFile() if args.grant_file else sys.stdin)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/lifecycle-validation.md b/libs/cua-driver/hyprland-plugin/tests/lifecycle-validation.md
new file mode 100644
index 0000000000..0c7f5fa053
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/lifecycle-validation.md
@@ -0,0 +1,156 @@
+# Held-input lifecycle validation
+
+On 2026-09-05, the experimental Hyprland input path released a held background
+button after operator Stop, agent disconnect, lease expiry, and plugin unload.
+The recorded runs observed release in 18–62 ms, with the expiry interval measured
+from compositor resume. The foreground fixture retained its grab and received
+no pointer or keyboard events during each measured fault window.
+
+This is focused reliability evidence for [draft
+#3572](https://github.com/trycua/cua/pull/3572), not production certification.
+The normal plugin build remains discovery-only. The earlier
+[Calc and Inkscape results](realapp-validation.md) retain their own source SHA;
+this pass does not recertify those applications.
+
+## Exact artifacts
+
+The native build uses committed source. Later commits change test orchestration
+only; the report and test instructions add no native-code changes.
+
+| Component | Tested identity |
+| --- | --- |
+| Native Driver and plugin source | `8882780b79514e35e5f5601800a740c17c95505c` |
+| Final lifecycle helper source | `b8c7ad0c578d260bc743783824a6c45cef9106fa` |
+| Baseline Driver source | `e71ed83f43e3d8cd2963c040b8d7d287bcbc9ba8` |
+| Omarchy | `4.0.1-1`, disposable Cua Fleet VM |
+| Hyprland | `0.56.2-1`, commit `efb50993780079460b0cbed1363e2166a2de1d9f` |
+| Portal | `xdg-desktop-portal-hyprland 1.4.1-1` |
+| Driver source and installed version | `0.23.2`, task-local source build |
+| Plugin | `0.1.0`, explicitly enabled input experiment |
+| Compiler | GCC `16.1.1`, matching the compositor |
+| Recorder | `wf-recorder 0.6.0-2`, task-local installation |
+| Display | One 1920 × 1080 output, scale 1 |
+
+The SHA-256 values are:
+
+- Native source archive: `533fa705e187655b6d4eb06657963571b6be43ed190f06c7b600820490261b5a`.
+- Driver: `2680d5f3e013b845b5f9c8bad625a551a5049f62f92f36dd6ae21c6a9b5ae55a`.
+- Plugin: `d7e9f050da45819304ca69b11dae1cf887ddb931efe1fd3747340fa710ddcd14`.
+- `input_lifecycle_live.py`: `801996a702cfa0800e7790f2c0b87bd223c53c427cfeb0ac0665275ba9bb29ed`.
+
+The installed Driver and the running service executable had identical digests.
+Driver `get_config` reported the native source SHA above. The release installation
+was preserved; the candidate and recorder were installed only in the guest's
+task directory. No host installation or Fleet image publication occurred.
+
+## Regression and fix
+
+The baseline disconnect test released the button **1962.39 ms** after the agent
+MCP proxy disconnected: the two-second drag completed instead of cancelling
+promptly. It failed the 750 ms release bound even though foreground isolation
+held and eventual release was balanced.
+
+The common lifecycle registry now exposes a read-only pending-termination
+signal. The experimental Linux adapter checks its private lifecycle identity
+before and after socket readiness, polling at most every 25 ms while waiting.
+On cancellation, it drops only that lifecycle's owned connection, allowing the
+plugin to release input before the normal dispatch-cleanup barrier finishes.
+Other platform adapters and the common final-cleanup barrier are unchanged.
+The plugin's timer-expiry refusal now reports `lease_expired` explicitly.
+
+## Test method
+
+[`input_lifecycle_live.py`](input_lifecycle_live.py) drives two native GTK
+DrawingArea fixtures through independent agent and observer MCP connections.
+Every background action uses a reviewed target and fresh Driver snapshots.
+The host operator signs a short-lived connection/target/epoch-bound grant;
+the private key never enters the guest.
+
+An independent virtual primary pointer holds a real foreground Wayland grab.
+Application journals prove receipt of the synthetic press and matching release.
+The foreground client's Wayland wire log detects input events, including
+transient motion, enter/leave, buttons, axes, keys, and modifiers. Foreground
+state and compositor cursor/focus/workspace readback supplement that log.
+Matching cursor endpoints alone cannot pass the test.
+
+Stop, disconnect, and unload occur within 900 ms of the application's actual
+press in a two-second drag. Natural completion cannot satisfy the 750 ms release
+bound. RPC entry is not the press timestamp: recording and snapshots introduced
+859–1000 ms of pre-delivery work in these recorded runs.
+
+Expiry uses a 500 ms drag and deliberately freezes the disposable compositor
+past the grant deadline. A separate PID-fd watchdog resumes the exact process
+if the caller fails. The measured release interval starts immediately before
+SIGCONT, and the action must refuse with `lease_expired`. This proves expiry
+cleanup after resume, not continued desktop responsiveness during the stall.
+See the [runner instructions](README.md#held-input-lifecycle-faults).
+
+## Recorded results
+
+Each row passed with a balanced synthetic release, zero foreground pointer or
+keyboard events, a preserved foreground grab, and no cleanup errors. Every row
+required fresh operator approval and refused replay of the previous grant.
+Disconnect and reload also refused the ended public session label; a new
+transport used a new label to request authorization.
+
+| Fault | Release latency | Action outcome | Original video duration |
+| --- | ---: | --- | ---: |
+| Operator Stop | 26.87 ms | `stopped` | 9.044 s |
+| Agent MCP disconnect | 61.76 ms | Transport closed | 10.662 s |
+| Lease expiry | 18.18 ms after resume | `lease_expired`; compositor stalled 1056.27 ms | 15.426 s |
+| Plugin unload/reload | 60.58 ms | `plugin_shutdown`; new epoch after reload | 13.820 s |
+
+The four original 1920 × 1080 H.264 recordings fully decoded, and representative
+frames plus fresh final Driver snapshots were inspected. Video is supporting
+evidence; application and wire timestamps establish the release bounds. Reload
+briefly displayed an unknown-plugin-config warning while the module was absent;
+it cleared after reload. This is not a claim of visually seamless reload.
+
+Earlier unrecorded candidate runs also passed: Stop 6.78 ms, disconnect 19.57 ms,
+expiry 27.39 ms after resume, and unload 39.16 ms. Those runs and the baseline
+have trajectory snapshots, not videos. They are individual observations, not a
+latency distribution or performance guarantee.
+
+Raw operational logs, grants, and machine-specific evidence remain outside the
+public repository. The retained private bundle includes both passing and failed
+attempts. No raw traces or authorization packets are needed to run the committed
+helpers against new synthetic fixtures.
+
+## Supporting checks and failed setup attempts
+
+- All 18 common lifecycle and nine Linux `hyprland_input` unit tests passed
+ natively. The tested Rust source tree matched the committed native archive.
+- All six native plugin CTests passed.
+- All 44 Python helper tests passed locally and in the Fleet guest with the
+ final helper. Rust formatting and diff checks passed.
+- Initial candidate disconnect released promptly but failed a test assumption
+ that a new transport could reuse an ended label. The corrected helper requires
+ a new lifecycle and fresh approval.
+- An initial expiry attempt exhausted its lease before pressing. The helper now
+ reserves snapshot time and requires an actual press before injecting the fault.
+- Initial trajectory runs omitted explicit video. The helper now requires
+ `video_active: true` and a nonempty finalized video file when recording is
+ requested. The fresh image also needed a task-local recorder dependency.
+- The first recorded disconnect attempt used RPC entry for its early-fault
+ threshold. The helper now uses the application's received-press timestamp.
+- One Stop attempt timed out waiting for a grant and cleaned up. A new run with
+ fresh approval passed; the timed-out attempt is not counted as evidence.
+
+## Remaining gates
+
+The later [desktop-state pass](desktop-state-validation.md) separately covers
+target loss, geometry changes, lock, and DPMS with its own candidate and matched
+controls. It does not change the scope of the lifecycle results recorded here.
+
+These tests prove held-pointer cleanup only. Atomic key packets do not expose a
+held-key stream. They do not establish physical-mouse behavior, target-loss or
+mid-action geometry handling, lock/DPMS behavior, broad app/toolkit compatibility,
+fractional scaling, multiple monitors, or the canonical cross-platform desktop
+matrix.
+
+Reload proves cleanup, epoch replacement, and refusal of stale authority. It
+does not prove surviving clients automatically bind replacement seats or accept
+new input. The bounded resident-handler workaround remains experimental.
+Production resource lifetime, authorization UX, and the protocol/RFC decision
+remain open. Keep the PR draft; this record does not authorize merge, release,
+or rollout.
diff --git a/libs/cua-driver/hyprland-plugin/tests/lifecycle_evidence.py b/libs/cua-driver/hyprland-plugin/tests/lifecycle_evidence.py
new file mode 100644
index 0000000000..53ebd08369
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/lifecycle_evidence.py
@@ -0,0 +1,77 @@
+"""Independent, fail-closed fixture oracles for held-input lifecycle tests.
+
+Application journals prove received input; Wayland client logs prove primary
+pointer/keyboard events. Plugin counters and Driver responses cannot substitute
+for either. Use only disposable fixtures: raw wire logs can contain keycodes.
+"""
+import re
+
+
+INPUT = re.compile(r"\b(wl_pointer|wl_keyboard)(?:#|@)(\d+)\.(\w+)\(")
+POINTER_EVENTS = {"enter", "leave", "motion", "button", "axis"}
+KEYBOARD_EVENTS = {"enter", "leave", "key", "modifiers"}
+
+
+def primary_wire_events(text):
+ """Return event categories only, never keycodes, text, or raw log lines."""
+ events = []
+ for line in text.splitlines():
+ match = INPUT.search(line)
+ if not match:
+ continue
+ interface, _resource, event = match.groups()
+ allowed = POINTER_EVENTS if interface == "wl_pointer" else KEYBOARD_EVENTS
+ if event in allowed:
+ events.append(interface + "." + event)
+ return events
+
+
+def held_release(rows, *, fault_ns, maximum_latency_ms=750):
+ """Require a real press before the fault and its matching release afterward.
+
+An eventual release at normal drag completion is not prompt cancellation. The
+caller must inject the fault with more than maximum_latency_ms left in the drag.
+"""
+ relevant = [row for row in rows if row["kind"] in ("button-press", "button-release")]
+ if not relevant or relevant[0]["kind"] != "button-press":
+ raise AssertionError("missing captured press before fault")
+ held = set()
+ fault_held = None
+ release_ns = None
+ previous = -1
+ for row in relevant:
+ stamp = row["time"]
+ if type(stamp) is not int or stamp < previous:
+ raise AssertionError("invalid or unordered application timestamps")
+ previous = stamp
+ if stamp >= fault_ns and fault_held is None:
+ fault_held = set(held)
+ button = row["button"]
+ if row["kind"] == "button-press":
+ if button in held or stamp >= fault_ns:
+ raise AssertionError("duplicate or post-fault press")
+ held.add(button)
+ else:
+ if button not in held:
+ raise AssertionError("release without matching press")
+ held.remove(button)
+ if stamp >= fault_ns and not held:
+ release_ns = stamp
+ if held or not fault_held or release_ns is None:
+ raise AssertionError("fault did not interrupt held input with a proven release")
+ latency = (release_ns - fault_ns) / 1_000_000
+ if not 0 <= latency <= maximum_latency_ms:
+ raise AssertionError("held input was not released within the cancellation bound")
+ return {"held_at_fault": True, "release_latency_ms": latency, "balanced_buttons": True}
+
+
+def unchanged_primary(before, after, wire):
+ for field in ("clicks", "keys", "held"):
+ if field not in before or field not in after or before[field] != after[field]:
+ raise AssertionError("foreground application state changed or is missing")
+ if before["held"] is not True:
+ raise AssertionError("foreground had no active grab")
+ events = primary_wire_events(wire)
+ if events:
+ raise AssertionError("unexpected primary input events: " + ", ".join(events))
+ return {"foreground_grab_preserved": True, "primary_wire_input_events": 0}
diff --git a/libs/cua-driver/hyprland-plugin/tests/lifecycle_evidence_test.py b/libs/cua-driver/hyprland-plugin/tests/lifecycle_evidence_test.py
new file mode 100644
index 0000000000..6837672a93
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/lifecycle_evidence_test.py
@@ -0,0 +1,56 @@
+import unittest
+
+from lifecycle_evidence import held_release, primary_wire_events, unchanged_primary
+
+
+def button(kind, timestamp, number=1):
+ return {"kind": kind, "time": timestamp, "button": number}
+
+
+class LifecycleEvidenceTest(unittest.TestCase):
+ def test_release_requires_input_held_at_fault(self):
+ rows = [button("button-press", 10), button("button-release", 40_000_010)]
+ result = held_release(rows, fault_ns=20_000_010)
+ self.assertEqual(result["release_latency_ms"], 20)
+ for bad in ([], rows[:1], rows[1:],
+ [button("button-press", 30_000_010), rows[1]],
+ [rows[0], button("button-release", 11)]):
+ with self.subTest(rows=bad), self.assertRaises(AssertionError):
+ held_release(bad, fault_ns=20_000_010)
+
+ def test_late_natural_completion_is_not_prompt_cancellation(self):
+ with self.assertRaises(AssertionError):
+ held_release([button("button-press", 10), button("button-release", 2_000_000_010)],
+ fault_ns=20_000_010)
+
+ def test_duplicate_press_wrong_release_and_bad_order_refuse(self):
+ press = button("button-press", 10)
+ release = button("button-release", 40)
+ for rows in ([press, press, release], [press, button("button-release", 40, 2)],
+ [press, release, button("button-release", 30)]):
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ held_release(rows, fault_ns=20)
+
+ def test_wire_parser_covers_both_wayland_debug_formats(self):
+ text = "[1] wl_pointer#8.motion(2, 3, 4)\n[2] [email protected](1, 2, 30, 1)"
+ self.assertEqual(primary_wire_events(text), ["wl_pointer.motion", "wl_keyboard.key"])
+ self.assertEqual(primary_wire_events("wl_pointer#8.frame()\nwl_surface#4.commit()"), [])
+
+ def test_warp_and_return_is_not_hidden_by_matching_endpoints(self):
+ state = {"held": True, "clicks": 0, "keys": ""}
+ wire = "wl_pointer#8.motion(2, 80, 80)\nwl_pointer#8.motion(3, 30, 30)"
+ with self.assertRaises(AssertionError):
+ unchanged_primary(state, state, wire)
+
+ def test_primary_state_needs_real_grab_and_complete_fields(self):
+ state = {"held": True, "clicks": 0, "keys": ""}
+ self.assertEqual(unchanged_primary(state, state, "")["primary_wire_input_events"], 0)
+ for after in ({}, {**state, "held": False}, {**state, "keys": "a"}):
+ with self.assertRaises(AssertionError):
+ unchanged_primary(state, after, "")
+ with self.assertRaises(AssertionError):
+ unchanged_primary({**state, "held": False}, {**state, "held": False}, "")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/live_discovery.py b/libs/cua-driver/hyprland-plugin/tests/live_discovery.py
index 9508b5952d..f5fd77844c 100644
--- a/libs/cua-driver/hyprland-plugin/tests/live_discovery.py
+++ b/libs/cua-driver/hyprland-plugin/tests/live_discovery.py
@@ -10,6 +10,7 @@ import socket
import stat
import struct
import subprocess
+import time
from pathlib import Path
if not __debug__:
@@ -24,10 +25,14 @@ def hyprctl(*args):
def status():
value = json.loads(hyprctl("-j", "cua:status"))
- assert value["state"] == "discovery_only"
+ if value.get("experiment"):
+ assert value["state"] == "input_experiment"
+ assert value["experiment"]["test_only"] is True
+ else:
+ assert value["state"] == "discovery_only"
assert value["abi"]["match"] is True
assert value["capabilities"]["supported"] == ["discovery"]
- assert value["capabilities"]["enabled"] == ["discovery"]
+ assert value["capabilities"]["enabled"] == ["discovery"], value
assert value["transport"]["ready"] is True
assert value["compositor_epoch"] != 0
assert value["protocol"] == {"major": 2, "minor": 0, "max_frame_bytes": 4120}
@@ -56,6 +61,34 @@ def desktop_state():
}
+def stable_desktop_state(timeout=5, samples=3, interval=0.1):
+ """Establish readiness before requests; never retry a mutation assertion."""
+ deadline = time.monotonic() + timeout
+ previous = None
+ consecutive = 0
+ while time.monotonic() < deadline:
+ current = desktop_state()
+ consecutive = consecutive + 1 if current == previous else 1
+ if consecutive >= samples:
+ return current
+ previous = current
+ time.sleep(interval)
+ raise TimeoutError("desktop state did not stabilize before discovery requests")
+
+
+def assert_unchanged(before, after):
+ if after == before:
+ return
+ # No titles, addresses, target tokens, or raw client records in diagnostics.
+ delta = {"changed_fields": sorted(key for key in before.keys() | after.keys()
+ if before.get(key) != after.get(key))}
+ for label, state in (("before", before), ("after", after)):
+ delta[label] = {"cursor": state.get("cursor"),
+ "active_workspace": state.get("active_workspace"),
+ "window_count": len(state.get("windows", []))}
+ raise AssertionError("refused packets changed compositor state: " + json.dumps(delta, sort_keys=True))
+
+
def exchange(client, message, request_id, payload=b""):
packet = HEADER.pack(b"CUA2", 2, 0, message, 0, request_id, len(payload)) + payload
assert client.send(packet) == len(packet)
@@ -84,8 +117,10 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--reload-module", type=Path)
args = parser.parse_args()
+ if not __debug__:
+ raise RuntimeError("assertions must be enabled; do not run Python with -O")
initial = status()
- before = desktop_state()
+ before = stable_desktop_state()
with connect(initial) as client:
assert exchange(client, 3, 2) == (4, b"")
kind, payload = exchange(client, 5, 3)
@@ -94,7 +129,7 @@ def main():
for request_id, kind in enumerate((0x100, 0x101, 0x102, 0x103, 0x110, 0x111), 4):
response_kind, payload = exchange(client, kind, request_id)
assert response_kind == 0xFFFF and struct.unpack_from("!I", payload)[0] == 8
- assert desktop_state() == before, "refused packets changed compositor state"
+ assert_unchanged(before, desktop_state())
if args.reload_module:
module = str(args.reload_module.resolve(strict=True))
assert hyprctl("plugin", "unload", module).strip() == "ok"
diff --git a/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.py b/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.py
index 3a2bad56b3..ef4a79f812 100644
--- a/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.py
+++ b/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.py
@@ -1,15 +1,50 @@
-"""Protocol helper checks; native evidence still requires a live compositor."""
+"""Protocol, readiness, and diagnostic checks; not native compositor evidence."""
import os
import subprocess
import sys
import unittest
from pathlib import Path
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
import live_discovery as discovery
+class DiscoveryReadinessTest(unittest.TestCase):
+ def test_requires_consecutive_equal_samples(self):
+ first = {"cursor": {"x": 0, "y": 0}}
+ settled = {"cursor": {"x": 100, "y": 100}}
+ with patch.object(discovery, "desktop_state", side_effect=[first, first, settled, settled, settled]) as observe, \
+ patch.object(discovery.time, "sleep"):
+ self.assertEqual(discovery.stable_desktop_state(), settled)
+ self.assertEqual(observe.call_count, 5)
+
+ def test_unstable_preflight_fails(self):
+ with patch.object(discovery, "desktop_state", side_effect=[{"cursor": 1}, {"cursor": 2}]), \
+ patch.object(discovery.time, "monotonic", side_effect=[0, 0, 1, 6]), \
+ patch.object(discovery.time, "sleep"):
+ with self.assertRaisesRegex(TimeoutError, "before discovery requests"):
+ discovery.stable_desktop_state()
+
+ def test_observation_failure_is_not_swallowed(self):
+ with patch.object(discovery, "desktop_state", side_effect=RuntimeError("query failed")):
+ with self.assertRaisesRegex(RuntimeError, "query failed"):
+ discovery.stable_desktop_state()
+
+ def test_post_request_change_still_fails_with_sanitized_delta(self):
+ before = {"active_window": "private-address", "active_workspace": 1,
+ "cursor": {"x": 10, "y": 20}, "windows": [("private-window",)]}
+ after = {**before, "cursor": {"x": 11, "y": 20}}
+ with self.assertRaises(AssertionError) as result:
+ discovery.assert_unchanged(before, after)
+ message = str(result.exception)
+ self.assertIn('"changed_fields": ["cursor"]', message)
+ self.assertIn('"x": 11', message)
+ self.assertNotIn("private-address", message)
+ self.assertNotIn("private-window", message)
+ discovery.assert_unchanged(before, before)
+
+
class DiscoveryTest(unittest.TestCase):
def test_exchange_sends_and_correlates_request(self):
packet = discovery.HEADER.pack(b"CUA2", 2, 0, 3, 0, 17, 0)
diff --git a/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hpp b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hpp
index 1ac297cf63..111e665c45 100644
--- a/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hpp
+++ b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hpp
@@ -135,6 +135,7 @@ class CBoolValue : public IValue {
const std::type_info* underlying() const override { return &typeid(Config::BOOL); }
void commence() override {}
Config::BOOL value() const { return m_value; }
+ void set_mock_value(Config::BOOL value) { m_value = value; }
private:
Config::BOOL m_value;
@@ -235,12 +236,14 @@ inline std::string runtime_abi_hash = __hyprland_api_get_client_hash();
inline SP<IPC::Socket1::SCommand> registered_command;
inline SP<SHyprCtlCommand> registered_legacy_command;
inline bool config_registration_succeeds = true;
+inline SP<Config::Values::CBoolValue> registered_bool;
inline SVersionInfo getHyprlandVersion(HANDLE) {
return runtime_version;
}
-inline bool addConfigValueV2(HANDLE, SP<Config::Values::IValue>) {
+inline bool addConfigValueV2(HANDLE, SP<Config::Values::IValue> value) {
+ registered_bool = std::dynamic_pointer_cast<Config::Values::CBoolValue>(value);
return config_registration_succeeds;
}
diff --git a/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.py b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.py
index ae104b5e1b..b0b96b36c1 100644
--- a/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.py
+++ b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.py
@@ -19,7 +19,18 @@ import live_discovery as live
def command(*args, env=None):
- return subprocess.check_output(args, env=env, text=True, timeout=10).strip()
+ try:
+ return subprocess.check_output(args, env=env, text=True, timeout=10).strip()
+ except subprocess.CalledProcessError as error:
+ # hyprctl writes its IPC failure reason to stdout. check_output keeps
+ # that out of the traceback, so retain fixed labels, never raw output
+ # or instance/path arguments. Do not retry a failed lifecycle check.
+ output = error.stdout if isinstance(error.stdout, str) else ""
+ details = {"exit_code": error.returncode,
+ "hyprctl": Path(args[0]).name == "hyprctl",
+ "ipc_read_timeout": "Hyprland IPC didn't respond in time" in output,
+ "ipc_read_failure": "Couldn't read (6)" in output}
+ raise RuntimeError("lifecycle command failed: " + json.dumps(details, sort_keys=True)) from None
def wait_for(check, description):
@@ -76,7 +87,9 @@ class NestedCompositor:
self.instance = matches[0]["instance"]
try:
json.loads(self.ctl("-j", "version"))
- return True
+ monitors = json.loads(self.ctl("-j", "monitors"))
+ workspace = json.loads(self.ctl("-j", "activeworkspace"))
+ return bool(monitors) and isinstance(workspace.get("id"), int)
except (subprocess.CalledProcessError, json.JSONDecodeError):
return False
return False
@@ -84,6 +97,20 @@ class NestedCompositor:
wait_for(ready, "owned nested compositor did not become ready")
assert self.ctl("plugin", "load", str(self.module)) == "ok"
assert self.ctl("reload") == "ok"
+
+ def desktop_ready():
+ # Socket1 can answer before nested output creation/config reload
+ # finishes. Discovery tests require an actual initialized desktop.
+ try:
+ status = json.loads(self.ctl("-j", "cua:status"))
+ monitors = json.loads(self.ctl("-j", "monitors"))
+ workspace = json.loads(self.ctl("-j", "activeworkspace"))
+ return (status["transport"]["ready"] and bool(monitors)
+ and isinstance(workspace.get("id"), int))
+ except (subprocess.CalledProcessError, json.JSONDecodeError, KeyError):
+ return False
+
+ wait_for(desktop_ready, "owned nested desktop/transport did not become ready")
env = dict(os.environ, HYPRLAND_INSTANCE_SIGNATURE=self.instance)
result = json.loads(command(sys.executable, str(Path(live.__file__)), env=env))
assert result["mutation_refusals"] == 6
@@ -121,6 +148,11 @@ def run(module, directory, binary):
if not parent or not os.environ.get("WAYLAND_DISPLAY"):
raise RuntimeError("run inside a disposable Hyprland Wayland parent session")
parent_version = json.loads(command("hyprctl", "-i", parent, "-j", "version"))
+ parents = [item for item in json.loads(command("hyprctl", "-j", "instances"))
+ if item.get("instance") == parent]
+ assert (len(parents) == 1 and type(parents[0].get("pid")) is int
+ and parents[0]["pid"] > 0), "ambiguous parent process"
+ parent_pid = parents[0]["pid"]
first = NestedCompositor(directory / "first", binary, module)
second = NestedCompositor(directory / "second", binary, module)
try:
@@ -148,7 +180,23 @@ def run(module, directory, binary):
second.stop()
finally:
first.stop()
- assert json.loads(command("hyprctl", "-i", parent, "-j", "version")) == parent_version
+ try:
+ assert json.loads(command("hyprctl", "-i", parent, "-j", "version")) == parent_version
+ except Exception:
+ # This is a post-failure observation, not a second liveness attempt.
+ # No parent IPC is retried and the original exception still fails.
+ parent_alive = True
+ try:
+ os.kill(parent_pid, 0)
+ except ProcessLookupError:
+ parent_alive = False
+ except OSError:
+ parent_alive = None
+ print(json.dumps({"phase": "parent_after_owned_cleanup",
+ "parent_process_exists": parent_alive,
+ "owned_processes_reaped": first.process is None and second.process is None}),
+ file=sys.stderr)
+ raise
return {
"result": "passed",
"module_sha256": hashlib.sha256(module.read_bytes()).hexdigest(),
diff --git a/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.py b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.py
index bc2ca52710..840010cf00 100644
--- a/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.py
+++ b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.py
@@ -1,16 +1,74 @@
"""Control-flow tests; native lifecycle evidence comes from nested_lifecycle.py."""
import os
+import json
+import io
import subprocess
import tempfile
import unittest
from pathlib import Path
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
import nested_lifecycle as lifecycle
class LifecycleTest(unittest.TestCase):
+ def test_command_keeps_ipc_failure_labels_without_raw_output_or_arguments(self):
+ failure = subprocess.CalledProcessError(
+ 6, ["hyprctl", "-i", "private-instance"],
+ output="Hyprland IPC didn't respond in time\nCouldn't read (6)\nprivate-value")
+ with patch.object(subprocess, "check_output", side_effect=failure) as call:
+ with self.assertRaises(RuntimeError) as raised:
+ lifecycle.command("hyprctl", "-i", "private-instance", "-j", "version")
+ message = str(raised.exception)
+ self.assertIn('"exit_code": 6', message)
+ self.assertIn('"ipc_read_timeout": true', message)
+ self.assertIn('"ipc_read_failure": true', message)
+ self.assertNotIn("private-instance", message)
+ self.assertNotIn("private-value", message)
+ self.assertEqual(call.call_count, 1)
+
+ def test_command_does_not_mislabel_another_read_error_as_timeout(self):
+ failure = subprocess.CalledProcessError(6, ["hyprctl"], output="Couldn't read (6)")
+ with patch.object(subprocess, "check_output", side_effect=failure):
+ with self.assertRaises(RuntimeError) as raised:
+ lifecycle.command("hyprctl", "-j", "version")
+ self.assertIn('"ipc_read_timeout": false', str(raised.exception))
+
+ def test_command_success_is_unchanged(self):
+ with patch.object(subprocess, "check_output", return_value="value\n"):
+ self.assertEqual(lifecycle.command("hyprctl", "version"), "value")
+
+ @patch.dict(os.environ, {"HYPRLAND_INSTANCE_SIGNATURE": "parent", "WAYLAND_DISPLAY": "parent"})
+ def test_parent_failure_stays_failed_after_diagnostic_and_cleanup(self):
+ failure = RuntimeError("lifecycle command failed")
+ for reply, expected in ((failure, RuntimeError), ('{"version":"changed"}', AssertionError)):
+ for process_error, alive in ((ProcessLookupError, False), (PermissionError, None)):
+ first, second = Mock(process=None), Mock(process=None)
+ metadata = lambda name: {"transport": {"socket": name}, "compositor_epoch": name}
+ first.start.return_value = metadata("first")
+ second.start.side_effect = [metadata("second"), metadata("replacement")]
+ connection = MagicMock()
+ connection.__enter__.return_value.recv.return_value = b""
+ diagnostics = io.StringIO()
+ with patch.object(lifecycle, "NestedCompositor", side_effect=[first, second]), \
+ patch.object(lifecycle, "command", side_effect=[
+ '{"version":"test"}', '[{"instance":"parent","pid":123}]', reply]) as command, \
+ patch.object(lifecycle.live, "connect", return_value=connection), \
+ patch.object(lifecycle.live, "exchange", return_value=(4, b"")), \
+ patch.object(lifecycle.os, "kill", side_effect=process_error) as check_pid, \
+ patch.object(lifecycle.sys, "stderr", diagnostics):
+ with self.assertRaises(expected) as raised:
+ lifecycle.run(Path("plugin.so"), Path("logs"), "Hyprland")
+ if reply is failure:
+ self.assertIs(raised.exception, failure)
+ self.assertEqual(command.call_count, 3)
+ check_pid.assert_called_once_with(123, 0)
+ first.stop.assert_called_once()
+ evidence = json.loads(diagnostics.getvalue())
+ self.assertEqual(evidence["parent_process_exists"], alive)
+ self.assertTrue(evidence["owned_processes_reaped"])
+
def test_failed_launch_closes_log(self):
with tempfile.TemporaryDirectory() as root:
compositor = lifecycle.NestedCompositor(
@@ -55,7 +113,7 @@ class LifecycleTest(unittest.TestCase):
self.assertIsNone(compositor.process)
@patch.dict(os.environ, {"HYPRLAND_INSTANCE_SIGNATURE": "parent", "WAYLAND_DISPLAY": "parent"})
- @patch.object(lifecycle, "command", return_value='{"version":"test"}')
+ @patch.object(lifecycle, "command", side_effect=['{"version":"test"}', '[{"instance":"parent","pid":123}]'])
@patch.object(lifecycle, "NestedCompositor")
def test_start_failure_stops_both_owned_children(self, factory, _command):
first, second = Mock(), Mock()
@@ -67,7 +125,7 @@ class LifecycleTest(unittest.TestCase):
second.stop.assert_called_once()
@patch.dict(os.environ, {"HYPRLAND_INSTANCE_SIGNATURE": "parent", "WAYLAND_DISPLAY": "parent"})
- @patch.object(lifecycle, "command", return_value='{"version":"test"}')
+ @patch.object(lifecycle, "command", side_effect=['{"version":"test"}', '[{"instance":"parent","pid":123}]'])
@patch.object(lifecycle, "NestedCompositor")
def test_cleanup_failure_still_stops_other_child(self, factory, _command):
first, second = Mock(), Mock()
diff --git a/libs/cua-driver/hyprland-plugin/tests/owned_socket_path_test.cpp b/libs/cua-driver/hyprland-plugin/tests/owned_socket_path_test.cpp
new file mode 100644
index 0000000000..f74f7ae3c3
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/owned_socket_path_test.cpp
@@ -0,0 +1,217 @@
+#include "owned_socket_path.hpp"
+
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <iostream>
+#include <string>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+namespace {
+using cua::hyprland::OwnedSocketPath;
+using Result = OwnedSocketPath::CleanupResult;
+
+void check(bool condition, const char* message) {
+ if (!condition) {
+ std::cerr << "FAIL: " << message << '\n';
+ std::exit(1);
+ }
+}
+
+class TempDirectory {
+ public:
+ TempDirectory() {
+ char pattern[] = "/tmp/cua-owned-socket-XXXXXX";
+ const char* created = mkdtemp(pattern);
+ check(created != nullptr, "create temporary directory");
+ path = created;
+ }
+ ~TempDirectory() { check(rmdir(path.c_str()) == 0, "remove empty test directory"); }
+ std::string path;
+};
+
+class BoundSocket {
+ public:
+ explicit BoundSocket(const std::string& path) {
+ fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ check(fd >= 0, "create Unix socket");
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ check(path.size() < sizeof(address.sun_path), "socket path fits");
+ std::memcpy(address.sun_path, path.c_str(), path.size() + 1);
+ check(bind(fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0,
+ "bind Unix socket");
+ }
+ ~BoundSocket() { check(close(fd) == 0, "close test socket"); }
+ int fd = -1;
+};
+
+struct stat metadata(const std::string& path) {
+ struct stat result{};
+ check(lstat(path.c_str(), &result) == 0, "inspect test path without following symlinks");
+ return result;
+}
+
+void remove_path(const std::string& path) {
+ check(unlink(path.c_str()) == 0, "remove exact test fixture path");
+}
+
+void create_file(const std::string& path) {
+ const int fd = open(path.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0600);
+ check(fd >= 0, "create regular-file fixture");
+ check(close(fd) == 0, "close regular-file fixture");
+}
+
+void check_absent(const std::string& path) {
+ struct stat value{};
+ check(lstat(path.c_str(), &value) != 0 && errno == ENOENT, "socket path is absent");
+}
+
+void test_cleanup() {
+ TempDirectory directory;
+ const auto path = directory.path + "/socket";
+ OwnedSocketPath owner;
+ check(owner.cleanup() == Result::NotCaptured, "uncaptured cleanup is inert");
+ BoundSocket socket(path);
+ check(owner.capture(path), "capture bound socket");
+ check(owner.cleanup() == Result::Removed, "remove matching socket");
+ check_absent(path);
+ check(owner.error_number() == 0, "successful cleanup has no error");
+ check(owner.cleanup() == Result::NotCaptured, "cleanup is idempotent");
+}
+
+void test_missing_path() {
+ TempDirectory directory;
+ const auto path = directory.path + "/socket";
+ OwnedSocketPath owner;
+ check(!owner.capture(path) && owner.error_number() == ENOENT,
+ "missing capture reports its error");
+ BoundSocket socket(path);
+ check(owner.cleanup() == Result::NotCaptured, "failed capture cannot remove a later socket");
+ check(S_ISSOCK(metadata(path).st_mode), "later socket survives failed capture");
+ check(owner.capture(path), "capture existing bound fixture");
+ remove_path(path);
+ check(owner.cleanup() == Result::AlreadyAbsent, "removed path is explicitly reported");
+ check(owner.cleanup() == Result::NotCaptured, "absent cleanup consumes identity");
+}
+
+void test_replaced_socket() {
+ TempDirectory directory;
+ const auto path = directory.path + "/socket";
+ const auto moved = directory.path + "/original";
+ BoundSocket original(path);
+ OwnedSocketPath owner;
+ check(owner.capture(path), "capture original socket");
+ // Keep the original inode alive to avoid filesystem inode reuse in this test.
+ check(rename(path.c_str(), moved.c_str()) == 0, "move original socket");
+ BoundSocket replacement(path);
+ const auto before = metadata(path);
+ check(owner.cleanup() == Result::Replaced, "refuse replacement socket");
+ check(metadata(path).st_ino == before.st_ino, "replacement socket survives");
+ check(owner.cleanup() == Result::NotCaptured, "refusal consumes identity");
+ remove_path(path);
+ remove_path(moved);
+}
+
+void test_replaced_file_and_symlink() {
+ for (bool symlink_fixture : {false, true}) {
+ TempDirectory directory;
+ const auto path = directory.path + "/socket";
+ const auto moved = directory.path + "/original";
+ BoundSocket original(path);
+ OwnedSocketPath owner;
+ check(owner.capture(path), "capture socket before replacement");
+ check(rename(path.c_str(), moved.c_str()) == 0, "move socket before replacement");
+ if (symlink_fixture)
+ check(symlink(moved.c_str(), path.c_str()) == 0, "create socket-targeting symlink");
+ else
+ create_file(path);
+ check(owner.cleanup() == Result::Replaced, "refuse non-socket replacement");
+ const auto current = metadata(path);
+ check(symlink_fixture ? S_ISLNK(current.st_mode) : S_ISREG(current.st_mode),
+ "replacement object survives");
+ check(!owner.capture(path) && owner.error_number() == EPERM,
+ "capture rejects symlink or regular file");
+ check(owner.cleanup() == Result::NotCaptured, "invalid capture fails closed");
+ check(S_ISSOCK(metadata(moved).st_mode), "original socket survives symlink inspection");
+ remove_path(path);
+ remove_path(moved);
+ }
+}
+
+void test_metadata_identity() {
+ TempDirectory directory;
+ const auto path = directory.path + "/socket";
+ BoundSocket socket(path);
+ const auto captured = metadata(path);
+ namespace detail = cua::hyprland::owned_socket_path_detail;
+ check(detail::matches_identity(captured, captured, getuid()), "same owned identity matches");
+ auto changed = captured;
+ changed.st_uid = captured.st_uid == 0 ? 1 : 0;
+ check(!detail::is_owned_socket(changed, getuid()), "capture predicate refuses foreign UID");
+ check(!detail::matches_identity(changed, captured, getuid()), "cleanup refuses foreign UID");
+ changed = captured;
+ changed.st_dev = captured.st_dev == 0 ? 1 : 0;
+ check(!detail::matches_identity(changed, captured, getuid()), "device mismatch refuses cleanup");
+ changed = captured;
+ changed.st_ino = captured.st_ino == 0 ? 1 : 0;
+ check(!detail::matches_identity(changed, captured, getuid()), "inode mismatch refuses cleanup");
+ changed = captured;
+ changed.st_mode = S_IFREG | 0600;
+ check(!detail::matches_identity(changed, captured, getuid()), "type mismatch refuses cleanup");
+ remove_path(path);
+}
+
+void test_inspection_failure() {
+ TempDirectory directory;
+ const auto parent = directory.path + "/parent";
+ const auto moved = directory.path + "/moved";
+ const auto path = parent + "/socket";
+ check(mkdir(parent.c_str(), 0700) == 0, "create socket parent");
+ BoundSocket socket(path);
+ OwnedSocketPath owner;
+ check(owner.capture(path), "capture before path becomes inaccessible");
+ check(rename(parent.c_str(), moved.c_str()) == 0, "move socket parent");
+ create_file(parent);
+ check(owner.cleanup() == Result::Failed && owner.error_number() == ENOTDIR,
+ "inspection failure is explicit and retains errno");
+ check(owner.cleanup() == Result::NotCaptured, "failed cleanup consumes identity");
+ check(S_ISSOCK(metadata(moved + "/socket").st_mode), "inspection failure preserves socket");
+ remove_path(parent);
+ remove_path(moved + "/socket");
+ check(rmdir(moved.c_str()) == 0, "remove moved empty parent");
+}
+
+void test_unlink_failure() {
+ if (geteuid() == 0) {
+ std::cout << "SKIP: directory permissions cannot force unlink failure as root\n";
+ return;
+ }
+ TempDirectory directory;
+ const auto path = directory.path + "/socket";
+ BoundSocket socket(path);
+ OwnedSocketPath owner;
+ check(owner.capture(path), "capture before unlink permission failure");
+ check(chmod(directory.path.c_str(), 0500) == 0, "remove directory write permission");
+ const auto result = owner.cleanup();
+ const int error = owner.error_number();
+ check(chmod(directory.path.c_str(), 0700) == 0, "restore test directory permissions");
+ check(result == Result::Failed && (error == EACCES || error == EPERM),
+ "unlink failure is explicit and retains errno");
+ check(S_ISSOCK(metadata(path).st_mode), "failed unlink preserves socket");
+ check(owner.cleanup() == Result::NotCaptured, "failed unlink consumes identity");
+ remove_path(path);
+}
+} // namespace
+
+int main() {
+ test_cleanup();
+ test_missing_path();
+ test_replaced_socket();
+ test_replaced_file_and_symlink();
+ test_metadata_identity();
+ test_inspection_failure();
+ test_unlink_failure();
+ std::cout << "owned socket path tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/passive_pointer_target_test.cpp b/libs/cua-driver/hyprland-plugin/tests/passive_pointer_target_test.cpp
new file mode 100644
index 0000000000..42478bd80f
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/passive_pointer_target_test.cpp
@@ -0,0 +1,141 @@
+#include "passive_pointer_target.hpp"
+
+#include <cstdlib>
+#include <iostream>
+#include <memory>
+
+namespace {
+struct Window {};
+struct Surface {
+ int application;
+ int client() const { return application; }
+};
+using Target = cua::hyprland::PassivePointerTarget<std::weak_ptr<Window>, std::weak_ptr<Surface>>;
+using cua::hyprland::InputLaneActivity;
+struct Owner {
+ std::shared_ptr<Window> window;
+ std::shared_ptr<Surface> surface;
+};
+
+void check(bool condition, const char* message) {
+ if (!condition) {
+ std::cerr << "FAIL: " << message << '\n';
+ std::exit(1);
+ }
+}
+}
+
+int main() {
+ const Target::Geometry geometry{20, 30, 500, 400, 20, 30};
+ auto window = std::make_shared<Window>();
+ auto surface = std::make_shared<Surface>(Surface{1});
+ const auto sibling = std::make_shared<Surface>(Surface{1});
+ const auto unrelated = std::make_shared<Surface>(Surface{2});
+ Target hover;
+ check(!hover.entered() && !hover.same_client(surface), "unused lane has no hover conflict");
+ {
+ auto owner = std::make_unique<Owner>(Owner{window, surface});
+ hover.capture(owner->window, owner->surface, geometry);
+ check(hover.matches(window, surface, geometry), "capture binds exact target and geometry");
+ }
+ check(hover.matches(window, surface, geometry), "owner destruction preserves live target hover");
+ check(hover.same_client(sibling), "orphan hover still conflicts with another window of its application");
+ check(!hover.same_client(unrelated), "orphan hover does not reserve unrelated applications");
+ check(hover.reclaimable_for(sibling, {}), "valid new target can retire a matching orphan hover");
+ check(!hover.reclaimable_for(unrelated, {}), "fresh target cannot evict unrelated passive hover");
+ for (const auto member : {&InputLaneActivity::reserved, &InputLaneActivity::leased,
+ &InputLaneActivity::dragging, &InputLaneActivity::button, &InputLaneActivity::keys,
+ &InputLaneActivity::keyboard_focus, &InputLaneActivity::capabilities,
+ &InputLaneActivity::grant, &InputLaneActivity::expiry}) {
+ InputLaneActivity activity;
+ activity.*member = true;
+ check(!hover.reclaimable_for(sibling, activity),
+ "any remaining ownership, authority, or held input prevents sibling eviction");
+ }
+ const InputLaneActivity fresh_claim{.reserved = true, .reservation_without_target = true};
+ check(hover.reclaimable_for(sibling, fresh_claim),
+ "a bare new claim cannot adopt the prior owner's matching hover");
+ check(!hover.reclaimable_for(unrelated, fresh_claim),
+ "a new claim never permits eviction of unrelated hover");
+ for (const auto member : {&InputLaneActivity::leased, &InputLaneActivity::dragging,
+ &InputLaneActivity::button, &InputLaneActivity::keys, &InputLaneActivity::keyboard_focus,
+ &InputLaneActivity::capabilities, &InputLaneActivity::grant, &InputLaneActivity::expiry}) {
+ auto activity = fresh_claim;
+ activity.*member = true;
+ check(!hover.reclaimable_for(sibling, activity),
+ "a fresh claim cannot excuse authority, keyboard focus, or held input");
+ }
+ auto bound_claim = fresh_claim;
+ bound_claim.reservation_without_target = false;
+ check(!hover.reclaimable_for(sibling, bound_claim),
+ "an owner that has bound a target protects hover even with no current grant");
+ for (int first = 0; first < 2; ++first) {
+ Target lanes[2];
+ const std::shared_ptr<Surface> old_targets[] = {surface, unrelated};
+ lanes[0].capture(window, old_targets[0], geometry);
+ lanes[1].capture(window, old_targets[1], geometry);
+ InputLaneActivity claims[] = {fresh_claim, fresh_claim};
+ // Both sockets CLAIM before either TARGET, in reverse app order.
+ // This reproduced a native agent_target_busy refusal in a scroll pair.
+ const int second = 1 - first;
+ lanes[first].reset();
+ check(lanes[second].reclaimable_for(old_targets[second], claims[second]),
+ "the first TARGET can retire matching hover on a freshly reserved peer");
+ lanes[second].reset();
+ claims[first].reservation_without_target = false;
+ lanes[first].capture(window, old_targets[second], geometry);
+ check(!lanes[first].reclaimable_for(old_targets[second], claims[first]),
+ "the first newly bound owner is protected from the second TARGET");
+ check(!lanes[first].same_client(old_targets[first]),
+ "the second TARGET does not conflict with the first replacement");
+ claims[second].reservation_without_target = false;
+ lanes[second].capture(window, old_targets[first], geometry);
+ check(lanes[0].matches(window, old_targets[1], geometry) &&
+ lanes[1].matches(window, old_targets[0], geometry),
+ "both reservation orders permit reversed target reuse without replay");
+ }
+ Target lane_a, lane_b;
+ lane_a.capture(window, surface, geometry);
+ lane_b.capture(window, unrelated, geometry);
+ // Both previous owners have gone. Driver claims lane A first, but requests
+ // B's target; then the next claimant uses lane B for A's former target.
+ lane_a.reset();
+ check(lane_b.reclaimable_for(unrelated, {}), "opposite-order target B can leave its old orphan lane");
+ lane_b.reset();
+ lane_a.capture(window, unrelated, geometry);
+ const InputLaneActivity active_a{.reserved = true, .leased = true};
+ check(!lane_a.reclaimable_for(unrelated, active_a), "active replacement owner stays protected");
+ check(!lane_a.same_client(surface), "opposite-order target A remains available to second claimant");
+ lane_b.capture(window, surface, geometry);
+ check(lane_a.matches(window, unrelated, geometry) && lane_b.matches(window, surface, geometry),
+ "both lanes can be reused in reverse target order");
+ const Owner next_owner{window, surface};
+ check(hover.matches(next_owner.window, next_owner.surface, geometry),
+ "fresh owner can reuse unchanged target without inheriting an owner identity");
+ auto moved = geometry;
+ ++moved[0];
+ check(!hover.matches(window, surface, moved), "geometry change invalidates retained hover");
+ check(!hover.matches(window, sibling, geometry), "target change invalidates retained hover");
+ check(hover.same_target(window, surface), "same target can be checked before geometry refresh");
+ check(!hover.same_target(window, sibling), "different target retires old hover even if new geometry fails");
+ hover.reset();
+ check(!hover.entered() && !hover.surface() && !hover.window() && !hover.same_client(sibling),
+ "conflict cleanup removes all target state");
+ hover.capture(window, unrelated, geometry);
+ check(hover.same_client(unrelated) && !hover.same_client(surface),
+ "retargeting the same lane replaces the old application conflict");
+ {
+ auto ephemeral_window = std::make_shared<Window>();
+ auto ephemeral_surface = std::make_shared<Surface>(Surface{3});
+ hover.capture(ephemeral_window, ephemeral_surface, geometry);
+ check(ephemeral_window.use_count() == 1 && ephemeral_surface.use_count() == 1,
+ "passive hover never extends window or surface lifetime");
+ }
+ check(hover.entered() && !hover.window() && !hover.surface(),
+ "destroyed target remains detectable for protocol focus cleanup");
+ check(!hover.same_client(surface), "expired target cannot create a stale application conflict");
+ check(!hover.matches(std::shared_ptr<Window>{}, std::shared_ptr<Surface>{}, geometry),
+ "expired weak references never compare as a usable target");
+ hover.reset();
+ std::cout << "passive pointer target tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp b/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp
new file mode 100644
index 0000000000..ff09451d63
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp
@@ -0,0 +1,98 @@
+#include "mock-hyprland/mock.hpp"
+#include "input_experiment.hpp"
+
+#include <array>
+#include <cstdlib>
+#include <iostream>
+#include <sys/stat.h>
+#include <unistd.h>
+
+extern "C" PLUGIN_DESCRIPTION_INFO pluginInit(HANDLE);
+extern "C" void pluginExit();
+
+namespace {
+unsigned created = 0, destroyed = 0, resumed = 0, suspended = 0;
+bool fail_resume = false;
+void check(bool value, const char* message) {
+ if (!value) {
+ std::cerr << "FAIL: " << message << '\n';
+ std::exit(1);
+ }
+}
+}
+
+// This mock tests the entry point's ownership decisions, not native wl_seat
+// delivery. Native resource-count and surviving-client tests remain separate.
+namespace cua::hyprland {
+struct InputExperiment::Impl {};
+struct InputExperiment::DesktopListeners {};
+class PrimaryTrace {};
+InputExperiment::InputExperiment(const std::string&, void*) { ++created; }
+InputExperiment::~InputExperiment() { ++destroyed; }
+void InputExperiment::suspend() { ++suspended; }
+void InputExperiment::resume() {
+ ++resumed;
+ if (fail_resume) throw std::runtime_error("test transport failure");
+}
+std::string InputExperiment::status_json() const { return "{}"; }
+}
+
+int main() {
+ std::array<char, 64> pattern{};
+ const std::string seed = "/tmp/cua-input-lifetime-api-XXXXXX";
+ seed.copy(pattern.data(), seed.size());
+ const auto* directory = mkdtemp(pattern.data());
+ check(directory != nullptr, "create isolated runtime");
+ const auto hypr = std::string(directory) + "/hypr";
+ const auto instance = hypr + "/mock";
+ const auto socket = instance + "/cua-inject-v2.sock";
+ check(mkdir(hypr.c_str(), 0700) == 0 && mkdir(instance.c_str(), 0700) == 0,
+ "create private instance path");
+ check(setenv("XDG_RUNTIME_DIR", directory, 1) == 0 &&
+ setenv("HYPRLAND_INSTANCE_SIGNATURE", "mock", 1) == 0,
+ "select runtime");
+ Config::Values::configured_bool_override = true;
+ static_cast<void>(pluginInit(nullptr));
+ const auto toggle = [](bool enabled) {
+ HyprlandAPI::registered_bool->set_mock_value(enabled);
+ Event::bus()->m_events.config.reloaded.emit();
+ };
+ for (unsigned i = 0; i < 20; ++i) {
+ toggle(true);
+#ifdef CUA_HYPRLAND_INPUT
+ const auto status = HyprlandAPI::registered_legacy_command->fn(FORMAT_JSON, {});
+ check(status.find("\"state\":\"input_v3_candidate\"") != std::string::npos &&
+ status.find("trusted_local_per_action") != std::string::npos &&
+ status.find("\"input\":{}") != std::string::npos &&
+ status.find("operator") == std::string::npos,
+ "v3 status advertises its actual admission mode");
+#endif
+ check(created == 1 && destroyed == 0 && resumed == i + 1,
+ "enable reuses the session's seat owner");
+ toggle(true);
+ check(resumed == i + 1, "unrelated config reload does not renew admission");
+ toggle(false);
+ check(destroyed == 0 && access(socket.c_str(), F_OK) != 0,
+ "disable stops transport but retains seat owner");
+ }
+ fail_resume = true;
+ toggle(true);
+ check(created == 1 && destroyed == 0 && access(socket.c_str(), F_OK) != 0,
+ "transport failure does not replace seats or leave discovery listener");
+ fail_resume = false;
+ toggle(true);
+ check(created == 1 && access(socket.c_str(), F_OK) == 0,
+ "retry after transport failure reuses seat owner");
+ const auto suspended_before_exit = suspended;
+ pluginExit();
+ check(destroyed == 1 && suspended >= 20 && access(socket.c_str(), F_OK) != 0,
+ "unload retires the single seat owner and stops transport");
+ check(suspended == suspended_before_exit,
+ "unload retires directly without first sending config-disable cancellation");
+ check(Event::bus()->m_events.config.reloaded.active_count() == 0,
+ "unload detaches configuration listener");
+ check(rmdir(instance.c_str()) == 0 && rmdir(hypr.c_str()) == 0 &&
+ rmdir(directory) == 0,
+ "remove test-owned runtime");
+ std::cout << "plugin input lifetime API tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/primary_grab.c b/libs/cua-driver/hyprland-plugin/tests/primary_grab.c
new file mode 100644
index 0000000000..5c8dbcd62e
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/primary_grab.c
@@ -0,0 +1,118 @@
+/* Independent foreground adversary. Build with the generated wlr virtual
+ * pointer client protocol and libwayland-client. This deliberately exercises
+ * the PRIMARY seat in a disposable test session; background actions must go
+ * through Cua Driver, not this program. A bounded hold always releases. */
+#define _POSIX_C_SOURCE 200809L
+#include <wayland-client.h>
+#include "wlr-virtual-pointer-unstable-v1-client-protocol.h"
+#include <errno.h>
+#include <signal.h>
+#include <poll.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+static struct zwlr_virtual_pointer_manager_v1 *manager;
+static volatile sig_atomic_t stopped;
+static void stop(int sig) { (void)sig; stopped = 1; }
+static void global(void *data, struct wl_registry *registry, uint32_t name,
+ const char *interface, uint32_t version) {
+ (void)data;
+ if (!strcmp(interface, "zwlr_virtual_pointer_manager_v1"))
+ manager = wl_registry_bind(registry, name,
+ &zwlr_virtual_pointer_manager_v1_interface, version < 2 ? version : 2);
+}
+static void removed(void *data, struct wl_registry *registry, uint32_t name) {
+ (void)data; (void)registry; (void)name;
+}
+static const struct wl_registry_listener listener = {global, removed};
+static uint32_t milliseconds(void) {
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return (uint32_t)((uint64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000);
+}
+static unsigned integer(const char *text) {
+ char *end;
+ errno = 0;
+ unsigned long value = strtoul(text, &end, 10);
+ if (errno || !*text || *end || value > 65535) exit(2);
+ return (unsigned)value;
+}
+int main(int argc, char **argv) {
+ if (argc != 6 && argc != 7) { fprintf(stderr, "usage: primary_grab X Y WIDTH HEIGHT HOLD_MS [canary|park|controlled]\n"); return 2; }
+ int canary = argc == 7 && !strcmp(argv[6], "canary");
+ int park = argc == 7 && !strcmp(argv[6], "park");
+ int controlled = argc == 7 && !strcmp(argv[6], "controlled");
+ if (argc == 7 && !canary && !park && !controlled) return 2;
+ unsigned x = integer(argv[1]), y = integer(argv[2]);
+ unsigned width = integer(argv[3]), height = integer(argv[4]), hold = integer(argv[5]);
+ if (!width || !height || x >= width || y >= height || hold < 100 || hold > 60000) return 2;
+ if (canary && (x + 40 >= width || y + 30 >= height)) return 2;
+ signal(SIGTERM, stop); signal(SIGINT, stop);
+ struct wl_display *display = wl_display_connect(NULL);
+ if (!display) return 1;
+ struct wl_registry *registry = wl_display_get_registry(display);
+ wl_registry_add_listener(registry, &listener, NULL);
+ if (wl_display_roundtrip(display) < 0 || !manager) return 1;
+ struct zwlr_virtual_pointer_v1 *pointer = zwlr_virtual_pointer_manager_v1_create_virtual_pointer(manager, NULL);
+ zwlr_virtual_pointer_v1_motion_absolute(pointer, milliseconds(), x, y, width, height);
+ zwlr_virtual_pointer_v1_frame(pointer);
+ if (wl_display_roundtrip(display) < 0) return 1;
+ if (canary || park) {
+ // Two warps, one flush/roundtrip: endpoint polling alone sees no change.
+ if (canary) {
+ zwlr_virtual_pointer_v1_motion_absolute(pointer, milliseconds(), x + 40, y + 30, width, height);
+ zwlr_virtual_pointer_v1_motion_absolute(pointer, milliseconds(), x, y, width, height);
+ }
+ zwlr_virtual_pointer_v1_frame(pointer);
+ int result = wl_display_roundtrip(display);
+ zwlr_virtual_pointer_v1_destroy(pointer);
+ zwlr_virtual_pointer_manager_v1_destroy(manager);
+ wl_registry_destroy(registry);
+ wl_display_flush(display);
+ wl_display_disconnect(display);
+ puts("CANARY_RETURNED");
+ return result < 0;
+ }
+ zwlr_virtual_pointer_v1_button(pointer, milliseconds(), 272, WL_POINTER_BUTTON_STATE_PRESSED);
+ zwlr_virtual_pointer_v1_frame(pointer);
+ if (wl_display_roundtrip(display) < 0) return 1;
+ puts("HELD"); fflush(stdout);
+ uint32_t start = milliseconds();
+ int bad_command = 0;
+ while (!stopped && (uint32_t)(milliseconds() - start) < hold) {
+ if (controlled) {
+ struct pollfd input = {STDIN_FILENO, POLLIN, 0};
+ int ready = poll(&input, 1, 10);
+ if (ready < 0 && errno == EINTR) continue;
+ if (ready < 0) { bad_command = 1; break; }
+ if (!ready) continue;
+ char line[128], extra;
+ unsigned mx, my;
+ if (!fgets(line, sizeof(line), stdin)) break;
+ if (!strchr(line, '\n') || sscanf(line, "MOVE %u %u %c", &mx, &my, &extra) != 2 || mx >= width || my >= height) {
+ bad_command = 1; break;
+ }
+ zwlr_virtual_pointer_v1_motion_absolute(pointer, milliseconds(), mx, my, width, height);
+ zwlr_virtual_pointer_v1_frame(pointer);
+ if (wl_display_roundtrip(display) < 0) { bad_command = 1; break; }
+ printf("MOVED %u %u\n", mx, my); fflush(stdout);
+ continue;
+ }
+ struct timespec pause = {0, 10000000};
+ nanosleep(&pause, NULL);
+ }
+ zwlr_virtual_pointer_v1_button(pointer, milliseconds(), 272, WL_POINTER_BUTTON_STATE_RELEASED);
+ zwlr_virtual_pointer_v1_frame(pointer);
+ int result = wl_display_roundtrip(display);
+ zwlr_virtual_pointer_v1_destroy(pointer);
+ zwlr_virtual_pointer_manager_v1_destroy(manager);
+ wl_registry_destroy(registry);
+ wl_display_flush(display);
+ wl_display_disconnect(display);
+ puts("RELEASED");
+ return result < 0 || bad_command;
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture.c b/libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture.c
new file mode 100644
index 0000000000..3eee8a1396
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture.c
@@ -0,0 +1,143 @@
+/* TEST ONLY: one explicit primary hover, never a primary button/key.
+ * Build with the same generated virtual-pointer protocol as primary_grab.c.
+ * Usage: primary_hover_fixture WIDTH HEIGHT LIFETIME_MS COMPOSITOR_PID
+ * READY creates no input. One MOVE X Y command sends motion+frame and waits
+ * for display.sync before reporting moved. The caller must independently
+ * attest the actual focused client; a sync is not a focus acknowledgement.
+ * EOF, signals and a bounded deadline destroy only this fixture's pointer.
+ */
+#define _GNU_SOURCE
+#include <wayland-client.h>
+#include "wlr-virtual-pointer-unstable-v1-client-protocol.h"
+#include <errno.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+
+static struct zwlr_virtual_pointer_manager_v1 *manager;
+static volatile sig_atomic_t stopped;
+static int synced;
+static uint64_t now_ns(void) {
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return (uint64_t)t.tv_sec * 1000000000ULL + t.tv_nsec;
+}
+static void stop(int sig) { (void)sig; stopped = 1; }
+static void event(const char *name, unsigned x, unsigned y) {
+ printf("{\"event\":\"%s\",\"x\":%u,\"y\":%u,\"observed_ns\":%llu}\n",
+ name, x, y, (unsigned long long)now_ns());
+ fflush(stdout);
+}
+static void global(void *data, struct wl_registry *registry, uint32_t name,
+ const char *interface, uint32_t version) {
+ (void)data;
+ if (!strcmp(interface, "zwlr_virtual_pointer_manager_v1"))
+ manager = wl_registry_bind(registry, name,
+ &zwlr_virtual_pointer_manager_v1_interface, version < 2 ? version : 2);
+}
+static void removed(void *data, struct wl_registry *registry, uint32_t name) {
+ (void)data; (void)registry; (void)name;
+}
+static const struct wl_registry_listener listener = {global, removed};
+static void on_sync(void *data, struct wl_callback *callback, uint32_t serial) {
+ (void)data; (void)serial; synced = 1; wl_callback_destroy(callback);
+}
+static const struct wl_callback_listener sync_listener = {on_sync};
+static void start_sync(struct wl_display *display) {
+ synced = 0;
+ wl_callback_add_listener(wl_display_sync(display), &sync_listener, NULL);
+}
+/* No roundtrip or line-buffered stdin wait may outlive the deadline. */
+static int pump(struct wl_display *display) {
+ if (wl_display_dispatch_pending(display) < 0) return -1;
+ if (wl_display_flush(display) < 0 && errno != EAGAIN) return -1;
+ struct pollfd fd = {wl_display_get_fd(display), POLLIN, 0};
+ int result = poll(&fd, 1, 10);
+ if (result < 0) return errno == EINTR ? 0 : -1;
+ if (fd.revents & (POLLERR | POLLHUP | POLLNVAL)) return -1;
+ return (fd.revents & POLLIN) ? wl_display_dispatch(display) : 0;
+}
+static unsigned number(const char *text, unsigned min, unsigned max) {
+ char *end; errno = 0;
+ if (!*text || strspn(text, "0123456789") != strlen(text)) exit(2);
+ unsigned long value = strtoul(text, &end, 10);
+ if (errno || *end || value < min || value > max) exit(2);
+ return (unsigned)value;
+}
+int main(int argc, char **argv) {
+ if (argc != 5) return 2;
+ unsigned width = number(argv[1], 1, 65535), height = number(argv[2], 1, 65535);
+ unsigned lifetime = number(argv[3], 2000, 20000);
+ pid_t expected = (pid_t)number(argv[4], 2, 2147483647);
+ signal(SIGTERM, stop); signal(SIGINT, stop); signal(SIGPIPE, SIG_IGN);
+ struct wl_display *display = wl_display_connect(NULL);
+ if (!display) return 1;
+ struct ucred peer;
+ socklen_t size = sizeof(peer);
+ if (getsockopt(wl_display_get_fd(display), SOL_SOCKET, SO_PEERCRED, &peer, &size) ||
+ size != sizeof(peer) || peer.pid != expected || peer.uid != getuid()) return 1;
+ struct wl_registry *registry = wl_display_get_registry(display);
+ wl_registry_add_listener(registry, &listener, NULL);
+ start_sync(display);
+ uint64_t deadline = now_ns() + 2000000000ULL;
+ while (!synced && !stopped && now_ns() < deadline)
+ if (pump(display) < 0) return 1;
+ if (!synced || !manager || stopped) return 1;
+ struct zwlr_virtual_pointer_v1 *pointer = zwlr_virtual_pointer_manager_v1_create_virtual_pointer(manager, NULL);
+ start_sync(display);
+ deadline = now_ns() + 2000000000ULL;
+ while (!synced && !stopped && now_ns() < deadline)
+ if (pump(display) < 0) return 1;
+ if (!synced || stopped) return 1;
+ event("ready", 0, 0);
+ char command[48] = {0}; unsigned used = 0;
+ deadline = now_ns() + 3000000000ULL;
+ while (used < sizeof(command) - 1 && !stopped && now_ns() < deadline) {
+ if (pump(display) < 0) return 1;
+ struct pollfd input = {STDIN_FILENO, POLLIN, 0};
+ if (poll(&input, 1, 10) < 0 && errno != EINTR) return 1;
+ if (input.revents & (POLLIN | POLLHUP | POLLERR)) {
+ if (read(STDIN_FILENO, command + used, 1) != 1) return 1;
+ if (command[used++] == '\n') break;
+ }
+ }
+ unsigned x, y; char extra;
+ if (!used || command[used - 1] != '\n' || stopped || now_ns() >= deadline ||
+ sscanf(command, "MOVE %u %u %c", &x, &y, &extra) != 2 || x >= width || y >= height) return 1;
+ /* This is the only input request in the entire fixture. */
+ zwlr_virtual_pointer_v1_motion_absolute(pointer, (uint32_t)(now_ns() / 1000000ULL), x, y, width, height);
+ zwlr_virtual_pointer_v1_frame(pointer);
+ start_sync(display);
+ deadline = now_ns() + 2000000000ULL;
+ while (!synced && !stopped && now_ns() < deadline)
+ if (pump(display) < 0) return 1;
+ if (!synced || stopped) return 1;
+ event("moved", x, y);
+ int failed = 0, closed = 0;
+ deadline = now_ns() + (uint64_t)lifetime * 1000000ULL;
+ while (!stopped && now_ns() < deadline) {
+ if (pump(display) < 0) { failed = 1; break; }
+ struct pollfd input = {STDIN_FILENO, POLLIN, 0};
+ if (poll(&input, 1, 10) < 0 && errno != EINTR) { failed = 1; break; }
+ if (input.revents & (POLLIN | POLLHUP | POLLERR)) {
+ char byte;
+ /* A second command is an error, never another movement. */
+ closed = read(STDIN_FILENO, &byte, 1) == 0;
+ failed = !closed;
+ break;
+ }
+ }
+ zwlr_virtual_pointer_v1_destroy(pointer);
+ zwlr_virtual_pointer_manager_v1_destroy(manager);
+ wl_registry_destroy(registry);
+ wl_display_flush(display);
+ wl_display_disconnect(display);
+ event("finished", x, y);
+ return failed || !closed; /* Deadline/signal cleanup cannot certify success. */
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture_test.py b/libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture_test.py
new file mode 100644
index 0000000000..8bad7154ef
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture_test.py
@@ -0,0 +1,86 @@
+"""Source contract/preflight checks only; Linux compilation and native proof remain required."""
+import hashlib
+import os
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+import production_active_primary_proof as proof
+
+
+class SourceContractTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.source = Path(__file__).with_name('primary_hover_fixture.c').read_text()
+
+ def test_peer_identity_precedes_protocol_binding_or_input(self):
+ source = self.source
+ peer = source.index('getsockopt(')
+ self.assertLess(peer, source.index('wl_display_get_registry(display)'))
+ self.assertIn('peer.pid != expected || peer.uid != getuid()', source)
+ self.assertIn('SO_PEERCRED', source)
+
+ def test_ready_has_no_input_and_only_one_explicit_motion_is_possible(self):
+ source = self.source
+ self.assertNotIn('zwlr_virtual_pointer_v1_button(', source)
+ self.assertEqual(source.count('zwlr_virtual_pointer_v1_motion_absolute('), 1)
+ self.assertLess(source.index('event("ready",'), source.index('sscanf(command,'))
+ self.assertLess(source.index('sscanf(command,'), source.index('zwlr_virtual_pointer_v1_motion_absolute('))
+ motion = source.index('zwlr_virtual_pointer_v1_motion_absolute(')
+ ack = source.index('event("moved",')
+ self.assertIn('start_sync(display);', source[motion:ack])
+ self.assertIn('if (!synced || stopped) return 1;', source[motion:ack])
+ self.assertIn('failed = !closed;', source[ack:])
+
+ def test_all_waits_are_bounded_and_partial_stdin_never_blocks_a_line_read(self):
+ source = self.source
+ self.assertNotIn('wl_display_roundtrip(', source)
+ self.assertNotIn('fgets(', source)
+ self.assertNotIn('scanf(', source.replace('sscanf(', ''))
+ for line in source.splitlines():
+ if line.strip().startswith('while ('):
+ self.assertIn('now_ns() < deadline', line)
+ self.assertIn('x >= width || y >= height', source)
+ self.assertIn('return failed || !closed;', source)
+
+
+class BinaryPreflightTests(unittest.TestCase):
+ def test_alias_replaced_inode_wrong_hash_or_unreviewed_source_fails(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ source = root / 'libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture.c'
+ source.parent.mkdir(parents=True)
+ source.write_text('reviewed fixture source')
+ binary = root / 'primary_hover_fixture'
+ binary.write_bytes(b'reviewed executable fixture')
+ binary.chmod(0o700)
+ info = binary.stat()
+ expected = {'path': str(binary), 'device': info.st_dev, 'inode': info.st_ino,
+ 'uid': info.st_uid, 'sha256': hashlib.sha256(binary.read_bytes()).hexdigest(),
+ 'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest()}
+ fixture = object.__new__(proof.HoverFixture)
+ fixture.args = SimpleNamespace(source=root, hover_fixture=binary)
+ fixture.expected = expected
+ fixture.check_binary()
+ for field, value in (('path', str(root / 'other')), ('device', info.st_dev + 1),
+ ('inode', info.st_ino + 1), ('uid', info.st_uid + 1),
+ ('sha256', '0' * 64), ('source_sha256', '0' * 64)):
+ fixture.expected = {**expected, field: value}
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ fixture.check_binary()
+ fixture.expected = expected
+ alias = root / 'alias'
+ alias.symlink_to(binary)
+ fixture.args.hover_fixture = alias
+ fixture.expected = {**expected, 'path': str(alias)}
+ with self.assertRaises(AssertionError): fixture.check_binary()
+ fixture.args.hover_fixture = binary
+ fixture.expected = expected
+ with patch.object(os, 'access', return_value=False), self.assertRaises(AssertionError):
+ fixture.check_binary()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/primary_trace.py b/libs/cua-driver/hyprland-plugin/tests/primary_trace.py
new file mode 100644
index 0000000000..e2bf2fabf1
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/primary_trace.py
@@ -0,0 +1,154 @@
+"""Collect and analyze the bounded, opt-in compositor trace.
+
+Only counters and coordinates are recorded. A missing, truncated, overflowing,
+or timed-out trace is inconclusive, never a pass. The parked/grab oracle rejects
+even a cursor warp that returned before the next Driver snapshot.
+"""
+import argparse
+import json
+import math
+from pathlib import Path
+import socket
+
+
+class Trace:
+ def __init__(self, path):
+ self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+ self.socket.settimeout(5)
+ self.socket.connect(str(path))
+ self.hello = self.exchange('HELLO')
+ assert self.hello['ok']
+
+ def exchange(self, packet):
+ self.socket.sendall(packet.encode('ascii'))
+ result = json.loads(self.socket.recv(65536))
+ if result.get('ok') is not True:
+ raise RuntimeError(result)
+ return result
+
+ def collect(self):
+ # TRACE_READ exposes eight rows from an append-only, bounded array.
+ # Primary motion can append while pages are read. Capture the first
+ # response's prefix, not a moving count that may never stop growing.
+ # No event inside that prefix may be omitted. A final start-page check
+ # binds every page to the same trace epoch; resets are never accepted.
+ def validate(page, offset):
+ if (not isinstance(page, dict) or page.get('ok') is not True
+ or type(page.get('count')) is not int or not 0 <= page['count'] <= 32768
+ or any(type(page.get(key)) is not bool for key in ('hook', 'active', 'overflow', 'timed_out'))
+ or not isinstance(page.get('events'), list)
+ or len(page['events']) != min(8, max(0, page['count'] - offset))
+ or any(not isinstance(row, list) or len(row) not in (7, 9)
+ or type(row[0]) is not int or row[0] != offset + index + 1
+ for index, row in enumerate(page['events']))):
+ raise RuntimeError('malformed or incomplete trace page')
+
+ first = self.exchange('TRACE_READ 0')
+ validate(first, 0)
+ status = {key: value for key, value in first.items() if key != 'events'}
+ rows = list(first['events'])
+ if rows and (rows[0][0] != 1 or rows[0][2] != 'start'):
+ raise RuntimeError('trace lacks its start identity')
+ latest_count = first['count']
+
+ def continuation(page):
+ nonlocal latest_count
+ if page['count'] < latest_count:
+ raise RuntimeError('trace count regressed while collecting')
+ if not first['active'] and any(page[key] != first[key] for key in
+ ('count', 'active', 'overflow', 'timed_out', 'hook')):
+ raise RuntimeError('stopped trace changed while collecting')
+ latest_count = page['count']
+ status['hook'] = status['hook'] and page['hook']
+ status['overflow'] = status['overflow'] or page['overflow']
+ status['timed_out'] = status['timed_out'] or page['timed_out']
+
+ while len(rows) < first['count']:
+ page = self.exchange('TRACE_READ ' + str(len(rows)))
+ validate(page, len(rows))
+ continuation(page)
+ rows.extend(page['events'][:first['count'] - len(rows)])
+ if first['count'] > 8:
+ anchor = self.exchange('TRACE_READ 0')
+ validate(anchor, 0)
+ continuation(anchor)
+ if anchor['events'] != first['events']:
+ raise RuntimeError('trace epoch changed while collecting')
+ return {**status, 'events': rows}
+
+ def close(self):
+ self.socket.close()
+
+
+def analyze(trace, *, expected_motion=None):
+ rows = trace.get('events', [])
+ complete = (trace.get('hook') is True and trace.get('active') is False
+ and trace.get('overflow') is False and trace.get('timed_out') is False
+ and trace.get('count') == len(rows) and len(rows) >= 2)
+ if complete:
+ kinds = {'start', 'stop', 'cursor', 'pointer_focus', 'keyboard_focus', 'pointer_motion',
+ 'pointer_enter', 'pointer_leave', 'pointer_button', 'pointer_axis',
+ 'keyboard_enter', 'keyboard_leave', 'keyboard_key', 'agent_cancel',
+ 'agent_approved', 'agent_admitted', 'agent_action_end', 'agent_drag_start', 'agent_drag_end'}
+ complete = all(isinstance(r, list) and len(r) in (7, 9)
+ and type(r[0]) is int and type(r[1]) is int and r[1] >= 0
+ and isinstance(r[2], str) and r[2] in kinds
+ and all(type(v) in (int, float) and math.isfinite(v) for v in r[3:5])
+ and type(r[5]) is int and r[5] in (0, 1, 2)
+ and type(r[6]) is int and r[6] in (0, 1)
+ and (len(r) == 7 or (r[2] in ('pointer_enter', 'pointer_motion') and r[5] in (1, 2)
+ and all(type(v) in (int, float) and math.isfinite(v) for v in r[7:9]))) for r in rows)
+ if complete:
+ complete = (rows[0][2] == 'start' and rows[-1][2] == 'stop'
+ and [r[0] for r in rows] == list(range(1, len(rows) + 1))
+ and all(a[1] <= b[1] for a, b in zip(rows, rows[1:])))
+ if not complete:
+ return {'result': 'inconclusive', 'reason': 'incomplete_telemetry'}
+ baseline = rows[0][3:5]
+ motion = [r for r in rows if r[2] == 'cursor']
+ max_displacement = max((math.dist(r[3:5], baseline) for r in rows), default=0)
+ if expected_motion is None:
+ unexpected_motion = [r for r in motion if math.dist(r[3:5], baseline) > 0.01]
+ if max_displacement > 0.01 and not unexpected_motion:
+ return {'result': 'inconclusive', 'reason': 'position_changed_without_motion_event'}
+ else:
+ # Ordered, externally issued primary-seat positions. No tolerance window
+ # can hide a warp between two legitimate movements.
+ actual = [r[3:5] for r in motion]
+ unexpected_motion = [] if len(actual) == len(expected_motion) and all(
+ math.dist(a, b) <= 0.01 for a, b in zip(actual, expected_motion)) else motion or [None]
+ if not unexpected_motion:
+ position = baseline
+ for row in rows:
+ if row[2] == 'cursor':
+ position = row[3:5]
+ elif math.dist(row[3:5], position) > 0.01:
+ return {'result': 'inconclusive', 'reason': 'position_changed_without_motion_event'}
+ primary = [r for r in rows if r[5] == 0]
+ focus = [r for r in primary if r[2] in ('pointer_focus', 'keyboard_focus',
+ 'pointer_enter', 'pointer_leave', 'keyboard_enter', 'keyboard_leave')]
+ leaked = [r for r in primary if r[2] in ('keyboard_key', 'pointer_axis', 'pointer_button')]
+ releases = [r for r in leaked if r[2] == 'pointer_button' and r[6] == 0]
+ starts, intervals = {}, []
+ for row in rows:
+ if row[2] == 'agent_drag_start':
+ starts[row[5]] = row[1]
+ elif row[2] in ('agent_drag_end', 'agent_cancel') and row[5] in starts:
+ intervals.append((row[5], starts.pop(row[5]), row[1]))
+ overlap = max((min(a[2], b[2]) - max(a[1], b[1]) for a in intervals for b in intervals
+ if a[0] != b[0]), default=0)
+ return {'result': 'passed' if not (unexpected_motion or focus or leaked) else 'failed',
+ 'telemetry_complete': True, 'events': len(rows),
+ 'primary_motion_events': len(motion), 'uncommanded_motion_events': len(unexpected_motion),
+ 'max_primary_displacement_px': max_displacement,
+ 'focus_events': len(focus), 'foreground_input_events': len(leaked),
+ 'unexpected_button_releases': len(releases),
+ 'agent_drag_overlap_ms': max(overlap, 0) / 1_000_000,
+ 'agent_action_completions': sum(r[2] in ('agent_action_end', 'agent_drag_end') for r in rows)}
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('trace', type=Path)
+ args = parser.parse_args()
+ print(json.dumps(analyze(json.loads(args.trace.read_text())), indent=2))
diff --git a/libs/cua-driver/hyprland-plugin/tests/primary_trace_test.py b/libs/cua-driver/hyprland-plugin/tests/primary_trace_test.py
new file mode 100644
index 0000000000..b185ba7a48
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/primary_trace_test.py
@@ -0,0 +1,172 @@
+import unittest
+import copy
+from unittest.mock import Mock, patch
+from primary_trace import Trace, analyze
+
+
+def trace(*events):
+ rows = [[i + 1, i * 1_000_000, kind, x, y, actor, state]
+ for i, (kind, x, y, actor, state) in enumerate(events)]
+ return dict(hook=True, active=False, overflow=False, timed_out=False,
+ count=len(rows), events=rows)
+
+
+START = ('start', 100, 200, 0, 0)
+STOP = ('stop', 100, 200, 0, 0)
+
+
+class TraceTest(unittest.TestCase):
+ def collect_pages(self, pages):
+ connection = Trace.__new__(Trace)
+ connection.exchange = Mock(side_effect=pages)
+ result = connection.collect()
+ return result, [call.args[0] for call in connection.exchange.call_args_list]
+
+ def pages(self, *, active=True):
+ data = trace(START, *(('cursor', 100 + i, 200, 0, 0) for i in range(20)))
+ data.update(ok=True, active=active)
+ return data
+
+ def test_active_trace_collects_exact_initial_prefix_while_appending(self):
+ data = self.pages()
+ first = {**data, 'count': 12, 'events': data['events'][:8]}
+ second = {**data, 'count': 18, 'events': data['events'][8:16]}
+ anchor = {**data, 'events': data['events'][:8]}
+ result, calls = self.collect_pages([first, second, anchor])
+ self.assertEqual(result['events'], data['events'][:12])
+ self.assertEqual(result['count'], 12)
+ self.assertTrue(result['active'])
+ self.assertEqual(calls, ['TRACE_READ 0', 'TRACE_READ 8', 'TRACE_READ 0'])
+ self.assertEqual(len(first['events']), 8, 'collector must not mutate replies')
+
+ def test_stopped_trace_is_complete_and_unchanged(self):
+ data = trace(START, *(('cursor', 100, 200, 0, 0) for _ in range(10)), STOP)
+ data['ok'] = True
+ result, _ = self.collect_pages([{**data, 'events': data['events'][:8]},
+ {**data, 'events': data['events'][8:]}, {**data, 'events': data['events'][:8]}])
+ self.assertEqual(result, data)
+ self.assertEqual(analyze(result)['result'], 'passed')
+
+ def test_live_failures_are_never_hidden_by_initial_healthy_flags(self):
+ data = self.pages()
+ first = {**data, 'count': 12, 'events': data['events'][:8]}
+ for key, value in (('overflow', True), ('timed_out', True), ('hook', False)):
+ with self.subTest(key=key):
+ second = {**data, key: value, 'events': data['events'][8:16]}
+ result, _ = self.collect_pages([first, second, {**data, 'events': data['events'][:8]}])
+ self.assertEqual(result[key], value)
+ self.assertEqual(analyze(result)['result'], 'inconclusive')
+
+ def test_reset_with_regrown_count_is_rejected_by_start_identity(self):
+ data = self.pages()
+ first = {**data, 'count': 12, 'events': data['events'][:8]}
+ anchor = copy.deepcopy({**data, 'events': data['events'][:8]})
+ anchor['events'][0][1] += 1
+ with self.assertRaisesRegex(RuntimeError, 'epoch'):
+ self.collect_pages([first, {**data, 'events': data['events'][8:16]}, anchor])
+
+ def test_count_regression_is_rejected_even_if_above_prefix_limit(self):
+ data = self.pages()
+ with self.assertRaisesRegex(RuntimeError, 'regressed'):
+ self.collect_pages([{**data, 'count': 12, 'events': data['events'][:8]},
+ {**data, 'events': data['events'][8:16]},
+ {**data, 'count': 20, 'events': data['events'][:8]}])
+
+ def test_malformed_or_missing_rows_fail(self):
+ data = self.pages()
+ first = {**data, 'count': 12, 'events': data['events'][:8]}
+ valid = {**data, 'events': data['events'][8:16]}
+ changes = [{'events': []}, {'count': True}, {'count': 32769}, {'active': 1},
+ {'events': [[], *valid['events'][1:]]},
+ {'events': [[99, *valid['events'][0][1:]], *valid['events'][1:]]}]
+ for change in changes:
+ with self.subTest(change=change), self.assertRaises(RuntimeError):
+ self.collect_pages([first, {**valid, **change}])
+
+ def test_stopped_trace_cannot_resume_during_collection(self):
+ data = self.pages(active=False)
+ with self.assertRaisesRegex(RuntimeError, 'stopped trace changed'):
+ self.collect_pages([{**data, 'count': 12, 'events': data['events'][:8]},
+ {**data, 'active': True, 'events': data['events'][8:16]}])
+
+ def test_handshake_is_sent_once_and_retained_for_version_validation(self):
+ peer = Mock()
+ peer.recv.return_value = b'{"ok":true,"protocol":3}'
+ with patch('primary_trace.socket.socket', return_value=peer):
+ connection = Trace('/synthetic/cua-input-v3.sock')
+ self.assertEqual(connection.hello['protocol'], 3)
+ peer.sendall.assert_called_once_with(b'HELLO')
+ connection.close()
+
+ def test_warp_and_return_is_not_hidden_by_equal_endpoints(self):
+ result = analyze(trace(START, ('cursor', 140, 230, 0, 0), ('cursor', 100, 200, 0, 0), STOP))
+ self.assertEqual(result['result'], 'failed')
+ self.assertEqual(result['max_primary_displacement_px'], 50)
+ self.assertEqual(result['uncommanded_motion_events'], 1)
+
+ def test_synthetic_events_do_not_count_as_foreground_leakage(self):
+ result = analyze(trace(START, ('pointer_button', 100, 200, 1, 0),
+ ('keyboard_key', 100, 200, 2, 1), STOP))
+ self.assertEqual(result['result'], 'passed')
+
+ def test_surface_coordinates_are_separate_from_primary_coordinates(self):
+ data = trace(START, ('pointer_motion', 100, 200, 1, 0), STOP)
+ data['events'][1].extend([400, 300])
+ result = analyze(data)
+ self.assertEqual(result['result'], 'passed')
+ self.assertEqual(result['max_primary_displacement_px'], 0)
+ for change in ([400], [400, float('nan')], [True, 300], [400, 300, 500]):
+ bad = {**data, 'events': [data['events'][0], data['events'][1][:7] + change, data['events'][2]]}
+ self.assertEqual(analyze(bad)['result'], 'inconclusive')
+ data['events'][1][5] = 0
+ self.assertEqual(analyze(data)['result'], 'inconclusive')
+
+ def test_v3_admission_marker_is_recognized_but_unknown_events_stay_inconclusive(self):
+ self.assertEqual(analyze(trace(START, ('agent_admitted', 100, 200, 1, 0), STOP))['result'], 'passed')
+ self.assertEqual(analyze(trace(START, ('unknown', 100, 200, 1, 0), STOP))['result'], 'inconclusive')
+
+ def test_missing_or_dropped_telemetry_is_inconclusive(self):
+ for change in ({'hook': False}, {'overflow': True}, {'timed_out': True},
+ {'active': True}, {'count': 9}, {'events': []}):
+ self.assertEqual(analyze({**trace(START, STOP), **change})['result'], 'inconclusive')
+ broken = trace(START, STOP)
+ broken['events'][1][0] = 3
+ self.assertEqual(analyze(broken)['result'], 'inconclusive')
+ for row in ([], [1], [1, 1, 'cursor', 'bad', 0, 0, 0],
+ [1, 1, 'cursor', float('nan'), 0, 0, 0]):
+ bad = trace(START, STOP)
+ bad['events'][0] = row
+ self.assertEqual(analyze(bad)['result'], 'inconclusive')
+
+ def test_primary_focus_keys_and_releases_fail(self):
+ for kind in ('pointer_focus', 'keyboard_enter', 'keyboard_key', 'pointer_button'):
+ self.assertEqual(analyze(trace(START, (kind, 100, 200, 0, 0), STOP))['result'], 'failed')
+
+ def test_real_overlap_is_measured_from_dispatch_not_animation(self):
+ result = analyze(trace(START, ('agent_drag_start', 100, 200, 1, 0),
+ ('agent_drag_start', 100, 200, 2, 0),
+ ('agent_drag_end', 100, 200, 1, 0),
+ ('agent_drag_end', 100, 200, 2, 0), STOP))
+ self.assertEqual(result['agent_drag_overlap_ms'], 1)
+
+ def test_controlled_motion_must_match_every_command_in_order(self):
+ data = trace(START, ('cursor', 120, 200, 0, 0), ('cursor', 100, 200, 0, 0), STOP)
+ self.assertEqual(analyze(data, expected_motion=[[120, 200], [100, 200]])['result'], 'passed')
+ self.assertEqual(analyze(data, expected_motion=[[100, 200]])['result'], 'failed')
+
+ def test_controlled_motion_reconciles_all_observed_positions(self):
+ moved = ('cursor', 120, 200, 0, 0)
+ stopped = ('stop', 120, 200, 0, 0)
+ for events in ((START, moved, STOP),
+ (START, moved, ('pointer_motion', 140, 200, 0, 0), stopped),
+ (START, moved, ('agent_action_end', 140, 200, 1, 0), stopped)):
+ with self.subTest(events=events):
+ result = analyze(trace(*events), expected_motion=[[120, 200]])
+ self.assertEqual(result['result'], 'inconclusive')
+ self.assertEqual(result['reason'], 'position_changed_without_motion_event')
+ self.assertEqual(analyze(trace(START, moved, ('pointer_motion', 120, 200, 0, 0), stopped),
+ expected_motion=[[120, 200]])['result'], 'passed')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production-cancel-proof.md b/libs/cua-driver/hyprland-plugin/tests/production-cancel-proof.md
new file mode 100644
index 0000000000..7b31d28af4
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production-cancel-proof.md
@@ -0,0 +1,210 @@
+# Native runtime cancellation proof preparation
+
+`production_cancel_proof.py` prepares a bounded cancellation test through two
+independent `cua-driver mcp --direct` processes. Its local tests use synthetic
+telemetry and mocked processes. An optional recovery phase starts a new direct
+runtime after cancellation. **Native cancellation and recovery remain unproven.**
+
+The test grounds both gestures before starting either drag. It starts one
+drag, identifies its compositor lane from admission and
+held-button telemetry, then starts the sibling drag. It sends the preselected
+termination signal to the first drag's exact owned Driver process only after a fresh trace prefix shows
+both buttons held and at least 100 ms of overlap. The last trace read must take
+at most 250 ms, neither call may have returned, and both owned processes must
+still be alive. A completed drag, stale read, or missing telemetry fails the
+test instead of authorizing termination. There is still a scheduling race
+between observation and termination; final trace validation rejects a drag
+that completed in that interval.
+
+Set `termination_signal` to `SIGKILL` (the default) or `SIGTERM` in the
+reviewed plan. The SIGTERM case fails if the process does not exit within three
+seconds; it does not substitute SIGKILL to pass. Unconditional cleanup can
+still terminate a surviving owned child after that failure. These are process
+termination tests, not evidence for MCP request cancellation or `end_session`.
+
+Only ordinary Driver calls target the apps. The trace connection uses `HELLO`,
+`TRACE_START`, `TRACE_READ`, and `TRACE_STOP`; it never sends target, input,
+grant, or cancellation protocol commands. An independent `primary-grab`
+fixture holds the foreground button at a parked position. This fixture is the
+primary-seat oracle, not an actuator for either app. Every Driver runtime,
+including the observer, uses the existing unrestricted permission mode with
+explicit approval bypass through `production_mcp.py`. This harness creates no
+signer, grant, approval panel, or permission profile.
+
+## Prepare the native gate
+
+Use the prepared disposable Hyprland desktop and the exact source candidate.
+Reconcile the loaded plugin with the build artifact before interpreting any
+result. The existing production provenance helper checks the source SHA,
+records versions, hashes, dirty status, package identities, and loaded plugins.
+It requires native Calc `libreoffice-fresh 26.2.5-3` and Inkscape `1.4.4-6`, each
+in a separate process with exactly one mapped native window. The foreground
+journal fixture must be a third process. Preserve the application documents
+for inspection after interruption.
+
+Create a reviewed JSON plan from fresh Driver window listings and snapshots.
+The plan fields are:
+
+- `purpose`: `"cancellation"`.
+- `kill_agent`: `0` or `1`. This agent starts first and is the sole deliberate
+ termination target; the other agent is the sibling.
+- `foreground`: exact positive integer `pid` and `window_id` values.
+- `primary_point`: two integer coordinates relative to the foreground window,
+ safely inside its bounds and the desktop.
+- `package_versions`: `{"libreoffice-fresh":"26.2.5-3","inkscape":"1.4.4-6"}`.
+- `agents`: exactly two objects with distinct `app` values `calc` and
+ `inkscape`, a `name`, exact `target` (`pid`, `window_id`), and reviewed
+ `bounds` (`x`, `y`, `width`, `height`). An optional `profile` must equal
+ `{"mode":"unrestricted","acknowledge_unrestricted":true}`.
+- Prefer `pointer_stage:"select_range"` for Calc and
+ `pointer_stage:"move_rectangle"` for Inkscape, each with `drag:{}`. The
+ runner derives a 1500 ms, 30-step gesture from the exact fresh full snapshot's
+ pixels and semantic state. These stages require the synthetic documents
+ described in `production-proof.md`; ambiguous, clipped, scaled, or already
+ satisfied state refuses before dispatch.
+- For a separately reviewed coordinate plan, each agent's `drag` contains
+ exactly `from_x`, `from_y`, `to_x`, `to_y`, and integer
+ `duration_ms`. Choose distinct endpoints inside that app's fresh screenshot
+ and a safe gesture on disposable content. Duration must be 1000–2000 ms. The harness
+ supplies the target, session, and background delivery mode.
+
+The runner checks Driver's PID/window listing and a fresh image for each drag,
+then retains both observations and derived arguments before dispatch. It
+positively resolves Calc's current name-field selection and requires the next
+Standard toolbar to establish that the Formula Tool Bar section is complete.
+A missing or truncated selection field is unknown, not an unselected range.
+It
+rejects changed bounds, endpoints outside the image, and grounding older than
+five seconds at dispatch. Before either drag, both observations must retain
+250 ms for dispatch scheduling. If not, the runner can refresh both observations
+once, retaining each attempt separately. A second stale pair fails without
+input. A final paired check includes evidence-write and primary-guard time.
+This reserve is not a worst-case scheduling guarantee: each actual dispatch
+still checks its own five-second limit. No snapshot refresh or input retry
+runs after either input attempt begins.
+The independent observer records fresh after-snapshots for both apps. When
+using pointer stages, the sibling must also show the expected selection or
+rectangle movement. The victim's interrupted effect remains uncertain and is
+preserved without replay. Explicit coordinate plans still require human
+review of their application meaning. Slow setup fails; it never authorizes a
+retry of an uncertain action.
+
+Run only after the native environment and plan are authorized and prepared.
+Substitute the reviewed paths and exact candidate SHA:
+
+```text
+python3 libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py \
+ --source <checkout> --source-sha <candidate-sha> \
+ --driver <driver> --plugin <loaded-trace-plugin-file> \
+ --primary-grab <primary-grab> --foreground-journal <fixture-journal> \
+ --trace-socket <runtime>/cua-input-v3.sock \
+ --plan <reviewed-plan.json> --evidence <new-evidence-directory>
+```
+
+Build the production v3 plugin with `CUA_HYPRLAND_INPUT_TRACE=ON` for this gate.
+An uninstrumented package smoke cannot substitute for cancellation evidence.
+
+## Optional fresh-runtime recovery
+
+Add `recovery:{"pointer_stage":"click_b2"}` when Calc is the victim, or
+`recovery:{"pointer_stage":"scroll_visible"}` when Inkscape is the victim.
+Calc also supports `click_a1`. Both agents must use the derived pointer stages
+above so the sibling's app effect is verified. Choose a Calc cell that will
+not already be selected after the interruption; already-satisfied or ambiguous
+state fails without another action. Inkscape recovery requires the interrupted
+rectangle to remain visible and uniquely selected. Before any recovery input,
+`scroll_visible` chooses up or down from the same fresh image, toward the larger
+visible canvas margin. It requires 100 pixels of margin for the pinned fixture's
+approximately 80-pixel scroll. The evidence records the requested and resolved
+stages. Pixel-size, document-geometry, and scroll-effect checks remain strict;
+clipping after dispatch fails without replay. The explicit `scroll_down` stage
+remains available for separately reviewed plans.
+
+The runner first verifies the cancellation phase, including victim release and
+normal sibling completion. It saves the victim's fresh observer snapshot and
+image hashes in `interrupted-state.json` before launching recovery. These are
+evidence of observed interrupted state, not saved-document or rollback proof.
+The runner does not issue a document save or infer which on-disk file holds
+unsaved changes.
+
+Recovery creates a third action runtime through `mcp --direct`, records its
+distinct process ID, and uses a new session name. The killed runtime remains
+poisoned and reaped. The new process loads the unrestricted startup profile
+and inherited managed/user policy through the existing normal runtime path;
+the evidence records that startup configuration, not an independent inspection
+of every effective policy rule. The new call still requires common dispatch
+admission and fresh compositor admission.
+
+The new runtime checks the app's canonical executable/GTK identity, exact
+PID/window listing, reviewed bounds, and a full fresh image. It derives one
+new click or scroll from that observation. Grounding older than five seconds
+refuses before dispatch. This action has a different tool and meaning from
+the canceled drag; no canceled arguments, snapshot tokens, or transport are
+reused. Target replacement, moved geometry, denied policy, unreadable state,
+or failed effect verification fails the recovery phase without replay.
+
+The independent observer then captures the result, and the existing app
+oracle must prove the new selection or viewport change. Lost replies remain
+unknown, with their observer snapshot retained when observation succeeds.
+Continuous telemetry must show exactly one fresh admission and one completed
+click or scroll on the released victim lane, with no sibling input, replayed
+drag, cancellation, held synthetic input, or primary-seat disturbance. Both
+victim indexes and both compositor lane mappings are supported.
+
+`cancellation-prefix.json` and `recovery-prefix.json` retain complete active
+trace prefixes. Phase analysis adds an in-memory stop sentinel only; it never
+resets or stops the real trace between phases. Final cleanup still requires
+the real stopped trace, unchanged prefix history, balanced synthetic input,
+and uninterrupted primary isolation. After recovery completion, synthetic
+events may only cancel an idle lease or leave its pointer/keyboard resources;
+any new admission, input, or gesture marker fails cleanup. A recovery or cleanup
+failure fails the overall run even when the cancellation phase was verified.
+
+## Interpret evidence
+
+An overall `result:"passed"` requires one cancellation on the victim lane,
+one subsequent release of its held synthetic button, and normal sibling
+release and drag completion after that cancellation. The sibling must return
+a dispatched response and remain alive. Both lanes must finish with balanced
+synthetic input. Complete continuous telemetry must show no primary cursor,
+focus, keyboard, scroll, or button disturbance. Foreground identity, workspace,
+cursor, and journal counters must also remain unchanged while the grab is held.
+
+The victim's lost response remains `outcome:"unknown"`; it does not mean no
+input was delivered or that the document was rolled back. If a response arrives,
+the helper retains it and accepts only the existing partial/unknown delivery
+contract. A successful victim response fails this cancellation test. The killed
+connection is poisoned before termination and is never reused. Neither action
+is replayed, including on failure. Optional recovery is a separately grounded
+new action, not a retry.
+
+Evidence includes the reviewed plan, provenance, MCP images/results,
+`agent-N-drag-grounding.json` with each exact image and derived arguments,
+`termination-prefix.json`, the stopped `trace.json`, observer after-snapshots,
+and `result.json` with the exact terminated PID, signal, and monotonic request
+and reap times. `cleanup.json` retains failures. Cleanup attempts every owned
+Driver process, pending worker, trace connection, and primary-grab child even
+when another cleanup fails; surviving owned children are killed and reaped.
+Pre-existing app and foreground fixture processes are not terminated. Raw
+evidence and local paths are for internal review.
+
+Recovery runs additionally retain `recovery-grounding.json` (startup profile,
+runtime identity, app identity, snapshot, arguments, and oracle),
+`recovery-action.json`, and `recovery-after.json`. The interrupted snapshot and
+image hashes are checked again after successful recovery. The new runtime is
+included in unconditional cleanup, including failed setup and lost replies.
+
+Without `recovery`, the cancellation-only contract is unchanged and reports
+`reacquisition:"unproven"`. With it, `reacquisition.result:"verified"` requires
+the new app effect and complete recovery trace. Saved-document effects remain
+explicitly unproven in either mode. Moving-primary cancellation,
+target/keymap/display/session faults, repetition controls, and the complete
+desktop matrix remain separate gates. A native run must establish both the
+claimed cancellation behavior and exact loaded-artifact provenance before this
+preparation can be described as certification.
+
+Focused deterministic verification from the tests directory:
+
+```text
+python3 -m unittest production_cancel_proof_test production_pointer_grounding_test production_realapp_proof_test realapp_proof_test primary_trace_test
+```
diff --git a/libs/cua-driver/hyprland-plugin/tests/production-proof.md b/libs/cua-driver/hyprland-plugin/tests/production-proof.md
new file mode 100644
index 0000000000..09824848d4
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production-proof.md
@@ -0,0 +1,360 @@
+# Production input proof preparation
+
+`production_realapp_proof.py` prepares a repeatable v3 native proof through
+`cua-driver mcp --direct`. Each agent owns a separate Driver process. No test
+signer, operator grant, input socket mutation command, or extra approval UI is
+used. Existing signed runners and their historical results remain unchanged.
+
+This harness has unit coverage. It has **not** certified a native candidate.
+The pinned qualification targets are native LibreOffice Calc package
+`26.2.5-3` and Inkscape package `1.4.4-6`; package versions alone are not proof
+that either app received isolated input.
+
+## Validation strategy decision (2026-09-07)
+
+The maintainer selects `scripts/ci/linux/run-rust-e2e.sh`, running its complete
+`all` suite in the prepared native Hyprland desktop at the exact candidate
+SHA, as the canonical regression gate. See the
+[test-harnesses guide](../../docs/test-harnesses-guide.md#hyprland-validation-decision-2026-09-07).
+Keep its required cells and evidence checks intact. Ordinary GTK, Electron,
+and Tauri fixtures are outside the production v3 package qualification gate;
+their refusals do not prove delivered plugin input. No admission widening,
+test bypass, or additional approval UI is part of this decision.
+
+Short real-app checks remain required supporting compatibility evidence:
+run the bounded production smoke on both pinned apps, and use bounded traced
+plans to establish actual v3 delivery, app effects, primary-seat isolation,
+and cleanup. Retain focused evidence for the supported operations and two-lane
+behavior being promoted. A smoke reporting `plugin_transport_attribution:false`
+cannot satisfy transport attribution or continuous isolation. Neither a
+canonical all-refusal result nor mocked helper tests close that evidence gap.
+
+The earlier requirement for three complete long Python Calc/Inkscape runs,
+including 34 policy cases across both apps, is retired. The extended plans below
+remain available for focused compatibility checks and stress diagnostics;
+they are not a second canonical E2E suite or a mandatory repetition count.
+Use focused policy coverage for the shared admission contract and investigate
+unresolved native failures with the relevant plan. Keep every executed plan's
+assertions and evidence requirements intact, and preserve failed results.
+
+This addendum records a strategy change, not completed native certification.
+Exact package versions, operation limits, existing Driver policy, and the
+separate release/package/Fleet requirements remain in force.
+
+## Bounded real-app smoke
+
+`production_app_smoke.py` provides the bounded production smoke. Run it in a
+disposable desktop with the exact source-built production plugin already loaded and
+enabled. Pass `--source`, `--source-sha`, `--driver`, `--plugin`, and a new
+`--evidence` directory. The runner verifies a clean source checkout, canonical
+ALPM-owned app executables, and the plugin's current mapped path, device, and
+inode in the active compositor.
+
+It opens two new synthetic documents through direct Driver MCP, grounds each
+keyboard action in fresh snapshots, and independently checks the saved files:
+Calc A1 contains `a`; Inkscape's single rectangle moves two SVG pixels right.
+The runtime uses unrestricted mode with explicit bypass acknowledgement.
+Missing semantic grounding returns `inspection_only` and a nonzero exit code;
+partial or unknown delivery fails without replay. App windows and evidence are
+retained for inspection until the disposable environment is deleted.
+
+This smoke does not prove foreground isolation, concurrency, pointer operations,
+the policy matrix, or package installation. Its `synthetic_events` response is
+a shared route family, not independent attribution to the loaded plugin.
+`plugin_transport_attribution:false` keeps that limitation explicit. Use the
+traced plans below for transport attribution and isolation. Mocked tests are
+not native results.
+
+## Reviewed native plans
+
+Run only inside the prepared disposable desktop, after mapping one window per
+app and the independent foreground journal fixture. Ground the exact window
+identities, bounds, and gesture coordinates using fresh Driver snapshots.
+The runner requires a clean exact-SHA checkout and verifies the active
+compositor's mapped plugin by path, kernel device, and inode. A private
+non-executable reference mapping of the exact candidate supplies the comparable
+kernel identity, including on Btrfs where `stat()` can report a different
+subvolume device. Replaced, changed, and deleted candidate files still refuse.
+Qualified app processes
+must resolve to canonical ALPM-owned executables with the GTK3 backend loaded;
+an executable basename or recorded hash alone is insufficient. The cancellation
+runner shares these checks. Store evidence outside the source checkout.
+Review a JSON plan before execution. The plan has:
+
+- `purpose`: `apps`, `policy`, `policy_cache`, `negative_control`, or `capacity`.
+- `foreground`: its exact `pid` and `window_id`.
+- `package_versions`: `{"libreoffice-fresh":"26.2.5-3","inkscape":"1.4.4-6"}`.
+- `agents`: one or two objects (exactly three for capacity, one for policy_cache) with `app`, `target`, `bounds`, `name`, and
+ `profile`. App proof requires distinct Calc and Inkscape processes. Public
+ names may be identical; they are not runtime ownership credentials.
+- `profile`: `mode` is `standard`, `bounded`, or `unrestricted`. Unrestricted
+ requires `acknowledge_unrestricted:true`. A reviewed `manifest` path requires
+ `approve_manifest:true` in every mode; bounded requires a manifest. These map
+ to the normal direct-runtime environment contract. Managed/user policy remains
+ inherited. Do not put secrets in the plan or evidence.
+ The independent observer uses `unrestricted` with explicit bypass acknowledgement;
+ the agent under test retains its reviewed profile and manifest ceiling.
+- `phases`: sequential `{agent,tool,arguments}` objects, or `parallel` arrays
+ with at most one call per runtime. Tools are click, press_key, hotkey, scroll,
+ and drag. Reserved ownership/delivery arguments cannot override the plan.
+- Optional per-step `smoke_stage` reuses the bounded keyboard smoke's semantic
+ grounding. Calc accepts `insert` (`press_key`, `{"key":"a"}`), `commit`
+ (`press_key`, `{"key":"Return"}`), and `save` (`hotkey`, `{"keys":["ctrl","s"]}`).
+ Inkscape accepts `select` (`hotkey`, `{"keys":["ctrl","a"]}`), `move`
+ (`press_key`, `{"key":"Right"}`), and `save` (`hotkey`, `{"keys":["ctrl","s"]}`).
+ These steps use fresh default-depth snapshots and verify the exact sole app
+ window before and after input. Missing semantic grounding or an unexpected
+ dialog stops the run without recovery keys or replay. Unmarked reviewed
+ steps retain their existing grounding contract. Saved-file and trace oracles
+ are still required; a grounded shortcut alone does not prove its effect.
+- Optional per-step `pointer_stage` derives coordinates from the same fresh
+ full snapshot used before dispatch. Supply empty `arguments` and the matching
+ tool: Calc `click_b2`/`click_a1` use `click`, `select_range` uses `drag`;
+ Inkscape `click_rectangle` uses `click`, `move_rectangle` uses `drag`. Both
+ apps accept `scroll_down`/`scroll_up` with `scroll`. These are app-effect
+ cases only, not refusal or partial-delivery cases. They cannot also use
+ `smoke_stage`. The native guest needs Python GI and GdkPixbuf for PNG reading.
+ Calc requires the visible, regular cell grid and a unique vertical scrollbar;
+ click/range cases require the top of the sheet and a changed name-field
+ selection. Inkscape requires the unique blue synthetic rectangle. Its click
+ case must start unselected and end selected; scroll must move the rendered
+ canvas without changing document geometry; drag must move the rectangle in
+ pixels and document coordinates without resizing it. The helper rejects
+ clipped, ambiguous, missing, or scaled observations. Exact derived arguments
+ and their source image are saved before the action. Both drags last 1.5 seconds
+ with 30 steps; a parallel phase still needs `require_overlap:true` and a
+ complete trace to prove actual overlap. Saved-output oracles remain required.
+ This is proof preparation, not evidence that these native cells have passed.
+ Drag proof separates the wire endpoint from app translation. Instrumented
+ synthetic pointer enter/motion records append surface-local X/Y to the seven
+ existing trace fields; primary cursor coordinates remain separate. The
+ complete trace must show the requested start/end, an ordered straight path,
+ balanced buttons, and uninterrupted drag focus. Inkscape's
+ [1.4.4 selection tool](https://gitlab.com/inkscape/inkscape/-/blob/INKSCAPE_1_4_4/src/ui/tools/select-tool.cpp)
+ anchors translation at its first processed motion, not button press. Its
+ completed selection, unchanged dimensions, and pixel/document translation
+ must agree, and the translation must match endpoint minus an actually
+ delivered motion position. A missing endpoint, unmatched translation, or
+ historical trace without synthetic coordinates fails this gate.
+ Each pointer action records the exact before/after MCP response numbers so
+ an artifact verifier can reconstruct its grounding and app effect from the
+ archived PNGs. Traced pointer episodes also save compositor status before
+ runtime close and after bounded cleanup: passive pointer focus must retain
+ neither a lease nor held input or keyboard focus. The complete wire trace
+ must show no same-target focus churn. Runtime close must release the lane
+ reservation without sending new input or disturbing its inert pointer focus.
+ These checks are prepared; a passing native run is still required.
+- Optional per-step `expect`: `{kind:"refused",reason:"<exact observed contract reason>"}`,
+ `{kind:"partial"}`, or `{kind:"unknown"}`. The default is dispatched. Denial
+ phases run serially so the no-dispatch interval contains no other action.
+- For interrupted drags, `delivery.delivered_count:1` accounts for the
+ acknowledged start phase, not a total event count. Explicit cancellation is
+ partial background delivery; loss of the final reply is unknown delivery,
+ retaining the start count when available. Neither means the document was
+ rolled back or that later events could not have landed. Preserve the output
+ and inspect fresh state without replaying the mutation.
+- `outputs`: independent saved-document oracles with `agent`, `path`, `xpath`,
+ optional `namespaces`, and exact `attributes` or `text`. SVG rectangle movement
+ can use `rect_translation:[[min_x,max_x],[min_y,max_y]]`, which also rejects
+ resizing. ODS files use `zip_member:"content.xml"`. App proof requires at least
+ one output oracle per app. Save the documents through reviewed Driver actions.
+- `require_overlap:true` requires at least 100 ms of traced drag overlap.
+ `primary_point` optionally changes the foreground hold point, default `[300,300]`.
+- `moving_primary:true` optionally moves the independent foreground primary grab
+ during the reviewed Driver actions. The default remains parked. This mode
+ requires `--trace-socket` and cannot be combined with `negative_control`.
+ The helper repeats the historical 160 px square in 20 px steps, issuing a
+ command every 100 ms after the preceding acknowledgement. The entire path
+ must fit inside the foreground window and desktop; adjust `primary_point`
+ using grounded geometry before running. At least one movement command and
+ its acknowledgement must fall inside a Driver action's call interval.
+
+Invoke from the exact source checkout, substituting the already reviewed paths
+and candidate SHA:
+
+```text
+python3 libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py \
+ --source <checkout> --source-sha <candidate-sha> \
+ --driver <driver> --plugin <loaded-plugin-file> \
+ --primary-grab <primary-grab> --foreground-journal <fixture-journal> \
+ --plan <reviewed-plan.json> --evidence <new-evidence-directory> --record-video
+```
+
+For instrumented certification, build v3 with `CUA_HYPRLAND_INPUT_TRACE=ON`
+and add `--trace-socket <runtime>/cua-input-v3.sock`. The runner reuses
+`primary_trace.py` and the independent foreground hold. Trace hooks must be
+complete, ordered, and free of overflow/timeouts. A refusal must contain the
+exact reason, refused effect, no delivery, and no synthetic event in its trace
+interval. A policy error alone never proves no dispatch. Trace instrumentation
+is disabled in production builds.
+
+For a capacity run, prepare a separate `purpose:"capacity"` plan with three
+independent native app processes. Agents 0 and 1 must be Calc and Inkscape;
+agent 2 can be another instance of either qualified app. Each process must own
+exactly one mapped native window. A second window in the same app process does
+not qualify. Ground each exact positive integer `pid` and `window_id`, bounds,
+and safe action coordinates from fresh snapshots. The runner cross-checks the
+PID/window pair against Driver's window listing before every snapshot. Use the
+normal reviewed permission profiles described above; capacity adds no grant or
+permission bypass.
+
+Use exactly three serial phases: one successful action by agent 0, one by agent
+1, then one action by agent 2 with
+`expect:{"kind":"refused","reason":"lane_busy"}`. Omit `expect` for the first
+two actions or set it to `{"kind":"dispatched"}`. Choose each action from a
+fresh snapshot and retain its after-snapshot. Do not copy coordinates from an
+unrelated app or evidence run. Capacity rejects parallel phases, extra phases,
+moving-primary mode, and `require_overlap:true`. Persistent lane reservations
+make simultaneous gestures unnecessary for this capacity check; use the
+separate app plan to prove overlap and saved document changes.
+
+Run the capacity plan with the command above and `--trace-socket`. A missing
+trace option fails before any Driver process starts. The runner keeps all three
+independent direct MCP processes alive through the third response. Each of the
+first two intervals must contain v3 admission, actual input for the requested
+tool, and completion in order on one compositor lane; together they must
+exercise lanes 1 and 2. Runtime PIDs and session names alone cannot satisfy this
+check. The third response must be an exact `lane_busy` refusal with no delivery
+and no synthetic event in its serial trace interval. Another policy denial,
+partial delivery, unknown effect, empty trace, missing instrumentation, or
+reused lane fails the run without replaying the action.
+
+Capacity evidence includes `capacity-agent-0-trace.json` through
+`capacity-agent-2-trace.json`, containing the active trace prefixes around each
+checked action, plus the normal stopped trace, continuous isolation, and
+cleanup results. `result.json` records the observed lane for each admission and
+the capacity verdict. Only an overall `result:"passed"` includes successful
+isolation and cleanup checks. This proves bounded lane capacity and refusal,
+not saved app effects, overlapping gestures, or the desktop matrix. Run the
+capacity plan separately from the package smoke: it cannot pass without
+instrumentation.
+
+For a cached-connection tool-ceiling run, prepare a separate
+`purpose:"policy_cache"` plan. Use exactly one qualified Calc or Inkscape process,
+one fixed positive integer PID/window pair, and one nonempty session name.
+The runner checks that pair against `list_windows` before each fresh snapshot.
+Use an approved capability manifest with any of the three shared profiles;
+`unrestricted` also needs `acknowledge_unrestricted:true`. The manifest must
+allow session startup, window listing, window snapshots, and the permitted
+input tool. Include the grounded resource scope required by those tools.
+For `bounded`, include the required `expires_after` and `idle_timeout` fields.
+Keep the profile, manifest, process, target, and session fixed for the entire
+run; no policy reload, target override, extra signer, or per-window consent
+mechanism is part of this proof.
+
+Use exactly three serial phases, all with `agent:0`: a permitted input action,
+an action using a different denied tool, then a fresh permitted action using
+the first tool. For example, allow `click` and deny `press_key`, then review two
+safe clicks and an Escape key call against fresh native state. The third call
+is a new reviewed action, not a retry of either preceding call. Its arguments
+can differ from the first call. Both permitted phases must omit `expect` or
+use `{"kind":"dispatched"}`. Set the middle expectation to:
+
+```json
+{
+ "kind": "refused",
+ "reason": "permission_denied",
+ "message": "Permission denied: capability manifest denies tool 'press_key'"
+}
+```
+
+If the denied tool is omitted from the manifest instead of explicitly denied,
+the only alternate message is
+`Permission denied: tool 'press_key' is outside the capability manifest`.
+Replace `press_key` with the actual middle-phase tool in either message. These
+strings come from `authorize_tool_call_with_context` in
+`rust/crates/cua-driver-core/src/authorization.rs`, the `AuthorizationError`
+display in `policy.rs`. Direct MCP's early tool-admission check in `server.rs`
+returns `isError:true`, `structuredContent:{"code":"permission_denied"}`, and
+one MCP text content block with the exact reviewed message. Later common
+admission in `tool.rs` uses `status:"refused"`,
+`refusal.code:"permission_denied"`, and the exact reviewed `refusal.message`.
+The verifier recognizes these two source-defined shapes, retains the raw
+structured and text content, and requires no delivery in either case.
+A generic plugin `permission_denied`, resource-scope denial,
+managed/user-policy denial, partial result, or unknown delivery fails this
+narrow manifest tool-ceiling case.
+
+Run with `--trace-socket`; its absence fails before process launch.
+`policy_cache` rejects parallel phases, moving-primary mode, and overlap claims.
+The same direct MCP runtime must remain alive through all three responses.
+Both permitted intervals must show ordered admission, tool input, and completion
+on the same compositor lane. Runtime PID or session equality alone is
+insufficient. The middle interval must contain zero synthetic-lane events,
+including `agent_admitted`, the successful v3 `TARGET` admission marker emitted
+by `input_experiment.cpp`. This trace measures that marker and input; it is not
+a raw socket packet capture. The quiet interval includes the denied call's
+before/after snapshots, and the runner also checks every gap between phases.
+No action is replayed after a refusal, partial result, unknown delivery, or
+transport failure.
+
+Evidence includes `policy-cache-phase-0-trace.json` through
+`policy-cache-phase-2-trace.json`, with continuous active prefixes, the stopped
+trace, action runtime/session identities, exact refusal, foreground journal
+checks, and cleanup results. `result.json.policy_cache` records the shared lane
+and tool-ceiling verdict. Accept only an overall `result:"passed"`, which also
+requires continuous foreground isolation and synthetic cleanup. This is
+preparation for one cached-connection manifest tool-ceiling proof, not native
+certification, the complete resource/managed-policy matrix, saved app effects,
+or the desktop matrix. The focused tests use mocked runtimes and telemetry.
+
+Moving-primary proof uses `primary-grab` in its independent `controlled` mode,
+with `MOVE` commands and exact `MOVED` acknowledgements. Driver actions remain
+background calls with before/after window snapshots. The foreground journal
+must retain its click, key, scroll, and held-button state, and foreground window
+identity and workspace must remain unchanged. Cursor endpoints may move along
+the commanded path. The continuous trace must match every acknowledged position
+in order, with no extra motion, focus changes, or foreground input events.
+Every other traced position, including the final endpoint, must agree with the
+latest cursor event; an unexplained position change leaves isolation unproven.
+Missing, malformed, incomplete, or reordered command logs fail the run, as do
+missing acknowledgements, an unjoined movement worker, or movement confined to
+setup. The worker stops before trace collection and primary-button release.
+Startup and movement acknowledgements both have bounded reads. If the worker
+fails to stop, cleanup retains the command log, reaps the helper, and retries
+the worker join; the run still fails.
+
+Run the production package separately without the trace option. Successful
+saved-output and foreground endpoint checks then produce a
+`production-package-smoke` result with continuous isolation and synthetic
+cleanup explicitly unproven. It cannot satisfy overlap or no-dispatch proof.
+A moving-primary plan fails before process launch when the trace option is absent.
+A `negative_control` plan contains only `{negative_control:true}` phases and
+requires the trace; it passes only when the independent warp-and-return is
+detected despite identical cursor endpoints. It is not an isolation pass.
+
+Evidence retains the reviewed plan, source SHA/branch/dirty status, source and
+Driver versions, helper/binary hashes, package and native process identities,
+loaded-plugin listing, MCP images/results, timeline, saved files before/after,
+cleanup failures, and available trace/video. The loaded-plugin listing and
+file digest must still be reconciled with installation/build provenance by the
+native operator; this helper cannot independently establish a loaded module's
+build origin. Local paths and raw evidence are for internal review.
+Moving runs also retain `primary-motion-commands.json` (ordered commands,
+acknowledgements, and monotonic timestamps) and, once validated,
+`expected-primary-motion.json`. The result identifies the primary mode and the
+number of commands completed during Driver calls. Helper provenance includes
+the independent `primary-grab` binary hash.
+
+The runner closes and reaps every owned Driver child, escalates termination
+only for those children, releases the foreground hold, and retains app files
+after failures or partial/unknown delivery. Transport failures poison the
+connection and are never replayed. Any cleanup failure fails the run.
+
+Available focused native work includes executing the cached-connection plan at
+the exact candidate SHA with verified loaded artifacts, successful plugin input on both
+sides of the exact manifest denial, the quiet trace interval, continuous
+foreground isolation, and cleanup. The complete mode/manifest/resource and
+managed-policy allow/deny matrix remains separate. Other focused plans cover
+moving-primary and capacity checks, runtime cancellation during overlapping
+gestures, target/keymap/display/session faults, exact loaded-artifact
+provenance, and repeat controls. Select these diagnostics for unresolved claims
+under the validation strategy above; the canonical desktop matrix remains
+required. No existing failed row is superseded by these helper tests.
+
+Focused local verification:
+
+```text
+cd libs/cua-driver/hyprland-plugin/tests
+python3 -m unittest production_realapp_proof_test realapp_proof_test primary_trace_test
+```
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_active_lock_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_active_lock_proof.py
new file mode 100644
index 0000000000..8ed6cab420
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_active_lock_proof.py
@@ -0,0 +1,433 @@
+"""TEST ONLY: active Calc drag cancellation by an acknowledged session lock.
+
+Use the settled lock proof's CLI flags and exact identity plan, but with
+purpose=active_lock and recovery={pointer_stages:[click_a1,click_b2]}. Ground
+before arming the reviewed real lock helper; its
+ready-to-LOCK window is only three seconds. Normal Driver supplies all app
+input. Require a fresh held-input gate before LOCK, an explicit partial
+desktop_changed response, cancellation and own-seat release before graceful
+protocol unlock, then a fresh-runtime, fresh-pixel, visibly effective click.
+Unknown attempts are retained and never replayed or promoted to success.
+
+The raw lock/unlock trace and its unchanged primary analysis are retained.
+Primary events are classified, not removed: continuous primary isolation
+across either transition is UNPROVEN, even if cancellation passes. Only the
+pre-request prefix and separate settled recovery trace use strict isolation.
+No native setup, authentication, product changes, or full-matrix certification.
+Portable tests exercise orchestration and failure oracles, not native behavior.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import time
+
+from desktop_faults import _identity
+from driver_input_live import state, wait_for, wm
+from primary_trace import analyze
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, active_drags,
+ close_owned, grounded_snapshot, poll_active, prepare_drag, stopped_prefix,
+ verify_recovery_cleanup, verify_recovery_trace)
+from production_lock_refusal_proof import (LOCK_MS, LockFixture, click_once,
+ settle_locked, stable_status, validate_plan as lock_plan, verify_runtimes)
+from production_mcp import DirectMCP, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, capacity_lane,
+ check_response, primary_acknowledgement, provenance, require_primary_active,
+ trace_interval)
+from production_session_fault_proof import connect_trace, lanes, power, production_status
+from production_desktop_fault_proof import idle_lanes
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'active_lock' and plan['fault'] == {'kind': 'lock'}
+ assert plan['recovery'] == {'pointer_stages': ['click_a1', 'click_b2']}
+ lock_plan({**plan, 'purpose': 'lock_refusal', 'recovery': {'pointer_stage': 'click_b2'}})
+
+
+def recovery_stage(snapshot):
+ """Choose one newly grounded click, never retry a sent action."""
+ return ('click_a1' if pointer_grounding.calc_formula_selection(
+ snapshot, pointer_grounding.rows(snapshot), 'B2') else 'click_b2')
+
+
+def prepare_recovery(client, spec, allowed_stages):
+ before = grounded_snapshot(client, spec['target'], spec)
+ prepared_ns = before['proof_observation_started_ns']
+ assert type(prepared_ns) is int and 0 < prepared_ns <= time.monotonic_ns(), 'invalid observation timestamp'
+ stage = recovery_stage(before)
+ assert stage in allowed_stages
+ arguments, oracle = pointer_grounding.action(
+ before, pointer_grounding.read_pixels(before['proof_image']), 'calc', stage)
+ return {'snapshot': before, 'arguments': arguments, 'oracle': oracle,
+ 'stage': stage, 'prepared_ns': prepared_ns}
+
+
+def held_status(status, lane):
+ """Trace lanes are one-based; production status lanes are zero-based."""
+ rows = lanes(status)
+ assert lane in (1, 2) and set(rows) == {0, 1}
+ for key, row in rows.items():
+ if key == lane - 1:
+ assert type(row['held_button']) is int and row['held_button'] == 272
+ assert type(row['held_keys']) is int and row['held_keys'] == 0
+ assert all(row.get(k) is True for k in ('drag_active', 'lease_active', 'pointer_focus', 'reserved'))
+ else:
+ assert all(type(row.get(k)) is int and row[k] == 0 for k in ('held_button', 'held_keys'))
+ assert all(row.get(k) is False for k in ('drag_active', 'lease_active', 'pointer_focus', 'keyboard_focus'))
+ assert row.get('reserved') is False, 'unowned lane is reserved'
+
+
+def cancelled_status(before, after):
+ old, new = lanes(before), lanes(after, cleared=True)
+ assert set(old) == set(new) == {0, 1}
+ for lane in old:
+ assert old[lane]['epoch'] == new[lane]['epoch'], 'compositor lane replaced'
+ assert old[lane]['dispatches'] == new[lane]['dispatches'], 'cancelled drag completed a dispatch'
+ assert new[lane]['desktop_generation'] > old[lane]['desktop_generation'], 'lock did not revoke authority'
+ assert new[lane].get('reserved') is False, 'reservation survived lock'
+
+
+class ActiveLockFixture(LockFixture):
+ """Keep the settled helper's identity and graceful-unlock guards intact."""
+ def arm(self):
+ self.check_targets()
+ self.check_binary()
+ assert self.child is None, 'fixture already armed'
+ self.record['before'] = production_status(self.config)
+ (self.args.evidence / 'pre-fault-status.json').write_text(json.dumps(self.record['before']))
+ idle_lanes(self.record['before'])
+ with (self.args.evidence / 'lock-fixture.stderr').open('wb') as log:
+ self.child = subprocess.Popen([str(self.args.lock_fixture), str(LOCK_MS),
+ str(self.config['compositor']['pid'])], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=log, start_new_session=True)
+ self.identity = _identity(self.child.pid)
+ assert self.identity['uid'] == self.config['compositor']['uid']
+ assert self.identity['exe'] == str(self.args.lock_fixture)
+ self.record['identity'] = self.identity
+ self.record['ready'] = self.event('ready')
+ self.check_running_binary()
+
+ def inject(self, trace, initial, pending):
+ assert self.child is not None and not self.requested
+ self.check_targets()
+ self.check_binary()
+ self.check_running_binary()
+ power(self.config, True)
+ first, _ = poll_active(trace, initial, None, [pending], timeout=1)
+ status_started = time.monotonic_ns()
+ gate = production_status(self.config)
+ page, active = poll_active(trace, first, None, [pending], timeout=0.25)
+ lane = next(iter(active))
+ held_status(gate, lane)
+ for key, row in lanes(self.record['before']).items():
+ assert all(row[field] == lanes(gate)[key][field]
+ for field in ('epoch', 'desktop_generation', 'dispatches')), 'desktop changed before LOCK'
+ self.record.update(gate_status=gate, status_started_ns=status_started,
+ prefix=page, lane=lane)
+ isolation = analyze(stopped_prefix(page))
+ self.record['pre_request_isolation'] = isolation
+ assert isolation['result'] == 'passed', isolation
+ assert not pending.done(), 'drag finished before LOCK'
+ requested = time.monotonic_ns()
+ assert 0 <= requested - page['events'][-1][1] <= 250_000_000, 'stale held-input trace'
+ assert 0 <= requested - status_started <= 250_000_000, 'stale held-input status'
+ assert 0 <= requested - self.record['ready']['observed_ns'] < 2_500_000_000, 'fixture ready window expired'
+ self.record['requested_ns'] = requested
+ self.deadline_ns = requested + LOCK_MS * 1_000_000
+ self.record['deadline_ns'] = self.deadline_ns
+ self.requested = True # A lost acknowledgement may still mean lock ownership.
+ self.child.stdin.write(b'LOCK\n')
+ self.child.stdin.flush()
+ self.record['ack'] = self.event('locked')
+ assert requested <= self.record['ack']['observed_ns'] < self.deadline_ns
+ self.record.update(after=production_status(self.config), observed_ns=time.monotonic_ns())
+ cancelled_status(gate, self.record['after'])
+ self.locked()
+ self.record['result'] = 'acknowledged'
+ return lane
+
+
+def drag_once(client, spec, prepared, record, save):
+ """Journal before transport; all exceptions preserve a single unknown attempt."""
+ assert prepared['target'] == spec['target'] and prepared['session'] == spec['name']
+ assert record['outcome'] == 'unknown' and record['replayed'] is False
+ record['request'] = {**prepared['arguments'], **spec['target'],
+ 'session': spec['name'], 'delivery_mode': 'background'}
+ save('drag-action.json', record)
+ try:
+ record['dispatch_ns'] = time.monotonic_ns()
+ assert 0 <= record['dispatch_ns'] - prepared['prepared_ns'] <= MAX_GROUNDING_AGE_NS, 'drag grounding expired; no input sent'
+ record.update(outcome='response', response=client.tool('drag', record['request']))
+ except Exception as error:
+ record['error'] = str(error)
+ finally:
+ record['observed_ns'] = time.monotonic_ns()
+ save('drag-action.json', record)
+ return record
+
+
+def transition_evidence(page, *, stopped=False):
+ """Never filter or relabel the canonical analysis, including its failures."""
+ analysis = analyze(page if stopped else stopped_prefix(page))
+ primary = [row for row in page['events'] if row[5] == 0 and row[2] not in ('start', 'stop')]
+ return {'continuous_primary_isolation': 'unproven', 'raw_primary_analysis': analysis,
+ 'analysis_uses_end_sentinel': not stopped, 'primary_transition_events': primary,
+ 'classification': 'observed_transition_events_not_attributed_to_lock_or_driver'}
+
+
+def verify_cancelled(boundary, record, action):
+ assert record['result'] == 'acknowledged'
+ prefix, lane = record['prefix'], record['lane']
+ assert set(active_drags(prefix)) == {lane}
+ assert all(row[5] in (0, lane) for row in prefix['events']), 'unowned synthetic activity'
+ assert all(row[2] in ('agent_approved', 'agent_admitted', 'agent_drag_start',
+ 'pointer_enter', 'pointer_motion', 'pointer_button')
+ for row in prefix['events'] if row[5] == lane), 'unexpected input before LOCK'
+ held_status(record['gate_status'], lane)
+ requested, deadline = record['requested_ns'], record['deadline_ns']
+ assert 0 <= requested - prefix['events'][-1][1] <= 250_000_000
+ assert 0 <= requested - record['status_started_ns'] <= 250_000_000
+ assert 0 <= requested - record['ready']['observed_ns'] < 2_500_000_000
+ assert record['ack']['event'] == 'locked'
+ assert requested <= record['ack']['observed_ns'] <= record['observed_ns'] < deadline
+ assert analyze(stopped_prefix(prefix))['result'] == 'passed', 'pre-LOCK isolation failed'
+ tail = trace_interval(prefix, boundary)
+ synthetic = [row for row in tail if row[5] in (1, 2)]
+ assert all(row[5] == lane for row in synthetic), 'cleanup crossed lanes'
+ cancels = [row for row in synthetic if row[2] == 'agent_cancel']
+ assert len(cancels) == 1 and requested <= cancels[0][1] < deadline, 'missing post-LOCK cancellation'
+ cancel = cancels[0]
+ assert all(row[2] in ('agent_cancel', 'pointer_button', 'pointer_leave', 'keyboard_leave',
+ 'pointer_motion', 'pointer_enter') for row in synthetic), 'extra action or false completion'
+ assert not any(row[2] in ('pointer_motion', 'pointer_enter') and row[0] > cancel[0]
+ for row in synthetic), 'input continued after cancellation'
+ releases = [row for row in synthetic if row[2] == 'pointer_button']
+ assert len(releases) == 1 and releases[0][6] == 0 and releases[0][0] > cancel[0], 'missing own-seat release'
+ assert releases[0][1] <= record['observed_ns'] < deadline, 'release was not observed before cleared lock status'
+ released_synthetic_input(boundary)
+ cancelled_status(record['gate_status'], record['after'])
+ # A transport-unknown response cannot establish the production reason.
+ assert action['outcome'] == 'response' and action['replayed'] is False, 'unknown drag outcome; no replay'
+ check_response(action['response'], {'kind': 'partial'})
+ content = action['response']['structuredContent']
+ assert content['delivery']['mode'] == 'background' and content['delivery']['delivered_count'] > 0
+ assert content.get('reason') == 'desktop_changed', 'lock cancellation reason is not established'
+ assert action['dispatch_ns'] <= prefix['events'][-1][1] <= action['observed_ns'] < deadline
+ return {'result': 'verified', 'reason': 'desktop_changed', 'lane': lane,
+ 'cancel_sequence': cancel[0], 'release_sequence': releases[0][0],
+ 'synthetic_release': 'verified', 'saved_app_effect': 'unproven',
+ 'continuous_primary_isolation': 'unproven'}
+
+
+def verify_transition_end(boundary, stopped):
+ analysis = analyze(stopped)
+ assert analysis.get('telemetry_complete') is True, analysis
+ assert stopped['events'][:boundary['count']] == boundary['events'], 'transition trace history changed'
+ assert not any(row[5] in (1, 2) for row in stopped['events'][boundary['count']:]), 'synthetic activity after cancellation boundary'
+ released_synthetic_input(stopped)
+ return transition_evidence(stopped, stopped=True)
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ report = {'result': 'failed', 'scope': 'active-session-lock-cancellation',
+ 'cancellation': {'result': 'unproven'}, 'recovery': {'result': 'unproven'},
+ 'continuous_isolation_across_transitions': 'unproven',
+ 'physical_hardware': False, 'full_desktop_matrix': False, 'runtime_pids': []}
+ clients, fixture, trace, grab, pool, future = [], None, None, None, None, None
+ tracing, phase = False, 'transition'
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ client = DirectMCP(args.driver, directory, PROFILE)
+ clients.append(client)
+ verify_runtimes(clients)
+ report['runtime_pids'].append(client.process.pid)
+ return client
+ def start_trace():
+ nonlocal tracing
+ started = time.monotonic_ns()
+ tracing = True
+ trace.exchange('TRACE_START')
+ page = trace.collect()
+ trace_interval(page, page)
+ assert page['count'] == 1 and started <= page['events'][0][1] <= time.monotonic_ns()
+ save(phase + '-trace-initial.json', page)
+ return page
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ fixture = ActiveLockFixture(plan, args)
+ origin = provenance(args, plan)
+ for name in (Path(__file__).name, 'production_active_lock_proof_test.py',
+ 'production_lock_refusal_proof.py', 'production_lock_refusal_proof_test.py',
+ 'session_lock_fixture.c', 'production_session_fault_proof.py',
+ 'production_cancel_proof.py', 'desktop_faults.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ origin['lock_fixture'] = plan['lock_fixture']
+ save('provenance.json', origin)
+ spec = plan['agents'][0]
+ observer, actor = launch('observer'), launch('agent')
+ assert not actor.tool('start_session', {'session': spec['name']}).get('isError')
+ assert state(args.foreground_journal)['held'] is False, 'lock setup requires released primary fixture'
+ prepared = prepare_drag(actor, spec)
+ save('drag-grounding.json', prepared)
+ trace = connect_trace(args.trace_socket, fixture.config)
+ initial = start_trace()
+ fixture.arm()
+ action = report['action'] = {'outcome': 'unknown', 'replayed': False,
+ 'prepared_ns': prepared['prepared_ns'], 'runtime_pid': actor.process.pid}
+ save('drag-action.json', action)
+ pool = ThreadPoolExecutor(max_workers=1)
+ future = pool.submit(drag_once, actor, spec, prepared, action, save)
+ fixture.inject(trace, initial, future)
+ future.result(timeout=3)
+ fixture.locked()
+ boundary = trace.collect()
+ save('cancellation-boundary.json', boundary)
+ save('cancellation-transition-analysis.json', transition_evidence(boundary))
+ report['cancellation'] = verify_cancelled(boundary, fixture.record, action)
+ # Do not close the actor to manufacture a release before this oracle.
+ close_owned(actor)
+ settle_locked(fixture)
+ stable_status(fixture.record['after'], production_status(fixture.config))
+ quiet = trace.collect()
+ save('locked-quiescent-prefix.json', quiet)
+ assert not any(row[5] in (1, 2) for row in trace_interval(boundary, quiet)), 'input after cancellation'
+ restoration = fixture.restore()
+ save('restoration.json', restoration)
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('transition-trace.json', stopped)
+ tracing = False
+ save('transition-analysis.json', transition_evidence(stopped, stopped=True))
+ report['transition'] = verify_transition_end(boundary, stopped)
+ fixture.check_targets()
+ power(fixture.config, True)
+ # Intentional foreground focus/grab setup is outside both action traces.
+ setup = {'before': wm(), 'started_ns': time.monotonic_ns(), 'continuous_isolation': 'unproven'}
+ foreground = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError')
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < foreground['width'] and 0 < y < foreground['height']
+ x, y = foreground['x'] + x, foreground['y'] + y
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ primary, baseline = wm(), state(args.foreground_journal)
+ assert primary['pid'] == plan['foreground']['pid'] and int(primary['address'], 16) == plan['foreground']['window_id']
+ assert primary['cursor'] == {'x': x, 'y': y} and baseline['held']
+ setup.update(after=primary, observed_ns=time.monotonic_ns())
+ save('foreground-setup.json', setup)
+ fixture.check_targets()
+ stable_status(restoration['after'], production_status(fixture.config))
+ phase = 'recovery'
+ initial = start_trace()
+ fresh = launch('recovery')
+ assert actor.process.poll() is not None and fresh.process.pid != actor.process.pid
+ recovery = report['recovery']
+ recovery.update(runtime_pid=fresh.process.pid, previous_runtime_pid=actor.process.pid, replayed=False)
+ spec = {**spec, 'name': spec['name'] + '-recovery'}
+ assert not fresh.tool('start_session', {'session': spec['name']}).get('isError')
+ grounding = prepare_recovery(fresh, spec, plan['recovery']['pointer_stages'])
+ prepared_ns, arguments, oracle = (grounding[key] for key in ('prepared_ns', 'arguments', 'oracle'))
+ recovery['stage'] = spec['pointer_stage'] = grounding['stage']
+ save('recovery-grounding.json', grounding)
+ require_primary_active(grab, deadline)
+ recovery['action'] = {'outcome': 'unknown', 'replayed': False, 'prepared_ns': prepared_ns}
+ response = click_once(fresh, {**arguments, **spec['target'], 'session': spec['name'],
+ 'delivery_mode': 'background'}, recovery['action'], save, 'recovery-action.json')
+ check_response(response, {'kind': 'dispatched'})
+ after = grounded_snapshot(observer, spec['target'], spec, session=False)
+ save('recovery-after.json', after)
+ recovery['app_effect'] = pointer_grounding.verify(after, pointer_grounding.read_pixels(after['proof_image']), oracle)
+ prefix = trace.collect()
+ save('recovery-trace-prefix.json', prefix)
+ recovery['trace'] = verify_recovery_trace(initial, prefix, capacity_lane(initial, prefix, 'click'), 'click')
+ close_owned(fresh)
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('recovery-trace.json', stopped)
+ tracing = False
+ recovery['isolation'] = verify_recovery_cleanup(prefix, stopped)
+ released_synthetic_input(stopped)
+ require_primary_active(grab, deadline)
+ current = state(args.foreground_journal)
+ save('recovery-primary-readback.json', {'before': primary, 'after': wm(), 'foreground_before': baseline, 'foreground_after': current})
+ assert wm() == primary and all(current[k] == baseline[k] for k in ('clicks', 'keys', 'scroll', 'held'))
+ fixture.check_targets()
+ final = production_status(fixture.config)
+ save('final-status.json', final)
+ old, new = lanes(restoration['after'], cleared=True), lanes(final, cleared=True, allow_passive=True)
+ assert set(old) == set(new) == {0, 1}
+ assert sum(new[k]['dispatches'] - old[k]['dispatches'] for k in old) == 1
+ for key in old:
+ assert new[key]['dispatches'] >= old[key]['dispatches'] and new[key].get('reserved') is False
+ assert all(new[key][field] == old[key][field] for field in ('epoch', 'desktop_generation'))
+ recovery['result'] = 'verified'
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = []
+ if fixture:
+ operations.append(('graceful_unlock', lambda: fixture.restore(cleanup=True)))
+ operations += [(f'close_runtime_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)]
+ if future:
+ def preserve_action():
+ # Retain the original attempt, even if closing its runtime was
+ # needed to unblock transport. Cleanup cannot certify it.
+ future.result(timeout=3)
+ save('drag-action.json', report['action'])
+ operations.append(('preserve_action', preserve_action))
+ if pool:
+ operations.append(('close_pool', lambda: pool.shutdown(wait=False)))
+ if trace:
+ if tracing:
+ def preserve_trace():
+ trace.exchange('TRACE_STOP')
+ page = trace.collect()
+ save('failed-' + phase + '-trace.json', page)
+ save('failed-' + phase + '-analysis.json', transition_evidence(page, stopped=True))
+ operations.append(('preserve_trace', preserve_trace))
+ operations.append(('close_trace', trace.close))
+ if grab:
+ def release_primary():
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release_primary))
+ errors = cleanup_all(operations)
+ if fixture:
+ save('lock-fixture.json', fixture.record)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence',
+ 'foreground-journal', 'trace-socket', 'lock-fixture'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_active_lock_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_active_lock_proof_test.py
new file mode 100644
index 0000000000..f2167b4472
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_active_lock_proof_test.py
@@ -0,0 +1,488 @@
+"""Portable failure-oracle tests only; never native lock certification."""
+from concurrent.futures import Future
+from contextlib import ExitStack
+from copy import deepcopy
+import io
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_active_lock_proof as proof
+import production_lock_refusal_proof as settled
+from production_lock_refusal_proof_test import plan as lock_plan
+from production_session_fault_proof_test import ACTIVE, CANCEL, PARTIAL, status, trace
+
+
+def plan():
+ return {**lock_plan(), 'purpose': 'active_lock',
+ 'recovery': {'pointer_stages': ['click_a1', 'click_b2']}}
+
+
+def action():
+ response = deepcopy(PARTIAL)
+ response['structuredContent']['reason'] = 'desktop_changed'
+ return {'outcome': 'response', 'replayed': False, 'response': response,
+ 'dispatch_ns': 500_000, 'observed_ns': 11_000_000}
+
+
+def record():
+ return {'result': 'acknowledged', 'before': status(1),
+ 'ready': {'event': 'ready', 'observed_ns': 1},
+ 'prefix': trace(ACTIVE), 'lane': 1, 'status_started_ns': 5_000_000,
+ 'requested_ns': 6_000_000, 'ack': {'event': 'locked', 'observed_ns': 7_000_000},
+ 'observed_ns': 12_000_000, 'deadline_ns': 20_000_000,
+ 'gate_status': status(1, held=True), 'after': status(2)}
+
+
+class OracleTests(unittest.TestCase):
+ def test_recovery_grounding_uses_original_snapshot_time_not_wrapper_clock(self):
+ client = Mock()
+ spec = plan()['agents'][0]
+ snapshot = {'proof_observation_started_ns': 10, 'proof_image': 'synthetic.png'}
+ with patch.object(proof, 'grounded_snapshot', return_value=snapshot) as observe, \
+ patch.object(proof, 'recovery_stage', return_value='click_b2'), \
+ patch.object(proof.time, 'monotonic_ns', return_value=50), \
+ patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'), \
+ patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1}, {'cell': 'B2'})):
+ result = proof.prepare_recovery(client, spec, ['click_a1', 'click_b2'])
+ observe.assert_called_once_with(client, spec['target'], spec)
+ self.assertEqual(result, {'snapshot': snapshot, 'arguments': {'x': 1},
+ 'oracle': {'cell': 'B2'}, 'stage': 'click_b2', 'prepared_ns': 10})
+ client.tool.assert_not_called()
+
+ def test_recovery_grounding_rejects_missing_invalid_or_future_snapshot_time(self):
+ for timestamp in (None, True, 0, -1, 51, 10.0):
+ snapshot = {'proof_image': 'synthetic.png'}
+ if timestamp is not None:
+ snapshot['proof_observation_started_ns'] = timestamp
+ with self.subTest(timestamp=timestamp), \
+ patch.object(proof, 'grounded_snapshot', return_value=snapshot), \
+ patch.object(proof.time, 'monotonic_ns', return_value=50), \
+ patch.object(proof.pointer_grounding, 'action') as action, \
+ self.assertRaises((AssertionError, KeyError)):
+ proof.prepare_recovery(Mock(), plan()['agents'][0], ['click_a1', 'click_b2'])
+ action.assert_not_called()
+
+ def test_recovery_stage_is_chosen_from_new_selection_before_input(self):
+ snapshot = {'snapshot_id': 'fresh-after-unlock'}
+ for selected_b2, expected in ((True, 'click_a1'), (False, 'click_b2')):
+ with patch.object(proof.pointer_grounding, 'rows', return_value=['fresh']) as rows, \
+ patch.object(proof.pointer_grounding, 'calc_formula_selection', return_value=selected_b2) as selection:
+ self.assertEqual(proof.recovery_stage(snapshot), expected)
+ rows.assert_called_once_with(snapshot)
+ selection.assert_called_once_with(snapshot, ['fresh'], 'B2')
+
+ def test_plan_requires_reviewed_disposable_calc_lock_and_fresh_recovery(self):
+ proof.validate_plan(plan())
+ for change in ({'purpose': 'lock_refusal'}, {'fault': {'kind': 'dpms'}},
+ {'disposable': False}, {'fault': {'kind': 'lock', 'kill': True}},
+ {'recovery': {'pointer_stage': 'select_range'}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **change})
+ for field in ('path', 'sha256', 'source_sha256', 'uid', 'inode'):
+ candidate = plan()
+ candidate['lock_fixture'][field] = 'unreviewed'
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_held_gate_cancel_and_own_release_are_verified_without_isolation_claim(self):
+ result = proof.verify_cancelled(trace(CANCEL), record(), action())
+ self.assertEqual(result['result'], 'verified')
+ self.assertEqual(result['reason'], 'desktop_changed')
+ self.assertEqual(result['continuous_primary_isolation'], 'unproven')
+
+ def test_primary_transition_violations_are_retained_never_filtered_to_pass(self):
+ for kind in ('cursor', 'pointer_focus', 'keyboard_focus', 'pointer_button', 'keyboard_key'):
+ page = trace(CANCEL + [(13, kind, 0, 0)])
+ if kind == 'cursor':
+ page['events'][-1][3] += 10
+ original = deepcopy(page)
+ result = proof.transition_evidence(page)
+ self.assertEqual(result['raw_primary_analysis']['result'], 'failed')
+ self.assertEqual(result['continuous_primary_isolation'], 'unproven')
+ self.assertEqual(result['primary_transition_events'], [page['events'][-1]])
+ self.assertEqual(page, original)
+ # This oracle proves synthetic cancellation only, not the cause
+ # or acceptability of any primary-seat transition event.
+ self.assertEqual(proof.verify_cancelled(page, record(), action())['result'], 'verified')
+
+ def test_primary_activity_before_lock_is_not_a_transition_exception(self):
+ candidate = record()
+ candidate['prefix'] = trace(ACTIVE + [(5, 'pointer_focus', 0, 0)])
+ page = trace(ACTIVE + [(5, 'pointer_focus', 0, 0)] + CANCEL[len(ACTIVE):])
+ with self.assertRaisesRegex(AssertionError, 'pre-LOCK isolation'):
+ proof.verify_cancelled(page, candidate, action())
+
+ def test_unrelated_input_before_lock_is_not_an_ordinary_drag(self):
+ candidate = record()
+ candidate['prefix'] = trace(ACTIVE + [(5, 'pointer_axis', 1, 0)])
+ page = trace(ACTIVE + [(5, 'pointer_axis', 1, 0)] + CANCEL[len(ACTIVE):])
+ with self.assertRaisesRegex(AssertionError, 'unexpected input before LOCK'):
+ proof.verify_cancelled(page, candidate, action())
+
+ def test_missing_release_extra_input_cross_lane_and_false_completion_fail(self):
+ tails = [
+ [(8, 'agent_cancel', 1, 0)],
+ [(8, 'agent_cancel', 1, 0), (9, 'pointer_button', 2, 0)],
+ [(8, 'pointer_button', 1, 0), (9, 'agent_cancel', 1, 0)],
+ [(8, 'agent_cancel', 1, 0), (9, 'pointer_button', 1, 1)],
+ [(8, 'agent_cancel', 2, 0), (9, 'pointer_button', 1, 0)],
+ [(5, 'agent_cancel', 1, 0), (9, 'pointer_button', 1, 0)],
+ ]
+ tails += [CANCEL[len(ACTIVE):] + [(11, kind, 1, 0)] for kind in
+ ('agent_cancel', 'agent_admitted', 'agent_drag_start', 'agent_drag_end',
+ 'agent_action_end', 'keyboard_key', 'pointer_axis', 'pointer_motion',
+ 'pointer_enter', 'pointer_button')]
+ for tail in tails:
+ with self.subTest(tail=tail), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(ACTIVE + tail), record(), action())
+
+ def test_incomplete_trace_rewritten_history_or_missing_held_prefix_fail(self):
+ for field, value in (('overflow', True), ('timed_out', True), ('hook', False),
+ ('active', False), ('count', 100)):
+ page = trace(CANCEL)
+ page[field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.verify_cancelled(page, record(), action())
+ for mutation in ('history', 'press', 'admitted', 'start'):
+ candidate, page = record(), trace(CANCEL)
+ if mutation == 'history':
+ page['events'][0][1] += 1
+ else:
+ index = {'press': 3, 'admitted': 1, 'start': 2}[mutation]
+ candidate['prefix']['events'][index][2] = 'pointer_motion'
+ page['events'][index][2] = 'pointer_motion'
+ with self.subTest(mutation=mutation), self.assertRaises(AssertionError):
+ proof.verify_cancelled(page, candidate, action())
+
+ def test_stale_or_unacknowledged_lock_and_bad_clocks_fail(self):
+ for change in ({'result': 'unproven'}, {'requested_ns': 3_000_000},
+ {'requested_ns': 300_000_000}, {'status_started_ns': -300_000_000},
+ {'ready': {'event': 'ready', 'observed_ns': -3_000_000_000}},
+ {'ack': {'event': 'finished', 'observed_ns': 7_000_000}},
+ {'ack': {'event': 'locked', 'observed_ns': 5_000_000}},
+ {'deadline_ns': 10_000_000}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), {**record(), **change}, action())
+
+ def test_unknown_refused_replayed_or_wrong_reason_cannot_certify_cancellation(self):
+ for change in ({'outcome': 'unknown'}, {'replayed': True}, {'observed_ns': 30_000_000},
+ {'dispatch_ns': 5_000_000}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), record(), {**action(), **change})
+ for field, value in (('reason', 'session_unavailable'), ('reason', 'primary_target_busy'),
+ ('effect', 'refused'), ('route', 'foreground')):
+ candidate = action()
+ candidate['response']['structuredContent'][field] = value
+ with self.subTest(field=field, value=value), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), record(), candidate)
+ for delivery in ({'mode': 'unknown', 'delivered_count': 1},
+ {'mode': 'background', 'delivered_count': 0}):
+ candidate = action()
+ candidate['response']['structuredContent']['delivery'] = delivery
+ with self.subTest(delivery=delivery), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), record(), candidate)
+
+ def test_status_requires_held_owned_lane_then_cleared_authority_and_no_dispatch(self):
+ for section, key, value, index in (
+ ('gate_status', 'held_button', 0, 0), ('gate_status', 'held_keys', 1, 0),
+ ('gate_status', 'drag_active', False, 0), ('gate_status', 'reserved', False, 0),
+ ('gate_status', 'held_button', 272, 1), ('gate_status', 'reserved', True, 1),
+ ('after', 'held_button', 272, 0), ('after', 'held_keys', 1, 0),
+ ('after', 'drag_active', True, 0), ('after', 'lease_active', True, 0),
+ ('after', 'pointer_focus', True, 0), ('after', 'keyboard_focus', True, 0),
+ ('after', 'reserved', True, 0), ('after', 'desktop_generation', 1, 0),
+ ('after', 'dispatches', 1, 0), ('after', 'epoch', 'replaced', 0)):
+ candidate = record()
+ candidate[section]['input']['lanes'][index][key] = value
+ with self.subTest(section=section, key=key, index=index), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), candidate, action())
+
+ def test_unlock_trace_keeps_primary_failures_but_rejects_any_new_synthetic_event(self):
+ boundary = trace(CANCEL)
+ stopped = proof.stopped_prefix(trace(CANCEL + [(14, 'keyboard_focus', 0, 0)]))
+ result = proof.verify_transition_end(boundary, stopped)
+ self.assertEqual(result['raw_primary_analysis']['result'], 'failed')
+ self.assertFalse(result['analysis_uses_end_sentinel'])
+ for kind in ('pointer_motion', 'pointer_button', 'agent_admitted', 'agent_cancel', 'pointer_leave'):
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ proof.verify_transition_end(boundary, proof.stopped_prefix(trace(CANCEL + [(14, kind, 1, 0)])))
+ for field, value in (('overflow', True), ('active', True), ('count', 1)):
+ malformed = {**stopped, field: value}
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.verify_transition_end(boundary, malformed)
+ rewritten = deepcopy(stopped)
+ rewritten['events'][0][1] += 1
+ with self.assertRaises(AssertionError):
+ proof.verify_transition_end(boundary, rewritten)
+
+
+class FixtureTests(unittest.TestCase):
+ def fixture(self):
+ fixture = object.__new__(proof.ActiveLockFixture)
+ fixture.child = Mock(stdin=io.BytesIO(), poll=Mock(return_value=None))
+ fixture.record = {'before': status(1), 'ready': {'event': 'ready', 'observed_ns': 1}}
+ fixture.config = {}
+ fixture.requested = False
+ fixture.check_targets = Mock()
+ fixture.check_binary = Mock()
+ fixture.check_running_binary = Mock()
+ fixture.locked = Mock()
+ fixture.event = Mock(return_value={'event': 'locked', 'observed_ns': 7_000_000})
+ return fixture
+
+ def test_injection_sends_one_lock_only_after_exact_identity_and_fresh_held_gate(self):
+ fixture = self.fixture()
+ pending = Mock(done=Mock(return_value=False))
+ with patch.object(proof, 'power'), \
+ patch.object(proof, 'production_status', side_effect=[status(1, held=True), status(2)]), \
+ patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2_000_000})), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=[5_000_000, 6_000_000, 12_000_000]):
+ self.assertEqual(fixture.inject(Mock(), trace([ACTIVE[0]]), pending), 1)
+ self.assertEqual(fixture.child.stdin.getvalue(), b'LOCK\n')
+ fixture.check_targets.assert_called_once()
+ fixture.check_binary.assert_called_once()
+ fixture.check_running_binary.assert_called_once()
+ fixture.event.assert_called_once_with('locked')
+ fixture.child.kill.assert_not_called()
+ fixture.child.terminate.assert_not_called()
+
+ def test_finished_stale_changed_identity_or_nonheld_drag_never_sends_lock(self):
+ for failure in ('finished', 'stale_trace', 'stale_status', 'ready_expired',
+ 'not_held', 'target', 'binary', 'running_binary', 'generation'):
+ fixture = self.fixture()
+ pending = Mock(done=Mock(return_value=failure == 'finished'))
+ gate = status(1, held=failure != 'not_held')
+ if failure == 'generation':
+ gate['input']['lanes'][0]['desktop_generation'] = 2
+ if failure in ('target', 'binary', 'running_binary'):
+ getattr(fixture, {'target': 'check_targets', 'binary': 'check_binary',
+ 'running_binary': 'check_running_binary'}[failure]).side_effect = AssertionError('identity changed')
+ if failure == 'ready_expired':
+ fixture.record['ready']['observed_ns'] = -3_000_000_000
+ page = trace(ACTIVE)
+ now = [5_000_000, 6_000_000, 12_000_000]
+ if failure == 'stale_trace':
+ now = [299_000_000, 300_000_000]
+ if failure == 'stale_status':
+ now = [-300_000_000, 6_000_000]
+ with self.subTest(failure=failure), patch.object(proof, 'power'), \
+ patch.object(proof, 'production_status', return_value=gate), \
+ patch.object(proof, 'poll_active', return_value=(page, {1: 2_000_000})), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=now), self.assertRaises(AssertionError):
+ fixture.inject(Mock(), trace([ACTIVE[0]]), pending)
+ self.assertEqual(fixture.child.stdin.getvalue(), b'')
+ self.assertFalse(fixture.requested)
+
+ def test_lost_lock_ack_keeps_requested_state_for_graceful_cleanup(self):
+ fixture = self.fixture()
+ fixture.event.side_effect = TimeoutError('lost acknowledgement')
+ with patch.object(proof, 'power'), \
+ patch.object(proof, 'production_status', return_value=status(1, held=True)), \
+ patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2_000_000})), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=[5_000_000, 6_000_000]), \
+ self.assertRaises(TimeoutError):
+ fixture.inject(Mock(), trace([ACTIVE[0]]), Mock(done=Mock(return_value=False)))
+ self.assertTrue(fixture.requested)
+ self.assertEqual(fixture.child.stdin.getvalue(), b'LOCK\n')
+ self.assertNotEqual(fixture.record.get('result'), 'acknowledged')
+ self.assertIs(proof.ActiveLockFixture.restore, settled.LockFixture.restore)
+ self.assertIs(proof.ActiveLockFixture.check_running_binary, settled.LockFixture.check_running_binary)
+
+ def test_arm_does_not_lock_and_binds_running_helper_after_ready(self):
+ fixture = self.fixture()
+ fixture.child = None
+ child = Mock(pid=99)
+ identity = {'pid': 99, 'uid': 1000, 'exe': '/test/session_lock_fixture', 'starttime': '1'}
+ fixture.config = {'compositor': {'pid': 50, 'uid': 1000}}
+ fixture.event.return_value = {'event': 'ready', 'observed_ns': 1}
+ with tempfile.TemporaryDirectory() as directory:
+ fixture.args = SimpleNamespace(evidence=Path(directory), lock_fixture=Path(identity['exe']))
+ before = status()
+ before['input']['lanes'][0]['pointer_focus'] = True
+ with patch.object(proof, 'production_status', return_value=before), \
+ patch.object(proof.subprocess, 'Popen', return_value=child) as launch, \
+ patch.object(proof, '_identity', return_value=identity):
+ fixture.arm()
+ self.assertEqual(json.loads((fixture.args.evidence / 'pre-fault-status.json').read_text()), before)
+ self.assertEqual(launch.call_args.args[0], ['/test/session_lock_fixture', '20000', '50'])
+ child.stdin.write.assert_not_called()
+ fixture.event.assert_called_once_with('ready')
+ fixture.check_running_binary.assert_called_once()
+
+ def test_drag_attempt_saved_before_transport_and_unknown_never_replayed(self):
+ for outcome in ('partial', 'unknown', 'stale'):
+ candidate = plan()['agents'][0]
+ prepared = {'target': candidate['target'], 'session': candidate['name'],
+ 'prepared_ns': 0, 'arguments': {'from_x': 1}}
+ client = Mock()
+ client.tool.return_value = action()['response']
+ if outcome == 'unknown':
+ client.tool.side_effect = TimeoutError('lost drag response')
+ saved = []
+ attempt = {'outcome': 'unknown', 'replayed': False}
+ with patch.object(proof.time, 'monotonic_ns', return_value=proof.MAX_GROUNDING_AGE_NS + 1 if outcome == 'stale' else 1):
+ result = proof.drag_once(client, candidate, prepared, attempt,
+ lambda name, value: saved.append((name, deepcopy(value))))
+ self.assertEqual(saved[0][1]['outcome'], 'unknown')
+ self.assertEqual(result['outcome'], 'response' if outcome == 'partial' else 'unknown')
+ self.assertFalse(result['replayed'])
+ self.assertEqual(client.tool.call_count, 0 if outcome == 'stale' else 1)
+ self.assertEqual(saved[-1][1], result)
+
+
+class RunTests(unittest.TestCase):
+ def test_invalid_plan_retained_without_native_setup(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps({**plan(), 'disposable': False}))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence')
+ with patch.object(proof, 'ActiveLockFixture') as fixture, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ fixture.assert_not_called()
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['result'], 'failed')
+ self.assertEqual(report['continuous_isolation_across_transitions'], 'unproven')
+
+ def episode(self, failure=None):
+ """Synthetic run ordering only; all native/Driver boundaries are mocked."""
+ with tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps(plan()))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence', driver=root / 'driver',
+ trace_socket=root / 'trace', foreground_journal=root / 'journal', primary_grab=root / 'grab')
+ events = []
+ clients = []
+ def launch(*_args):
+ client = Mock(process=Mock(pid=30 + len(clients) * 10, poll=Mock(return_value=None)), closed=False)
+ client.tool.return_value = {'structuredContent': {'screen_width': 1280, 'screen_height': 800,
+ 'effect': 'unverifiable', 'route': 'synthetic_events'}}
+ clients.append(client)
+ events.append('launch_' + str(client.process.pid))
+ return client
+ def close(client):
+ events.append('close_' + str(client.process.pid))
+ client.closed = True
+ client.process.poll.return_value = 0
+ fixture = Mock(config={}, record=record())
+ fixture.inject.side_effect = lambda *_args: events.append('LOCK')
+ def restore(*, cleanup=False):
+ events.append('cleanup_unlock' if cleanup else 'explicit_unlock')
+ if failure == 'restore' and not cleanup:
+ raise AssertionError('deadline unlock cannot pass')
+ return {'result': 'restored', 'after': status(3)}
+ fixture.restore.side_effect = restore
+ initial, boundary = trace([ACTIVE[0]]), trace(CANCEL)
+ if failure == 'release':
+ boundary = trace(ACTIVE + [(8, 'agent_cancel', 1, 0)])
+ transition = proof.stopped_prefix(trace(CANCEL + [(14, 'keyboard_focus', 0, 0)]))
+ recovery = trace([(0, 'start', 0, 0), (1, 'agent_admitted', 1, 0),
+ (2, 'pointer_button', 1, 1), (3, 'pointer_button', 1, 0), (4, 'agent_action_end', 1, 0)])
+ trace_client = Mock()
+ trace_client.collect.side_effect = [initial, boundary, boundary, transition, initial,
+ recovery, proof.stopped_prefix(recovery)]
+ def exchange(command):
+ events.append(command)
+ if failure == 'start_ack' and command == 'TRACE_START':
+ trace_client.collect.side_effect = None
+ trace_client.collect.return_value = transition
+ raise TimeoutError('lost trace start acknowledgement')
+ trace_client.exchange.side_effect = exchange
+ def drag(_client, _spec, _prepared, attempt, save):
+ events.append('drag')
+ attempt.update(action())
+ if failure == 'unknown':
+ attempt.update(outcome='unknown', error='lost response')
+ save('drag-action.json', attempt)
+ return attempt
+ pool = Mock()
+ def submit(fn, *args):
+ future = Future()
+ future.set_result(fn(*args))
+ return future
+ pool.submit.side_effect = submit
+ primary = {'pid': 10, 'address': '0x64', 'cursor': {'x': 30, 'y': 40}}
+ baseline = {'held': True, 'clicks': 0, 'keys': 0, 'scroll': 0}
+ final = status(3)
+ final['input']['lanes'][0]['dispatches'] = 1
+ def status_read(*_args):
+ if len(clients) == 3:
+ return final
+ return status(3 if 'explicit_unlock' in events else 2)
+ snapshot = {'window_bounds': {'x': 10, 'y': 20, 'width': 800, 'height': 600},
+ 'proof_image': 'fresh.png', 'proof_observation_started_ns': 10}
+ mocks = {
+ 'ActiveLockFixture': Mock(return_value=fixture), 'provenance': Mock(return_value={'files': {}}),
+ 'DirectMCP': launch, 'connect_trace': Mock(return_value=trace_client),
+ 'close_owned': close, 'ThreadPoolExecutor': Mock(return_value=pool), 'drag_once': drag,
+ 'prepare_drag': Mock(return_value={'prepared_ns': 0}), 'settle_locked': Mock(),
+ 'grounded_snapshot': Mock(return_value=snapshot), 'wm': Mock(return_value=primary),
+ 'state': Mock(side_effect=lambda *_args: baseline if 'explicit_unlock' in events else {'held': False}),
+ 'production_status': status_read, 'power': Mock(), 'primary_acknowledgement': Mock(return_value='HELD\n'),
+ 'wait_for': Mock(), 'require_primary_active': Mock(), 'stop_process': Mock(),
+ }
+ for name, value in mocks.items():
+ stack.enter_context(patch.object(proof, name, value))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns',
+ side_effect=lambda: 50 if len(clients) == 3 else 0))
+ stack.enter_context(patch.object(proof.subprocess, 'Popen', return_value=Mock()))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'rows', return_value=[]))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'calc_formula_selection', return_value=False))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1, 'y': 2}, {})))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'verify', return_value={'result': 'verified'}))
+ stack.enter_context(patch('builtins.print'))
+ result = proof.run(args)
+ evidence = {file.name: json.loads(file.read_text()) for file in args.evidence.glob('*.json')}
+ return result, evidence, events, clients
+
+ def test_complete_synthetic_episode_restores_before_fresh_visible_recovery(self):
+ result, evidence, events, clients = self.episode()
+ self.assertEqual(result, 0, evidence.get('result.json'))
+ report = evidence['result.json']
+ self.assertEqual(report['runtime_pids'], [30, 40, 50])
+ self.assertEqual(report['cancellation']['result'], 'verified')
+ self.assertEqual(report['recovery']['result'], 'verified')
+ self.assertEqual(evidence['recovery-grounding.json']['prepared_ns'], 10)
+ self.assertEqual(evidence['recovery-action.json']['prepared_ns'], 10)
+ self.assertEqual(report['transition']['raw_primary_analysis']['result'], 'failed')
+ self.assertEqual(report['continuous_isolation_across_transitions'], 'unproven')
+ self.assertLess(events.index('drag'), events.index('LOCK'))
+ self.assertLess(events.index('LOCK'), events.index('close_40'))
+ self.assertLess(events.index('close_40'), events.index('explicit_unlock'))
+ self.assertLess(events.index('explicit_unlock'), events.index('launch_50'))
+ self.assertEqual([c.args[0] for c in clients[-1].tool.call_args_list], ['start_session', 'click'])
+ for name in ('transition-trace.json', 'transition-analysis.json', 'cancellation-boundary.json',
+ 'recovery-grounding.json', 'recovery-after.json', 'recovery-trace.json', 'restoration.json'):
+ self.assertIn(name, evidence)
+
+ def test_unknown_attempt_or_failed_unlock_is_preserved_without_recovery_or_replay(self):
+ for failure in ('unknown', 'restore', 'release'):
+ result, evidence, events, clients = self.episode(failure)
+ with self.subTest(failure=failure):
+ self.assertEqual(result, 1)
+ self.assertEqual(evidence['result.json']['recovery']['result'], 'unproven')
+ self.assertEqual(len(clients), 2)
+ self.assertEqual(events.count('drag'), 1)
+ self.assertIn('cleanup_unlock', events)
+ self.assertIn('drag-action.json', evidence)
+ self.assertIn('failed-transition-trace.json', evidence)
+ if failure == 'unknown':
+ self.assertEqual(evidence['drag-action.json']['outcome'], 'unknown')
+
+ def test_lost_trace_start_ack_is_stopped_and_retained_without_dispatch(self):
+ result, evidence, events, _clients = self.episode('start_ack')
+ self.assertEqual(result, 1)
+ self.assertNotIn('drag', events)
+ self.assertNotIn('LOCK', events)
+ self.assertIn('TRACE_STOP', events)
+ self.assertIn('failed-transition-trace.json', evidence)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_active_primary_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_active_primary_proof.py
new file mode 100644
index 0000000000..316fa780d8
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_active_primary_proof.py
@@ -0,0 +1,489 @@
+"""TEST ONLY: ordinary Calc drag cancelled by a fixture-owned primary hover.
+
+Use settled primary-conflict CLI flags plus --hover-fixture. The exact VM plan
+has purpose=active_primary, case=active_drag, fault={kind:primary_hover},
+recovery={pointer_stages:[click_a1,click_b2]}, and hover_fixture containing
+path/device/inode/uid/sha256/source_sha256 for the reviewed primary_hover_fixture.
+Only one native 1:1 monitor at origin, input:follow_mouse=1, and an initially
+parked, RELEASED foreground fixture qualify. No config edits or hidden clicks.
+
+The new helper arms without input, binds the compositor's SO_PEERCRED identity,
+then accepts one explicit MOVE after a fresh held-Calc-drag gate. Its sync ACK
+is NOT focus proof: independently require the exact Calc primary client plus
+the product's partial primary_target_busy response and own-seat release.
+Keep the raw transition trace and its canonical isolation failures. Continuous
+isolation across setup/transition is UNPROVEN. Only the distinct settled
+recovery action has a strict isolation claim. No replay of unknown/partial work.
+Portable tests establish preparation only, never native certification.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import select
+import stat
+import subprocess
+import time
+
+from desktop_faults import _hypr, _identity
+from driver_input_live import state, wait_for
+from primary_trace import analyze
+from production_active_lock_proof import (drag_once, held_status, recovery_stage,
+ transition_evidence as _transition_evidence,
+ verify_transition_end as _verify_transition_end)
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, active_drags,
+ close_owned, grounded_snapshot, poll_active, prepare_drag, stopped_prefix,
+ verify_fresh_observation, verify_recovery_cleanup, verify_recovery_trace)
+from production_lock_refusal_proof import click_once, verify_runtimes
+from production_mcp import DirectMCP, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_primary_conflict_proof import (ExactDesktop, clear_status,
+ validate_plan as settled_plan)
+from production_realapp_proof import (app_process_identity, capacity_lane,
+ check_response, provenance, trace_interval)
+from production_session_fault_proof import lanes
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+HOVER_MS = 20000
+REASON = 'primary_target_busy'
+
+
+def verify_parked_foreground(before, after):
+ """The fixture emits a new timestamp every 250 ms, even without input."""
+ assert before.get('kind') == after.get('kind') == 'state'
+ assert all(type(row.get('time')) is int and row['time'] >= 0 for row in (before, after))
+ assert after['time'] >= before['time'], 'foreground observation moved backwards'
+ assert {key: value for key, value in before.items() if key != 'time'} == \
+ {key: value for key, value in after.items() if key != 'time'}, 'foreground state changed before hover'
+
+
+def transition_evidence(page, *, stopped=False):
+ result = _transition_evidence(page, stopped=stopped)
+ result['classification'] = 'observed_transition_events_not_attributed_to_hover_fixture_or_driver'
+ return result
+
+
+def verify_transition_end(boundary, stopped):
+ result = _verify_transition_end(boundary, stopped)
+ result['classification'] = 'observed_transition_events_not_attributed_to_hover_fixture_or_driver'
+ return result
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'active_primary' and plan['case'] == 'active_drag'
+ assert plan['fault'] == {'kind': 'primary_hover'}
+ assert plan['recovery'] == {'pointer_stages': ['click_a1', 'click_b2']}
+ candidate = {k: v for k, v in plan.items() if k != 'fault'}
+ settled_plan({**candidate, 'purpose': 'primary_conflict', 'case': 'initial_refusal',
+ 'recovery': {'pointer_stage': 'click_b2'}})
+ assert plan['agents'][0]['app'] == 'calc'
+ expected = plan['hover_fixture']
+ assert set(expected) == {'path', 'device', 'inode', 'uid', 'sha256', 'source_sha256'}
+ assert Path(expected['path']).is_absolute() and Path(expected['path']).name == 'primary_hover_fixture'
+ assert all(type(expected[k]) is int and expected[k] >= 0 for k in ('device', 'inode', 'uid'))
+ assert expected['uid'] == plan['compositor']['uid']
+ assert all(re.fullmatch(r'[0-9a-f]{64}', expected[k]) for k in ('sha256', 'source_sha256'))
+
+
+def desktop_mode(desktop):
+ """A precondition, never a request to modify compositor policy."""
+ desktop.guard()
+ follow = json.loads(_hypr(desktop.instance, '-j', 'getoption', 'input:follow_mouse'))
+ assert type(follow.get('int')) is int and follow['int'] == 1, 'need existing input:follow_mouse=1'
+ monitors = json.loads(_hypr(desktop.instance, '-j', 'monitors'))
+ assert len(monitors) == 1, 'only a single monitor is qualified'
+ monitor = monitors[0]
+ assert monitor['x'] == monitor['y'] == 0 and monitor['scale'] == 1 and monitor['transform'] == 0
+ assert monitor.get('dpmsStatus') is True
+ assert all(type(monitor[k]) is int and 0 < monitor[k] <= 65535 for k in ('width', 'height'))
+ return {'follow_mouse': follow['int'],
+ **{k: monitor[k] for k in ('id', 'name', 'x', 'y', 'width', 'height', 'scale', 'transform')}}
+
+
+def cancelled_status(before, after, lane):
+ held_status(before, lane)
+ clear_status(after)
+ old, new = lanes(before), lanes(after, cleared=True)
+ assert set(old) == set(new) == {0, 1}
+ for key in old:
+ assert all(old[key][field] == new[key][field]
+ for field in ('epoch', 'desktop_generation', 'dispatches')), 'unrelated desktop transition or dispatch'
+ if key != lane - 1:
+ assert old[key] == new[key], 'sibling lane changed'
+ else:
+ # Unlike lock, primary_changed keeps this runtime's reservation.
+ assert new[key].get('reserved') is True, 'primary cancellation lost its reservation'
+
+
+def verify_cancelled(boundary, record, action, target):
+ prefix, lane = record['prefix'], record['lane']
+ assert record['result'] == 'observed' and record['target'] == target
+ assert set(active_drags(prefix)) == {lane}
+ assert all(row[5] in (0, lane) for row in prefix['events']), 'unowned synthetic input'
+ assert all(row[2] in ('agent_approved', 'agent_admitted', 'agent_drag_start',
+ 'pointer_enter', 'pointer_motion', 'pointer_button')
+ for row in prefix['events'] if row[5] == lane), 'unexpected pre-transition input'
+ assert analyze(stopped_prefix(prefix))['result'] == 'passed', 'isolation failed before fixture MOVE'
+ requested, observed = record['requested_ns'], record['observed_ns']
+ assert 0 <= requested - prefix['events'][-1][1] <= 250_000_000
+ assert 0 <= requested - record['status_started_ns'] <= 250_000_000
+ assert 0 <= requested - record['ready']['observed_ns'] < 2_500_000_000
+ assert record['ack']['event'] == 'moved' and record['ready']['event'] == 'ready'
+ assert [record['ack']['x'], record['ack']['y']] == record['point']
+ assert requested <= record['ack']['observed_ns'] <= observed < record['deadline_ns']
+ assert record['primary_after']['pid'] == target['pid'] and record['primary_after']['window_id'] == target['window_id']
+ assert record['primary_after']['cursor'] == dict(zip(('x', 'y'), record['point']))
+ tail = trace_interval(prefix, boundary)
+ assert any(row[5] == 0 and row[2] in ('pointer_focus', 'keyboard_focus')
+ and requested <= row[1] <= observed for row in tail), 'missing primary focus transition'
+ synthetic = [row for row in tail if row[5] in (1, 2)]
+ assert all(row[5] == lane for row in synthetic), 'cancellation crossed lanes'
+ cancels = [row for row in synthetic if row[2] == 'agent_cancel']
+ assert len(cancels) == 1 and requested <= cancels[0][1] <= observed
+ cancel = cancels[0]
+ assert all(row[2] in ('agent_cancel', 'pointer_button', 'pointer_leave', 'keyboard_leave',
+ 'pointer_enter', 'pointer_motion') for row in synthetic), 'extra action or false completion'
+ assert not any(row[2] in ('pointer_enter', 'pointer_motion') and row[0] > cancel[0]
+ for row in synthetic), 'input continued after cancellation'
+ releases = [row for row in synthetic if row[2] == 'pointer_button']
+ assert len(releases) == 1 and releases[0][6] == 0 and releases[0][0] > cancel[0]
+ assert releases[0][1] <= observed, 'release not observed at cleared status'
+ released_synthetic_input(boundary)
+ cancelled_status(record['gate_status'], record['after'], lane)
+ assert action['outcome'] == 'response' and action['replayed'] is False, 'unknown outcome; never replay'
+ check_response(action['response'], {'kind': 'partial'})
+ content = action['response']['structuredContent']
+ assert content.get('reason') == REASON and content['delivery']['mode'] == 'background'
+ assert content['delivery']['delivered_count'] > 0, 'no acknowledged gesture progress'
+ assert action['dispatch_ns'] <= prefix['events'][-1][1] <= action['observed_ns'] < record['deadline_ns']
+ return {'result': 'verified', 'reason': REASON, 'lane': lane,
+ 'cancel_sequence': cancel[0], 'release_sequence': releases[0][0],
+ 'continuous_primary_isolation': 'unproven', 'saved_app_effect': 'unproven'}
+
+
+class HoverFixture:
+ """One reviewed executable, exact compositor, one command, no held buttons."""
+ def __init__(self, desktop, args):
+ self.desktop, self.args = desktop, args
+ self.expected = desktop.plan['hover_fixture']
+ self.child = None
+ self.buffer = b''
+ self.sent = False
+ self.record = {'result': 'unproven', 'events': []}
+ self.mode = desktop_mode(desktop)
+ self.record['mode'] = self.mode
+ self.check_binary()
+
+ def check_binary(self):
+ path, expected = self.args.hover_fixture, self.expected
+ assert str(path) == expected['path'] and path.resolve(strict=True) == path
+ info = path.lstat()
+ assert stat.S_ISREG(info.st_mode) and os.access(path, os.X_OK)
+ assert [info.st_dev, info.st_ino, info.st_uid] == [expected[k] for k in ('device', 'inode', 'uid')]
+ assert hashlib.sha256(path.read_bytes()).hexdigest() == expected['sha256']
+ source = self.args.source / 'libs/cua-driver/hyprland-plugin/tests/primary_hover_fixture.c'
+ assert source.resolve(strict=True) == source
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == expected['source_sha256']
+
+ def guard(self):
+ assert desktop_mode(self.desktop) == self.mode, 'display geometry changed'
+ self.check_binary()
+ assert self.child.poll() is None and _identity(self.child.pid) == self.identity
+ with Path(f'/proc/{self.child.pid}/exe').open('rb') as stream:
+ info = os.fstat(stream.fileno())
+ assert [info.st_dev, info.st_ino, info.st_uid] == [self.expected[k] for k in ('device', 'inode', 'uid')]
+ assert hashlib.sha256(stream.read()).hexdigest() == self.expected['sha256']
+ assert self.child.poll() is None and _identity(self.child.pid) == self.identity
+
+ def event(self, expected):
+ def read():
+ if b'\n' not in self.buffer:
+ if not select.select([self.child.stdout], [], [], 0)[0]:
+ return None
+ chunk = os.read(self.child.stdout.fileno(), 4096)
+ assert chunk, 'fixture EOF before acknowledgement'
+ self.buffer += chunk
+ assert len(self.buffer) <= 4096
+ if b'\n' not in self.buffer:
+ return None
+ line, self.buffer = self.buffer.split(b'\n', 1)
+ value = json.loads(line)
+ assert set(value) == {'event', 'x', 'y', 'observed_ns'} and value['event'] == expected
+ assert all(type(value[k]) is int and value[k] >= 0 for k in ('x', 'y', 'observed_ns'))
+ assert 0 < value['observed_ns'] <= time.monotonic_ns()
+ assert not self.record['events'] or self.record['events'][-1]['observed_ns'] <= value['observed_ns']
+ self.record['events'].append(value)
+ return value
+ return wait_for(read, timeout=2)
+
+ def arm(self):
+ assert self.child is None
+ assert desktop_mode(self.desktop) == self.mode
+ self.check_binary()
+ with (self.args.evidence / ('hover-' + str(time.monotonic_ns()) + '.stderr')).open('wb') as log:
+ self.child = subprocess.Popen([str(self.args.hover_fixture), str(self.mode['width']),
+ str(self.mode['height']), str(HOVER_MS), str(self.desktop.compositor['pid'])],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, start_new_session=True)
+ self.identity = _identity(self.child.pid)
+ assert self.identity['uid'] == self.desktop.compositor['uid'] and self.identity['exe'] == str(self.args.hover_fixture)
+ self.record['identity'] = self.identity
+ self.record['ready'] = self.event('ready')
+ self.guard()
+
+ def move(self, point, target, prepared_ns, *, pending=None):
+ assert not self.sent, 'a fixture command is never replayed'
+ self.guard()
+ assert target in (self.desktop.plan['foreground'], self.desktop.plan['agents'][0]['target'])
+ assert len(point) == 2 and all(type(v) is int for v in point)
+ assert 0 <= point[0] < self.mode['width'] and 0 <= point[1] < self.mode['height']
+ # Target containment must remain true at the last identity check.
+ window = next(w for w in self.desktop.guard() if w['pid'] == target['pid'])
+ assert all(start < value < start + size for value, start, size in zip(point, window['at'], window['size']))
+ requested = time.monotonic_ns()
+ assert 0 <= requested - prepared_ns <= MAX_GROUNDING_AGE_NS, 'stale hover grounding'
+ assert 0 <= requested - self.record['ready']['observed_ns'] < 2_500_000_000, 'ready window expired'
+ if pending is not None:
+ assert not pending.done(), 'drag returned before MOVE'
+ assert 0 <= requested - self.record['prefix']['events'][-1][1] <= 250_000_000, 'stale held trace'
+ assert 0 <= requested - self.record['status_started_ns'] <= 250_000_000, 'stale held status'
+ self.record.update(requested_ns=requested, point=point, target=target,
+ prepared_ns=prepared_ns, deadline_ns=requested + HOVER_MS * 1_000_000)
+ self.sent = True # Lost ack still means the single command may have landed.
+ self.child.stdin.write(f'MOVE {point[0]} {point[1]}\n'.encode('ascii'))
+ self.child.stdin.flush()
+ self.record['ack'] = self.event('moved')
+ assert [self.record['ack']['x'], self.record['ack']['y']] == point
+ self.record['primary_after'] = self.desktop.primary(target)
+ assert self.record['primary_after']['cursor'] == dict(zip(('x', 'y'), point)), 'hover missed grounded target'
+ self.guard()
+ self.record['observed_ns'] = time.monotonic_ns()
+ self.record['result'] = 'observed'
+
+ def inject(self, trace, initial, pending, prepared):
+ self.guard()
+ first, _ = poll_active(trace, initial, None, [pending], timeout=1)
+ started = time.monotonic_ns()
+ gate = json.loads(_hypr(self.desktop.instance, '-j', 'cua:status'))
+ page, active = poll_active(trace, first, None, [pending], timeout=.25)
+ lane = next(iter(active))
+ held_status(gate, lane)
+ assert analyze(stopped_prefix(page))['result'] == 'passed'
+ self.record.update(prefix=page, lane=lane, gate_status=gate, status_started_ns=started)
+ bounds = prepared['snapshot']['window_bounds']
+ point = [bounds['x'] + prepared['arguments']['from_x'], bounds['y'] + prepared['arguments']['from_y']]
+ self.move(point, prepared['target'], prepared['prepared_ns'], pending=pending)
+ self.record['after'] = json.loads(_hypr(self.desktop.instance, '-j', 'cua:status'))
+ self.record['observed_ns'] = time.monotonic_ns()
+ cancelled_status(gate, self.record['after'], lane)
+
+ def close(self):
+ if not self.child:
+ return
+ if self.child.poll() is None and not self.child.stdin.closed:
+ self.child.stdin.close() # Never manufactures a button release.
+ stop_process(self.child)
+ self.record['exit_code'] = self.child.returncode
+ if self.sent:
+ assert self.child.returncode == 0, 'hover helper did not finish by acknowledged controller EOF'
+ if 'finished' not in self.record:
+ self.record['finished'] = self.event('finished')
+
+
+def prepare_recovery(client, spec, previous, allowed_stages):
+ started_ns = time.monotonic_ns()
+ before = grounded_snapshot(client, spec['target'], spec)
+ verify_fresh_observation(previous, before, client, after_ns=started_ns)
+ stage = recovery_stage(before)
+ assert stage in allowed_stages
+ arguments, oracle = pointer_grounding.action(before, pointer_grounding.read_pixels(before['proof_image']), 'calc', stage)
+ return {'snapshot': before, 'arguments': arguments, 'oracle': oracle,
+ 'stage': stage, 'prepared_ns': before['proof_observation_started_ns']}
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2) + '\n')
+ report = {'result': 'failed', 'scope': 'active-primary-client-conflict-cancellation',
+ 'cancellation': {'result': 'unproven'}, 'recovery': {'result': 'unproven'},
+ 'continuous_isolation_across_transitions': 'unproven', 'full_desktop_matrix': False,
+ 'physical_hardware': False, 'runtime_pids': []}
+ clients, fixtures, trace, pool, future = [], [], None, None, None
+ tracing, phase = False, 'transition'
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ client = DirectMCP(args.driver, directory, PROFILE)
+ clients.append(client)
+ verify_runtimes(clients)
+ report['runtime_pids'].append(client.process.pid)
+ return client
+ def start_trace():
+ nonlocal tracing
+ started = time.monotonic_ns()
+ tracing = True
+ trace.exchange('TRACE_START')
+ page = trace.collect()
+ trace_interval(page, page)
+ assert page['count'] == 1 and started <= page['events'][0][1] <= time.monotonic_ns()
+ save(phase + '-initial.json', page)
+ return page
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ desktop = ExactDesktop(plan)
+ spec = plan['agents'][0]
+ app_process_identity('calc', spec['target']['pid'])
+ origin = provenance(args, plan)
+ for name in (Path(__file__).name, 'production_active_primary_proof_test.py',
+ 'primary_hover_fixture.c', 'primary_hover_fixture_test.py',
+ 'production_active_lock_proof.py', 'production_primary_conflict_proof.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ origin['hover_fixture'] = plan['hover_fixture']
+ origin['ownership'] = {key: plan[key] for key in ('vm', 'compositor', 'processes')}
+ save('provenance.json', origin)
+ save('initial-status.json', desktop.status(unreserved=True, allow_passive=True))
+ before_primary = desktop.primary(plan['foreground'])
+ baseline = state(args.foreground_journal)
+ assert baseline['held'] is False, 'a primary grab prevents the required cross-client hover'
+ save('initial-primary.json', {'primary': before_primary, 'foreground': baseline})
+ observer, actor = launch('observer'), launch('drag')
+ assert not actor.tool('start_session', {'session': spec['name']}).get('isError')
+ prepared = prepare_drag(actor, spec)
+ save('drag-grounding.json', prepared)
+ fixture = HoverFixture(desktop, args)
+ fixtures.append(fixture)
+ trace = desktop.trace(args.trace_socket)
+ initial = start_trace()
+ fixture.arm()
+ assert desktop.primary(plan['foreground']) == before_primary
+ verify_parked_foreground(baseline, state(args.foreground_journal))
+ action = report['action'] = {'outcome': 'unknown', 'replayed': False,
+ 'prepared_ns': prepared['prepared_ns'], 'runtime_pid': actor.process.pid}
+ pool = ThreadPoolExecutor(max_workers=1)
+ future = pool.submit(drag_once, actor, spec, prepared, action, save)
+ fixture.inject(trace, initial, future, prepared)
+ future.result(timeout=3)
+ boundary = trace.collect()
+ save('cancellation-boundary.json', boundary)
+ save('cancellation-transition-analysis.json', transition_evidence(boundary))
+ save('primary-transition.json', fixture.record)
+ report['cancellation'] = verify_cancelled(boundary, fixture.record, action, spec['target'])
+ save('cancelled-app-state.json', grounded_snapshot(observer, spec['target'], spec, session=False))
+ close_owned(actor) # Release was proved before runtime teardown.
+ desktop.status(unreserved=True)
+ fixture.close()
+ # Freshly observe the foreground before one explicitly owned restoration.
+ grounded_ns = time.monotonic_ns()
+ foreground_snapshot = grounded_snapshot(observer, plan['foreground'])
+ save('foreground-grounding.json', {'snapshot': foreground_snapshot, 'prepared_ns': grounded_ns})
+ foreground = foreground_snapshot['window_bounds']
+ point = [foreground['x'] + plan['primary_point'][0], foreground['y'] + plan['primary_point'][1]]
+ restored = HoverFixture(desktop, args)
+ fixtures.append(restored)
+ restored.arm()
+ restored.move(point, plan['foreground'], grounded_ns)
+ save('foreground-restoration.json', restored.record)
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ tracing = False
+ save('transition-trace.json', stopped)
+ save('transition-analysis.json', transition_evidence(stopped, stopped=True))
+ report['transition'] = verify_transition_end(boundary, stopped)
+ settled = desktop.status(unreserved=True)
+ save('settled-status.json', settled)
+ primary, baseline = desktop.primary(plan['foreground']), state(args.foreground_journal)
+ assert baseline['held'] is False
+ phase = 'recovery'
+ initial = start_trace()
+ fresh = launch('recovery')
+ assert actor.process.poll() is not None and fresh.process.pid != actor.process.pid
+ recovery = report['recovery']
+ spec = {**spec, 'name': spec['name'] + '-recovery'}
+ assert not fresh.tool('start_session', {'session': spec['name']}).get('isError')
+ grounding = prepare_recovery(fresh, spec, prepared['snapshot'], plan['recovery']['pointer_stages'])
+ before, arguments, oracle = grounding['snapshot'], grounding['arguments'], grounding['oracle']
+ prepared_ns, spec['pointer_stage'] = grounding['prepared_ns'], grounding['stage']
+ save('recovery-grounding.json', grounding)
+ restored.guard()
+ assert desktop.primary(plan['foreground']) == primary
+ recovery['action'] = {'outcome': 'unknown', 'replayed': False, 'prepared_ns': prepared_ns,
+ 'runtime_pid': fresh.process.pid}
+ response = click_once(fresh, {**arguments, **spec['target'], 'session': spec['name'],
+ 'delivery_mode': 'background'}, recovery['action'], save, 'recovery-action.json')
+ check_response(response, {'kind': 'dispatched'})
+ after = grounded_snapshot(observer, spec['target'], spec, session=False)
+ save('recovery-after.json', after)
+ verify_runtimes(clients)
+ assert recovery['action']['dispatch_ns'] <= recovery['action']['observed_ns']
+ verify_fresh_observation(before, after, observer, after_ns=recovery['action']['observed_ns'])
+ recovery['app_effect'] = pointer_grounding.verify(after, pointer_grounding.read_pixels(after['proof_image']), oracle)
+ prefix = trace.collect()
+ save('recovery-prefix.json', prefix)
+ recovery['trace'] = verify_recovery_trace(initial, prefix, capacity_lane(initial, prefix, 'click'), 'click')
+ close_owned(fresh)
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ tracing = False
+ save('recovery-trace.json', stopped)
+ recovery['isolation'] = verify_recovery_cleanup(prefix, stopped)
+ restored.guard()
+ assert time.monotonic_ns() < restored.record['deadline_ns']
+ current = state(args.foreground_journal)
+ assert desktop.primary(plan['foreground']) == primary
+ assert all(current[k] == baseline[k] for k in ('held', 'clicks', 'keys', 'scroll'))
+ final = desktop.status(unreserved=True, allow_passive=True)
+ save('recovery-primary-readback.json', {'before': primary, 'after': desktop.primary(plan['foreground']),
+ 'foreground_before': baseline, 'foreground_after': current})
+ save('final-status.json', final)
+ old, new = lanes(settled, cleared=True), lanes(final, cleared=True, allow_passive=True)
+ assert sum(new[k]['dispatches'] - old[k]['dispatches'] for k in old) == 1
+ for key in old:
+ assert new[key]['dispatches'] >= old[key]['dispatches']
+ assert all(new[key][field] == old[key][field] for field in ('epoch', 'desktop_generation'))
+ recovery['result'] = 'verified'
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = {'type': type(error).__name__, 'message': str(error)}
+ finally:
+ operations = [(f'close_runtime_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)]
+ if future:
+ operations.append(('retain_action', lambda: future.result(timeout=3)))
+ if pool:
+ operations.append(('close_pool', lambda: pool.shutdown(wait=False)))
+ if trace:
+ if tracing:
+ def preserve_trace():
+ trace.exchange('TRACE_STOP')
+ page = trace.collect()
+ save('failed-' + phase + '-trace.json', page)
+ save('failed-' + phase + '-analysis.json', transition_evidence(page, stopped=True))
+ operations.append(('preserve_trace', preserve_trace))
+ operations.append(('close_trace', trace.close))
+ operations += [(f'close_hover_{i}', f.close) for i, f in enumerate(fixtures)]
+ errors = cleanup_all(operations)
+ for i, fixture in enumerate(fixtures):
+ save(f'hover-{i}.json', fixture.record)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'hover-fixture',
+ 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_active_primary_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_active_primary_proof_test.py
new file mode 100644
index 0000000000..9563ffbed6
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_active_primary_proof_test.py
@@ -0,0 +1,370 @@
+"""Portable orchestration/failure oracles; no native client transition is certified."""
+from copy import deepcopy
+import io
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_active_primary_proof as proof
+from production_primary_conflict_proof_test import plan as settled_plan
+from production_session_fault_proof_test import ACTIVE, CANCEL, PARTIAL, status, trace
+
+
+def plan():
+ return {**settled_plan(), 'purpose': 'active_primary', 'case': 'active_drag',
+ 'fault': {'kind': 'primary_hover'}, 'recovery': {'pointer_stages': ['click_a1', 'click_b2']},
+ 'hover_fixture': {'path': '/test/primary_hover_fixture', 'device': 1, 'inode': 2,
+ 'uid': 1000, 'sha256': 'a' * 64, 'source_sha256': 'b' * 64}}
+
+
+def after_status():
+ result = status(1)
+ result['input']['lanes'][0]['reserved'] = True
+ return result
+
+
+def boundary():
+ return trace(ACTIVE + [(7, 'pointer_focus', 0, 0)] + CANCEL[len(ACTIVE):])
+
+
+def record():
+ target = plan()['agents'][0]['target']
+ return {'result': 'observed', 'target': target, 'prefix': trace(ACTIVE), 'lane': 1,
+ 'gate_status': status(1, held=True), 'after': after_status(),
+ 'ready': {'event': 'ready', 'x': 0, 'y': 0, 'observed_ns': 1},
+ 'requested_ns': 6_000_000, 'status_started_ns': 5_000_000,
+ 'ack': {'event': 'moved', 'x': 100, 'y': 100, 'observed_ns': 11_000_000},
+ 'point': [100, 100], 'primary_after': {**target, 'cursor': {'x': 100, 'y': 100}},
+ 'observed_ns': 12_000_000, 'deadline_ns': 20_000_000}
+
+
+def action():
+ response = deepcopy(PARTIAL)
+ response['structuredContent']['reason'] = 'primary_target_busy'
+ return {'outcome': 'response', 'replayed': False, 'response': response,
+ 'dispatch_ns': 500_000, 'observed_ns': 11_000_000}
+
+
+class OracleTests(unittest.TestCase):
+ def test_parked_foreground_accepts_new_observation_time_only(self):
+ before = {'kind': 'state', 'time': 10, 'clicks': 2, 'keys': '',
+ 'scroll': 0, 'motion': 4, 'held': False}
+ for timestamp in (10, 20):
+ proof.verify_parked_foreground(before, {**before, 'time': timestamp})
+ for key, value in (('kind', 'event'), ('time', 9), ('time', True),
+ ('clicks', 3), ('keys', 'a'), ('scroll', 1),
+ ('motion', 5), ('held', True), ('unknown', 0)):
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_parked_foreground(before, {**before, key: value})
+ for key in before:
+ with self.subTest(missing=key), self.assertRaises(AssertionError):
+ proof.verify_parked_foreground(before, {k: v for k, v in before.items() if k != key})
+
+ def verify(self, page=None, fault=None, attempt=None):
+ return proof.verify_cancelled(boundary() if page is None else page,
+ record() if fault is None else fault, action() if attempt is None else attempt,
+ plan()['agents'][0]['target'])
+
+ def test_plan_requires_one_calc_exact_identity_hover_and_dynamic_recovery(self):
+ proof.validate_plan(plan())
+ for change in ({'purpose': 'primary_conflict'}, {'case': 'initial_refusal'},
+ {'disposable': False}, {'fault': {'kind': 'click'}},
+ {'recovery': {'pointer_stage': 'click_b2'}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **change})
+ for key, value in (('path', '/test/primary_grab'), ('uid', 1001),
+ ('sha256', 'unknown'), ('source_sha256', 'unknown'), ('inode', -1)):
+ candidate = plan()
+ candidate['hover_fixture'][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_verifies_partial_conflict_release_without_transition_isolation_claim(self):
+ result = self.verify()
+ self.assertEqual(result['reason'], 'primary_target_busy')
+ self.assertEqual(result['result'], 'verified')
+ self.assertEqual(result['continuous_primary_isolation'], 'unproven')
+ self.assertEqual(result['saved_app_effect'], 'unproven')
+
+ def test_sync_ack_alone_or_wrong_primary_client_cannot_prove_transition(self):
+ with self.assertRaisesRegex(AssertionError, 'missing primary focus'):
+ self.verify(page=trace(CANCEL))
+ for field, value in (('pid', 999), ('window_id', 201), ('cursor', {'x': 101, 'y': 100})):
+ fault = record()
+ fault['primary_after'][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ self.verify(fault=fault)
+
+ def test_raw_primary_transition_is_never_filtered_or_relabelled_as_isolation(self):
+ for kind in ('cursor', 'pointer_focus', 'keyboard_focus', 'pointer_button', 'keyboard_key'):
+ page = boundary()
+ row = [len(page['events']) + 1, 13_000_000, kind, 100, 100, 0, 0]
+ if kind == 'cursor':
+ row[3] += 10
+ page['events'].append(row)
+ page['count'] += 1
+ original = deepcopy(page)
+ result = proof.transition_evidence(page)
+ self.assertEqual(result['raw_primary_analysis']['result'], 'failed')
+ self.assertEqual(result['continuous_primary_isolation'], 'unproven')
+ self.assertEqual(page, original)
+ self.assertEqual(self.verify(page=page)['result'], 'verified')
+
+ def test_incomplete_trace_bad_history_and_preexisting_primary_changes_fail(self):
+ for field, value in (('overflow', True), ('hook', False), ('timed_out', True), ('active', False), ('count', 99)):
+ page = boundary()
+ page[field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ self.verify(page=page)
+ page = boundary()
+ page['events'][0][1] += 1
+ with self.assertRaises(AssertionError):
+ self.verify(page=page)
+ fault, page = record(), boundary()
+ fault['prefix']['events'][4][2] = page['events'][4][2] = 'pointer_focus'
+ fault['prefix']['events'][4][5] = page['events'][4][5] = 0
+ with self.assertRaisesRegex(AssertionError, 'isolation failed'):
+ self.verify(page=page, fault=fault)
+
+ def test_missing_release_repeated_input_sibling_mutation_and_false_completion_fail(self):
+ for kind in ('agent_cancel', 'agent_admitted', 'agent_drag_start', 'agent_drag_end',
+ 'agent_action_end', 'keyboard_key', 'pointer_axis', 'pointer_motion', 'pointer_button'):
+ page = boundary()
+ page['events'].append([page['count'] + 1, 11_000_000, kind, 100, 100, 1, 0])
+ page['count'] += 1
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ self.verify(page=page)
+ for index, field, value in ((7, 5, 2), (7, 6, 1), (6, 5, 2), (7, 2, 'pointer_motion')):
+ page = boundary()
+ page['events'][index][field] = value
+ with self.subTest(index=index, field=field), self.assertRaises(AssertionError):
+ self.verify(page=page)
+
+ def test_exact_reason_acknowledged_delivery_and_no_replay_are_mandatory(self):
+ for change in ({'outcome': 'unknown'}, {'replayed': True}, {'dispatch_ns': 9_000_000},
+ {'observed_ns': 30_000_000}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ self.verify(attempt={**action(), **change})
+ for field, value in (('reason', 'desktop_changed'), ('reason', 'cancelled'),
+ ('effect', 'refused'), ('route', 'foreground'),
+ ('delivery', {'mode': 'unknown', 'delivered_count': 1}),
+ ('delivery', {'mode': 'background', 'delivered_count': 0})):
+ attempt = action()
+ attempt['response']['structuredContent'][field] = value
+ with self.subTest(field=field, value=value), self.assertRaises(AssertionError):
+ self.verify(attempt=attempt)
+
+ def test_stale_hold_or_fixture_ack_fails(self):
+ for change in ({'requested_ns': 300_000_000}, {'status_started_ns': -300_000_000},
+ {'deadline_ns': 10_000_000}, {'observed_ns': 8_000_000},
+ {'result': 'unproven'}, {'target': {'pid': 99, 'window_id': 99}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ self.verify(fault={**record(), **change})
+ for section, key, value in (('ready', 'observed_ns', -3_000_000_000), ('ack', 'x', 99),
+ ('ack', 'event', 'ready'), ('ack', 'observed_ns', 1)):
+ fault = record()
+ fault[section][key] = value
+ with self.subTest(section=section, key=key), self.assertRaises(AssertionError):
+ self.verify(fault=fault)
+
+ def test_primary_cancel_preserves_generation_reservation_and_entire_sibling(self):
+ for section, key, value, lane in (
+ ('gate_status', 'held_button', 0, 0), ('gate_status', 'held_keys', 1, 0),
+ ('after', 'held_button', 272, 0), ('after', 'held_keys', 1, 0),
+ ('after', 'reserved', False, 0), ('after', 'pointer_focus', True, 0),
+ ('after', 'desktop_generation', 2, 0), ('after', 'epoch', 'changed', 0),
+ ('after', 'dispatches', 1, 0), ('after', 'reserved', True, 1),
+ ('after', 'desktop_generation', 2, 1)):
+ fault = record()
+ fault[section]['input']['lanes'][lane][key] = value
+ with self.subTest(section=section, key=key, lane=lane), self.assertRaises(AssertionError):
+ self.verify(fault=fault)
+
+ def test_recovery_chooses_effective_stage_from_current_selection(self):
+ before = {'snapshot_id': 'new-after-cancellation'}
+ for b2, stage in ((True, 'click_a1'), (False, 'click_b2')):
+ with patch.object(proof.pointer_grounding, 'rows', return_value=['fresh']), \
+ patch.object(proof.pointer_grounding, 'calc_formula_selection', return_value=b2) as selection:
+ self.assertEqual(proof.recovery_stage(before), stage)
+ selection.assert_called_once_with(before, ['fresh'], 'B2')
+
+ def test_invalid_plan_writes_failed_evidence_without_native_actions(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps({**plan(), 'fault': {'kind': 'click'}}))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence')
+ with patch.object(proof, 'ExactDesktop') as desktop, patch.object(proof, 'DirectMCP') as driver, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ desktop.assert_not_called()
+ driver.assert_not_called()
+ result = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(result['result'], 'failed')
+ self.assertEqual(result['cancellation']['result'], 'unproven')
+
+ def test_initial_idle_hover_is_admitted_before_primary_setup_without_input(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps(plan()))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence')
+ before = status()
+ before['input']['lanes'][0]['pointer_focus'] = True
+ desktop = Mock()
+ desktop.status.side_effect = lambda **kwargs: proof.clear_status(before, **kwargs)
+ desktop.primary.side_effect = RuntimeError('reached primary setup')
+ with patch.object(proof, 'ExactDesktop', return_value=desktop), \
+ patch.object(proof, 'app_process_identity'), \
+ patch.object(proof, 'provenance', return_value={'files': {}}), \
+ patch.object(proof, 'DirectMCP') as driver, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ driver.assert_not_called()
+ desktop.status.assert_called_once_with(unreserved=True, allow_passive=True)
+ self.assertEqual(json.loads((args.evidence / 'initial-status.json').read_text()), before)
+ self.assertIn('reached primary setup', str(json.loads((args.evidence / 'result.json').read_text())['error']))
+
+ def test_recovery_grounding_scopes_counter_and_preserves_original_age(self):
+ spec = plan()['agents'][0]
+ runtime = {'pid': 102, 'directory': str(Path.cwd())}
+ previous = {'snapshot_id': 's00000001', 'proof_runtime': {**runtime, 'pid': 101},
+ 'proof_image': 'previous.png', 'proof_observation_started_ns': 10, 'proof_observation_finished_ns': 20}
+ for failure in (None, 'cached', 'same_snapshot', 'same_artifact', 'dead'):
+ observed = {**previous, 'proof_runtime': runtime, 'proof_image': 'fresh.png',
+ 'proof_observation_started_ns': 40, 'proof_observation_finished_ns': 50}
+ if failure == 'cached':
+ observed.update(proof_observation_started_ns=10, proof_observation_finished_ns=20)
+ elif failure == 'same_snapshot':
+ observed = dict(previous)
+ elif failure == 'same_artifact':
+ observed['proof_image'] = previous['proof_image']
+ client = Mock(directory=Path.cwd(), process=Mock(pid=102, poll=Mock(return_value=0 if failure == 'dead' else None)))
+ with self.subTest(failure=failure), \
+ patch.object(proof, 'grounded_snapshot', return_value=observed), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=[30, 60]), \
+ patch.object(proof, 'recovery_stage', return_value='click_b2'), \
+ patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'), \
+ patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1}, {'stage': 'click_b2'})) as action:
+ if failure:
+ with self.assertRaises(AssertionError):
+ proof.prepare_recovery(client, spec, previous, ['click_a1', 'click_b2'])
+ action.assert_not_called()
+ else:
+ prepared = proof.prepare_recovery(client, spec, previous, ['click_a1', 'click_b2'])
+ self.assertEqual(prepared['prepared_ns'], 40)
+ self.assertIs(prepared['snapshot'], observed)
+ action.assert_called_once_with(observed, 'pixels', 'calc', 'click_b2')
+ client.tool.assert_not_called()
+
+
+class FixtureTests(unittest.TestCase):
+ def fixture(self):
+ value = object.__new__(proof.HoverFixture)
+ value.desktop = Mock(plan=plan())
+ value.desktop.guard.return_value = [{'pid': 20, 'at': [10, 20], 'size': [800, 600]}]
+ value.desktop.primary.return_value = record()['primary_after']
+ value.guard = Mock()
+ value.mode = {'width': 1280, 'height': 800}
+ value.sent = False
+ value.record = record()
+ value.child = Mock(stdin=io.BytesIO())
+ value.event = Mock(return_value=record()['ack'])
+ return value
+
+ def test_exact_move_only_after_fresh_hold_target_and_ready_checks(self):
+ fixture = self.fixture()
+ pending = Mock(done=Mock(return_value=False))
+ with patch.object(proof.time, 'monotonic_ns', side_effect=[6_000_000, 12_000_000]):
+ fixture.move([100, 100], plan()['agents'][0]['target'], 1, pending=pending)
+ self.assertEqual(fixture.child.stdin.getvalue(), b'MOVE 100 100\n')
+ self.assertTrue(fixture.sent)
+ self.assertEqual(fixture.record['prepared_ns'], 1)
+ fixture.desktop.primary.assert_called_once_with(plan()['agents'][0]['target'])
+ fixture.event.assert_called_once_with('moved')
+
+ def test_replay_stale_gate_unheld_or_wrong_target_never_sends(self):
+ for failure in ('replay', 'finished', 'stale_trace', 'stale_status', 'stale_ready',
+ 'stale_image', 'outside_window', 'target', 'guard'):
+ fixture = self.fixture()
+ pending = Mock(done=Mock(return_value=failure == 'finished'))
+ point, target, prepared_ns = [100, 100], plan()['agents'][0]['target'], 1
+ if failure == 'replay': fixture.sent = True
+ if failure == 'stale_trace': fixture.record['prefix']['events'][-1][1] = -300_000_000
+ if failure == 'stale_status': fixture.record['status_started_ns'] = -300_000_000
+ if failure == 'stale_ready': fixture.record['ready']['observed_ns'] = -3_000_000_000
+ if failure == 'stale_image': prepared_ns = -6_000_000_000
+ if failure == 'outside_window': point = [5, 5]
+ if failure == 'target': target = {'pid': 33, 'window_id': 44}
+ if failure == 'guard': fixture.guard.side_effect = AssertionError('identity changed')
+ with self.subTest(failure=failure), patch.object(proof.time, 'monotonic_ns', return_value=6_000_000), self.assertRaises(AssertionError):
+ fixture.move(point, target, prepared_ns, pending=pending)
+ self.assertEqual(fixture.child.stdin.getvalue(), b'')
+
+ def test_lost_ack_retains_single_attempt_and_cannot_retry(self):
+ fixture = self.fixture()
+ fixture.event.side_effect = RuntimeError('EOF')
+ with patch.object(proof.time, 'monotonic_ns', return_value=6_000_000), self.assertRaises(RuntimeError):
+ fixture.move([100, 100], plan()['agents'][0]['target'], 1)
+ self.assertTrue(fixture.sent)
+ with self.assertRaises(AssertionError):
+ fixture.move([100, 100], plan()['agents'][0]['target'], 1)
+ self.assertEqual(fixture.child.stdin.getvalue(), b'MOVE 100 100\n')
+
+ def test_injection_requires_both_current_trace_and_current_held_status(self):
+ prepared = {'snapshot': {'window_bounds': {'x': 10, 'y': 20}},
+ 'arguments': {'from_x': 90, 'from_y': 80},
+ 'target': plan()['agents'][0]['target'], 'prepared_ns': 1}
+ for held in (True, False):
+ fixture = self.fixture()
+ fixture.move = Mock()
+ pending = Mock(done=Mock(return_value=False))
+ with patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2_000_000})), \
+ patch.object(proof, '_hypr', side_effect=[json.dumps(status(1, held=held)), json.dumps(after_status())]), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=[5_000_000, 12_000_000]):
+ if held:
+ fixture.inject(Mock(), trace([ACTIVE[0]]), pending, prepared)
+ fixture.move.assert_called_once_with([100, 100], prepared['target'], 1, pending=pending)
+ else:
+ with self.assertRaises(AssertionError):
+ fixture.inject(Mock(), trace([ACTIVE[0]]), pending, prepared)
+ fixture.move.assert_not_called()
+
+ def test_close_checks_graceful_exit_and_finished_ack_without_input(self):
+ fixture = self.fixture()
+ fixture.sent = True
+ fixture.child.poll.return_value = None
+ fixture.child.returncode = 0
+ fixture.record.pop('finished', None)
+ fixture.event.return_value = {'event': 'finished', 'x': 100, 'y': 100, 'observed_ns': 1}
+ with patch.object(proof, 'stop_process') as stop:
+ fixture.close()
+ self.assertTrue(fixture.child.stdin.closed)
+ stop.assert_called_once_with(fixture.child)
+ self.assertEqual(fixture.record['exit_code'], 0)
+ fixture.event.assert_called_once_with('finished')
+ fixture.child.returncode = 1
+ with patch.object(proof, 'stop_process'), self.assertRaisesRegex(AssertionError, 'controller EOF'):
+ fixture.close()
+
+ def test_follow_mouse_and_single_unscaled_monitor_are_readonly_preconditions(self):
+ monitor = {'id': 0, 'name': 'Test-1', 'x': 0, 'y': 0, 'width': 1280,
+ 'height': 800, 'scale': 1, 'transform': 0, 'dpmsStatus': True}
+ for field, value in ((None, None), ('scale', 2), ('x', 10), ('transform', 1), ('dpmsStatus', False)):
+ mode = {**monitor, **({field: value} if field else {})}
+ with patch.object(proof, '_hypr', side_effect=[json.dumps({'int': 1}), json.dumps([mode])]) as hypr:
+ if field:
+ with self.assertRaises(AssertionError): proof.desktop_mode(Mock())
+ else:
+ mode = proof.desktop_mode(Mock())
+ self.assertEqual(mode['width'], 1280)
+ self.assertEqual(mode['follow_mouse'], 1)
+ self.assertTrue(all('dispatch' not in call.args for call in hypr.call_args_list))
+ for value in (0, 2, 3, True, '1'):
+ with patch.object(proof, '_hypr', return_value=json.dumps({'int': value})), self.assertRaises(AssertionError):
+ proof.desktop_mode(Mock())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.py b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.py
new file mode 100644
index 0000000000..924635671f
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.py
@@ -0,0 +1,575 @@
+"""Bounded native Calc/Inkscape keyboard smoke on a disposable Hyprland VM.
+
+Setup must load and enable the production plugin before this runner starts.
+Only new synthetic documents inside --evidence are opened. Missing semantic
+grounding produces inspection_only, never a pass. This is not isolation,
+concurrency, pointer-operation, or full desktop-matrix certification.
+"""
+import argparse
+import ctypes
+import hashlib
+import io
+import json
+import math
+import mmap
+import os
+from pathlib import Path
+import re
+import stat
+import subprocess
+import time
+import xml.etree.ElementTree as ET
+import zipfile
+
+from production_mcp import DirectMCP
+
+
+PACKAGES = {'libreoffice-fresh': '26.2.5-3', 'inkscape': '1.4.4-6'}
+EXECUTABLES = {'calc': Path('/usr/lib/libreoffice/program/soffice.bin'),
+ 'inkscape': Path('/usr/bin/inkscape')}
+NS = {'office': 'urn:oasis:names:tc:opendocument:xmlns:office:1.0',
+ 'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
+ 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
+ 'svg': 'http://www.w3.org/2000/svg'}
+LIMITS = {'cursor_isolation': False, 'concurrency': False,
+ 'plugin_transport_attribution': False,
+ 'all_operations': False, 'full_desktop_matrix': False}
+
+
+class GroundingUnavailable(RuntimeError):
+ """The snapshots do not authorize the next deterministic key action."""
+
+
+def read(command):
+ return subprocess.check_output(command, text=True, timeout=10).strip()
+
+
+def digest(path):
+ return {'path': str(path.resolve(strict=True)),
+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+
+
+def save_json(directory, name, value):
+ (directory / name).write_text(json.dumps(value, indent=2) + '\n')
+
+
+def package_owner(path, package):
+ assert path.resolve(strict=True) == path, 'noncanonical package executable'
+ assert path.is_file() and path.stat().st_mode & 0o111, 'package executable is not executable'
+ assert read(['pacman', '-Qqo', str(path)]) == package, 'noncanonical package owner'
+ assert read(['pacman', '-Q', package]) == f'{package} {PACKAGES[package]}'
+ return digest(path)
+
+
+def kernel_file_identity(plugin):
+ """Read the kernel mapping identity of the exact open candidate file.
+
+ Btrfs can report a subvolume device in stat() but the filesystem device in
+ proc maps. Compare two proc-map identities, not different device namespaces.
+ This private, non-executable reference mapping never loads code or writes
+ the file. Keep the descriptor and mapping alive until the checks finish.
+ """
+ def fingerprint(info):
+ return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
+
+ descriptor = os.open(plugin, os.O_RDONLY | os.O_NOFOLLOW)
+ with os.fdopen(descriptor, 'rb') as stream:
+ opened = os.fstat(stream.fileno())
+ assert stat.S_ISREG(opened.st_mode) and opened.st_size > 0, 'candidate must be a nonempty regular file'
+ # ACCESS_COPY is writable only to let ctypes expose the mapping address;
+ # no byte is written, and the file descriptor itself is read-only.
+ with mmap.mmap(stream.fileno(), 1, access=mmap.ACCESS_COPY) as reference:
+ address = ctypes.addressof(ctypes.c_char.from_buffer(reference))
+ matches = []
+ for line in Path('/proc/self/maps').read_text().splitlines():
+ fields = line.split(maxsplit=5)
+ if len(fields) != 6:
+ continue
+ start, end = (int(value, 16) for value in fields[0].split('-'))
+ if not start <= address < end:
+ continue
+ assert fields[5] == str(plugin), 'candidate reference mapping path differs or was deleted'
+ assert int(fields[2], 16) == 0, 'candidate reference mapping has wrong offset'
+ major, minor = (int(value, 16) for value in fields[3].split(':'))
+ identity = (major, minor, int(fields[4]))
+ assert identity[2] == opened.st_ino, 'candidate reference mapping inode differs'
+ matches.append(identity)
+ assert len(matches) == 1, 'cannot identify exact candidate reference mapping'
+ assert fingerprint(os.fstat(stream.fileno())) == fingerprint(opened), 'open candidate changed'
+ assert fingerprint(plugin.stat(follow_symlinks=False)) == fingerprint(opened), \
+ 'candidate path was replaced or changed'
+ return matches[0]
+
+
+def mapped_plugin(maps, plugin):
+ """Require current path AND kernel device/inode; reject replaced/deleted DSOs."""
+ expected = kernel_file_identity(plugin)
+ matches = []
+ for line in maps.splitlines():
+ fields = line.split(maxsplit=5)
+ if len(fields) != 6:
+ continue
+ path = fields[5]
+ if Path(path.removesuffix(' (deleted)')).name != plugin.name:
+ continue
+ assert path == str(plugin), 'different or deleted plugin mapped in compositor'
+ major, minor = (int(part, 16) for part in fields[3].split(':'))
+ assert (major, minor, int(fields[4])) == expected, 'mapped plugin identity differs'
+ matches.append(line)
+ assert matches, 'declared plugin is not mapped in the active Hyprland process'
+ return matches
+
+
+def require_enabled_plugin(option):
+ # The pinned Hyprland 0.56.2 getoption reply for a V2 CBoolValue uses
+ # "bool": true, not the legacy integer config representation.
+ assert isinstance(option, dict) and option.get('option') == 'plugin:cua:enabled' \
+ and option.get('bool') is True and 'int' not in option, 'setup has not enabled the plugin'
+
+
+def provenance(args):
+ source = args.source.resolve(strict=True)
+ assert Path(read(['git', '-C', str(source), 'rev-parse', '--show-toplevel'])).resolve() == source
+ sha = read(['git', '-C', str(source), 'rev-parse', 'HEAD'])
+ assert re.fullmatch(r'[0-9a-f]{40}', args.source_sha) and sha == args.source_sha, 'source SHA mismatch'
+ dirty = read(['git', '-C', str(source), 'status', '--porcelain'])
+ assert not dirty, 'exact-source smoke requires a clean checkout'
+ assert Path(__file__).resolve().is_relative_to(source), 'runner is outside declared source'
+ assert dict(line.split() for line in read(['pacman', '-Q', *PACKAGES]).splitlines()) == PACKAGES
+ app_files = {app: package_owner(path,
+ 'libreoffice-fresh' if app == 'calc' else app)
+ for app, path in EXECUTABLES.items()}
+ launcher = Path('/usr/bin/libreoffice').resolve(strict=True)
+ app_files['calc_launcher'] = package_owner(launcher, 'libreoffice-fresh')
+ signature = os.environ.get('HYPRLAND_INSTANCE_SIGNATURE')
+ assert signature, 'missing active Hyprland instance identity'
+ instances = json.loads(read(['hyprctl', '-j', 'instances']))
+ matches = [row for row in instances if row.get('instance') == signature]
+ assert len(matches) == 1, 'cannot identify the active Hyprland instance'
+ pid = matches[0]['pid']
+ assert Path(f'/proc/{pid}/exe').resolve(strict=True).name == 'Hyprland'
+ plugin = args.plugin.resolve(strict=True)
+ maps = mapped_plugin(Path(f'/proc/{pid}/maps').read_text(), plugin)
+ plugins = read(['hyprctl', 'plugin', 'list'])
+ assert 'cua-hyprland-plugin' in plugins, 'plugin is mapped but not registered'
+ enabled = json.loads(read(['hyprctl', '-j', 'getoption', 'plugin:cua:enabled']))
+ save_json(args.evidence, 'plugin-enabled-option.json', enabled)
+ require_enabled_plugin(enabled)
+ files = {'driver': args.driver, 'plugin': plugin,
+ **{name: Path(__file__).with_name(name) for name in
+ ('production_app_smoke.py', 'production_mcp.py', 'driver_input_live.py')}}
+ return {'source': str(source), 'source_sha': sha,
+ 'branch': read(['git', '-C', str(source), 'branch', '--show-current']),
+ 'dirty': dirty,
+ 'source_versions': {
+ 'driver': re.search(r'(?m)^version = "([^"]+)"',
+ (source / 'libs/cua-driver/rust/Cargo.toml').read_text())[1],
+ 'plugin': re.search(r'project\(cua_hyprland_plugin VERSION ([\d.]+)',
+ (source / 'libs/cua-driver/hyprland-plugin/CMakeLists.txt').read_text())[1]},
+ 'driver_version': read([str(args.driver), '--version']),
+ 'packages': PACKAGES, 'app_files': app_files,
+ 'files': {name: digest(path) for name, path in files.items()},
+ 'hyprland_pid': pid, 'hyprland_version': read(['hyprctl', 'version']),
+ 'loaded_plugins': plugins, 'plugin_maps': maps, 'plugin_enabled': enabled}
+
+
+def create_documents(directory):
+ """Minimal native formats, with one blank A1 and one uniquely named rectangle."""
+ ods = directory / 'cua-smoke-calc.ods'
+ content = f'''<?xml version="1.0" encoding="UTF-8"?>
+<office:document-content xmlns:office="{NS['office']}" xmlns:table="{NS['table']}"
+ xmlns:text="{NS['text']}" office:version="1.3"><office:body><office:spreadsheet>
+<table:table table:name="Smoke"><table:table-row><table:table-cell/></table:table-row>
+</table:table></office:spreadsheet></office:body></office:document-content>'''
+ manifest = '''<?xml version="1.0" encoding="UTF-8"?>
+<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">
+<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>
+<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
+</manifest:manifest>'''
+ with zipfile.ZipFile(ods, 'x') as archive:
+ archive.writestr('mimetype', 'application/vnd.oasis.opendocument.spreadsheet',
+ compress_type=zipfile.ZIP_STORED)
+ archive.writestr('content.xml', content)
+ archive.writestr('META-INF/manifest.xml', manifest)
+ svg = directory / 'cua-smoke-inkscape.svg'
+ with svg.open('x') as stream:
+ stream.write('''<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300">
+<rect id="smoke-rectangle" x="40" y="60" width="80" height="50" fill="#336699"/>
+</svg>''')
+ return {'calc': ods, 'inkscape': svg}
+
+
+def verify_calc(before, after):
+ assert before != after, 'Calc did not save a changed document'
+ with zipfile.ZipFile(io.BytesIO(after)) as archive:
+ root = ET.fromstring(archive.read('content.xml'))
+ table = root.find('.//table:table', NS)
+ assert table is not None and table.get(f"{{{NS['table']}}}name") == 'Smoke'
+ row = table.find('table:table-row', NS)
+ assert row is not None
+ cell = row.find('table:table-cell', NS)
+ assert cell is not None
+ assert cell.get(f"{{{NS['office']}}}value-type") == 'string'
+ assert ''.join(cell.itertext()) == 'a', 'saved A1 does not contain the expected letter'
+ assert cell.get(f"{{{NS['table']}}}formula") is None
+ return {'cell': 'A1', 'text': 'a', 'verified': True}
+
+
+def rectangle(content):
+ root = ET.fromstring(content)
+ assert root.get('viewBox') == '0 0 400 300', 'coordinate system changed'
+ nodes = root.findall('svg:rect', NS)
+ assert len(nodes) == 1 and nodes[0].get('id') == 'smoke-rectangle'
+ node = nodes[0]
+ x, y = float(node.get('x', '0')), float(node.get('y', '0'))
+ if node.get('transform'):
+ match = re.fullmatch(r'translate\(\s*([-+\d.eE]+)[,\s]+([-+\d.eE]+)\s*\)', node.get('transform'))
+ assert match, 'unsupported saved transform; geometry remains unproven'
+ x += float(match[1])
+ y += float(match[2])
+ assert all(math.isfinite(value) for value in (x, y))
+ return node, (x, y)
+
+
+def verify_inkscape(before, after):
+ assert before != after, 'Inkscape did not save a changed document'
+ original, start = rectangle(before)
+ saved, end = rectangle(after)
+ assert all(float(original.get(key)) == float(saved.get(key)) for key in ('width', 'height'))
+ # Default unmodified Inkscape preferences: one Right moves two SVG pixels.
+ assert math.isclose(end[0] - start[0], 2, abs_tol=1e-6)
+ assert math.isclose(end[1] - start[1], 0, abs_tol=1e-6)
+ return {'rectangle': 'smoke-rectangle', 'translation': [2, 0], 'verified': True}
+
+
+def content(result):
+ assert not result.get('isError'), result
+ return result['structuredContent']
+
+
+def check_delivery(result):
+ value = content(result)
+ assert value.get('route') == 'synthetic_events', 'input did not use the synthetic-events route'
+ assert value.get('effect') in ('confirmed', 'unverifiable'), 'partial/refused input cannot pass'
+ delivery = value.get('delivery')
+ assert delivery is None or delivery.get('mode') == 'background', 'unknown/foreground delivery cannot pass'
+ return value
+
+
+def rows(snapshot):
+ elements = snapshot.get('elements', [])
+ if not elements:
+ raise GroundingUnavailable('snapshot has no semantic elements; inspect retained screenshot')
+ if any(str(row.get('role', '')).lower() in ('dialog', 'alert', 'alert dialog') for row in elements):
+ raise GroundingUnavailable('unexpected dialog; no dismissal keys were sent')
+ return elements
+
+
+def calc_formula_selection(snapshot, elements, expected='A1'):
+ """Recognize the pinned GTK3 Calc name field, not an arbitrary matching label.
+
+ Calc's non-actionable Formula Tool Bar appears only in tree_markdown.
+ Cross-check that section's indexed name-field panel against structured
+ rows; the panel's parent_index cannot identify an omitted toolbar.
+ """
+ lines = snapshot.get('tree_markdown', '').splitlines()
+ headers = [index for index, line in enumerate(lines)
+ if line.strip() == '- tool bar = "Formula Tool Bar"']
+ if len(headers) != 1:
+ return False
+ start = headers[0]
+ indent = len(lines[start]) - len(lines[start].lstrip())
+ section = []
+ for line in lines[start + 1:]:
+ if line.strip() and len(line) - len(line.lstrip()) <= indent:
+ break
+ section.append(line.strip())
+ candidates = [row for row in elements if row.get('role') == 'text'
+ and row.get('label') == expected and row.get('enabled') is True]
+ if len(candidates) != 1:
+ return False
+ field = candidates[0]
+ panels = [row for row in elements if row.get('element_index') == field.get('parent_index')
+ and row.get('role') == 'panel' and row.get('enabled') is True]
+ if len(panels) != 1:
+ return False
+ panel = panels[0]
+ field_line = f'- [{field.get("element_index")}] text "{expected}" '
+ panel_line = f'- [{panel.get("element_index")}] panel "" '
+ return (sum(line.startswith(field_line) for line in section) == 1
+ and sum(line.startswith(panel_line) for line in section) == 1
+ and any(row.get('role') == 'combo box' and row.get('enabled') is True
+ and row.get('parent_index') == panel.get('element_index') for row in elements)
+ and any(row.get('role') == 'table' and row.get('label') == 'Sheet Smoke'
+ for row in elements))
+
+
+def inkscape_selection_command(snapshot, elements):
+ """Ground Ctrl+A in the pinned document UI, which exposes no canvas role.
+
+ The non-actionable selection status exists only in tree_markdown. Require
+ the exact initial status, the fixture's object row, and Edit > Select All
+ in both projections; a label mentioning a canvas is not evidence.
+ """
+ menus = [row for row in elements if row.get('role') == 'menu'
+ and row.get('label') == 'Edit' and row.get('enabled') is True]
+ objects = [row for row in elements if row.get('role') == 'table cell'
+ and row.get('label') == 'smoke-rectangle' and row.get('enabled') is True]
+ if len(menus) != 1 or len(objects) != 1:
+ return False
+ commands = [row for row in elements if row.get('role') == 'menu item'
+ and row.get('label') == 'Select All' and row.get('enabled') is True
+ and row.get('parent_index') == menus[0].get('element_index')]
+ if len(commands) != 1:
+ return False
+ lines = [line.strip() for line in snapshot.get('tree_markdown', '').splitlines()]
+ status = ('- label = "No objects selected. Click, Shift+click, Alt+scroll mouse '
+ 'on top of objects, or drag around objects to select."')
+ return lines.count(status) == 1 and all(
+ sum(line.startswith(f'- [{row.get("element_index")}] {row["role"]} "{row["label"]}" ')
+ for line in lines) == 1
+ for row in (menus[0], objects[0], commands[0]))
+
+
+def inkscape_selected_rectangle(snapshot, elements):
+ """Cross-check the pinned root rectangle's status and selection geometry.
+
+ Inkscape omits its non-actionable status from structured elements. The
+ actual status says "Rectangle in root", not "1 object selected". Require
+ that exact status plus the named object and the four indexed geometry
+ controls in both projections; an arbitrary selection label cannot pass.
+ """
+ lines = [line.strip() for line in snapshot.get('tree_markdown', '').splitlines()]
+ status = ('- label = "Rectangle in root. Click selection again to toggle '
+ 'scale/rotation handles."')
+ if lines.count(status) != 1 or any('No objects selected.' in line for line in lines):
+ return False
+ objects = [row for row in elements if row.get('role') == 'table cell'
+ and row.get('label') == 'smoke-rectangle' and row.get('enabled') is True]
+ if len(objects) != 1 or sum(line.startswith(
+ f'- [{objects[0].get("element_index")}] table cell "smoke-rectangle" ')
+ for line in lines) != 1:
+ return False
+ for axis, value in (('X', 40), ('Y', 60), ('W', 80), ('H', 50)):
+ controls = [row for row in elements if row.get('role') == 'spin button'
+ and row.get('label') == f'{value:.3f}'
+ and row.get('value') == f'{value:.1f}' and row.get('enabled') is True]
+ matches = []
+ for row in controls:
+ prefix = (f'- [{row.get("element_index")}] spin button "{value:.3f}" '
+ f'value="{value:.1f}" ')
+ matches.extend(index for index, line in enumerate(lines) if index > 0
+ and line.startswith(prefix) and lines[index - 1] == f'- label = "{axis}:"')
+ if len(matches) != 1:
+ return False
+ return True
+
+
+def ground(snapshot, app, stage):
+ elements = rows(snapshot)
+ if app == 'calc' and stage == 'insert':
+ selected = any(row.get('selected') is True and row.get('label') == 'A1'
+ and row.get('role') == 'table cell' for row in elements)
+ named = any(row.get('label') == 'Name Box' and row.get('value') == 'A1' for row in elements)
+ if not (selected or named or calc_formula_selection(snapshot, elements)):
+ raise GroundingUnavailable('cannot prove initial Calc selection A1 from the snapshot')
+ if app == 'inkscape':
+ if stage == 'select':
+ if not inkscape_selection_command(snapshot, elements):
+ raise GroundingUnavailable('cannot ground Inkscape document selection shortcut')
+ elif stage == 'move':
+ if not inkscape_selected_rectangle(snapshot, elements):
+ raise GroundingUnavailable('cannot prove the single rectangle is selected before Right')
+
+
+def snapshot(mcp, target, filename, app, stage):
+ result = content(mcp.tool('get_window_state', target))
+ assert filename in result.get('window_title', ''), 'snapshot is not the synthetic document'
+ windows = content(mcp.tool('list_windows', {}))['windows']
+ owned = [row for row in windows if row.get('pid') == target['pid']]
+ if len(owned) != 1 or owned[0]['window_id'] != target['window_id']:
+ raise GroundingUnavailable('extra app window or dialog; inspect fresh snapshot and window list')
+ ground(result, app, stage)
+ return result
+
+
+def input_step(mcp, target, filename, app, stage, tool, arguments):
+ snapshot(mcp, target, filename, app, stage)
+ try:
+ response = mcp.tool(tool, {**target, **arguments, 'delivery_mode': 'background'})
+ except BaseException:
+ # DirectMCP forbids all RPC after an unknown result, including a snapshot.
+ # A best-effort compositor observation retains state without replaying input.
+ try:
+ save_json(mcp.directory, 'unknown-outcome-windows.json',
+ json.loads(read(['hyprctl', '-j', 'clients'])))
+ except Exception:
+ pass
+ raise
+ try:
+ snapshot(mcp, target, filename, app, 'after')
+ finally:
+ # A dialog cannot downgrade a partial/unknown delivery to inspection_only.
+ check_delivery(response)
+
+
+def discover(mcp, app, document, old_pids):
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline:
+ windows = content(mcp.tool('list_windows', {}))['windows']
+ matches = [row for row in windows if document.name in row.get('title', '')
+ and row.get('pid') not in old_pids]
+ if matches:
+ assert len(matches) == 1, 'ambiguous launched document window'
+ window = matches[0]
+ pid = window['pid']
+ executable = Path(f'/proc/{pid}/exe').resolve(strict=True)
+ assert executable == EXECUTABLES[app].resolve(strict=True), 'noncanonical running executable'
+ assert str(document).encode() in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0'), \
+ 'running process is not bound to the new document'
+ clients = json.loads(read(['hyprctl', '-j', 'clients']))
+ native = [row for row in clients if row.get('pid') == pid]
+ assert len(native) == 1 and native[0].get('xwayland') is False, 'not one native Wayland app window'
+ maps = Path(f'/proc/{pid}/maps').read_text()
+ assert '/libgtk-3.so' in maps, 'running app did not load GTK3'
+ if app == 'calc':
+ assert '/libvclplug_gtk3lo.so' in maps, 'Calc did not load its GTK3 backend'
+ return {key: window[key] for key in ('pid', 'window_id')}, {
+ 'window': window, 'hyprland_window': native[0], 'executable': digest(executable),
+ 'gtk3_maps': [line for line in maps.splitlines()
+ if '/libgtk-3.so' in line or '/libvclplug_gtk3lo.so' in line]}
+ time.sleep(0.2)
+ # A startup dialog may replace the document title. Capture only new,
+ # canonical app processes; never send recovery/dismissal keys.
+ for window in windows:
+ pid = window.get('pid')
+ if pid in old_pids or type(pid) is not int:
+ continue
+ try:
+ executable = Path(f'/proc/{pid}/exe').resolve(strict=True)
+ if executable == EXECUTABLES[app].resolve(strict=True):
+ mcp.tool('get_window_state', {key: window[key] for key in ('pid', 'window_id')})
+ except OSError:
+ continue
+ raise GroundingUnavailable('launched document window not discovered; inspect launch and window evidence')
+
+
+def launch_arguments(app, document, directory):
+ launch = {'launch_path': str(EXECUTABLES[app])}
+ if app == 'calc':
+ launch['launch_path'] = '/usr/bin/libreoffice'
+ launch['additional_arguments'] = [f'-env:UserInstallation={(directory / "calc-profile").as_uri()}',
+ '--norestore', '--nologo', '--calc', str(document)]
+ else:
+ # Inkscape 1.4.4 accepts positional documents, not --new-instance.
+ # discover() still requires a new PID, exact executable and document.
+ launch['additional_arguments'] = [str(document)]
+ return launch
+
+
+def require_background_target(target, directory):
+ """Reject bad fixture setup before input; the plugin remains authoritative.
+
+ Launching a native app can make it foreground. An external test fixture
+ must own primary interaction before this standalone smoke sends keys.
+ This read-only check does not move focus or prove pointer isolation.
+ """
+ active = json.loads(read(['hyprctl', '-j', 'activewindow']))
+ save_json(directory, 'primary-window-before-input.json', active)
+ pid = active.get('pid') if isinstance(active, dict) else None
+ if type(pid) is not int or pid <= 0 or pid == target['pid']:
+ raise GroundingUnavailable('a separate foreground fixture must be active before background input')
+
+
+def run_app(mcp, app, document, directory):
+ old_pids = {int(path.name) for path in Path('/proc').iterdir() if path.name.isdigit()}
+ before = document.read_bytes()
+ (directory / ('before' + document.suffix)).write_bytes(before)
+ content(mcp.tool('launch_app', launch_arguments(app, document, directory)))
+ target, identity = discover(mcp, app, document, old_pids)
+ save_json(directory, 'target.json', identity)
+ try:
+ require_background_target(target, directory)
+ if app == 'calc':
+ steps = [('insert', 'press_key', {'key': 'a'}),
+ ('commit', 'press_key', {'key': 'Return'}),
+ ('save', 'hotkey', {'keys': ['ctrl', 's']})]
+ else:
+ steps = [('select', 'hotkey', {'keys': ['ctrl', 'a']}),
+ ('move', 'press_key', {'key': 'Right'}),
+ ('save', 'hotkey', {'keys': ['ctrl', 's']})]
+ for stage, tool, arguments in steps:
+ input_step(mcp, target, document.name, app, stage, tool, arguments)
+ oracle = verify_calc if app == 'calc' else verify_inkscape
+ # Read-only bounded save completion wait: never replay Ctrl+S.
+ deadline = time.monotonic() + 10
+ while True:
+ try:
+ result = oracle(before, document.read_bytes())
+ break
+ except (AssertionError, ET.ParseError, zipfile.BadZipFile, FileNotFoundError):
+ if time.monotonic() >= deadline:
+ raise
+ time.sleep(0.1)
+ snapshot(mcp, target, document.name, app, 'saved')
+ return {'result': 'passed', 'target': target, 'saved_document': result}
+ finally:
+ if document.exists():
+ (directory / ('after' + document.suffix)).write_bytes(document.read_bytes())
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence = args.evidence.resolve()
+ args.driver = args.driver.resolve(strict=True)
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ result = {'result': 'failed', 'apps': {}, 'limitations': LIMITS,
+ 'cleanup': 'App windows are retained for inspection; no app processes are closed.'}
+ previous_env = {key: os.environ.get(key) for key in ('GDK_BACKEND', 'SAL_USE_VCLPLUGIN', 'XDG_CONFIG_HOME')}
+ try:
+ save_json(args.evidence, 'requested-inputs.json', {
+ 'source': str(args.source), 'source_sha': args.source_sha,
+ 'driver': digest(args.driver), 'plugin': digest(args.plugin)})
+ save_json(args.evidence, 'provenance.json', provenance(args))
+ documents = create_documents(args.evidence)
+ # Inherited by the ordinary Driver launcher; preferences are run-local.
+ os.environ.update(GDK_BACKEND='wayland', SAL_USE_VCLPLUGIN='gtk3',
+ XDG_CONFIG_HOME=str(args.evidence / 'config'))
+ for app, document in documents.items():
+ directory = args.evidence / app
+ directory.mkdir()
+ mcp = None
+ try:
+ mcp = DirectMCP(args.driver, directory,
+ {'mode': 'unrestricted', 'acknowledge_unrestricted': True})
+ result['apps'][app] = run_app(mcp, app, document, directory)
+ except GroundingUnavailable as error:
+ result['apps'][app] = {'result': 'inspection_only', 'blocker': str(error)}
+ except Exception as error:
+ result['apps'][app] = {'result': 'failed', 'error': str(error)}
+ finally:
+ if mcp:
+ mcp.close()
+ statuses = [row['result'] for row in result['apps'].values()]
+ result['result'] = ('passed' if statuses == ['passed', 'passed'] else
+ 'failed' if 'failed' in statuses else 'inspection_only')
+ except Exception as error:
+ result['error'] = str(error)
+ finally:
+ for key, value in previous_env.items():
+ if value is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = value
+ save_json(args.evidence, 'result.json', result)
+ print(json.dumps(result), flush=True)
+ return 0 if result['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('source', 'driver', 'plugin', 'evidence'):
+ parser.add_argument('--' + name, type=Path, required=True)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.py b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.py
new file mode 100644
index 0000000000..304c9dbb4d
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.py
@@ -0,0 +1,381 @@
+"""No native applications or input: fixtures and fail-closed orchestration only."""
+import copy
+import io
+import os
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+import zipfile
+
+from production_app_smoke import (
+ LIMITS, GroundingUnavailable, check_delivery, create_documents, ground, input_step,
+ kernel_file_identity, launch_arguments, mapped_plugin, package_owner,
+ require_background_target, require_enabled_plugin, run_app, verify_calc, verify_inkscape,
+)
+
+
+TARGET = {'pid': 123, 'window_id': 456}
+GOOD_DELIVERY = {'structuredContent': {'route': 'synthetic_events',
+ 'effect': 'unverifiable',
+ 'delivery': {'mode': 'background'}}}
+CALC = {'window_title': 'cua-smoke-calc.ods - LibreOffice Calc',
+ 'elements': [{'role': 'text', 'label': 'Name Box', 'value': 'A1'}]}
+WINDOWS = {'structuredContent': {'windows': [TARGET]}}
+INKSCAPE = {
+ 'elements': [
+ {'element_index': 10, 'role': 'menu', 'label': 'Edit', 'enabled': True},
+ {'element_index': 11, 'parent_index': 10, 'role': 'menu item',
+ 'label': 'Select All', 'enabled': True},
+ {'element_index': 12, 'role': 'table cell', 'label': 'smoke-rectangle', 'enabled': True}],
+ 'tree_markdown': '\n'.join([
+ ' - [10] menu "Edit" [actions=[click]]',
+ ' - [11] menu item "Select All" [actions=[click]]',
+ ' - [12] table cell "smoke-rectangle" [actions=[activate]]',
+ ' - label = "No objects selected. Click, Shift+click, Alt+scroll mouse on top of '
+ 'objects, or drag around objects to select."']),
+}
+INKSCAPE_SELECTED = {
+ 'elements': [{'element_index': 1, 'role': 'table cell',
+ 'label': 'smoke-rectangle', 'enabled': True}] + [
+ {'element_index': index, 'role': 'spin button', 'label': f'{value:.3f}',
+ 'value': f'{value:.1f}', 'enabled': True}
+ for index, value in enumerate((40, 60, 80, 50), 2)],
+ 'tree_markdown': '\n'.join([
+ ' - [1] table cell "smoke-rectangle" [actions=[activate]]',
+ ' - label = "Rectangle in root. Click selection again to toggle scale/rotation handles."',
+ *[f' - label = "{axis}:"\n - [{index}] spin button "{value:.3f}" '
+ f'value="{value:.1f}" [actions=[activate]]'
+ for index, (axis, value) in enumerate((('X', 40), ('Y', 60), ('W', 80), ('H', 50)), 2)]]),
+}
+
+
+def changed_ods(original, text='a', empty_first=False):
+ destination = io.BytesIO()
+ with zipfile.ZipFile(io.BytesIO(original)) as source, zipfile.ZipFile(destination, 'w') as target:
+ for name in source.namelist():
+ value = source.read(name)
+ if name == 'content.xml':
+ cell = (f'<table:table-cell office:value-type="string"><text:p>{text}</text:p>'
+ '</table:table-cell>')
+ if empty_first:
+ cell = '<table:table-cell/>' + cell
+ value = value.replace(b'<table:table-cell/>', cell.encode())
+ target.writestr(name, value)
+ return destination.getvalue()
+
+
+class FixtureTests(unittest.TestCase):
+ def test_enabled_option_uses_exact_pinned_v2_boolean_contract(self):
+ enabled = {'option': 'plugin:cua:enabled', 'bool': True, 'set': True}
+ require_enabled_plugin(enabled)
+ for value in ({}, [], {'option': 'plugin:cua:enabled', 'int': 1},
+ {**enabled, 'option': 'some:other:option'}, {**enabled, 'int': 1},
+ *({**enabled, 'bool': value} for value in (False, 1, 'true', None))):
+ with self.subTest(value=value), self.assertRaisesRegex(AssertionError, 'not enabled'):
+ require_enabled_plugin(value)
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.directory = Path(self.temp.name).resolve()
+ self.documents = create_documents(self.directory)
+
+ def test_native_fixtures_and_exclusive_creation(self):
+ with zipfile.ZipFile(self.documents['calc']) as archive:
+ self.assertEqual(archive.infolist()[0].filename, 'mimetype')
+ self.assertEqual(archive.infolist()[0].compress_type, zipfile.ZIP_STORED)
+ self.assertEqual(archive.read('mimetype'), b'application/vnd.oasis.opendocument.spreadsheet')
+ with self.assertRaises(FileExistsError):
+ create_documents(self.directory)
+
+ def test_launched_foreground_app_is_retained_without_input(self):
+ mcp = Mock()
+ mcp.tool.return_value = {'structuredContent': {}}
+ original = self.documents['calc'].read_bytes()
+ with patch('production_app_smoke.Path.iterdir', return_value=iter([])), \
+ patch('production_app_smoke.discover', return_value=(TARGET, {})), \
+ patch('production_app_smoke.read', return_value='{"pid": 123}'):
+ with self.assertRaisesRegex(GroundingUnavailable, 'separate foreground fixture'):
+ run_app(mcp, 'calc', self.documents['calc'], self.directory)
+ self.assertEqual([call.args[0] for call in mcp.tool.call_args_list], ['launch_app'])
+ self.assertEqual((self.directory / 'after.ods').read_bytes(), original)
+
+ def test_calc_requires_exact_saved_a1(self):
+ original = self.documents['calc'].read_bytes()
+ self.assertTrue(verify_calc(original, changed_ods(original))['verified'])
+ for value in (original, changed_ods(original, 'b'), changed_ods(original, empty_first=True)):
+ with self.assertRaises(AssertionError):
+ verify_calc(original, value)
+
+ def test_inkscape_requires_exact_translation_and_size(self):
+ original = self.documents['inkscape'].read_bytes()
+ self.assertTrue(verify_inkscape(original, original.replace(b'x="40"', b'x="42"'))['verified'])
+ self.assertTrue(verify_inkscape(original, original.replace(
+ b'id="smoke-rectangle"', b'id="smoke-rectangle" transform="translate(2,0)"'))['verified'])
+ for changed in (original, original.replace(b'x="40"', b'x="41"'),
+ original.replace(b'x="40"', b'x="42"').replace(b'width="80"', b'width="81"'),
+ original.replace(b'x="40"', b'x="nan"'),
+ original.replace(b'id="smoke-rectangle"',
+ b'id="smoke-rectangle" transform="scale(2)"')):
+ with self.assertRaises(AssertionError):
+ verify_inkscape(original, changed)
+
+ def test_loaded_plugin_requires_current_device_inode_and_path(self):
+ plugin = self.directory / 'plugin.so'
+ plugin.write_bytes(b'synthetic test fixture')
+ stat = plugin.stat()
+ device = f'{os.major(stat.st_dev):x}:{os.minor(stat.st_dev):x}'
+ row = f'1000-2000 r-xp 00000000 {device} {stat.st_ino} {plugin}'
+ expected = (os.major(stat.st_dev), os.minor(stat.st_dev), stat.st_ino)
+ with patch('production_app_smoke.kernel_file_identity', return_value=expected):
+ self.assertEqual(mapped_plugin(row, plugin), [row])
+ for invalid in ('', row + ' (deleted)', row.replace(str(stat.st_ino), '0'),
+ row.replace(str(plugin), '/elsewhere/plugin.so'),
+ row.replace(device, f'{expected[0]:x}:{expected[1] + 1:x}')):
+ with self.assertRaises(AssertionError):
+ mapped_plugin(invalid, plugin)
+
+ def test_kernel_identity_handles_btrfs_device_presentation_without_ignoring_device(self):
+ plugin = self.directory / 'plugin.so'
+ plugin.write_bytes(b'synthetic test fixture')
+ inode = plugin.stat().st_ino
+ # The kernel reports a device different from stat(), as on Btrfs.
+ device = os.minor(plugin.stat().st_dev) + 1
+ row = f'1000-2000 rw-p 00000000 0:{device:x} {inode} {plugin}'
+ fake_mapping = Mock()
+ fake_mapping.__enter__ = Mock(return_value=bytearray(b'x'))
+ fake_mapping.__exit__ = Mock(return_value=False)
+ with patch('production_app_smoke.mmap.mmap', return_value=fake_mapping), \
+ patch('production_app_smoke.ctypes.addressof', return_value=0x1000), \
+ patch('production_app_smoke.Path.read_text', return_value=row):
+ self.assertEqual(kernel_file_identity(plugin), (0, device, inode))
+ self.assertEqual(mapped_plugin(row, plugin), [row])
+ with self.assertRaisesRegex(AssertionError, 'mapped plugin identity differs'):
+ mapped_plugin(row.replace(f'0:{device:x}', f'0:{device + 1:x}'), plugin)
+
+ def test_reference_mapping_rejects_wrong_range_path_offset_inode_and_replacement(self):
+ plugin = self.directory / 'plugin.so'
+ plugin.write_bytes(b'synthetic test fixture')
+ inode = plugin.stat().st_ino
+ row = f'1000-2000 rw-p 00000000 0:20 {inode} {plugin}'
+ fake_mapping = Mock()
+ fake_mapping.__enter__ = Mock(return_value=bytearray(b'x'))
+ fake_mapping.__exit__ = Mock(return_value=False)
+ with patch('production_app_smoke.mmap.mmap', return_value=fake_mapping), \
+ patch('production_app_smoke.ctypes.addressof', return_value=0x1000):
+ for invalid in ('', row + '\n' + row, row + ' (deleted)',
+ row.replace('1000-2000', '2000-3000'),
+ row.replace('00000000', '00001000'),
+ row.replace(str(inode), '0'),
+ row.replace(str(plugin), '/elsewhere/plugin.so')):
+ with self.subTest(maps=invalid), patch('production_app_smoke.Path.read_text', return_value=invalid):
+ with self.assertRaises(AssertionError):
+ kernel_file_identity(plugin)
+ replacement = self.directory / 'replacement.so'
+ replacement.write_bytes(b'different current file')
+ def replace_path():
+ replacement.replace(plugin)
+ return row
+ with patch('production_app_smoke.Path.read_text', side_effect=replace_path):
+ with self.assertRaisesRegex(AssertionError, 'candidate.*changed'):
+ kernel_file_identity(plugin)
+
+ @unittest.skipUnless(Path('/proc/self/maps').is_file(), 'requires native Linux proc maps')
+ def test_reference_identity_from_real_kernel_mapping(self):
+ plugin = self.directory / 'plugin.so'
+ plugin.write_bytes(b'synthetic test fixture')
+ identity = kernel_file_identity(plugin)
+ self.assertEqual(identity[2], plugin.stat().st_ino)
+ self.assertTrue(all(type(value) is int and value >= 0 for value in identity))
+
+ def test_alpm_owner_required_even_when_version_matches(self):
+ executable = self.directory / 'app'
+ executable.write_bytes(b'synthetic executable')
+ executable.chmod(0o700)
+ with patch('production_app_smoke.read', return_value='unrelated-package'):
+ with self.assertRaisesRegex(AssertionError, 'noncanonical package owner'):
+ package_owner(executable, 'libreoffice-fresh')
+
+ def test_package_executable_rejects_symlink_and_nonexecutable(self):
+ executable = self.directory / 'app'
+ executable.write_bytes(b'synthetic executable')
+ with self.assertRaisesRegex(AssertionError, 'not executable'):
+ package_owner(executable, 'inkscape')
+ executable.chmod(0o700)
+ alias = self.directory / 'alias'
+ alias.symlink_to(executable)
+ with self.assertRaisesRegex(AssertionError, 'noncanonical package executable'):
+ package_owner(alias, 'inkscape')
+
+
+class InputTests(unittest.TestCase):
+ def test_foreground_target_or_missing_foreground_is_inspection_only(self):
+ for active in ('{}', 'null', '[]', '{"pid": 123}', '{"pid": 0}',
+ '{"pid": true}', '{"pid": "456"}'):
+ with self.subTest(active=active), \
+ patch('production_app_smoke.read', return_value=active), \
+ patch('production_app_smoke.save_json') as save:
+ with self.assertRaisesRegex(GroundingUnavailable, 'separate foreground fixture'):
+ require_background_target(TARGET, Path('/evidence'))
+ save.assert_called_once()
+ with patch('production_app_smoke.read', return_value='{"pid": 456}') as read, \
+ patch('production_app_smoke.save_json'):
+ require_background_target(TARGET, Path('/evidence'))
+ read.assert_called_once_with(['hyprctl', '-j', 'activewindow'])
+
+ def test_inkscape_launch_uses_supported_positional_document(self):
+ self.assertEqual(launch_arguments('inkscape', Path('/docs/smoke.svg'), Path('/evidence')),
+ {'launch_path': '/usr/bin/inkscape',
+ 'additional_arguments': ['/docs/smoke.svg']})
+
+ def test_calc_formula_name_field_requires_matching_toolbar_and_rows(self):
+ state = {'elements': [
+ {'element_index': 10, 'role': 'panel', 'enabled': True},
+ {'element_index': 11, 'parent_index': 10, 'role': 'text', 'label': 'A1', 'enabled': True},
+ {'element_index': 12, 'parent_index': 10, 'role': 'combo box', 'enabled': True},
+ {'element_index': 13, 'role': 'table', 'label': 'Sheet Smoke'}],
+ 'tree_markdown': '\n'.join([
+ ' - tool bar = "Formula Tool Bar"',
+ ' - [10] panel "" value="0.0" [actions=[press]]',
+ ' - [11] text "A1" [actions=[activate]]',
+ ' - [12] combo box "" [actions=[press]]',
+ ' - table = "Sheet Smoke"'])}
+ ground(state, 'calc', 'insert')
+ for old, new in [('Formula Tool Bar', 'Other toolbar'), ('[11]', '[99]'),
+ ('[10]', '[99]'), ('text "A1"', 'text "B1"')]:
+ with self.subTest(old=old), self.assertRaises(GroundingUnavailable):
+ ground({**state, 'tree_markdown': state['tree_markdown'].replace(old, new)}, 'calc', 'insert')
+ for index, replacement in [(0, {'role': 'menu'}), (1, {'parent_index': 9}),
+ (1, {'enabled': False}), (1, {'label': 'B1'}),
+ (2, {'parent_index': 9}), (3, {'label': 'Sheet Other'})]:
+ bad = copy.deepcopy(state)
+ bad['elements'][index].update(replacement)
+ with self.subTest(index=index, replacement=replacement), self.assertRaises(GroundingUnavailable):
+ ground(bad, 'calc', 'insert')
+ for markdown in ['', state['tree_markdown'] + '\n' + state['tree_markdown'],
+ state['tree_markdown'].replace(' - [10]', ' - panel = "Other"\n - [10]')]:
+ with self.subTest(markdown=markdown), self.assertRaises(GroundingUnavailable):
+ ground({**state, 'tree_markdown': markdown}, 'calc', 'insert')
+ with self.assertRaises(GroundingUnavailable):
+ ground({**state, 'elements': state['elements'] + [state['elements'][1]]}, 'calc', 'insert')
+
+ def test_route_family_does_not_claim_plugin_transport_attribution(self):
+ self.assertIs(LIMITS['plugin_transport_attribution'], False)
+
+ def test_inkscape_requires_document_command_and_exact_initial_status(self):
+ ground(INKSCAPE, 'inkscape', 'select')
+ for index, replacement in [(0, {'role': 'label'}), (0, {'enabled': False}),
+ (1, {'parent_index': 99}), (1, {'enabled': False}),
+ (1, {'label': 'Select All in All Layers'}),
+ (2, {'label': 'other-rectangle'}), (2, {'role': 'label'})]:
+ bad = copy.deepcopy(INKSCAPE)
+ bad['elements'][index].update(replacement)
+ with self.subTest(index=index, replacement=replacement), self.assertRaises(GroundingUnavailable):
+ ground(bad, 'inkscape', 'select')
+ for old, new in [('[10]', '[99]'), ('[11]', '[99]'), ('[12]', '[99]'),
+ ('No objects selected.', '1 object selected.'), ('- label =', '- button =')]:
+ with self.subTest(old=old), self.assertRaises(GroundingUnavailable):
+ ground({**INKSCAPE, 'tree_markdown': INKSCAPE['tree_markdown'].replace(old, new)},
+ 'inkscape', 'select')
+ for markdown in ('', INKSCAPE['tree_markdown'] + '\n' + INKSCAPE['tree_markdown']):
+ with self.assertRaises(GroundingUnavailable):
+ ground({**INKSCAPE, 'tree_markdown': markdown}, 'inkscape', 'select')
+ for row in INKSCAPE['elements']:
+ with self.assertRaises(GroundingUnavailable):
+ ground({**INKSCAPE, 'elements': INKSCAPE['elements'] + [row]}, 'inkscape', 'select')
+ for role in ('canvas', 'drawing area'):
+ with self.assertRaises(GroundingUnavailable):
+ ground({'elements': [{'role': role}]}, 'inkscape', 'select')
+
+ def test_only_acknowledged_synthetic_background_delivery_accepted(self):
+ check_delivery(GOOD_DELIVERY)
+ for replacement in ({'route': 'atspi'}, {'effect': 'partial'},
+ {'delivery': {'mode': 'unknown'}}, {'delivery': {'mode': 'foreground'}}):
+ with self.assertRaises(AssertionError):
+ check_delivery({'structuredContent': {**GOOD_DELIVERY['structuredContent'], **replacement}})
+ with self.assertRaises(AssertionError):
+ check_delivery({**GOOD_DELIVERY, 'isError': True})
+
+ def test_selected_rectangle_requires_exact_status_object_and_geometry(self):
+ ground(INKSCAPE_SELECTED, 'inkscape', 'move')
+ for index, replacement in [(0, {'label': 'other-rectangle'}), (0, {'enabled': False}),
+ (1, {'value': '42.0'}), (2, {'role': 'text'}),
+ (3, {'enabled': False}), (4, {'element_index': 99})]:
+ bad = copy.deepcopy(INKSCAPE_SELECTED)
+ bad['elements'][index].update(replacement)
+ with self.subTest(index=index, replacement=replacement), self.assertRaises(GroundingUnavailable):
+ ground(bad, 'inkscape', 'move')
+ for old, new in [('Rectangle in root.', '2 objects selected.'),
+ ('Rectangle in root.', 'Rectangle in layer.'),
+ ('- label = "Rectangle', '- text = "Rectangle'),
+ ('[1]', '[99]'), ('"X:"', '"Y:"'), ('value="80.0"', 'value="81.0"')]:
+ bad = {**INKSCAPE_SELECTED,
+ 'tree_markdown': INKSCAPE_SELECTED['tree_markdown'].replace(old, new)}
+ with self.subTest(old=old, new=new), self.assertRaises(GroundingUnavailable):
+ ground(bad, 'inkscape', 'move')
+ for extra in ('\n' + INKSCAPE_SELECTED['tree_markdown'], '\n- label = "No objects selected."'):
+ with self.assertRaises(GroundingUnavailable):
+ ground({**INKSCAPE_SELECTED, 'tree_markdown': INKSCAPE_SELECTED['tree_markdown'] + extra},
+ 'inkscape', 'move')
+ for row in INKSCAPE_SELECTED['elements']:
+ with self.assertRaises(GroundingUnavailable):
+ ground({**INKSCAPE_SELECTED, 'elements': INKSCAPE_SELECTED['elements'] + [row]},
+ 'inkscape', 'move')
+ for state in ({**INKSCAPE_SELECTED, 'tree_markdown': ''},
+ {'elements': [{'role': 'status bar', 'value': '1 object selected'}]}, INKSCAPE):
+ with self.assertRaises(GroundingUnavailable):
+ ground(state, 'inkscape', 'move')
+
+ def test_grounding_rejects_dialog_missing_selection_and_missing_canvas(self):
+ ground(CALC, 'calc', 'insert')
+ for state in ({'elements': []},
+ {'elements': [{'role': 'dialog', 'label': 'Recover documents'}]},
+ {'elements': [{'role': 'text', 'label': 'Name Box', 'value': 'B1'}]}):
+ with self.assertRaises(GroundingUnavailable):
+ ground(state, 'calc', 'insert')
+ with self.assertRaises(GroundingUnavailable):
+ ground(CALC, 'inkscape', 'select')
+ ground(INKSCAPE, 'inkscape', 'select')
+ with self.assertRaises(GroundingUnavailable):
+ ground({'elements': [{'role': 'status bar', 'value': 'No objects selected'}]}, 'inkscape', 'move')
+ ground(INKSCAPE_SELECTED, 'inkscape', 'move')
+
+ def test_snapshot_action_snapshot_and_no_replay(self):
+ mcp = Mock()
+ mcp.tool.side_effect = [{'structuredContent': CALC}, WINDOWS, GOOD_DELIVERY,
+ {'structuredContent': CALC}, WINDOWS]
+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})
+ calls = mcp.tool.call_args_list
+ self.assertEqual([call.args[0] for call in calls],
+ ['get_window_state', 'list_windows', 'press_key', 'get_window_state', 'list_windows'])
+ self.assertEqual(calls[2].args[1], {**TARGET, 'key': 'a', 'delivery_mode': 'background'})
+
+ def test_missing_grounding_sends_no_input(self):
+ mcp = Mock()
+ mcp.tool.side_effect = [{'structuredContent': {**CALC, 'elements': []}}, WINDOWS]
+ with self.assertRaises(GroundingUnavailable):
+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})
+ self.assertEqual(mcp.tool.call_count, 2)
+
+ def test_partial_delivery_stays_failure_even_if_dialog_appears(self):
+ mcp = Mock()
+ partial = {'structuredContent': {**GOOD_DELIVERY['structuredContent'], 'effect': 'partial'}}
+ dialog = {**CALC, 'elements': [{'role': 'dialog'}]}
+ mcp.tool.side_effect = [{'structuredContent': CALC}, WINDOWS, partial,
+ {'structuredContent': dialog}, WINDOWS]
+ with self.assertRaises(AssertionError):
+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})
+ self.assertEqual(mcp.tool.call_count, 5)
+
+ def test_unknown_transport_outcome_is_not_replayed(self):
+ mcp = Mock()
+ mcp.tool.side_effect = [{'structuredContent': CALC}, WINDOWS, TimeoutError('unknown')]
+ with patch('production_app_smoke.read', side_effect=OSError('unavailable')):
+ with self.assertRaises(TimeoutError):
+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})
+ self.assertEqual(mcp.tool.call_count, 3)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py
new file mode 100644
index 0000000000..b50f6d5a7b
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py
@@ -0,0 +1,633 @@
+"""Bounded native cancellation proof; deterministic tests do not certify native behavior.
+
+Only normal direct Driver calls send app input. The trace connection is read-only
+apart from TRACE_START/TRACE_STOP. Kill one exact owned runtime only after fresh
+telemetry proves two active drags; preserve unknown delivery without replay.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import math
+from pathlib import Path
+import subprocess
+import time
+
+from driver_input_live import state, wait_for, wm
+from primary_trace import Trace, analyze
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_realapp_proof import (app_process_identity, capacity_lane, check_response,
+ primary_acknowledgement, provenance, trace_interval,
+ PRIMARY_LIFETIME_MS, require_primary_active)
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+PROFILE = {'mode': 'unrestricted', 'acknowledge_unrestricted': True}
+DRAG_KEYS = {'from_x', 'from_y', 'to_x', 'to_y', 'duration_ms'}
+POINTER_STAGES = {'calc': 'select_range', 'inkscape': 'move_rectangle'}
+RECOVERY_STAGES = {'calc': {'click_a1', 'click_b2'}, 'inkscape': {'scroll_down', 'scroll_visible'}}
+MAX_GROUNDING_AGE_NS = 5_000_000_000
+# Leave margin over the observed 25–30 ms lane-admission interval. This is not
+# a worst-case scheduling bound: call_drag still checks the actual age.
+GROUNDING_DISPATCH_RESERVE_NS = 250_000_000
+MAX_GROUNDING_ATTEMPTS = 2
+# max_elements counts all visited AT-SPI nodes, not only emitted controls.
+# The native 2,000-node run retained the object row but stopped 14 rendered
+# tree lines before the selection status. Allow 500 more visited nodes while
+# keeping the trailing menu tree bounded; native coverage must verify this.
+# Keep depth uncapped (the object row is deeply nested). Missing oracle
+# evidence still fails closed, as does the unchanged five-second age limit.
+POINTER_SNAPSHOT_LIMITS = {'inkscape': {'max_elements': 2500}}
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'cancellation'
+ assert type(plan['kill_agent']) is int and plan['kill_agent'] in (0, 1)
+ assert plan.get('termination_signal', 'SIGKILL') in ('SIGKILL', 'SIGTERM'), 'unsupported termination signal'
+ assert len(plan['agents']) == 2
+ assert {spec['app'] for spec in plan['agents']} == {'calc', 'inkscape'}
+ targets = [plan['foreground'], *(spec['target'] for spec in plan['agents'])]
+ assert len({target['pid'] for target in targets}) == 3, 'need three separate app processes'
+ for target in targets:
+ assert set(target) == {'pid', 'window_id'}
+ assert all(type(value) is int and value > 0 for value in target.values())
+ for spec in plan['agents']:
+ assert isinstance(spec['name'], str) and spec['name']
+ assert spec.get('profile', PROFILE) == PROFILE, 'this run requires unrestricted plus explicit bypass'
+ assert set(spec['bounds']) == {'x', 'y', 'width', 'height'}
+ assert all(type(v) in (int, float) and math.isfinite(v) for v in spec['bounds'].values())
+ assert spec['bounds']['width'] > 0 and spec['bounds']['height'] > 0
+ drag = spec['drag']
+ if 'pointer_stage' in spec:
+ assert spec['pointer_stage'] == POINTER_STAGES[spec['app']] and drag == {}, \
+ 'pointer cancellation derives its drag from the fresh image'
+ continue
+ assert set(drag) == DRAG_KEYS, 'drag cannot override target/session/delivery'
+ assert all(type(v) in (int, float) and math.isfinite(v) for v in drag.values())
+ assert type(drag['duration_ms']) is int and 1000 <= drag['duration_ms'] <= 2000
+ assert (drag['from_x'], drag['from_y']) != (drag['to_x'], drag['to_y'])
+ point = plan['primary_point']
+ assert len(point) == 2 and all(type(v) is int for v in point)
+ if 'recovery' in plan:
+ recovery = plan['recovery']
+ assert isinstance(recovery, dict) and set(recovery) == {'pointer_stage'}
+ assert all('pointer_stage' in spec for spec in plan['agents']), 'recovery needs both app-effect oracles'
+ victim = plan['agents'][plan['kill_agent']]
+ assert recovery['pointer_stage'] in RECOVERY_STAGES[victim['app']], 'recovery must be a new non-drag action'
+
+
+def stopped_prefix(page):
+ """Analyze a phase boundary without stopping or resetting the real trace."""
+ trace_interval(page, page)
+ last = page['events'][-1]
+ return {**page, 'active': False, 'count': page['count'] + 1,
+ 'events': page['events'] + [[last[0] + 1, last[1], 'stop', *last[3:5], 0, 0]]}
+
+
+def verify_recovery_trace(before, after, lane, tool):
+ assert tool in ('click', 'scroll'), 'recovery must use a new non-drag action'
+ events = trace_interval(before, after)
+ assert capacity_lane(before, after, tool) == lane, 'recovery did not reacquire the victim lane'
+ assert sum(row[2] == 'agent_admitted' for row in events) == 1, 'recovery admission is not unique'
+ assert sum(row[2] == 'agent_action_end' for row in events) == 1, 'recovery completion is not unique'
+ assert not any(row[2] in ('agent_cancel', 'agent_drag_start', 'agent_drag_end', 'keyboard_key')
+ for row in events), 'recovery replayed or sent unexpected input'
+ buttons = [row[6] for row in events if row[2] == 'pointer_button']
+ axes = [row for row in events if row[2] == 'pointer_axis']
+ assert (buttons == [1, 0] and not axes) if tool == 'click' else (not buttons and axes), \
+ 'unexpected recovery input sequence'
+ stopped = stopped_prefix(after)
+ isolation = analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ return {'result': 'verified', 'lane': lane, 'tool': tool, 'continuous_isolation': isolation}
+
+
+def verify_recovery_cleanup(prefix, stopped):
+ """Allow seat teardown after completion, never another synthetic action."""
+ trace_interval(prefix, prefix)
+ isolation = analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ assert stopped['events'][:prefix['count']] == prefix['events'], 'trace history changed during recovery'
+ cleanup_events = {'agent_cancel', 'pointer_leave', 'keyboard_leave'}
+ assert all(row[2] in cleanup_events for row in stopped['events'][prefix['count']:]
+ if row[5] in (1, 2)), 'unexpected synthetic activity after recovery'
+ return isolation
+
+
+def recover_once(client, observer, victim, sibling, spec, stage, trace, boundary, lane, save, result, guard=None):
+ """One new action, never a continuation of the killed transport or gesture."""
+ assert victim.failed and victim.process.poll() is not None, 'victim must be torn down before recovery'
+ pids = assert_distinct_runtimes([client, sibling, observer])
+ assert victim.process.pid not in pids, 'recovery reused the victim runtime'
+ assert stage in RECOVERY_STAGES[spec['app']]
+ fresh = {**spec, 'name': spec['name'] + '-recovery', 'pointer_stage': stage}
+ result.update(runtime_pid=client.process.pid, victim_pid=victim.process.pid,
+ policy={'startup_profile': dict(PROFILE), 'managed_user_policy': 'inherited by new runtime'},
+ session=fresh['name'], replayed=False)
+ response = client.tool('start_session', {'session': fresh['name']})
+ assert not response.get('isError'), response
+ identity = app_process_identity(spec['app'], spec['target']['pid'])
+ started_ns = time.monotonic_ns()
+ before = grounded_snapshot(client, fresh['target'], fresh)
+ # Match prepare_drag: discovery precedes the observation; the complete
+ # snapshot and pixel grounding remain inside the five-second limit.
+ started_ns = before.get('proof_observation_started_ns', started_ns)
+ image = pointer_grounding.read_pixels(before['proof_image'])
+ requested_stage = stage
+ if stage == 'scroll_visible':
+ stage = pointer_grounding.visible_inkscape_scroll_stage(before, image)
+ arguments, oracle = pointer_grounding.action(before, image, spec['app'], stage)
+ tool = pointer_grounding.STAGES[spec['app']][stage]
+ assert tool in ('click', 'scroll'), 'recovery cannot replay the interrupted drag'
+ result['grounding'] = {'snapshot': before, 'app_identity': identity, 'arguments': arguments,
+ 'oracle': oracle, 'prepared_ns': started_ns, 'target': fresh['target'],
+ 'requested_stage': requested_stage}
+ save('recovery-grounding.json', result)
+ if guard:
+ guard()
+ dispatch_ns = time.monotonic_ns()
+ assert 0 <= dispatch_ns - started_ns <= MAX_GROUNDING_AGE_NS, 'recovery grounding expired; no input sent'
+ result['action'] = {'outcome': 'unknown', 'replayed': False, 'dispatch_ns': dispatch_ns}
+ try:
+ response = client.tool(tool, {**arguments, **fresh['target'], 'session': fresh['name'],
+ 'delivery_mode': 'background'})
+ except Exception as error:
+ result['action']['error'] = str(error)
+ else:
+ result['action'].update(outcome='response', response=response)
+ save('recovery-action.json', result['action'])
+ # Preserve the observed result even if delivery classification or the app oracle fails.
+ after = grounded_snapshot(observer, fresh['target'], fresh, session=False)
+ save('recovery-after.json', after)
+ assert result['action']['outcome'] == 'response', 'recovery delivery remains unknown; no replay'
+ check_response(response, {'kind': 'dispatched'})
+ result['app_effect'] = pointer_grounding.verify(
+ after, pointer_grounding.read_pixels(after['proof_image']), oracle)
+ page = trace.collect()
+ save('recovery-prefix.json', page)
+ result['trace'] = verify_recovery_trace(boundary, page, lane, tool)
+ assert client.process.poll() is None and sibling.process.poll() is None, 'runtime exited during recovery'
+ if guard:
+ guard()
+ result['result'] = 'verified'
+ return page
+
+
+def observation_runtime(client):
+ """Snapshot counters belong to one direct process and its evidence directory."""
+ assert_distinct_runtimes([client])
+ return {'pid': client.process.pid, 'directory': str(client.directory.resolve(strict=True))}
+
+
+def verify_fresh_observation(before, after, observer, *, after_ns):
+ """Verify original observation chronology, without comparing unscoped counters."""
+ assert after['proof_runtime'] == observation_runtime(observer), 'wrong observation runtime'
+ assert before['snapshot_id'] and after['snapshot_id'], 'missing snapshot identity'
+ assert (before['proof_runtime'], before['snapshot_id']) != (after['proof_runtime'], after['snapshot_id']), \
+ 'reused snapshot'
+ assert Path(before['proof_image']).resolve() != Path(after['proof_image']).resolve(), 'reused image artifact'
+ times = [before['proof_observation_started_ns'], before['proof_observation_finished_ns'],
+ after_ns, after['proof_observation_started_ns'], after['proof_observation_finished_ns'],
+ time.monotonic_ns()]
+ assert all(type(value) is int and value >= 0 for value in times), 'invalid observation timestamp'
+ assert times == sorted(times) and times[0] < times[3], 'stale or out-of-order observation'
+
+
+def grounded_snapshot(client, target, spec=None, *, session=True):
+ windows = client.tool('list_windows', {})
+ assert not windows.get('isError'), windows
+ matches = [w for w in windows['structuredContent']['windows'] if w.get('pid') == target['pid']]
+ assert len(matches) == 1 and matches[0].get('window_id') == target['window_id'], 'stale target identity'
+ pixels = spec is not None and 'pointer_stage' in spec
+ runtime = observation_runtime(client)
+ observation_started_ns = time.monotonic_ns()
+ result = client.tool('get_window_state', {**target,
+ **(POINTER_SNAPSHOT_LIMITS.get(spec['app'], {}) if pixels
+ else {'max_elements': 100, 'max_depth': 6}),
+ **({'session': spec['name']} if spec and session else {})})
+ assert not result.get('isError'), result
+ observation_finished_ns = time.monotonic_ns()
+ assert observation_runtime(client) == runtime, 'observation runtime changed'
+ content = {**result['structuredContent'], 'proof_runtime': runtime,
+ 'proof_observation_started_ns': observation_started_ns,
+ 'proof_observation_finished_ns': observation_finished_ns}
+ width, height = content.get('screenshot_width', 0), content.get('screenshot_height', 0)
+ assert width > 0 and height > 0, 'missing grounding image'
+ if spec:
+ assert content['window_bounds'] == spec['bounds'], 'reviewed geometry is stale'
+ if not pixels:
+ for end in ('from', 'to'):
+ assert 0 < spec['drag'][end + '_x'] < width and 0 < spec['drag'][end + '_y'] < height, \
+ 'drag leaves the fresh snapshot'
+ # A cached response must not gain a new age from this wrapper's clock.
+ snapshot_id = content.get('snapshot_id')
+ assert isinstance(snapshot_id, str) and snapshot_id, 'missing snapshot identity'
+ seen = vars(client).setdefault('_proof_snapshot_ids', set())
+ assert snapshot_id not in seen, 'reused snapshot in Driver runtime'
+ seen.add(snapshot_id)
+ if pixels:
+ images = [row for row in result.get('content', []) if row.get('type') == 'image']
+ assert len(images) == 1 and images[0].get('image_file'), 'missing exact snapshot image'
+ path = client.directory / images[0]['image_file']
+ assert path.resolve(strict=True).parent == client.directory.resolve(strict=True), 'image escapes evidence'
+ images_seen = vars(client).setdefault('_proof_image_paths', set())
+ assert path.resolve() not in images_seen, 'reused image artifact in Driver runtime'
+ images_seen.add(path.resolve())
+ content = {**content, 'proof_image': str(path)}
+ return content
+
+
+def prepare_drag(client, spec):
+ """Ground once before either gesture starts; never reuse an earlier action's image."""
+ started_ns = time.monotonic_ns()
+ before = grounded_snapshot(client, spec['target'], spec)
+ observation_started_ns = before.get('proof_observation_started_ns', started_ns)
+ observed_ns = time.monotonic_ns()
+ arguments, oracle = dict(spec['drag']), None
+ if 'pointer_stage' in spec:
+ arguments, oracle = pointer_grounding.action(
+ before, pointer_grounding.read_pixels(before['proof_image']), spec['app'], spec['pointer_stage'])
+ return {'snapshot': before, 'arguments': arguments, 'oracle': oracle,
+ 'target': dict(spec['target']), 'session': spec['name'],
+ 'prepared_ns': observation_started_ns,
+ 'timing': {'preparation_started_ns': started_ns,
+ 'observation_started_ns': observation_started_ns, 'observation_finished_ns': observed_ns,
+ 'grounding_finished_ns': time.monotonic_ns()}}
+
+
+def pair_has_dispatch_budget(prepared):
+ """Check the whole pair without extending either action's freshness bound."""
+ assert len(prepared) == 2
+ assert 0 < GROUNDING_DISPATCH_RESERVE_NS < MAX_GROUNDING_AGE_NS
+ checked_ns = time.monotonic_ns()
+ ages = [checked_ns - item['prepared_ns'] for item in prepared]
+ for item, age in zip(prepared, ages):
+ item.setdefault('timing', {}).update(pair_gate_ns=checked_ns, pair_grounding_age_ns=age)
+ assert all(age >= 0 for age in ages), 'grounding timestamp is in the future'
+ return all(age <= MAX_GROUNDING_AGE_NS - GROUNDING_DISPATCH_RESERVE_NS for age in ages)
+
+
+def prepare_drags(clients, specs, save):
+ """Observe independent apps concurrently before either timed action starts.
+
+ Reserve time for the first drag's admission before dispatching its sibling.
+ At most one paired observation refresh is allowed here, before ANY input
+ attempt. It never retries a failed observation or an input action. The
+ unchanged five-second gate in call_drag still checks each actual dispatch.
+ """
+ assert len(clients) == len(specs) == 2
+ for attempt in range(1, MAX_GROUNDING_ATTEMPTS + 1):
+ assert_distinct_runtimes(clients)
+ with ThreadPoolExecutor(max_workers=2) as observations:
+ pending = [observations.submit(prepare_drag, client, spec)
+ for client, spec in zip(clients, specs)]
+ prepared = [future.result() for future in pending]
+ for index, item in enumerate(prepared):
+ # Preserve superseded observations as well as the final canonical
+ # names consumed by the independent evidence verifier.
+ save(f'agent-{index}-drag-grounding-attempt-{attempt}.json', item)
+ save(f'agent-{index}-drag-grounding.json', item)
+ ready = pair_has_dispatch_budget(prepared)
+ if not ready:
+ # If preparation raises, the runner never receives this pair to
+ # re-save it during cleanup. Retain the failed gate's timing here.
+ for index, item in enumerate(prepared):
+ save(f'agent-{index}-drag-grounding-attempt-{attempt}.json', item)
+ save(f'agent-{index}-drag-grounding.json', item)
+ save(f'drag-grounding-attempt-{attempt}.json', {
+ 'attempt': attempt, 'checked_ns': prepared[0]['timing']['pair_gate_ns'],
+ 'grounding_ages_ns': [item['timing']['pair_grounding_age_ns'] for item in prepared],
+ 'dispatch_reserve_ns': GROUNDING_DISPATCH_RESERVE_NS, 'ready': ready,
+ 'input_attempted': False})
+ if ready:
+ return prepared
+ raise AssertionError('paired drag grounding has insufficient dispatch time; no input sent')
+
+
+def active_drags(page):
+ """Reject incomplete telemetry before using its last observed lane state."""
+ trace_interval(page, page)
+ active, admitted, pressed = {}, set(), set()
+ for seq, timestamp, kind, _x, _y, lane, value, *_surface in page['events']:
+ if lane not in (1, 2):
+ continue
+ if kind == 'agent_admitted':
+ assert lane not in admitted, 'multiple admissions before termination'
+ admitted.add(lane)
+ elif kind == 'agent_drag_start':
+ assert lane in admitted and lane not in active, 'ambiguous drag admission'
+ active[lane] = timestamp
+ elif kind in ('agent_drag_end', 'agent_cancel'):
+ raise AssertionError('drag ended before the termination gate')
+ elif kind in ('agent_action_end', 'keyboard_key'):
+ raise AssertionError('unexpected action before termination')
+ elif kind == 'pointer_button':
+ assert value == 1 and lane in active and lane not in pressed, 'drag is not held'
+ pressed.add(lane)
+ return {lane: start for lane, start in active.items() if lane in pressed}
+
+
+def poll_active(trace, previous, lanes, pending, timeout=3):
+ """A stale prefix or completed action must never authorize a process kill."""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ started = time.monotonic()
+ page = trace.collect()
+ assert time.monotonic() - started <= 0.25, 'trace read too stale for termination'
+ trace_interval(previous, page)
+ active = active_drags(page)
+ assert all(not future.done() for future in pending), 'action already returned'
+ ready = set(active) == set(lanes) if lanes else len(active) == 1
+ if ready:
+ if len(active) == 1 or page['events'][-1][1] - max(active.values()) >= 100_000_000:
+ return page, active
+ previous = page
+ time.sleep(0.01)
+ raise AssertionError('no fresh active overlap within bounded wait')
+
+
+def terminate_owned(victim, sibling, pending, signal='SIGKILL'):
+ assert signal in ('SIGKILL', 'SIGTERM'), 'unsupported termination signal'
+ assert_distinct_runtimes([victim, sibling])
+ assert all(not future.done() for future in pending), 'action returned before termination'
+ # Poison before killing: no further RPC, including a snapshot, may use it.
+ victim.failed = True
+ requested_ns = time.monotonic_ns()
+ if signal == 'SIGKILL':
+ victim.process.kill()
+ else:
+ victim.process.terminate()
+ # A timeout fails this case. Cleanup may reap the exact child later, but
+ # must not turn an ignored SIGTERM into a passing SIGKILL result.
+ victim.process.wait(timeout=3)
+ assert victim.process.poll() is not None, 'owned runtime was not reaped'
+ assert sibling.process.poll() is None, 'sibling exited during termination'
+ return {'pid': victim.process.pid, 'signal': signal, 'requested_ns': requested_ns,
+ 'reaped_ns': time.monotonic_ns()}
+
+
+def close_owned(client):
+ """Retain close failures while still reaping the exact child if it survives."""
+ try:
+ client.close()
+ finally:
+ if client.process.poll() is None:
+ client.process.kill()
+ client.process.wait(timeout=3)
+
+
+def verify_cancellation(stopped, kill_prefix, victim_lane, sibling_lane):
+ isolation = analyze(stopped)
+ assert isolation.get('telemetry_complete') is True and isolation['result'] == 'passed', isolation
+ assert {victim_lane, sibling_lane} == {1, 2}
+ assert set(active_drags(kill_prefix)) == {1, 2}
+ assert stopped['events'][:kill_prefix['count']] == kill_prefix['events'], 'trace history changed'
+ tail = stopped['events'][kill_prefix['count']:]
+ cancelled = [r for r in tail if r[2] == 'agent_cancel']
+ completed = [r for r in tail if r[2] == 'agent_drag_end']
+ assert len(cancelled) == 1 and cancelled[0][5] == victim_lane, 'cancellation crossed lanes or is missing'
+ assert len(completed) == 1 and completed[0][5] == sibling_lane, 'sibling did not complete alone'
+ assert cancelled[0][0] < completed[0][0], 'sibling completed before cancellation'
+ assert not any(r[2] in ('agent_admitted', 'agent_drag_start', 'agent_action_end', 'keyboard_key')
+ for r in tail), 'unexpected extra action after termination'
+ for lane in (victim_lane, sibling_lane):
+ releases = [r for r in tail if r[5] == lane and r[2] == 'pointer_button']
+ assert len(releases) == 1 and releases[0][6] == 0, 'missing own-lane button release'
+ assert releases[0][0] > cancelled[0][0], 'release preceded observed cancellation'
+ if lane == sibling_lane:
+ assert releases[0][0] < completed[0][0], 'sibling release followed completion'
+ assert released_synthetic_input(stopped)
+ assert isolation['agent_drag_overlap_ms'] >= 100, 'insufficient traced overlap'
+ return {'result': 'verified', 'victim_lane': victim_lane, 'sibling_lane': sibling_lane,
+ 'continuous_isolation': isolation, 'synthetic_cleanup': 'verified'}
+
+
+def call_drag(client, spec, prepared=None, guard=None):
+ prepared = prepare_drag(client, spec) if prepared is None else prepared
+ assert prepared['target'] == spec['target'] and prepared['session'] == spec['name']
+ if guard:
+ guard()
+ dispatch_ns = time.monotonic_ns()
+ age = dispatch_ns - prepared['prepared_ns']
+ prepared.setdefault('timing', {}).update(dispatch_attempt_ns=dispatch_ns, grounding_age_ns=age)
+ assert 0 <= age <= MAX_GROUNDING_AGE_NS, 'prepared drag snapshot expired; no input sent'
+ try:
+ response = client.tool('drag', {**prepared['arguments'], **spec['target'],
+ 'session': spec['name'], 'delivery_mode': 'background'})
+ except Exception as error:
+ return {'outcome': 'unknown', 'error': str(error), 'replayed': False}
+ return {'outcome': 'response', 'response': response, 'replayed': False}
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ report = {'result': 'failed', 'scope': 'native-runtime-cancellation', 'actions': {},
+ 'cancellation': 'unproven', 'reacquisition': 'unproven',
+ 'sibling_pointer_delivery': 'unproven',
+ 'saved_app_effects': 'unproven', 'full_desktop_matrix': False}
+ clients, observer, grab, trace, pool = [], None, None, None, None
+ futures, kill_prefix, lanes = {}, None, None
+ cancellation_boundary = recovery_prefix = None
+ prepared = []
+ primary_before = baseline = None
+ deadline = None
+ def guard():
+ require_primary_active(grab, deadline)
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ assert args.trace_socket and args.trace_socket.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock'), \
+ 'cancellation requires continuous v3 trace'
+ origin = provenance(args, plan)
+ for name in ('production_cancel_proof.py', 'production_cancel_proof_test.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ save('provenance.json', origin)
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ return DirectMCP(args.driver, directory, PROFILE)
+ for index, spec in enumerate(plan['agents']):
+ clients.append(launch(f'agent-{index}'))
+ result = clients[-1].tool('start_session', {'session': spec['name']})
+ assert not result.get('isError'), result
+ grounded_snapshot(clients[-1], spec['target'], spec)
+ observer = launch('observer')
+ report['driver_processes'] = assert_distinct_runtimes([*clients, observer])
+ fg = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError'), desktop
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < fg['width'] and 0 < y < fg['height']
+ x, y = fg['x'] + x, fg['y'] + y
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'])
+ grounded_snapshot(observer, plan['foreground'])
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid'] and baseline['held']
+ trace = Trace(args.trace_socket)
+ assert trace.hello['protocol'] == 3
+ trace.exchange('TRACE_START')
+ initial = trace.collect()
+ assert not active_drags(initial) and not any(r[5] in (1, 2) for r in initial['events']), 'trace is not quiet'
+ victim, sibling = plan['kill_agent'], 1 - plan['kill_agent']
+ pool = ThreadPoolExecutor(max_workers=2)
+ # Complete both app observations before starting either timed gesture.
+ # The exact images, derived coordinates, and oracles are retained before
+ # any dispatch. Expired grounding fails without replaying an action.
+ prepared = prepare_drags(clients, plan['agents'], save)
+ guard()
+ # Include evidence-write and primary-guard latency in the final paired
+ # gate. Never re-observe after this point or after any input attempt.
+ assert pair_has_dispatch_budget(prepared), 'paired drag grounding has insufficient dispatch time; no input sent'
+ futures[victim] = pool.submit(call_drag, clients[victim], plan['agents'][victim], prepared[victim], guard)
+ first, active = poll_active(trace, initial, None, list(futures.values()))
+ victim_lane = next(iter(active))
+ guard()
+ futures[sibling] = pool.submit(call_drag, clients[sibling], plan['agents'][sibling], prepared[sibling], guard)
+ kill_prefix, _ = poll_active(trace, first, {1, 2}, list(futures.values()))
+ # No disk I/O or observation between the fresh trace gate and exact-child kill.
+ guard()
+ report['termination'] = terminate_owned(clients[victim], clients[sibling], list(futures.values()),
+ plan.get('termination_signal', 'SIGKILL'))
+ lanes = victim_lane, 3 - victim_lane
+ save('termination-prefix.json', kill_prefix)
+ for index, future in futures.items():
+ report['actions'][str(index)] = future.result(timeout=5)
+ killed = report['actions'][str(victim)]
+ if killed['outcome'] == 'response':
+ content = killed['response'].get('structuredContent', {})
+ kind = 'unknown' if (content.get('delivery') or {}).get('mode') == 'unknown' else 'partial'
+ check_response(killed['response'], {'kind': kind})
+ surviving = report['actions'][str(sibling)]
+ assert surviving['outcome'] == 'response', 'sibling delivery remains unknown'
+ check_response(surviving['response'], {'kind': 'dispatched'})
+ assert clients[sibling].process.poll() is None, 'sibling runtime exited'
+ for index in (victim, sibling):
+ spec = plan['agents'][index]
+ # The observer uses its own fresh read after the killed connection is lost.
+ after = grounded_snapshot(observer, spec['target'], spec, session=False)
+ save(f'agent-{index}-after.json', after)
+ guard()
+ if index == victim and 'recovery' in plan:
+ image = Path(after['proof_image'])
+ report['interrupted_state'] = {
+ 'snapshot': f'agent-{index}-after.json', 'image': str(image),
+ 'snapshot_sha256': hashlib.sha256(
+ (args.evidence / f'agent-{index}-after.json').read_bytes()).hexdigest(),
+ 'image_sha256': hashlib.sha256(image.read_bytes()).hexdigest(),
+ 'action': killed, 'saved_document_effect': 'unproven', 'replayed': False}
+ save('interrupted-state.json', report['interrupted_state'])
+ if index == sibling and prepared[index]['oracle'] is not None:
+ report['sibling_app_effect'] = pointer_grounding.verify(
+ after, pointer_grounding.read_pixels(after['proof_image']), prepared[index]['oracle'])
+ if 'recovery' in plan:
+ cancellation_boundary = trace.collect()
+ save('cancellation-prefix.json', cancellation_boundary)
+ report['cancellation'] = verify_cancellation(stopped_prefix(cancellation_boundary), kill_prefix, *lanes)
+ assert clients[victim].failed and clients[victim].process.poll() is not None
+ # Register the fresh runtime for unconditional cleanup before any RPC.
+ clients.append(launch('recovery'))
+ report['reacquisition'] = {'result': 'unproven', 'replayed': False}
+ recovery_prefix = recover_once(
+ clients[-1], observer, clients[victim], clients[sibling], plan['agents'][victim],
+ plan['recovery']['pointer_stage'], trace, cancellation_boundary, victim_lane,
+ save, report['reacquisition'], guard)
+ interrupted = report['interrupted_state']
+ for path, digest in ((args.evidence / interrupted['snapshot'], interrupted['snapshot_sha256']),
+ (Path(interrupted['image']), interrupted['image_sha256'])):
+ assert hashlib.sha256(path.read_bytes()).hexdigest() == digest, 'interrupted evidence changed'
+ grounded_snapshot(observer, plan['foreground'])
+ assert wm() == primary_before, 'primary cursor/focus/workspace changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), current
+ guard()
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = [(f'close_agent_{i}', lambda c=client: close_owned(c)) for i, client in enumerate(clients)]
+ if kill_prefix is not None:
+ operations.append(('preserve_termination_prefix', lambda: save('termination-prefix.json', kill_prefix)))
+ if pool:
+ # Closing owned transports first unblocks pending RPCs, including failed setup.
+ def join_actions():
+ for index, future in futures.items():
+ try:
+ report['actions'][str(index)] = future.result(timeout=5)
+ except Exception as error:
+ report['actions'][str(index)] = {'outcome': 'unknown', 'error': str(error), 'replayed': False}
+ assert all(future.done() for future in futures.values()), 'action worker did not stop'
+ operations.append(('join_actions', join_actions))
+ operations.append(('shutdown_pool', lambda: pool.shutdown(wait=False, cancel_futures=True)))
+ # Keep dispatch-attempt timing even when the freshness gate raises before
+ # MCP input. Initial grounding was already saved before either action.
+ for index, item in enumerate(prepared):
+ operations.append((f'preserve_grounding_{index}',
+ lambda i=index, value=item: save(f'agent-{i}-drag-grounding.json', value)))
+ if trace:
+ def finish_trace():
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('trace.json', stopped)
+ guard()
+ assert kill_prefix is not None and lanes, 'no termination evidence'
+ if cancellation_boundary is None:
+ report['cancellation'] = verify_cancellation(stopped, kill_prefix, *lanes)
+ else:
+ report['cancellation'] = verify_cancellation(stopped_prefix(cancellation_boundary), kill_prefix, *lanes)
+ prefix = recovery_prefix or cancellation_boundary
+ assert stopped['events'][:prefix['count']] == prefix['events'], 'trace history changed during recovery'
+ isolation = analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ if recovery_prefix is not None:
+ isolation = verify_recovery_cleanup(recovery_prefix, stopped)
+ report['continuous_isolation'] = isolation
+ if 'sibling_app_effect' in report:
+ # Bound the completed gesture to the admitted survivor lane.
+ # The victim may share its start coordinates and was canceled;
+ # neither it nor a later recovery action proves this delivery.
+ drag_trace = stopped_prefix(cancellation_boundary) if cancellation_boundary else stopped
+ report['sibling_pointer_delivery'] = pointer_grounding.verify_drag_trace(
+ drag_trace, prepared[sibling]['arguments'], report['sibling_app_effect'],
+ expected_lane=lanes[1])
+ assert wm() == primary_before, 'primary changed during cleanup'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), current
+ guard()
+ operations += [('finish_trace', finish_trace), ('close_trace', trace.close)]
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'])
+ operations.append(('release_primary', release_primary))
+ if observer:
+ operations.append(('close_observer', lambda: close_owned(observer)))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.py
new file mode 100644
index 0000000000..c06f27a2a1
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.py
@@ -0,0 +1,926 @@
+"""Synthetic orchestration/telemetry tests only; no native desktop is exercised."""
+from contextlib import ExitStack
+from concurrent.futures import ThreadPoolExecutor
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import threading
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+from production_cancel_proof import (
+ GROUNDING_DISPATCH_RESERVE_NS, MAX_GROUNDING_AGE_NS, PROFILE,
+ active_drags, call_drag, close_owned, grounded_snapshot,
+ pair_has_dispatch_budget, poll_active, prepare_drag, prepare_drags, recover_once, run, stopped_prefix,
+ terminate_owned, validate_plan, verify_cancellation, verify_fresh_observation,
+ verify_recovery_cleanup, verify_recovery_trace,
+)
+
+
+BOUNDS = {'x': 0, 'y': 0, 'width': 800, 'height': 600}
+
+
+def plan():
+ return {'purpose': 'cancellation', 'kill_agent': 0,
+ 'foreground': {'pid': 10, 'window_id': 100}, 'primary_point': [100, 100],
+ 'agents': [{'app': app, 'name': f'agent-{i}', 'target': {'pid': 20 + i, 'window_id': 200 + i},
+ 'bounds': BOUNDS.copy(), 'profile': PROFILE.copy(),
+ 'drag': {'from_x': 100, 'from_y': 100, 'to_x': 200, 'to_y': 200, 'duration_ms': 2000}}
+ for i, app in enumerate(('calc', 'inkscape'))]}
+
+
+def trace(rows, active=True):
+ return {'hook': True, 'active': active, 'overflow': False, 'timed_out': False, 'count': len(rows),
+ 'events': [[i + 1, ms * 1_000_000, kind, 100, 100, lane, value]
+ for i, (ms, kind, lane, value) in enumerate(rows)]}
+
+
+START = [(0, 'start', 0, 0)]
+FIRST = START + [(1, 'agent_admitted', 1, 0), (2, 'agent_drag_start', 1, 0), (2, 'pointer_button', 1, 1)]
+OVERLAP = FIRST + [(10, 'agent_admitted', 2, 0), (11, 'agent_drag_start', 2, 0),
+ (11, 'pointer_button', 2, 1), (150, 'pointer_motion', 2, 0)]
+FINISH = OVERLAP + [(151, 'agent_cancel', 1, 0), (151, 'pointer_button', 1, 0),
+ (1900, 'pointer_button', 2, 0), (1901, 'agent_drag_end', 2, 0), (2000, 'stop', 0, 0)]
+RESPONSE = {'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background'}}}
+
+
+def wire_trace(rows, active=True):
+ """Both lanes start at the same point; only lane two reaches the end."""
+ result = trace(rows, active)
+ events = []
+ for row in result['events']:
+ if row[2] == 'agent_drag_start':
+ events.append([0, row[1], 'pointer_motion', *row[3:6], 0, 100, 100])
+ if row[2] == 'pointer_button' and row[1] == 1900 * 1_000_000:
+ events.append([0, row[1], 'pointer_motion', *row[3:6], 0, 200, 200])
+ events.append(row + ([110, 110] if row[2] == 'pointer_motion' else []))
+ for sequence, row in enumerate(events, 1):
+ row[0] = sequence
+ return {**result, 'events': events, 'count': len(events)}
+
+
+def recovery_rows(tool='click', lane=1):
+ inputs = [(2010, 'pointer_button', lane, 1), (2011, 'pointer_button', lane, 0)] if tool == 'click' else [
+ (2010, 'pointer_axis', lane, 0)]
+ return FINISH[:-1] + [(2001, 'agent_admitted', lane, 0), *inputs, (2012, 'agent_action_end', lane, 0)]
+
+
+class TelemetryTests(unittest.TestCase):
+ def test_active_drags_accepts_surface_coordinates_without_losing_lane_state(self):
+ self.assertEqual(active_drags(wire_trace(OVERLAP)), active_drags(trace(OVERLAP)))
+ self.assertEqual(verify_cancellation(wire_trace(FINISH, False), wire_trace(OVERLAP), 1, 2)
+ ['result'], 'verified')
+
+ def test_complete_overlap_and_own_lane_release(self):
+ result = verify_cancellation(trace(FINISH, False), trace(OVERLAP), 1, 2)
+ self.assertEqual(result['result'], 'verified')
+ self.assertEqual(result['synthetic_cleanup'], 'verified')
+ def swap(rows):
+ return [(ms, kind, 3 - lane if lane else lane, value) for ms, kind, lane, value in rows]
+ self.assertEqual(verify_cancellation(trace(swap(FINISH), False), trace(swap(OVERLAP)), 2, 1)['result'], 'verified')
+
+ def test_missing_truncated_overflowed_and_reordered_telemetry_fail(self):
+ for field, value in [('hook', False), ('active', False), ('overflow', True), ('timed_out', True),
+ ('count', 100), ('events', []), ('events', [[1, 0, 'bogus', 0, 0, 0, 0]])]:
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ active_drags({**trace(OVERLAP), field: value})
+ page = trace(OVERLAP)
+ page['events'][3][0] = 100
+ with self.assertRaises(AssertionError):
+ active_drags(page)
+
+ def test_cancelled_ended_or_unheld_drag_cannot_authorize_kill(self):
+ for kind, value in [('agent_cancel', 0), ('agent_drag_end', 0), ('pointer_button', 0),
+ ('agent_admitted', 0), ('agent_action_end', 0), ('keyboard_key', 1)]:
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ active_drags(trace(OVERLAP + [(151, kind, 1, value)]))
+
+ def test_sibling_cancel_missing_release_extra_action_or_primary_disturbance_fails(self):
+ mutations = [FINISH[:8] + FINISH[9:], # missing victim cancellation
+ FINISH[:9] + FINISH[10:], # missing victim release
+ FINISH[:10] + [(1900, 'agent_cancel', 2, 0)] + FINISH[10:],
+ FINISH[:10] + [(1900, 'agent_drag_start', 1, 0)] + FINISH[10:],
+ FINISH[:10] + [(1900, 'keyboard_key', 1, 1)] + FINISH[10:]]
+ for kind in ('keyboard_key', 'pointer_button', 'pointer_focus', 'pointer_axis'):
+ mutations.append(FINISH[:-1] + [(1999, kind, 0, 0)] + FINISH[-1:])
+ for rows in mutations:
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ verify_cancellation(trace(rows, False), trace(OVERLAP), 1, 2)
+ warped = trace(FINISH, False)
+ warped['events'][8][3] = 110
+ with self.assertRaises(AssertionError):
+ verify_cancellation(warped, trace(OVERLAP), 1, 2)
+
+ def test_poll_requires_fresh_contiguous_overlap_and_pending_calls(self):
+ pending = Mock(done=Mock(return_value=False))
+ page, active = poll_active(Mock(collect=Mock(return_value=trace(OVERLAP))), trace(FIRST), {1, 2}, [pending])
+ self.assertEqual(set(active), {1, 2})
+ for done, clocks in [(True, None), (False, [0, 0, 0, 1])]:
+ with ExitStack() as stack, self.assertRaises(AssertionError):
+ if clocks:
+ stack.enter_context(patch('production_cancel_proof.time.monotonic', side_effect=clocks))
+ poll_active(Mock(collect=Mock(return_value=page)), trace(FIRST), {1, 2}, [Mock(done=lambda: done)])
+ altered = trace(OVERLAP)
+ altered['events'][1][1] += 1
+ with self.assertRaisesRegex(AssertionError, 'history'):
+ poll_active(Mock(collect=lambda: altered), trace(FIRST), {1, 2}, [pending])
+ with patch('production_cancel_proof.time.monotonic', side_effect=[0, 4]), self.assertRaisesRegex(AssertionError, 'bounded'):
+ poll_active(Mock(), trace(FIRST), {1, 2}, [pending])
+
+ def test_gate_waits_for_observed_100ms_overlap(self):
+ pending = Mock(done=Mock(return_value=False))
+ collector = Mock(collect=Mock(side_effect=[trace(OVERLAP[:-1]), trace(OVERLAP)]))
+ with patch('production_cancel_proof.time.sleep'):
+ page, _ = poll_active(collector, trace(FIRST), {1, 2}, [pending])
+ self.assertEqual(collector.collect.call_count, 2)
+ self.assertEqual(page, trace(OVERLAP))
+
+
+def client(pid):
+ process = Mock(pid=pid, poll=Mock(return_value=None))
+ process.kill.side_effect = lambda: setattr(process.poll, 'return_value', -9)
+ process.terminate.side_effect = lambda: setattr(process.poll, 'return_value', -15)
+ return Mock(process=process, failed=False)
+
+
+class RecoveryTests(unittest.TestCase):
+ def test_completed_recovery_allows_only_seat_cleanup(self):
+ rows = recovery_rows()
+ cleanup = [(2020 + i, kind, lane, 0) for i, (kind, lane) in enumerate(
+ [('agent_cancel', 1), ('pointer_leave', 1), ('keyboard_leave', 1),
+ ('agent_cancel', 2), ('pointer_leave', 2), ('keyboard_leave', 2)])]
+ prefix = trace(rows)
+ for tail in ([], cleanup):
+ stopped = trace(rows + tail + [(2030, 'stop', 0, 0)], False)
+ self.assertEqual(verify_recovery_cleanup(prefix, stopped)['result'], 'passed')
+ for kind in ('agent_admitted', 'agent_action_end', 'agent_drag_start', 'agent_drag_end',
+ 'pointer_motion', 'pointer_button', 'pointer_axis', 'keyboard_key'):
+ for lane in (1, 2):
+ with self.subTest(kind=kind, lane=lane), self.assertRaises(AssertionError):
+ verify_recovery_cleanup(prefix,
+ trace(rows + cleanup + [(2028, kind, lane, 0), (2030, 'stop', 0, 0)], False))
+ for field, value in (('active', True), ('hook', False), ('overflow', True),
+ ('timed_out', True), ('count', 0)):
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ verify_recovery_cleanup(prefix, {**trace(rows + [(2030, 'stop', 0, 0)], False), field: value})
+ changed = trace(rows + cleanup + [(2030, 'stop', 0, 0)], False)
+ changed['events'][1][1] += 1
+ with self.assertRaisesRegex(AssertionError, 'history'):
+ verify_recovery_cleanup(prefix, changed)
+
+ def test_recovery_plan_requires_new_supported_action_and_both_oracles(self):
+ for victim, stage in ((0, 'click_b2'), (1, 'scroll_down'), (1, 'scroll_visible')):
+ candidate = plan()
+ candidate.update(kill_agent=victim, recovery={'pointer_stage': stage})
+ with self.assertRaisesRegex(AssertionError, 'both app-effect'):
+ validate_plan(candidate)
+ for spec, drag_stage in zip(candidate['agents'], ('select_range', 'move_rectangle')):
+ spec.update(drag={}, pointer_stage=drag_stage)
+ validate_plan(candidate)
+ for bad in ({'pointer_stage': 'move_rectangle'}, {'pointer_stage': 'select_range'},
+ {'pointer_stage': stage, 'arguments': {'x': 10}}, None):
+ with self.subTest(victim=victim, bad=bad), self.assertRaises(AssertionError):
+ validate_plan({**candidate, 'recovery': bad})
+
+ def test_phase_traces_require_one_fresh_action_on_released_lane(self):
+ for lane in (1, 2):
+ for tool in ('click', 'scroll'):
+ rows = recovery_rows(tool, lane)
+ if lane == 2:
+ rows[:len(FINISH) - 1] = [
+ (ms, kind, 3 - old if old else old, value) for ms, kind, old, value in FINISH[:-1]]
+ boundary, after = trace(rows[:len(FINISH) - 1]), trace(rows)
+ self.assertEqual(verify_recovery_trace(boundary, after, lane, tool)['result'], 'verified')
+ self.assertEqual(verify_cancellation(stopped_prefix(boundary),
+ trace(rows[:len(OVERLAP)]), lane, 3 - lane)['result'], 'verified')
+ for extra in ((2013, 'agent_admitted', lane, 0), (2013, 'agent_cancel', lane, 0),
+ (2013, 'agent_action_end', lane, 0), (2013, 'agent_drag_start', lane, 0),
+ (2013, 'keyboard_key', lane, 1), (2013, 'pointer_button', lane, 1),
+ (2013, 'pointer_motion', 3 - lane, 0), (2013, 'pointer_axis', 0, 0)):
+ with self.subTest(extra=extra), self.assertRaises(AssertionError):
+ verify_recovery_trace(boundary, trace(rows + [extra]), lane, tool)
+ for missing in (-1, len(FINISH) - 1, len(FINISH)):
+ damaged = list(rows)
+ damaged.pop(missing)
+ with self.assertRaises(AssertionError):
+ verify_recovery_trace(boundary, trace(damaged), lane, tool)
+ for key in ('hook', 'active'):
+ with self.assertRaises(AssertionError):
+ verify_recovery_trace(boundary, {**after, key: False}, lane, tool)
+ changed = trace(rows)
+ changed['events'][1][1] += 1
+ with self.assertRaisesRegex(AssertionError, 'history'):
+ verify_recovery_trace(boundary, changed, lane, tool)
+
+ def test_fresh_runtime_snapshot_single_action_and_observer_effect(self):
+ for app, stage, tool in (('calc', 'click_b2', 'click'), ('inkscape', 'scroll_down', 'scroll'),
+ ('inkscape', 'scroll_visible', 'scroll')):
+ for failure in (None, 'slow_discovery', 'alive', 'reused', 'stale', 'identity', 'snapshot', 'unknown', 'denied', 'effect', 'trace', 'primary_before', 'primary_after',
+ *(['margin'] if stage == 'scroll_visible' else [])):
+ with self.subTest(app=app, failure=failure), ExitStack() as stack:
+ victim, sibling, observer, fresh = [client(pid) for pid in (100, 101, 102, 103)]
+ victim.failed = True
+ victim.process.poll.return_value = None if failure == 'alive' else -9
+ if failure == 'reused':
+ fresh.process.pid = victim.process.pid
+ response = RESPONSE if failure != 'denied' else {'isError': True, 'structuredContent': {
+ 'status': 'refused', 'refusal': {'code': 'permission_denied'}}}
+ fresh.tool.side_effect = [{}, TimeoutError('lost reply') if failure == 'unknown' else response]
+ spec = next(spec for spec in plan()['agents'] if spec['app'] == app)
+ before, after = {'proof_image': 'before.png'}, {'proof_image': 'after.png'}
+ dispatch_ns = 101
+ if failure == 'slow_discovery':
+ before['proof_observation_started_ns'] = MAX_GROUNDING_AGE_NS + 200
+ dispatch_ns = MAX_GROUNDING_AGE_NS + 301
+ snapshot = stack.enter_context(patch('production_cancel_proof.grounded_snapshot',
+ side_effect=AssertionError('geometry changed') if failure == 'snapshot' else [before, after]))
+ identity = stack.enter_context(patch('production_cancel_proof.app_process_identity',
+ side_effect=AssertionError('app changed') if failure == 'identity' else None,
+ return_value={'pid': spec['target']['pid']}))
+ stack.enter_context(patch('production_cancel_proof.time.monotonic_ns',
+ side_effect=[100, MAX_GROUNDING_AGE_NS + 101 if failure == 'stale' else dispatch_ns]))
+ stack.enter_context(patch('production_cancel_proof.pointer_grounding.read_pixels', return_value='pixels'))
+ resolved_stage = 'scroll_up' if stage == 'scroll_visible' else stage
+ choose_stage = stack.enter_context(patch('production_cancel_proof.pointer_grounding.visible_inkscape_scroll_stage',
+ side_effect=AssertionError('insufficient margin') if failure == 'margin' else None,
+ return_value=resolved_stage))
+ arguments, oracle = {'x': 20, 'y': 30}, {'app': app, 'stage': resolved_stage}
+ action = stack.enter_context(patch('production_cancel_proof.pointer_grounding.action',
+ return_value=(arguments, oracle)))
+ verify = stack.enter_context(patch('production_cancel_proof.pointer_grounding.verify',
+ side_effect=AssertionError('no app effect') if failure == 'effect' else None,
+ return_value={'verified': True}))
+ page = trace(recovery_rows(tool))
+ if failure == 'trace':
+ page['overflow'] = True
+ trace_client, save, result = Mock(collect=Mock(return_value=page)), Mock(), {}
+ guard = Mock(side_effect=AssertionError('primary lifetime ended') if failure == 'primary_before'
+ else [None, AssertionError('primary lifetime ended')] if failure == 'primary_after' else None)
+ def attempt():
+ return recover_once(fresh, observer, victim, sibling, spec, stage, trace_client,
+ trace(FINISH[:-1]), 1, save, result, guard)
+ if failure not in (None, 'slow_discovery'):
+ with self.assertRaises((AssertionError, TimeoutError)):
+ attempt()
+ else:
+ self.assertEqual(attempt(), page)
+ self.assertEqual(result['result'], 'verified')
+ self.assertEqual(result['policy']['startup_profile'], PROFILE)
+ self.assertNotEqual(result['runtime_pid'], result['victim_pid'])
+ self.assertFalse(result['replayed'])
+ self.assertEqual(result['action']['dispatch_ns'], dispatch_ns)
+ self.assertEqual(result['grounding']['prepared_ns'],
+ before.get('proof_observation_started_ns', 100))
+ identity.assert_called_once_with(app, spec['target']['pid'])
+ action.assert_called_once_with(before, 'pixels', app, resolved_stage)
+ self.assertEqual(result['grounding']['requested_stage'], stage)
+ if stage == 'scroll_visible':
+ choose_stage.assert_called_once_with(before, 'pixels')
+ else:
+ choose_stage.assert_not_called()
+ verify.assert_called_once_with(after, 'pixels', oracle)
+ self.assertIs(snapshot.call_args_list[0].args[0], fresh)
+ self.assertIs(snapshot.call_args_list[1].args[0], observer)
+ inputs = [call for call in fresh.tool.call_args_list if call.args[0] != 'start_session']
+ self.assertEqual(len(inputs), 0 if failure in ('alive', 'reused', 'stale', 'identity', 'snapshot', 'primary_before', 'margin') else 1)
+ if inputs:
+ self.assertEqual(inputs[0].args, (tool, {**arguments, **spec['target'],
+ 'session': spec['name'] + '-recovery', 'delivery_mode': 'background'}))
+ if failure == 'unknown':
+ self.assertEqual(result['action']['outcome'], 'unknown')
+ self.assertFalse(result['action']['replayed'])
+ self.assertEqual([call.args[0] for call in save.call_args_list],
+ ['recovery-grounding.json', 'recovery-action.json', 'recovery-after.json'])
+ self.assertIs(snapshot.call_args_list[-1].args[0], observer)
+ victim.tool.assert_not_called()
+ sibling.tool.assert_not_called()
+
+
+class OwnershipTests(unittest.TestCase):
+ def test_both_grounding_calls_overlap_without_app_input(self):
+ clients = [client(100), client(101)]
+ specs = plan()['agents']
+ rendezvous = threading.Barrier(2, timeout=2)
+ save = Mock()
+ def observe(owned, spec):
+ rendezvous.wait()
+ return {'target': spec['target'], 'session': spec['name'], 'prepared_ns': 100}
+ with patch('production_cancel_proof.prepare_drag', side_effect=observe), \
+ patch('production_cancel_proof.time.monotonic_ns', return_value=200):
+ result = prepare_drags(clients, specs, save)
+ self.assertEqual([item['target'] for item in result], [spec['target'] for spec in specs])
+ self.assertEqual([call.args[0] for call in save.call_args_list],
+ ['agent-0-drag-grounding-attempt-1.json', 'agent-0-drag-grounding.json',
+ 'agent-1-drag-grounding-attempt-1.json', 'agent-1-drag-grounding.json',
+ 'drag-grounding-attempt-1.json'])
+ for owned in clients:
+ owned.tool.assert_not_called()
+
+ def test_aging_pair_refreshes_both_observations_before_any_input(self):
+ clients, specs, retained = [client(100), client(101)], plan()['agents'], {}
+ counts = [0, 0]
+ now = 10_000_000_000
+ def observe(owned, spec):
+ index = specs.index(spec)
+ counts[index] += 1
+ age = (4_995_561_185, 4_995_070_539)[index] if counts[index] == 1 else 2_000_000_000
+ return {'target': spec['target'], 'session': spec['name'], 'prepared_ns': now - age,
+ 'snapshot': {'fresh_attempt': counts[index]}}
+ with patch('production_cancel_proof.prepare_drag', side_effect=observe), \
+ patch('production_cancel_proof.time.monotonic_ns', return_value=now):
+ result = prepare_drags(clients, specs, lambda name, value: retained.update({name: value}))
+ self.assertEqual(counts, [2, 2])
+ for index, item in enumerate(result):
+ self.assertEqual(item['snapshot']['fresh_attempt'], 2)
+ self.assertIs(retained[f'agent-{index}-drag-grounding.json'], item)
+ self.assertEqual(retained[f'agent-{index}-drag-grounding-attempt-1.json']['snapshot']['fresh_attempt'], 1)
+ self.assertFalse(retained['drag-grounding-attempt-1.json']['ready'])
+ self.assertTrue(retained['drag-grounding-attempt-2.json']['ready'])
+ for owned in clients:
+ owned.tool.assert_not_called()
+
+ def test_pair_freshness_boundary_and_attempt_cap(self):
+ limit = MAX_GROUNDING_AGE_NS - GROUNDING_DISPATCH_RESERVE_NS
+ for age, attempts, error in ((limit, 1, None), (limit + 1, 2, 'insufficient dispatch time'),
+ (MAX_GROUNDING_AGE_NS + 1, 2, 'insufficient dispatch time'),
+ (-1, 1, 'in the future')):
+ with self.subTest(age=age):
+ clients, save = [client(100), client(101)], Mock()
+ with patch('production_cancel_proof.prepare_drag', return_value={'prepared_ns': 100}) as observe, \
+ patch('production_cancel_proof.time.monotonic_ns', return_value=100 + age):
+ if error:
+ with self.assertRaisesRegex(AssertionError, error):
+ prepare_drags(clients, plan()['agents'], save)
+ else:
+ prepare_drags(clients, plan()['agents'], save)
+ self.assertEqual(observe.call_count, 2 * attempts)
+ for owned in clients:
+ owned.tool.assert_not_called()
+
+ def test_grounding_retention_time_counts_toward_pair_freshness(self):
+ clients, now = [client(100), client(101)], [100]
+ def save(name, item):
+ if name == 'agent-1-drag-grounding.json':
+ now[0] += MAX_GROUNDING_AGE_NS
+ with patch('production_cancel_proof.prepare_drag', side_effect=lambda *args: {'prepared_ns': now[0]}) as observe, \
+ patch('production_cancel_proof.time.monotonic_ns', side_effect=lambda: now[0]):
+ with self.assertRaisesRegex(AssertionError, 'insufficient dispatch time; no input sent'):
+ prepare_drags(clients, plan()['agents'], save)
+ self.assertEqual(observe.call_count, 4)
+ for owned in clients:
+ owned.tool.assert_not_called()
+
+ def test_pair_requires_each_item_to_have_budget(self):
+ now = 10_000_000_000
+ for stale in (0, 1):
+ prepared = [{'prepared_ns': now}, {'prepared_ns': now}]
+ prepared[stale]['prepared_ns'] = now - MAX_GROUNDING_AGE_NS + GROUNDING_DISPATCH_RESERVE_NS - 1
+ with patch('production_cancel_proof.time.monotonic_ns', return_value=now):
+ self.assertFalse(pair_has_dispatch_budget(prepared))
+ self.assertEqual(prepared[stale]['timing']['pair_gate_ns'], now)
+
+ def test_failed_parallel_grounding_never_dispatches(self):
+ clients = [client(100), client(101)]
+ save = Mock()
+ with patch('production_cancel_proof.prepare_drag', side_effect=AssertionError('bad image')) as observe:
+ with self.assertRaisesRegex(AssertionError, 'bad image'):
+ prepare_drags(clients, plan()['agents'], save)
+ self.assertEqual(observe.call_count, 2)
+ save.assert_not_called()
+ for owned in clients:
+ owned.tool.assert_not_called()
+
+ def test_pointer_plan_requires_derived_drag_and_exact_app_stage(self):
+ candidate = plan()
+ for spec, stage in zip(candidate['agents'], ('select_range', 'move_rectangle')):
+ spec.update(drag={}, pointer_stage=stage)
+ validate_plan(candidate)
+ for change in ({'pointer_stage': 'click_a1'}, {'drag': plan()['agents'][0]['drag']},
+ {'pointer_stage': 'move_rectangle'}):
+ invalid = json.loads(json.dumps(candidate))
+ invalid['agents'][0].update(change)
+ with self.assertRaises(AssertionError):
+ validate_plan(invalid)
+
+ def test_pointer_preparation_uses_exact_image_and_preserves_oracle(self):
+ spec = {**plan()['agents'][0], 'drag': {}, 'pointer_stage': 'select_range'}
+ before = {'proof_image': 'fresh.png', 'window_bounds': BOUNDS}
+ arguments = {**plan()['agents'][0]['drag'], 'steps': 30}
+ oracle = {'selection': 'A1:B3'}
+ with patch('production_cancel_proof.grounded_snapshot', return_value=before) as snapshot, \
+ patch('production_cancel_proof.pointer_grounding.read_pixels', return_value='pixels') as pixels, \
+ patch('production_cancel_proof.pointer_grounding.action', return_value=(arguments, oracle)) as action:
+ result = prepare_drag(Mock(), spec)
+ snapshot.assert_called_once()
+ pixels.assert_called_once_with('fresh.png')
+ action.assert_called_once_with(before, 'pixels', 'calc', 'select_range')
+ self.assertEqual(result['arguments'], arguments)
+ self.assertEqual(result['oracle'], oracle)
+ self.assertEqual(result['snapshot'], before)
+
+ def test_freshness_starts_before_snapshot_and_records_each_phase(self):
+ spec, mcp = plan()['agents'][0], Mock()
+ mcp.tool.return_value = RESPONSE
+ before = {'proof_observation_started_ns': 200}
+ with patch('production_cancel_proof.grounded_snapshot', return_value=before), \
+ patch('production_cancel_proof.time.monotonic_ns', side_effect=[100, 300, 400, 500]):
+ prepared = prepare_drag(mcp, spec)
+ call_drag(mcp, spec, prepared)
+ self.assertEqual(prepared['prepared_ns'], 200)
+ self.assertEqual(prepared['timing'], {
+ 'preparation_started_ns': 100, 'observation_started_ns': 200,
+ 'observation_finished_ns': 300, 'grounding_finished_ns': 400,
+ 'dispatch_attempt_ns': 500, 'grounding_age_ns': 300})
+
+ def test_slow_snapshot_or_guard_expires_without_input_and_retains_age(self):
+ spec, mcp = plan()['agents'][0], Mock()
+ for slow_phase in ('snapshot', 'guard'):
+ with self.subTest(slow_phase=slow_phase):
+ now = [100]
+ def snapshot(*args):
+ if slow_phase == 'snapshot':
+ now[0] += MAX_GROUNDING_AGE_NS + 1
+ return {'proof_observation_started_ns': 100}
+ def guard():
+ if slow_phase == 'guard':
+ now[0] += MAX_GROUNDING_AGE_NS + 1
+ with patch('production_cancel_proof.grounded_snapshot', side_effect=snapshot), \
+ patch('production_cancel_proof.time.monotonic_ns', side_effect=lambda: now[0]):
+ prepared = prepare_drag(mcp, spec)
+ with self.assertRaisesRegex(AssertionError, 'snapshot expired; no input sent'):
+ call_drag(mcp, spec, prepared, guard)
+ self.assertEqual(prepared['timing']['grounding_age_ns'], MAX_GROUNDING_AGE_NS + 1)
+ mcp.tool.assert_not_called()
+
+ def test_expired_or_retargeted_grounding_never_dispatches(self):
+ spec, mcp = plan()['agents'][0], Mock()
+ with patch('production_cancel_proof.grounded_snapshot', return_value={}), \
+ patch('production_cancel_proof.time.monotonic_ns', return_value=100):
+ prepared = prepare_drag(mcp, spec)
+ for change, now in [({}, 101 + MAX_GROUNDING_AGE_NS), ({}, 99),
+ ({'target': {'pid': 99, 'window_id': 99}}, 100),
+ ({'session': 'different'}, 100)]:
+ with patch('production_cancel_proof.time.monotonic_ns', return_value=now), self.assertRaises(AssertionError):
+ call_drag(mcp, spec, {**prepared, **change})
+ mcp.tool.assert_not_called()
+
+ def test_prepared_drag_does_not_snapshot_during_sibling_gesture(self):
+ spec, mcp = plan()['agents'][0], Mock()
+ mcp.tool.return_value = RESPONSE
+ with patch('production_cancel_proof.grounded_snapshot', return_value={}) as snapshot, \
+ patch('production_cancel_proof.time.monotonic_ns', return_value=100):
+ prepared = prepare_drag(mcp, spec)
+ result = call_drag(mcp, spec, prepared)
+ snapshot.assert_called_once()
+ self.assertEqual(result['outcome'], 'response')
+ mcp.tool.assert_called_once()
+
+ def test_pointer_snapshot_requires_own_exact_png(self):
+ spec = {**plan()['agents'][0], 'drag': {}, 'pointer_stage': 'select_range'}
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / 'image.png').touch()
+ content = {'snapshot_id': 's00000001', 'window_bounds': BOUNDS, 'screenshot_width': 800, 'screenshot_height': 600}
+ for image_file, valid in [('image.png', True), ('missing.png', False), ('../escape.png', False)]:
+ mcp = Mock(directory=root, process=Mock(pid=101, poll=Mock(return_value=None)), tool=Mock(side_effect=[
+ {'structuredContent': {'windows': [spec['target']]}},
+ {'structuredContent': content, 'content': [{'type': 'image', 'image_file': image_file}]}]))
+ if valid:
+ result = grounded_snapshot(mcp, spec['target'], spec)
+ self.assertEqual(result['proof_image'], str(root / 'image.png'))
+ self.assertNotIn('max_elements', mcp.tool.call_args.args[1])
+ else:
+ with self.assertRaises((AssertionError, FileNotFoundError)):
+ grounded_snapshot(mcp, spec['target'], spec)
+
+ def test_inkscape_pointer_snapshot_bounds_walk_without_limiting_depth(self):
+ spec = {**plan()['agents'][1], 'drag': {}, 'pointer_stage': 'move_rectangle'}
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ now = [100]
+ snapshots = [0]
+ def tool(name, arguments):
+ if name == 'list_windows':
+ now[0] = 200
+ return {'structuredContent': {'windows': [spec['target']]}}
+ now[0] = 300
+ snapshots[0] += 1
+ image_file = f'image-{snapshots[0]}.png'
+ (root / image_file).touch()
+ return {'structuredContent': {'snapshot_id': f's{snapshots[0]:08x}', 'window_bounds': BOUNDS, 'screenshot_width': 800,
+ 'screenshot_height': 600},
+ 'content': [{'type': 'image', 'image_file': image_file}]}
+ mcp = Mock(directory=root, process=Mock(pid=101, poll=Mock(return_value=None)), tool=Mock(side_effect=tool))
+ with patch('production_cancel_proof.time.monotonic_ns', side_effect=lambda: now[0]):
+ result = grounded_snapshot(mcp, spec['target'], spec)
+ self.assertEqual(result['proof_observation_started_ns'], 200)
+ self.assertEqual(result['proof_observation_finished_ns'], 300)
+ self.assertEqual(result['proof_runtime'], {'pid': 101, 'directory': str(root.resolve())})
+ self.assertEqual(mcp.tool.call_args.args, ('get_window_state', {
+ **spec['target'], 'session': spec['name'], 'max_elements': 2500}))
+ # A bounded walk is not permission to omit the existing oracle.
+ with patch('production_cancel_proof.pointer_grounding.read_pixels', return_value='pixels'):
+ with self.assertRaisesRegex(RuntimeError, 'snapshot has no semantic elements'):
+ prepare_drag(mcp, spec)
+ self.assertTrue(all(call.args[0] in ('list_windows', 'get_window_state')
+ for call in mcp.tool.call_args_list))
+
+ def test_cleanup_reaps_child_even_when_close_raises(self):
+ owned = client(100)
+ owned.close.side_effect = RuntimeError('close failed')
+ with self.assertRaisesRegex(RuntimeError, 'close failed'):
+ close_owned(owned)
+ owned.process.kill.assert_called_once_with()
+ owned.process.wait.assert_called_once_with(timeout=3)
+
+ def test_kill_one_exact_owned_process_and_poison_without_replay(self):
+ victim, sibling = client(100), client(101)
+ terminate_owned(victim, sibling, [Mock(done=lambda: False)])
+ self.assertTrue(victim.failed)
+ victim.process.kill.assert_called_once_with()
+ victim.process.wait.assert_called_once_with(timeout=3)
+ sibling.process.kill.assert_not_called()
+ victim.tool.assert_not_called()
+
+ def test_sigterm_is_preselected_and_never_falls_back_to_kill(self):
+ candidate = {**plan(), 'termination_signal': 'SIGTERM'}
+ validate_plan(candidate)
+ victim, sibling = client(100), client(101)
+ result = terminate_owned(victim, sibling, [Mock(done=lambda: False)], 'SIGTERM')
+ self.assertTrue(victim.failed)
+ self.assertEqual(result['signal'], 'SIGTERM')
+ self.assertEqual(result['pid'], 100)
+ victim.process.terminate.assert_called_once_with()
+ victim.process.kill.assert_not_called()
+ sibling.process.terminate.assert_not_called()
+ sibling.process.kill.assert_not_called()
+
+ victim = client(100)
+ victim.process.terminate.side_effect = None
+ victim.process.wait.side_effect = subprocess.TimeoutExpired('owned-driver', 3)
+ with self.assertRaises(subprocess.TimeoutExpired):
+ terminate_owned(victim, sibling, [Mock(done=lambda: False)], 'SIGTERM')
+ self.assertTrue(victim.failed)
+ victim.process.terminate.assert_called_once_with()
+ victim.process.kill.assert_not_called()
+
+ def test_unknown_signal_is_refused_before_process_mutation(self):
+ for signal in ('SIGINT', 'SIGSTOP', '', None, 9):
+ victim, sibling = client(100), client(101)
+ with self.assertRaises(AssertionError):
+ validate_plan({**plan(), 'termination_signal': signal})
+ with self.assertRaises(AssertionError):
+ terminate_owned(victim, sibling, [Mock(done=lambda: False)], signal)
+ self.assertFalse(victim.failed)
+ victim.process.kill.assert_not_called()
+ victim.process.terminate.assert_not_called()
+
+ def test_shared_exited_or_completed_process_cannot_be_killed(self):
+ for same, exited, done in [(True, False, False), (False, True, False), (False, False, True)]:
+ victim, sibling = client(100), client(100 if same else 101)
+ if exited:
+ victim.process.poll.return_value = 0
+ with self.assertRaises(AssertionError):
+ terminate_owned(victim, sibling, [Mock(done=lambda: done)])
+ victim.process.kill.assert_not_called()
+
+ def test_unknown_drag_is_called_once_with_fresh_grounding(self):
+ mcp, spec = Mock(), plan()['agents'][0]
+ mcp.tool.side_effect = TimeoutError('lost reply')
+ with patch('production_cancel_proof.grounded_snapshot', return_value={}) as snapshot:
+ result = call_drag(mcp, spec)
+ snapshot.assert_called_once_with(mcp, spec['target'], spec)
+ self.assertEqual(result['outcome'], 'unknown')
+ self.assertFalse(result['replayed'])
+ mcp.tool.assert_called_once_with('drag', {**spec['drag'], **spec['target'],
+ 'session': spec['name'], 'delivery_mode': 'background'})
+
+ def test_plan_rejects_unsafe_targets_profiles_and_unbounded_drags(self):
+ validate_plan(plan())
+ for change in ({'profile': {'mode': 'standard'}}, {'drag': {**plan()['agents'][0]['drag'], 'pid': 5}},
+ {'drag': {**plan()['agents'][0]['drag'], 'duration_ms': 2001}},
+ {'drag': {**plan()['agents'][0]['drag'], 'from_x': float('nan')}},
+ {'target': {'pid': 10, 'window_id': 200}}):
+ candidate = plan()
+ candidate['agents'][0].update(change)
+ with self.assertRaises(AssertionError):
+ validate_plan(candidate)
+
+ def test_snapshot_rejects_stale_identity_geometry_and_off_image_coordinates(self):
+ spec = plan()['agents'][0]
+ good = {'structuredContent': {'snapshot_id': 's00000001', 'window_bounds': BOUNDS, 'screenshot_width': 800, 'screenshot_height': 600}}
+ for windows, content in [([], good), ([{'pid': 20, 'window_id': 999}], good),
+ ([spec['target']], {'structuredContent': {**good['structuredContent'], 'window_bounds': {}}}),
+ ([spec['target']], {'structuredContent': {**good['structuredContent'], 'screenshot_width': 50}})]:
+ mcp = Mock(directory=Path.cwd(), process=Mock(pid=101, poll=Mock(return_value=None)),
+ tool=Mock(side_effect=[{'structuredContent': {'windows': windows}}, content]))
+ with self.assertRaises(AssertionError):
+ grounded_snapshot(mcp, spec['target'], spec)
+
+
+class ObservationTests(unittest.TestCase):
+ def test_counter_identity_and_original_chronology(self):
+ with tempfile.TemporaryDirectory() as directory:
+ observer = Mock(directory=Path(directory), process=Mock(pid=102, poll=Mock(return_value=None)))
+ runtime = {'pid': 102, 'directory': str(Path(directory).resolve())}
+ before = {'snapshot_id': 's00000001', 'proof_runtime': {**runtime, 'pid': 101},
+ 'proof_image': str(Path(directory) / 'before.png'),
+ 'proof_observation_started_ns': 10, 'proof_observation_finished_ns': 20}
+ after = {**before, 'proof_runtime': runtime, 'proof_image': str(Path(directory) / 'after.png'),
+ 'proof_observation_started_ns': 40, 'proof_observation_finished_ns': 50}
+ for failure in (None, 'cached', 'same_artifact', 'artifact_alias', 'same_runtime_counter',
+ 'wrong_runtime', 'dead', 'before_return', 'future', 'invalid_time'):
+ with self.subTest(failure=failure), patch('production_cancel_proof.time.monotonic_ns', return_value=60):
+ old, new = dict(before), dict(after)
+ observer.process.poll.return_value = 0 if failure == 'dead' else None
+ if failure == 'cached':
+ new.update(proof_observation_started_ns=10, proof_observation_finished_ns=20)
+ elif failure in ('same_artifact', 'artifact_alias'):
+ new['proof_image'] = old['proof_image'] if failure == 'same_artifact' else str(Path(directory) / 'unused' / '..' / 'before.png')
+ elif failure == 'same_runtime_counter':
+ old['proof_runtime'] = runtime
+ elif failure == 'wrong_runtime':
+ new['proof_runtime'] = old['proof_runtime']
+ elif failure == 'before_return':
+ new['proof_observation_started_ns'] = 29
+ elif failure == 'future':
+ new['proof_observation_finished_ns'] = 61
+ elif failure == 'invalid_time':
+ new['proof_observation_started_ns'] = True
+ if failure:
+ with self.assertRaises(AssertionError):
+ verify_fresh_observation(old, new, observer, after_ns=30)
+ else:
+ verify_fresh_observation(old, new, observer, after_ns=30)
+ self.assertEqual(new['proof_observation_started_ns'], 40)
+
+ def test_observation_rejects_runtime_exit_during_snapshot(self):
+ spec = plan()['agents'][0]
+ for polls in ([0], [None, 0]):
+ mcp = Mock(directory=Path.cwd(), process=Mock(pid=101, poll=Mock(side_effect=polls)),
+ tool=Mock(side_effect=[{'structuredContent': {'windows': [spec['target']]}},
+ {'structuredContent': {'window_bounds': BOUNDS, 'screenshot_width': 800, 'screenshot_height': 600}}]))
+ with self.subTest(polls=polls), self.assertRaisesRegex(AssertionError, 'process exited'):
+ grounded_snapshot(mcp, spec['target'], spec)
+ self.assertEqual(mcp.tool.call_count, len(polls))
+
+ def test_runtime_cache_cannot_restamp_reused_counter_or_image(self):
+ spec = {**plan()['agents'][0], 'drag': {}, 'pointer_stage': 'select_range'}
+ for failure in (None, 'counter', 'image'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / 'first.png').touch()
+ (root / 'second.png').touch()
+ def response(snapshot_id, image_file):
+ return {'structuredContent': {'snapshot_id': snapshot_id, 'window_bounds': BOUNDS,
+ 'screenshot_width': 800, 'screenshot_height': 600},
+ 'content': [{'type': 'image', 'image_file': image_file}]}
+ windows = {'structuredContent': {'windows': [spec['target']]}}
+ first = response('s00000001', 'first.png')
+ second = response('s00000001' if failure == 'counter' else 's00000002',
+ 'first.png' if failure == 'image' else 'second.png')
+ mcp = Mock(directory=root, process=Mock(pid=101, poll=Mock(return_value=None)),
+ tool=Mock(side_effect=[windows, first, windows, second]))
+ with patch('production_cancel_proof.time.monotonic_ns', side_effect=[10, 20, 40, 50]):
+ old = grounded_snapshot(mcp, spec['target'], spec)
+ if failure:
+ with self.assertRaisesRegex(AssertionError, 'reused'):
+ grounded_snapshot(mcp, spec['target'], spec)
+ else:
+ new = grounded_snapshot(mcp, spec['target'], spec)
+ self.assertEqual(new['proof_observation_started_ns'], 40)
+ self.assertEqual(old['proof_observation_started_ns'], 10)
+
+
+class RunnerTests(unittest.TestCase):
+ def test_success_and_failures_reap_all_owned_children_without_replay(self):
+ for failure in (None, 'sigterm', 'pointer', 'pointer_partial', 'pointer_effect', 'pointer_endpoint', 'pointer_anchor',
+ 'pointer_coordinates', 'trace', 'unknown_sibling',
+ 'successful_victim', 'close', 'snapshot', 'grab', 'primary_before', 'primary_after', 'dispatch_budget',
+ 'prepare_budget',
+ 'recovery_calc', 'recovery_inkscape', 'recovery_effect', 'recovery_close', 'recovery_trace'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ source_plan = root / 'plan.json'
+ candidate = plan()
+ if failure == 'sigterm':
+ candidate['termination_signal'] = 'SIGTERM'
+ recovery = failure is not None and failure.startswith('recovery_')
+ pointer = failure is not None and failure.startswith('pointer')
+ if pointer or recovery:
+ for spec, stage in zip(candidate['agents'], ('select_range', 'move_rectangle')):
+ spec.update(drag={}, pointer_stage=stage)
+ if recovery:
+ candidate['kill_agent'] = 1 if failure == 'recovery_inkscape' else 0
+ candidate['recovery'] = {'pointer_stage': 'scroll_down' if candidate['kill_agent'] else 'click_b2'}
+ victim = candidate['kill_agent']
+ source_plan.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=source_plan, evidence=root / 'evidence', driver=root / 'driver',
+ trace_socket=root / 'cua-input-v3.sock', primary_grab=root / 'primary-grab',
+ foreground_journal=root / 'journal')
+ agents, observer = [client(100), client(101)], client(102)
+ fresh = client(103)
+ fresh.tool.side_effect = [{}, RESPONSE]
+ for owned in [*agents, observer, fresh]:
+ owned.close.side_effect = lambda c=owned: setattr(c.process.poll, 'return_value', 0)
+ if failure == 'recovery_close':
+ fresh.close.side_effect = RuntimeError('recovery close failed')
+ observer.tool.return_value = {'structuredContent': {'screen_width': 1000, 'screen_height': 800}}
+ for agent in agents:
+ agent.tool.return_value = {'structuredContent': {}}
+ held = [True]
+ grab = Mock(stdout=Mock(), poll=Mock(return_value=None))
+ if failure == 'primary_before':
+ grab.poll.return_value = 0
+ trace_client = Mock(hello={'protocol': 3})
+ make_trace = wire_trace if pointer or recovery else trace
+ stopped = make_trace(FINISH, False)
+ if failure in ('pointer_endpoint', 'pointer_coordinates'):
+ endpoint = next(row for row in stopped['events']
+ if row[2] == 'pointer_motion' and row[7:9] == [200, 200])
+ if failure == 'pointer_endpoint':
+ endpoint[7:9] = [199, 199]
+ else:
+ del endpoint[7:9]
+ if failure == 'trace':
+ stopped['overflow'] = True
+ trace_client.collect.side_effect = [make_trace(START), make_trace(FIRST), make_trace(OVERLAP), stopped]
+ if recovery:
+ rows = recovery_rows('scroll' if victim else 'click')
+ complete = make_trace(rows + [(2015, 'agent_cancel', 1, 0), (2016, 'pointer_leave', 1, 0),
+ (2017, 'agent_cancel', 2, 0), (2018, 'keyboard_leave', 2, 0), (2020, 'stop', 0, 0)], False)
+ if failure == 'recovery_trace':
+ complete['overflow'] = True
+ trace_client.collect.side_effect = [make_trace(START), make_trace(FIRST), make_trace(OVERLAP),
+ make_trace(FINISH[:-1]), *([] if failure == 'recovery_effect' else [make_trace(rows)]), complete]
+ outcomes = [{'outcome': 'unknown', 'replayed': False},
+ {'outcome': 'response', 'response': RESPONSE, 'replayed': False}]
+ if failure == 'unknown_sibling':
+ outcomes[1] = outcomes[0]
+ if failure == 'successful_victim':
+ outcomes[0] = outcomes[1]
+ if failure == 'pointer_partial':
+ outcomes[0] = {'outcome': 'response', 'response': {'structuredContent': {
+ **RESPONSE['structuredContent'], 'effect': 'partial',
+ 'delivery': {'mode': 'background', 'delivered_count': 3}}}, 'replayed': False}
+ futures = [Mock(done=Mock(return_value=False), result=Mock(return_value=o)) for o in outcomes]
+ for future in futures:
+ def finish(*args, f=future, **kwargs):
+ f.done.return_value = True
+ return f.result.return_value
+ future.result.side_effect = finish
+ pool = Mock(submit=Mock(side_effect=futures))
+ proof_image = root / 'fresh.png'
+ proof_image.write_bytes(b'synthetic-test-image')
+ snapshot = Mock(return_value={'window_bounds': BOUNDS, 'proof_image': str(proof_image)})
+ if failure == 'prepare_budget':
+ snapshot.return_value['proof_observation_started_ns'] = 1
+ if failure == 'snapshot':
+ snapshot.side_effect = AssertionError('stale geometry')
+ if failure == 'primary_after':
+ def primary_exits_after_action(*args, **kwargs):
+ if kwargs.get('session') is False:
+ grab.poll.return_value = 0
+ return snapshot.return_value
+ snapshot.side_effect = primary_exits_after_action
+ if failure == 'close':
+ agents[0].close.side_effect = RuntimeError('cleanup failure')
+ sibling_effect = {'verified': True, 'app': candidate['agents'][1 - victim]['app'],
+ 'observed_delta': [80, 80] if failure == 'pointer_anchor' else [90, 90]}
+ replacements = {
+ 'provenance': Mock(return_value={'files': {}}), 'DirectMCP': Mock(side_effect=[*agents, observer, fresh]),
+ 'app_process_identity': Mock(return_value={'pid': candidate['agents'][victim]['target']['pid']}),
+ 'grounded_snapshot': snapshot, 'subprocess.Popen': Mock(return_value=grab),
+ 'primary_acknowledgement': Mock(side_effect=AssertionError('missing HELD')) if failure == 'grab' else Mock(return_value='HELD\n'),
+ 'wait_for': lambda fn: self.assertTrue(fn()),
+ 'state': lambda path: {'held': held[0], 'clicks': 0, 'keys': 0, 'scroll': 0},
+ 'wm': lambda: {'pid': 10, 'cursor': {'x': 100, 'y': 100}}, 'Trace': Mock(return_value=trace_client),
+ 'ThreadPoolExecutor': Mock(return_value=pool), 'stop_process': lambda proc: held.__setitem__(0, False),
+ 'pointer_grounding.read_pixels': Mock(return_value='pixels'),
+ 'pointer_grounding.action': Mock(side_effect=lambda before, pixels, app, stage:
+ (plan()['agents'][0]['drag'] if stage in ('select_range', 'move_rectangle') else {'x': 20, 'y': 30},
+ {'app': app, 'stage': stage})),
+ 'pointer_grounding.verify': Mock(side_effect=AssertionError('sibling did not move'))
+ if failure == 'pointer_effect' else Mock(side_effect=[sibling_effect, AssertionError('recovery no effect')])
+ if failure == 'recovery_effect' else Mock(return_value=sibling_effect),
+ 'print': Mock(),
+ }
+ # The real concurrent preparation helper has its own barrier
+ # tests. Keep this runner's fake executor scoped to actions.
+ def observations(owned, specs, save):
+ prepared = [prepare_drag(c, s) for c, s in zip(owned, specs)]
+ for i, item in enumerate(prepared):
+ if failure == 'dispatch_budget':
+ item['prepared_ns'] -= MAX_GROUNDING_AGE_NS
+ save(f'agent-{i}-drag-grounding.json', item)
+ return prepared
+ if failure == 'prepare_budget':
+ # Exercise the real bounded preparation loop, including
+ # its two read-only executors and failure cleanup.
+ executor_count = [0]
+ def executor(*args, **kwargs):
+ executor_count[0] += 1
+ return pool if executor_count[0] == 1 else ThreadPoolExecutor(*args, **kwargs)
+ replacements['ThreadPoolExecutor'] = executor
+ replacements['prepare_drag'] = Mock(wraps=prepare_drag)
+ else:
+ replacements['prepare_drags'] = observations
+ for name, value in replacements.items():
+ stack.enter_context(patch('production_cancel_proof.' + name, value))
+ self.assertEqual(run(args), 0 if failure in (None, 'sigterm', 'pointer', 'pointer_partial', 'recovery_calc', 'recovery_inkscape') else 1)
+ result = json.loads((args.evidence / 'result.json').read_text())
+ if failure == 'sigterm':
+ self.assertEqual(result['termination']['signal'], 'SIGTERM')
+ agents[victim].process.terminate.assert_called_once_with()
+ agents[victim].process.kill.assert_not_called()
+ if not recovery:
+ self.assertEqual(result['reacquisition'], 'unproven')
+ else:
+ self.assertEqual(result['reacquisition']['result'], 'unproven' if failure == 'recovery_effect' else 'verified')
+ self.assertEqual(result['cancellation']['victim_lane'], 1)
+ self.assertEqual(result['termination']['pid'], agents[victim].process.pid)
+ self.assertEqual(result['saved_app_effects'], 'unproven')
+ self.assertEqual(result['interrupted_state']['saved_document_effect'], 'unproven')
+ self.assertEqual(proof_image.read_bytes(), b'synthetic-test-image')
+ self.assertTrue((args.evidence / 'interrupted-state.json').is_file())
+ self.assertTrue((args.evidence / 'recovery-grounding.json').is_file())
+ self.assertTrue((args.evidence / 'recovery-after.json').is_file())
+ self.assertEqual(fresh.tool.call_count, 2)
+ fresh.close.assert_called_once()
+ self.assertIsNotNone(fresh.process.poll())
+ if failure in ('pointer', 'pointer_effect'):
+ replacements['pointer_grounding.verify'].assert_called_once()
+ self.assertEqual(replacements['pointer_grounding.action'].call_count, 2)
+ self.assertTrue((args.evidence / 'agent-0-drag-grounding.json').is_file())
+ self.assertTrue((args.evidence / 'agent-1-drag-grounding.json').is_file())
+ if failure in ('pointer', 'pointer_partial') or recovery:
+ self.assertEqual(result['sibling_app_effect'], sibling_effect)
+ if failure != 'recovery_trace':
+ self.assertTrue(result['sibling_pointer_delivery']['verified'])
+ self.assertEqual(result['sibling_pointer_delivery']['lane'], 2)
+ if failure == 'pointer_partial':
+ self.assertEqual(result['actions'][str(victim)], outcomes[0])
+ self.assertEqual(result['saved_app_effects'], 'unproven')
+ if pointer and failure not in ('pointer', 'pointer_partial'):
+ self.assertEqual(result['sibling_pointer_delivery'], 'unproven')
+ self.assertEqual(result['actions'][str(victim)]['outcome'], 'unknown')
+ self.assertFalse(result['actions'][str(victim)]['replayed'])
+ if failure != 'pointer_effect':
+ self.assertEqual(result['sibling_app_effect'], sibling_effect)
+ self.assertIn('finish_trace', (args.evidence / 'cleanup.json').read_text())
+ agents[0].close.assert_called_once()
+ if failure != 'snapshot':
+ agents[1].close.assert_called_once()
+ observer.close.assert_called_once()
+ self.assertFalse(held[0])
+ if failure == 'primary_before':
+ pool.submit.assert_not_called()
+ agents[victim].process.kill.assert_not_called()
+ self.assertIn('primary', result['error'])
+ if failure == 'primary_after':
+ self.assertIn('primary', result['error'])
+ if failure in ('dispatch_budget', 'prepare_budget'):
+ pool.submit.assert_not_called()
+ self.assertNotIn('termination', result)
+ self.assertIn('no input sent', result['error'])
+ for i, owned in enumerate(agents):
+ owned.process.kill.assert_not_called()
+ owned.process.terminate.assert_not_called()
+ saved = json.loads((args.evidence / f'agent-{i}-drag-grounding.json').read_text())
+ self.assertGreaterEqual(saved['timing']['pair_grounding_age_ns'], MAX_GROUNDING_AGE_NS)
+ trace_client.close.assert_called_once()
+ if failure == 'prepare_budget':
+ self.assertEqual(replacements['prepare_drag'].call_count, 4)
+ self.assertEqual(executor_count[0], 3)
+ for attempt in (1, 2):
+ saved_attempt = json.loads((args.evidence / f'drag-grounding-attempt-{attempt}.json').read_text())
+ self.assertFalse(saved_attempt['ready'])
+ self.assertFalse(saved_attempt['input_attempted'])
+ self.assertFalse((args.evidence / 'drag-grounding-attempt-3.json').exists())
+ if failure not in ('snapshot', 'grab', 'primary_before', 'dispatch_budget', 'prepare_budget'):
+ self.assertEqual(pool.submit.call_count, 2)
+ if failure == 'sigterm':
+ agents[victim].process.terminate.assert_called_once()
+ else:
+ agents[victim].process.kill.assert_called_once()
+ agents[1 - victim].process.kill.assert_not_called()
+ trace_client.close.assert_called_once()
+ self.assertEqual(trace_client.exchange.call_args_list[0].args, ('TRACE_START',))
+ self.assertEqual(trace_client.exchange.call_args_list[-1].args, ('TRACE_STOP',))
+
+ def test_missing_trace_stops_before_native_process_launch(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source_plan = root / 'plan.json'
+ source_plan.write_text(json.dumps(plan()))
+ with patch('production_cancel_proof.provenance') as origin, patch('production_cancel_proof.DirectMCP') as launch:
+ self.assertEqual(run(SimpleNamespace(plan=source_plan, evidence=root / 'evidence', trace_socket=None)), 1)
+ origin.assert_not_called()
+ launch.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.py
new file mode 100644
index 0000000000..906f1815f7
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.py
@@ -0,0 +1,713 @@
+"""Production v3 config/keymap fault proof for an exact disposable VM.
+
+Use the geometry proof CLI flags. The plan has purpose=desktop_fault, one
+Calc/Inkscape pointer agent and new-action recovery as in the geometry proof.
+fault={kind:config_disable|keymap}; vm={machine_id,boot_id}; compositor includes
+pid,instance,uid,starttime,exe; config includes absolute path,device,inode,uid,
+mode,sha256. Config-disable requires the already sourced, exact ENABLED Lua
+include from input_config_toggle. Main configuration and policy are never edited.
+
+Config suspension disconnects the trace transport. Restore the fixture, reconnect
+without TRACE_START, and require unchanged trace history with cancellation and
+owned release BEFORE restoration. Normal Driver snapshots and one NEW action
+then prove recovery. No replay, signing, module swap, automatic wake or unlock.
+Keymap uses the separate exact KEYMAP_US include, changes only to KEYMAP_DE,
+and restores the same original US map. Exact option readback, compositor lane
+generation changes and the compiled-map-gated unsupported_layout refusal from
+a fresh normal Driver action prove invalidation; no keymap hash is exposed.
+The keymap fixture has a fixed 30-second restoration watchdog to cover the
+fresh-runtime refusal and both app snapshots; config-disable keeps 12 seconds.
+Watchdog restoration, stale grounding, or readback crossing either deadline
+still fails the episode. Neither duration is a product cancellation limit.
+DPMS and lock are deliberately unsupported here. Portable tests prepare
+this proof; only execution on the exact native candidate can certify a row.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import select
+import socket
+import stat
+import struct
+import subprocess
+import sys
+import tempfile
+import time
+
+from desktop_faults import _identity, _same_compositor, _hypr
+from input_config_toggle import ENABLED, DISABLED
+from driver_input_live import state, wait_for, wm
+from primary_trace import Trace, analyze
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, active_drags, call_drag, close_owned,
+ grounded_snapshot, poll_active, prepare_drag, stopped_prefix, verify_recovery_cleanup)
+from production_geometry_fault_proof import recover, fault_outcome, validate_plan as geometry_plan
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity, check_response, primary_acknowledgement,
+ provenance, require_primary_active, trace_interval)
+from realapp_proof import cleanup_all, released_synthetic_input
+import production_pointer_grounding as pointer_grounding
+
+
+KEYMAP_US = 'hl.config({input = {kb_rules = "evdev", kb_model = "pc105", kb_layout = "us", kb_variant = "", kb_options = "", kb_file = ""}})\n'
+KEYMAP_DE = 'hl.config({input = {kb_rules = "evdev", kb_model = "pc105", kb_layout = "de", kb_variant = "", kb_options = "", kb_file = ""}})\n'
+WATCHDOG_SECONDS = {'config_disable': 12, 'keymap': 30}
+
+
+def fixed_bytes(kind):
+ assert kind in ('config_disable', 'keymap'), 'unsupported desktop fault'
+ return (ENABLED, DISABLED) if kind == 'config_disable' else (KEYMAP_US, KEYMAP_DE)
+
+
+def keymap_options(instance, restored):
+ expected = {'kb_rules': 'evdev', 'kb_model': 'pc105', 'kb_layout': 'us' if restored else 'de',
+ 'kb_variant': '', 'kb_options': '', 'kb_file': ''}
+ replies = {key: json.loads(_hypr(instance, '-j', 'getoption', 'input:' + key)) for key in expected}
+ verify_keymap_options(replies, restored)
+ return replies
+
+
+def verify_keymap_options(replies, restored):
+ expected = {'kb_rules': 'evdev', 'kb_model': 'pc105', 'kb_layout': 'us' if restored else 'de',
+ 'kb_variant': '', 'kb_options': '', 'kb_file': ''}
+ assert set(replies) == set(expected), 'incomplete keymap option readback'
+ for key, value in expected.items():
+ assert replies[key].get('option') == 'input:' + key and replies[key].get('str') == value, \
+ 'exact sourced keymap option not observed'
+
+
+def keymap_lanes(status, *, cleared=False):
+ verify_status(status, True)
+ lanes = {row['lane']: row for row in status['input']['lanes']}
+ for row in lanes.values():
+ assert isinstance(row.get('epoch'), str) and row['epoch'], 'missing compositor epoch'
+ assert type(row.get('desktop_generation')) is int and row['desktop_generation'] >= 0
+ assert type(row.get('dispatches')) is int and row['dispatches'] >= 0
+ if cleared:
+ assert all(type(row.get(key)) is int and row[key] == 0 for key in ('held_button', 'held_keys'))
+ assert all(row.get(key) is False for key in ('drag_active', 'lease_active', 'pointer_focus', 'keyboard_focus'))
+ return lanes
+
+
+def verify_keymap_transition(before, after):
+ old, new = keymap_lanes(before), keymap_lanes(after, cleared=True)
+ for lane in old:
+ assert old[lane]['epoch'] == new[lane]['epoch'], 'compositor lane replaced'
+ assert new[lane]['desktop_generation'] > old[lane]['desktop_generation'], 'keymap did not invalidate authority'
+ assert new[lane].get('reserved') is False, 'pre-transition reservation survived'
+
+
+def idle_lanes(status):
+ """Before a new episode, only unreserved inert pointer focus may remain.
+
+ Runtime close retires input authority without removing passive hover.
+ This is not the stronger post-keymap/DPMS/lock transition assertion.
+ """
+ rows = keymap_lanes(status)
+ for row in rows.values():
+ assert all(type(row.get(key)) is int and row[key] == 0
+ for key in ('held_button', 'held_keys')), 'pre-fault input still held'
+ assert all(row.get(key) is False for key in
+ ('drag_active', 'lease_active', 'keyboard_focus', 'reserved')), 'pre-fault authority remains'
+ assert type(row.get('pointer_focus')) is bool, 'missing pre-fault pointer state'
+ return rows
+
+
+def digest(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def guest_identity():
+ return {'machine_id': Path('/etc/machine-id').read_text().strip(),
+ 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip()}
+
+
+def file_identity(path):
+ """Reject links, aliases, shared files and non-private parent directories."""
+ path = Path(path)
+ assert path.is_absolute() and path.resolve(strict=True) == path, 'canonical config path required'
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ try:
+ info = os.fstat(fd)
+ assert stat.S_ISREG(info.st_mode) and info.st_nlink == 1, 'regular unlinked config required'
+ assert info.st_uid == os.getuid() and not info.st_mode & 0o022, 'config ownership or permissions'
+ assert info.st_size <= 4096, 'bounded dedicated include required'
+ data = os.read(fd, 4097)
+ assert len(data) == info.st_size and len(data) <= 4096, 'config changed during read'
+ fields = ('st_dev', 'st_ino', 'st_uid', 'st_gid', 'st_mode', 'st_size', 'st_mtime_ns', 'st_ctime_ns', 'st_nlink')
+ assert all(getattr(observed, key) == getattr(info, key)
+ for observed in (path.lstat(), os.fstat(fd)) for key in fields), 'config changed during read'
+ return {'device': info.st_dev, 'inode': info.st_ino, 'uid': info.st_uid,
+ 'mode': stat.S_IMODE(info.st_mode), 'sha256': digest(data)}
+ finally:
+ os.close(fd)
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'desktop_fault' and set(plan['fault']) == {'kind'}
+ original, _ = fixed_bytes(plan['fault']['kind'])
+ # Reuse the strict existing target/grounding/recovery plan checks unchanged.
+ bounds = plan['agents'][0]['bounds']
+ geometry_plan({**plan, 'purpose': 'geometry_fault',
+ 'compositor': {key: plan['compositor'][key] for key in ('pid', 'instance')},
+ 'fault': {'kind': 'move', 'to': [bounds['x'] + 1, bounds['y']]}})
+ assert set(plan['vm']) == {'machine_id', 'boot_id'}
+ assert re.fullmatch(r'[0-9a-f]{32}', plan['vm']['machine_id'])
+ assert re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', plan['vm']['boot_id'])
+ compositor = plan['compositor']
+ assert set(compositor) == {'pid', 'instance', 'uid', 'starttime', 'exe'}
+ assert type(compositor['uid']) is int and compositor['uid'] >= 0
+ assert re.fullmatch(r'[0-9]+', compositor['starttime'])
+ assert Path(compositor['exe']).is_absolute() and Path(compositor['exe']).name == 'Hyprland'
+ config = plan['config']
+ assert set(config) == {'path', 'device', 'inode', 'uid', 'mode', 'sha256'}
+ assert Path(config['path']).is_absolute()
+ assert all(type(config[key]) is int and config[key] >= 0 for key in ('device', 'inode', 'uid', 'mode'))
+ assert config['sha256'] == digest(original.encode()), 'only the exact dedicated include is permitted'
+
+
+def _guard(config):
+ assert platform.system() == 'Linux' and guest_identity() == config['vm'], 'wrong disposable VM'
+ assert subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode == 0, 'virtual machine required'
+ assert os.environ.get('HYPRLAND_INSTANCE_SIGNATURE') == config['instance'], 'wrong session'
+ assert config['compositor']['uid'] == os.getuid() and Path(config['compositor']['exe']).name == 'Hyprland'
+ _same_compositor(config['compositor'], config['instance'])
+ parent = Path(config['path']).parent
+ info = parent.lstat()
+ assert parent.resolve(strict=True) == parent and stat.S_ISDIR(info.st_mode)
+ assert [info.st_dev, info.st_ino, info.st_uid, stat.S_IMODE(info.st_mode)] == config['directory'], 'config directory changed'
+
+
+@contextmanager
+def _locked(config):
+ # Separate opens in parent/watchdog give separate flock descriptions.
+ import fcntl
+ _guard(config)
+ fd = os.open(str(Path(config['path']).parent), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ _guard(config)
+ yield
+ finally:
+ os.close(fd)
+
+
+def _replace(config, enabled, before_replace=None):
+ """Atomic replacement from fixed, pre-created files with known identities."""
+ _guard(config)
+ current = file_identity(config['path'])
+ known = config['files']
+ original, changed = fixed_bytes(config.get('kind', 'config_disable'))
+ assert set(known) == {'original', 'disabled', 'restored'}
+ for name, data in (('original', original), ('disabled', changed), ('restored', original)):
+ assert known[name]['identity']['sha256'] == digest(data.encode()), 'only fixed toggle bytes are permitted'
+ assert Path(known[name]['path']).parent == Path(config['path']).parent, 'stage escaped config directory'
+ assert known['original']['path'] == config['path']
+ assert current in [row['identity'] for row in known.values()], 'unowned config change; restoration refused'
+ wanted = 'restored' if enabled else 'disabled'
+ if enabled and current in (known['original']['identity'], known['restored']['identity']):
+ return
+ assert current == known['disabled' if enabled else 'original']['identity'], 'invalid config transition'
+ staged = known[wanted]
+ assert file_identity(staged['path']) == staged['identity'], 'staged config changed'
+ assert file_identity(config['path']) == current, 'config changed before atomic replacement'
+ if before_replace:
+ before_replace()
+ os.replace(staged['path'], config['path'])
+ assert file_identity(config['path']) == staged['identity'], 'atomic config replacement not observed'
+
+
+def verify_status(status, enabled):
+ assert 'experiment' not in status, 'signed experiment is not production evidence'
+ production = status.get('input', {})
+ assert production.get('protocol') == 3 and production.get('test_only') is False, 'production v3 required'
+ assert production.get('seat_lifetime') == 'compositor' and production.get('upgrade') == 'desktop_restart'
+ assert status.get('configured') is enabled and status.get('transport', {}).get('ready') is enabled
+ assert production.get('transport_ready') is enabled, 'input transport state not acknowledged'
+ assert len(production.get('lanes', [])) == 2 and {r['lane'] for r in production['lanes']} == {0, 1}
+ if not enabled:
+ assert all(type(row.get('held_button')) is int and row['held_button'] == 0 and
+ type(row.get('held_keys')) is int and row['held_keys'] == 0 and
+ row.get('drag_active') is False and row.get('lease_active') is False
+ for row in production['lanes']), 'disabled input still held'
+ return status
+
+
+def production_status(instance, enabled):
+ return verify_status(json.loads(_hypr(instance, '-j', 'cua:status')), enabled)
+
+
+def verify_trace_peer(trace, config):
+ peer = struct.unpack('3i', trace.socket.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
+ assert peer[:2] == (config['compositor']['pid'], config['compositor']['uid']), 'wrong trace compositor peer'
+ assert trace.hello['protocol'] == 3
+ _guard(config)
+
+
+def connect_trace(path, config):
+ _guard(config)
+ expected = Path(os.environ['XDG_RUNTIME_DIR']) / 'hypr' / config['instance'] / path.name
+ assert path.is_absolute() and path == expected and path.resolve(strict=True) == path, 'wrong trace socket path'
+ info = path.lstat()
+ assert stat.S_ISSOCK(info.st_mode) and info.st_uid == config['compositor']['uid']
+ trace = Trace(path)
+ try:
+ verify_trace_peer(trace, config)
+ return trace
+ except BaseException:
+ trace.close()
+ raise
+
+
+def _reload(config, enabled):
+ _guard(config)
+ assert _hypr(config['instance'], 'reload') == 'ok', 'config reload refused'
+ return production_status(config['instance'], enabled or config.get('kind') == 'keymap')
+
+
+def restore_config(config):
+ with _locked(config):
+ started = time.monotonic_ns()
+ untouched = file_identity(config['path']) == config['files']['original']['identity']
+ _replace(config, True)
+ status = production_status(config['instance'], True) if untouched else _reload(config, True)
+ original, _ = fixed_bytes(config.get('kind', 'config_disable'))
+ assert Path(config['path']).read_bytes() == original.encode(), 'exact config bytes not restored'
+ options = keymap_options(config['instance'], True) if config.get('kind') == 'keymap' else None
+ record = {'result': 'restored', 'started_ns': started, 'observed_ns': time.monotonic_ns(),
+ 'config': file_identity(config['path']), 'status': status}
+ if options is not None:
+ record['keymap_options'] = options
+ return record
+
+
+def watchdog(config, cancel_fd):
+ record = {'result': 'failed'}
+ try:
+ _guard(config)
+ print('ARMED', flush=True)
+ delay = max(0, (config['deadline_ns'] - time.monotonic_ns()) / 1e9)
+ ready = select.select([cancel_fd], [], [], delay)[0]
+ if ready and os.read(cancel_fd, 1) == b'C':
+ record = {'result': 'cancelled_after_restoration'}
+ else:
+ record = restore_config(config)
+ except BaseException as error:
+ record['error'] = str(error)
+ finally:
+ Path(config['record']).write_text(json.dumps(record))
+
+
+class ConfigFault:
+ def __init__(self, plan, evidence):
+ validate_plan(plan)
+ kind = plan['fault']['kind']
+ original, changed = fixed_bytes(kind)
+ assert platform.system() == 'Linux', 'disposable Linux VM required'
+ assert subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode == 0
+ expected = plan['compositor']
+ compositor = {key: expected[key] for key in ('pid', 'uid', 'starttime', 'exe')}
+ assert compositor['uid'] == os.getuid() and _identity(compositor['pid']) == compositor
+ path = Path(plan['config']['path'])
+ assert file_identity(path) == {k: v for k, v in plan['config'].items() if k != 'path'}
+ assert path.read_bytes() == original.encode(), 'not the dedicated sourced include'
+ parent = path.parent.stat()
+ assert parent.st_uid == os.getuid() and not parent.st_mode & 0o022, 'private owned config directory required'
+ self.config = {'kind': kind, 'vm': plan['vm'], 'compositor': compositor, 'instance': expected['instance'],
+ 'path': str(path), 'directory': [parent.st_dev, parent.st_ino, parent.st_uid, stat.S_IMODE(parent.st_mode)],
+ 'record': str((evidence / 'config-watchdog.json').resolve()), 'files': {
+ 'original': {'path': str(path), 'identity': file_identity(path)}}}
+ self.record, self.restoration = {'result': 'unproven', 'kind': kind}, None
+ self.child = self.cancel_fd = None
+ self.mutated = False
+ _guard(self.config)
+ self.record['before'] = production_status(expected['instance'], True)
+ (evidence / 'pre-fault-status.json').write_text(json.dumps(self.record['before']))
+ if kind == 'keymap':
+ self.record['keymap_before'] = keymap_options(expected['instance'], True)
+ idle_lanes(self.record['before'])
+ # Files are prepared before the watchdog and before any live drag.
+ # Known inodes let either process reject an unrelated replacement.
+ try:
+ for name, data in (('disabled', changed.encode()), ('restored', original.encode())):
+ fd, staged = tempfile.mkstemp(prefix='.cua-config-proof-', suffix='.stage', dir=path.parent)
+ with os.fdopen(fd, 'wb') as stream:
+ os.fchmod(stream.fileno(), plan['config']['mode'])
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ self.config['files'][name] = {'path': staged, 'identity': file_identity(staged)}
+ except BaseException:
+ self._clean_staged()
+ raise
+
+ def _clean_staged(self):
+ for name, row in self.config['files'].items():
+ if name != 'original' and Path(row['path']).exists():
+ assert file_identity(row['path']) == row['identity'], 'staged file changed; preserve it'
+ Path(row['path']).unlink()
+
+ def arm(self):
+ assert self.child is None, 'one watchdog per episode'
+ self.config['deadline_ns'] = time.monotonic_ns() + WATCHDOG_SECONDS[self.config['kind']] * 1_000_000_000
+ reader, self.cancel_fd = os.pipe()
+ try:
+ self.child = subprocess.Popen([sys.executable, str(Path(__file__).resolve()),
+ '--watchdog', json.dumps(self.config), str(reader)], pass_fds=(reader,),
+ stdout=subprocess.PIPE, text=True, start_new_session=True)
+ assert select.select([self.child.stdout], [], [], 2)[0], 'watchdog failed to arm'
+ assert self.child.stdout.readline().strip() == 'ARMED', 'watchdog rejected identity'
+ finally:
+ os.close(reader)
+
+ def inject(self, trace, initial, pending, guard):
+ assert self.child and self.child.poll() is None, 'live restoration watchdog required'
+ prefix, lanes = poll_active(trace, initial, None, [pending])
+ gate_ns = time.monotonic_ns()
+ with _locked(self.config):
+ if self.config.get('kind') == 'keymap':
+ self.record['gate_status'] = production_status(self.config['instance'], True)
+ previous = keymap_lanes(self.record['before'])
+ current = keymap_lanes(self.record['gate_status'])
+ for lane in previous:
+ assert all(previous[lane][key] == current[lane][key] for key in ('epoch', 'desktop_generation'))
+ active = current[next(iter(lanes)) - 1]
+ assert active['drag_active'] is True and active['lease_active'] is True
+ assert type(active['held_button']) is int and active['held_button'] > 0, 'drag ended before keymap fault'
+ self.record['keymap_before'] = keymap_options(self.config['instance'], True)
+ def authorize():
+ # Run AFTER all potentially blocking identity checks, directly
+ # before replacement: a slow guard must not authorize stale input.
+ assert self.child.poll() is None
+ guard()
+ assert not pending.done(), 'drag returned before config fault'
+ requested_ns = time.monotonic_ns()
+ assert 0 <= requested_ns - gate_ns <= 250_000_000, 'stale fault gate'
+ assert requested_ns + 3_000_000_000 < self.config['deadline_ns'], 'watchdog deadline too near'
+ self.record.update(prefix=prefix, lane=next(iter(lanes)), gate_ns=gate_ns,
+ requested_ns=requested_ns, watchdog_deadline_ns=self.config['deadline_ns'])
+ self.mutated = True # Lost replies still require restoration.
+ _replace(self.config, False, before_replace=authorize)
+ self.record['after'] = _reload(self.config, False)
+ if self.config.get('kind') == 'keymap':
+ self.record['keymap_after'] = keymap_options(self.config['instance'], False)
+ verify_keymap_transition(self.record['gate_status'], self.record['after'])
+ self.record['acknowledged_ns'] = time.monotonic_ns()
+ self.record['config'] = file_identity(self.config['path'])
+ self.record['result'] = 'observed'
+ guard()
+ return prefix, self.record['lane']
+
+ def restore(self):
+ if self.restoration is None:
+ if self.mutated:
+ self.restoration = restore_config(self.config)
+ else:
+ self.restoration = {'result': 'not_needed'}
+ if self.cancel_fd is not None:
+ try:
+ os.write(self.cancel_fd, b'C')
+ except BrokenPipeError:
+ pass
+ return self.restoration
+
+ def close(self):
+ try:
+ self.restore()
+ finally:
+ if self.cancel_fd is not None:
+ os.close(self.cancel_fd) # EOF independently restores after failure.
+ self.cancel_fd = None
+ if self.child:
+ self.child.wait(timeout=5)
+ self.child.stdout.close()
+ if self.restoration is not None:
+ self._clean_staged()
+
+
+def verify_cancelled(boundary, record, before_restore_ns):
+ """Check the live fault before any restoration or new action is attempted."""
+ prefix, lane = record['prefix'], record['lane']
+ assert set(active_drags(prefix)) == {lane}
+ tail = trace_interval(prefix, boundary)
+ assert prefix['events'][-1][1] <= record['gate_ns'] <= record['requested_ns'] <= record['acknowledged_ns']
+ assert record['acknowledged_ns'] <= before_restore_ns
+ assert 0 <= record['requested_ns'] - record['gate_ns'] <= 250_000_000
+ synthetic = [row for row in tail if row[5] in (1, 2)]
+ assert all(row[5] == lane for row in synthetic), 'cleanup crossed lanes'
+ cancelled = [row for row in synthetic if row[2] == 'agent_cancel']
+ assert len(cancelled) == 1 and record['requested_ns'] <= cancelled[0][1] < before_restore_ns, 'no cancellation during fault'
+ assert not any(row[2] in ('agent_admitted', 'agent_drag_start', 'agent_drag_end', 'agent_action_end',
+ 'keyboard_key', 'pointer_axis') for row in synthetic), 'extra action or false completion'
+ releases = [row for row in synthetic if row[2] == 'pointer_button']
+ assert len(releases) == 1 and releases[0][6] == 0 and releases[0][0] > cancelled[0][0]
+ assert releases[0][1] < before_restore_ns, 'release was delayed until restoration'
+ assert not any(row[2] in ('pointer_motion', 'pointer_enter') and row[0] > cancelled[0][0] for row in synthetic)
+ stopped = stopped_prefix(boundary)
+ isolation = analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ return isolation
+
+
+def verify_layout_refusal(record):
+ assert record['outcome'] == 'response' and record['replayed'] is False
+ assert record['tool'] in ('click', 'scroll')
+ assert type(record['runtime_pid']) is int and record['runtime_pid'] != record['previous_runtime_pid']
+ assert record['prepared_ns'] <= record['dispatch_ns'] <= record['observed_ns']
+ assert record['dispatch_ns'] - record['prepared_ns'] <= MAX_GROUNDING_AGE_NS
+ assert record['snapshot']['window_bounds'] == record['after_snapshot']['window_bounds'], 'refused target geometry changed'
+ check_response(record['response'], {'kind': 'refused', 'reason': 'unsupported_layout'})
+ content = record['response']['structuredContent']
+ assert content.get('route') == 'synthetic_events' and content.get('detail') == 'unsupported_layout'
+ assert content.get('code') == 'background_unavailable', 'not the compositor layout refusal'
+ before, after = keymap_lanes(record['before'], cleared=True), keymap_lanes(record['after'], cleared=True)
+ for lane in before:
+ assert all(before[lane][key] == after[lane][key] for key in ('epoch', 'desktop_generation', 'dispatches')), \
+ 'layout refusal changed compositor state or dispatched input'
+ verify_keymap_options(record['keymap_options'], False)
+ tail = trace_interval(record['trace_before'], record['trace_after'])
+ assert not any(row[5] in (1, 2) for row in tail), 'refused fresh action dispatched synthetic input'
+ assert analyze(stopped_prefix(record['trace_after']))['result'] == 'passed'
+ return {'result': 'verified', 'reason': 'unsupported_layout', 'no_dispatch': 'verified',
+ 'compiled_map_invalidation': 'verified', 'keymap_hash': 'not_exposed'}
+
+
+def refuse_new_action(client, observer, victim, spec, stage, trace, config, guard, save):
+ """Exercise real Driver admission while the compiled physical map is invalid."""
+ assert victim.process.poll() is not None, 'old runtime must be reaped before refusal probe'
+ assert victim.process.pid not in assert_distinct_runtimes([client, observer])
+ fresh = {**spec, 'name': spec['name'] + '-wrong-layout', 'pointer_stage': stage}
+ assert not client.tool('start_session', {'session': fresh['name']}).get('isError')
+ app_process_identity(spec['app'], spec['target']['pid'])
+ prepared_ns = time.monotonic_ns()
+ snapshot = grounded_snapshot(client, spec['target'], fresh)
+ arguments, _ = pointer_grounding.action(snapshot, pointer_grounding.read_pixels(snapshot['proof_image']), spec['app'], stage)
+ tool = pointer_grounding.STAGES[spec['app']][stage]
+ assert tool in ('click', 'scroll'), 'never replay the interrupted drag'
+ record = {'outcome': 'unknown', 'replayed': False, 'runtime_pid': client.process.pid,
+ 'previous_runtime_pid': victim.process.pid, 'tool': tool, 'prepared_ns': prepared_ns,
+ 'snapshot': snapshot, 'arguments': arguments, 'session': fresh['name'],
+ 'before': production_status(config['instance'], True), 'trace_before': trace.collect()}
+ keymap_lanes(record['before'], cleared=True)
+ record['keymap_options'] = keymap_options(config['instance'], False)
+ guard()
+ _guard(config)
+ assert file_identity(config['path']) == config['files']['disabled']['identity']
+ record['dispatch_ns'] = time.monotonic_ns()
+ assert record['dispatch_ns'] - prepared_ns <= MAX_GROUNDING_AGE_NS
+ assert record['dispatch_ns'] + 1_000_000_000 < config['deadline_ns'], 'watchdog deadline too near'
+ save('wrong-layout-action.json', record)
+ try:
+ record['response'] = client.tool(tool, {**arguments, **spec['target'], 'session': fresh['name'],
+ 'delivery_mode': 'background'})
+ record['outcome'] = 'response'
+ record['after_snapshot'] = grounded_snapshot(observer, spec['target'], fresh, session=False)
+ record['after'] = production_status(config['instance'], True)
+ record['trace_after'] = trace.collect()
+ record['keymap_options'] = keymap_options(config['instance'], False)
+ record['observed_ns'] = time.monotonic_ns()
+ assert record['observed_ns'] < config['deadline_ns'], 'watchdog restored during refusal probe'
+ guard()
+ record['verification'] = verify_layout_refusal(record)
+ return record
+ finally:
+ save('wrong-layout-action.json', record)
+
+
+def verify_fault(boundary, record, restoration, action):
+ original, changed = fixed_bytes(record['kind'])
+ assert record['result'] == 'observed' and restoration['result'] == 'restored'
+ assert record['config']['sha256'] == digest(changed.encode())
+ assert restoration['config']['sha256'] == digest(original.encode())
+ verify_status(record['before'], True)
+ verify_status(record['after'], record['kind'] == 'keymap')
+ verify_status(restoration['status'], True)
+ assert record['acknowledged_ns'] <= restoration['started_ns'] <= restoration['observed_ns']
+ assert restoration['observed_ns'] < record['watchdog_deadline_ns'], 'watchdog recovery cannot certify the episode'
+ if record['kind'] == 'keymap':
+ verify_keymap_options(record['keymap_before'], True)
+ verify_keymap_options(record['keymap_after'], False)
+ verify_keymap_options(restoration['keymap_options'], True)
+ assert record['keymap_before'] == restoration['keymap_options'], 'original map options not restored'
+ verify_keymap_transition(record['gate_status'], record['after'])
+ refusal = record['wrong_layout']
+ verify_layout_refusal(refusal)
+ after, before_refusal = keymap_lanes(record['after']), keymap_lanes(refusal['before'])
+ for lane in after:
+ assert all(after[lane][key] == before_refusal[lane][key] for key in ('epoch', 'desktop_generation', 'dispatches')), \
+ 'keymap state changed before fresh refusal'
+ trace_interval(record['prefix'], refusal['trace_before'])
+ trace_interval(refusal['trace_after'], boundary)
+ assert record['acknowledged_ns'] <= refusal['prepared_ns'] <= refusal['observed_ns'] < restoration['started_ns']
+ verify_keymap_transition(refusal['after'], restoration['status'])
+ isolation = verify_cancelled(boundary, record, restoration['started_ns'])
+ result = {'result': 'verified', 'outcome': fault_outcome(action), 'continuous_isolation': isolation,
+ 'synthetic_cleanup': 'verified', 'saved_document_effect': 'unproven'}
+ if record['kind'] == 'keymap':
+ result['wrong_layout'] = verify_layout_refusal(record['wrong_layout'])
+ return result
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ report = {'result': 'failed', 'scope': 'native-config-disable', 'recovery': {'result': 'unproven'},
+ 'full_desktop_matrix': False, 'physical_hardware': False}
+ clients, observer, grab, trace, fault, pool, future = [], None, None, None, None, None, None
+ prefix = primary_before = baseline = deadline = None
+ def guard():
+ require_primary_active(grab, deadline)
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ return DirectMCP(args.driver, directory, PROFILE)
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ report['scope'] = 'native-' + plan['fault']['kind'].replace('_', '-')
+ assert args.trace_socket.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')
+ origin = provenance(args, plan)
+ for name in ('production_desktop_fault_proof.py', 'production_desktop_fault_proof_test.py',
+ 'production_geometry_fault_proof.py', 'production_cancel_proof.py',
+ 'input_config_toggle.py', 'desktop_faults.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': digest(path.read_bytes())}
+ save('provenance.json', origin)
+ fault = ConfigFault(plan, args.evidence)
+ spec = plan['agents'][0]
+ clients.append(launch('agent'))
+ assert not clients[0].tool('start_session', {'session': spec['name']}).get('isError')
+ observer = launch('observer')
+ report['driver_processes'] = assert_distinct_runtimes([clients[0], observer])
+ foreground = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError')
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < foreground['width'] and 0 < y < foreground['height']
+ x, y = foreground['x'] + x, foreground['y'] + y
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid'] and baseline['held']
+ trace = connect_trace(args.trace_socket, fault.config)
+ start_ns = time.monotonic_ns()
+ trace.exchange('TRACE_START')
+ initial = trace.collect()
+ assert start_ns <= initial['events'][0][1] <= time.monotonic_ns()
+ assert not active_drags(initial) and not any(row[5] in (1, 2) for row in initial['events'])
+ prepared = prepare_drag(clients[0], spec)
+ save('drag-grounding.json', prepared)
+ fault.arm()
+ guard()
+ pool = ThreadPoolExecutor(max_workers=1)
+ future = pool.submit(call_drag, clients[0], spec, prepared, guard)
+ _, lane = fault.inject(trace, initial, future, guard)
+ save('fault.json', fault.record)
+ report['action'] = future.result(timeout=5)
+ save('drag-action.json', report['action'])
+ if plan['fault']['kind'] == 'keymap':
+ cancelled = trace.collect()
+ save('keymap-cancelled-prefix.json', cancelled)
+ verify_cancelled(cancelled, fault.record, time.monotonic_ns())
+ close_owned(clients[0])
+ clients.append(launch('wrong-layout'))
+ fault.record['wrong_layout'] = refuse_new_action(
+ clients[-1], observer, clients[0], spec, plan['recovery']['pointer_stage'],
+ trace, fault.config, guard, save)
+ close_owned(clients[-1])
+ save('fault.json', fault.record)
+ restoration = fault.restore()
+ save('restoration.json', restoration)
+ trace.close()
+ trace = None
+ trace = connect_trace(args.trace_socket, fault.config) # NEVER reset trace history.
+ boundary = trace.collect()
+ save('fault-prefix.json', boundary)
+ report['fault'] = verify_fault(boundary, fault.record, restoration, report['action'])
+ save('interrupted-state.json', {'snapshot': grounded_snapshot(observer, spec['target'], spec, session=False),
+ 'action': report['action'], 'replayed': False})
+ close_owned(clients[0])
+ teardown = trace.collect()
+ save('pre-recovery-prefix.json', teardown)
+ report['runtime_teardown'] = verify_recovery_cleanup(boundary, stopped_prefix(teardown))
+ clients.append(launch('recovery'))
+ prefix = recover(clients[-1], observer, clients[0], spec, plan['recovery']['pointer_stage'],
+ trace, teardown, lane, guard, save, report['recovery'])
+ save('recovery-prefix.json', prefix)
+ guard()
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = [(f'close_agent_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)]
+ if future:
+ def preserve_action():
+ try:
+ report['action'] = future.result(timeout=5)
+ except Exception as error:
+ report['action'] = {'outcome': 'unknown', 'error': str(error), 'replayed': False}
+ save('drag-action.json', report['action'])
+ operations.append(('preserve_action', preserve_action))
+ if pool:
+ operations.append(('shutdown_pool', lambda: pool.shutdown(wait=False, cancel_futures=True)))
+ if fault:
+ operations += [('preserve_fault', lambda: save('fault.json', fault.record)),
+ ('restore_config', lambda: save('restoration.json', fault.restore())),
+ ('close_fault', fault.close)]
+ if trace:
+ def finish_trace():
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('trace.json', stopped)
+ guard()
+ isolation = verify_recovery_cleanup(prefix, stopped) if prefix else analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ report['continuous_isolation'] = isolation
+ assert wm() == primary_before, 'primary cursor/focus/workspace changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held'))
+ guard()
+ operations += [('finish_trace', finish_trace), ('close_trace', trace.close)]
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release_primary))
+ if observer:
+ operations.append(('close_observer', lambda: close_owned(observer)))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ if not __debug__:
+ raise SystemExit('assertions must be enabled')
+ if len(sys.argv) == 4 and sys.argv[1] == '--watchdog':
+ watchdog(json.loads(sys.argv[2]), int(sys.argv[3]))
+ else:
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.py
new file mode 100644
index 0000000000..c7a1c10c92
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.py
@@ -0,0 +1,744 @@
+"""Portable contracts only: no native VM, compositor, policy or input is touched."""
+from contextlib import ExitStack, nullcontext
+from copy import deepcopy
+import json
+import os
+from pathlib import Path
+import struct
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_desktop_fault_proof as proof
+from production_geometry_fault_proof_test import (ACTIVE, CANCEL, BOUNDS, action,
+ client, plan as geometry_plan, trace)
+
+
+def plan(kind='config_disable'):
+ candidate = geometry_plan()
+ candidate.update(purpose='desktop_fault', fault={'kind': 'config_disable'},
+ vm={'machine_id': 'a' * 32, 'boot_id': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'},
+ compositor={'pid': 50, 'instance': 'test_1', 'uid': 1000, 'starttime': '77', 'exe': '/usr/bin/Hyprland'},
+ config={'path': '/guest/input.lua', 'device': 1, 'inode': 2, 'uid': 1000,
+ 'mode': 0o600, 'sha256': proof.digest(proof.ENABLED.encode())})
+ candidate['fault'] = {'kind': kind}
+ candidate['config']['sha256'] = proof.digest(proof.fixed_bytes(kind)[0].encode())
+ return candidate
+
+
+def status(enabled=True):
+ return {'configured': enabled, 'transport': {'ready': enabled}, 'input': {
+ 'protocol': 3, 'test_only': False, 'seat_lifetime': 'compositor', 'upgrade': 'desktop_restart',
+ 'transport_ready': enabled, 'lanes': [
+ {'lane': lane, 'held_button': 0, 'held_keys': 0, 'drag_active': False, 'lease_active': False}
+ for lane in (0, 1)]}}
+
+
+def record():
+ return {'result': 'observed', 'kind': 'config_disable', 'prefix': trace(ACTIVE), 'lane': 1,
+ 'gate_ns': 5_000_000, 'requested_ns': 6_000_000, 'acknowledged_ns': 10_000_000,
+ 'watchdog_deadline_ns': 90_000_000, 'before': status(), 'after': status(False),
+ 'config': {'sha256': proof.digest(proof.DISABLED.encode())}}
+
+
+def restoration():
+ return {'result': 'restored', 'started_ns': 12_000_000, 'observed_ns': 13_000_000,
+ 'config': {'sha256': proof.digest(proof.ENABLED.encode())}, 'status': status()}
+
+
+def options(restored=True):
+ values = {'kb_rules': 'evdev', 'kb_model': 'pc105', 'kb_layout': 'us' if restored else 'de',
+ 'kb_variant': '', 'kb_options': '', 'kb_file': ''}
+ return {key: {'option': 'input:' + key, 'str': value, 'set': True} for key, value in values.items()}
+
+
+def keymap_status(generation=2):
+ result = status()
+ for row in result['input']['lanes']:
+ row.update(epoch='lane-' + str(row['lane']), desktop_generation=generation,
+ dispatches=1, reserved=False, pointer_focus=False, keyboard_focus=False)
+ return result
+
+
+def layout_refusal():
+ return {'outcome': 'response', 'replayed': False, 'runtime_pid': 103, 'previous_runtime_pid': 100,
+ 'tool': 'click', 'prepared_ns': 10_100_000, 'dispatch_ns': 10_500_000, 'observed_ns': 11_000_000,
+ 'snapshot': {'window_bounds': dict(BOUNDS)}, 'after_snapshot': {'window_bounds': dict(BOUNDS)},
+ 'response': {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'unsupported_layout',
+ 'code': 'background_unavailable', 'detail': 'unsupported_layout', 'route': 'synthetic_events'}},
+ 'before': keymap_status(), 'after': keymap_status(), 'keymap_options': options(False),
+ 'trace_before': trace(CANCEL), 'trace_after': trace(CANCEL)}
+
+
+def keymap_record():
+ return {**record(), 'kind': 'keymap', 'config': {'sha256': proof.digest(proof.KEYMAP_DE.encode())},
+ 'before': keymap_status(1), 'gate_status': keymap_status(1), 'after': keymap_status(2),
+ 'keymap_before': options(), 'keymap_after': options(False), 'wrong_layout': layout_refusal()}
+
+
+def keymap_restoration():
+ return {**restoration(), 'config': {'sha256': proof.digest(proof.KEYMAP_US.encode())},
+ 'keymap_options': options(), 'status': keymap_status(3)}
+
+
+class KeymapTests(unittest.TestCase):
+ def test_idle_baseline_allows_only_unreserved_inert_hover_on_either_lane(self):
+ for lane in (0, 1):
+ passive = keymap_status(1)
+ passive['input']['lanes'][lane]['pointer_focus'] = True
+ proof.idle_lanes(passive)
+ proof.verify_keymap_transition(passive, keymap_status(2))
+ with self.assertRaises(AssertionError):
+ proof.keymap_lanes(passive, cleared=True)
+ for key, value in (('held_button', 272), ('held_button', False), ('held_keys', 1),
+ ('drag_active', True), ('lease_active', True), ('keyboard_focus', True),
+ ('reserved', True), ('reserved', None), ('pointer_focus', 1),
+ ('pointer_focus', None)):
+ changed = deepcopy(passive)
+ changed['input']['lanes'][lane][key] = value
+ with self.subTest(lane=lane, key=key, value=value), self.assertRaises(AssertionError):
+ proof.idle_lanes(changed)
+
+ def test_keymap_constructor_preserves_and_checks_passive_baseline_before_staging(self):
+ for reserved in (False, True):
+ with self.subTest(reserved=reserved), tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ directory = Path(root).resolve()
+ path = directory / 'keymap.lua'
+ path.write_text(proof.KEYMAP_US)
+ path.chmod(0o600)
+ candidate = plan('keymap')
+ candidate['config'] = {'path': str(path), **proof.file_identity(path)}
+ candidate['compositor']['uid'] = os.getuid()
+ identity = {k: v for k, v in candidate['compositor'].items() if k != 'instance'}
+ before = keymap_status(1)
+ before['input']['lanes'][0].update(pointer_focus=True, reserved=reserved)
+ stack.enter_context(patch.object(proof.platform, 'system', return_value='Linux'))
+ stack.enter_context(patch.object(proof.subprocess, 'run', return_value=Mock(returncode=0)))
+ stack.enter_context(patch.object(proof, '_identity', return_value=identity))
+ stack.enter_context(patch.object(proof, '_guard'))
+ stack.enter_context(patch.object(proof, 'production_status', return_value=before))
+ stack.enter_context(patch.object(proof, 'keymap_options', return_value=options()))
+ if reserved:
+ with patch.object(proof.tempfile, 'mkstemp') as stage, self.assertRaisesRegex(AssertionError, 'authority'):
+ proof.ConfigFault(candidate, directory)
+ stage.assert_not_called()
+ else:
+ fault = proof.ConfigFault(candidate, directory)
+ fault.close()
+ self.assertEqual(json.loads((directory / 'pre-fault-status.json').read_text()), before)
+ self.assertEqual(path.read_text(), proof.KEYMAP_US)
+
+ def test_keymap_plan_requires_its_own_exact_include(self):
+ proof.validate_plan(plan('keymap'))
+ for kind, data in (('keymap', proof.ENABLED), ('config_disable', proof.KEYMAP_US),
+ ('keymap', proof.KEYMAP_DE), ('keymap', proof.KEYMAP_US + '-- extra\n')):
+ candidate = plan(kind)
+ candidate['config']['sha256'] = proof.digest(data.encode())
+ with self.subTest(kind=kind, data=data), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_compiled_map_gate_refusal_and_original_map_restoration_pass(self):
+ self.assertEqual(proof.verify_fault(trace(CANCEL), keymap_record(), keymap_restoration(), action())['result'], 'verified')
+ result = proof.verify_layout_refusal(layout_refusal())
+ self.assertEqual(result['no_dispatch'], 'verified')
+ self.assertEqual(result['keymap_hash'], 'not_exposed')
+
+ def test_exact_option_readback_rejects_labels_variants_options_and_override(self):
+ for key in options():
+ candidate = options()
+ candidate[key]['str'] = 'wrong'
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_keymap_options(candidate, True)
+ for candidate in ({}, {'active_keymap': 'English (US)'}, {**options(), 'other': {}}):
+ with self.assertRaises(AssertionError):
+ proof.verify_keymap_options(candidate, True)
+ with patch.object(proof, '_hypr', side_effect=lambda _, *_args: json.dumps(options(False)[_args[-1].split(':')[1]])) as hypr:
+ self.assertEqual(proof.keymap_options('exact', False), options(False))
+ self.assertEqual(hypr.call_count, 6)
+
+ def test_transition_requires_real_generation_same_epoch_and_retired_authority(self):
+ for key, value in (('desktop_generation', 1), ('desktop_generation', True), ('epoch', 'replaced'),
+ ('reserved', True), ('held_button', 272), ('held_button', False), ('held_keys', 1),
+ ('drag_active', True), ('lease_active', True), ('pointer_focus', True), ('keyboard_focus', True)):
+ after = keymap_status(2)
+ after['input']['lanes'][0][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_keymap_transition(keymap_status(1), after)
+
+ def test_refusal_rejects_generic_error_unknown_replay_and_stale_runtime(self):
+ for key, value in (('outcome', 'unknown'), ('replayed', True), ('runtime_pid', 100), ('tool', 'drag'),
+ ('dispatch_ns', 9_000_000), ('dispatch_ns', 99_000_000_000)):
+ candidate = layout_refusal()
+ candidate[key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_layout_refusal(candidate)
+ for key, value in (('reason', 'unsupported_operation'), ('detail', 'wrong layout'), ('route', 'foreground'),
+ ('effect', 'partial'), ('delivery', {'mode': 'background'}), ('code', 'unsupported_layout')):
+ candidate = layout_refusal()
+ candidate['response']['structuredContent'][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_layout_refusal(candidate)
+
+ def test_refusal_requires_no_dispatch_and_no_primary_disturbance(self):
+ candidate = layout_refusal()
+ candidate['after_snapshot']['window_bounds']['x'] += 1
+ with self.assertRaises(AssertionError):
+ proof.verify_layout_refusal(candidate)
+ for kind, lane in (('agent_admitted', 1), ('pointer_button', 1), ('pointer_axis', 2),
+ ('keyboard_key', 0), ('pointer_focus', 0)):
+ candidate = layout_refusal()
+ candidate['trace_after'] = trace(CANCEL + [(11, kind, lane, 0)])
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ proof.verify_layout_refusal(candidate)
+ for key, value in (('dispatches', 2), ('desktop_generation', 3), ('epoch', 'replaced'), ('held_button', 1)):
+ candidate = layout_refusal()
+ candidate['after']['input']['lanes'][1][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_layout_refusal(candidate)
+ candidate = layout_refusal()
+ candidate['trace_after']['events'][0][3] += 1
+ with self.assertRaises(AssertionError):
+ proof.verify_layout_refusal(candidate)
+
+ def test_restoration_requires_original_options_and_new_generation(self):
+ for mutate in (lambda r: r.update(keymap_options=options(False)),
+ lambda r: r.update(status=keymap_status(2)),
+ lambda r: r.update(config={'sha256': proof.digest(proof.ENABLED.encode())})):
+ restored = keymap_restoration()
+ mutate(restored)
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), keymap_record(), restored, action())
+ for mutate in (lambda r: r['wrong_layout'].update(observed_ns=13_000_000),
+ lambda r: r['wrong_layout'].update(keymap_options=options()),
+ lambda r: r.update(after=keymap_status(1))):
+ candidate = keymap_record()
+ mutate(candidate)
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), candidate, keymap_restoration(), action())
+
+ def test_new_driver_action_is_fresh_guarded_and_preserves_failed_evidence(self):
+ for failure in (None, 'runtime', 'stale', 'watchdog', 'file', 'held', 'unknown', 'generic', 'dispatch',
+ 'expired_during_snapshot', 'restored_during_snapshot'):
+ with self.subTest(failure=failure), ExitStack() as stack:
+ candidate = plan('keymap')
+ spec = candidate['agents'][0]
+ fresh, observer, victim = client(103), client(101), client(100, alive=False)
+ if failure == 'runtime':
+ victim.process.poll.return_value = None
+ response = layout_refusal()['response']
+ if failure == 'generic':
+ response['structuredContent']['reason'] = 'unsupported_operation'
+ fresh.tool.side_effect = [{}, TimeoutError('lost response') if failure == 'unknown' else response]
+ page = trace(CANCEL + [(11, 'pointer_button', 1, 1)]) if failure == 'dispatch' else trace(CANCEL)
+ transport = Mock(collect=Mock(side_effect=[trace(CANCEL), page]))
+ before = keymap_status()
+ if failure == 'held':
+ before['input']['lanes'][0]['held_button'] = 272
+ stack.enter_context(patch.object(proof, 'production_status', side_effect=[before, keymap_status()]))
+ stack.enter_context(patch.object(proof, 'app_process_identity'))
+ snapshot = stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value={
+ 'proof_image': '/synthetic/image', 'window_bounds': dict(BOUNDS)}))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value=[]))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({'x': 20, 'y': 20}, {})))
+ stack.enter_context(patch.object(proof, 'keymap_options', side_effect=[options(False),
+ AssertionError('watchdog restored keymap') if failure == 'restored_during_snapshot' else options(False)]))
+ stack.enter_context(patch.object(proof, '_guard'))
+ stack.enter_context(patch.object(proof, 'file_identity', return_value={} if failure == 'file' else {'inode': 20}))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[10_100_000,
+ 99_000_000_000 if failure == 'stale' else 10_500_000,
+ 13_000_000_000 if failure == 'expired_during_snapshot' else 11_000_000]))
+ config = {'instance': 'exact', 'path': '/unused', 'deadline_ns': 11_000_000 if failure == 'watchdog' else 12_000_000_000,
+ 'files': {'disabled': {'identity': {'inode': 20}}}}
+ saved = {}
+ def save(name, record):
+ saved[name] = deepcopy(record)
+ if failure:
+ with self.assertRaises((AssertionError, TimeoutError)):
+ proof.refuse_new_action(fresh, observer, victim, spec, 'click_b2', transport, config, Mock(), save)
+ else:
+ result = proof.refuse_new_action(fresh, observer, victim, spec, 'click_b2', transport, config, Mock(), save)
+ self.assertEqual(result['verification']['no_dispatch'], 'verified')
+ self.assertEqual(fresh.tool.call_args.args[0], 'click')
+ self.assertEqual(fresh.tool.call_args.args[1]['session'], spec['name'] + '-wrong-layout')
+ self.assertEqual(snapshot.call_args_list[0].args[0], fresh)
+ self.assertEqual(snapshot.call_args_list[1].args[0], observer)
+ self.assertEqual(snapshot.call_args_list[1].kwargs, {'session': False})
+ self.assertEqual(result['snapshot']['window_bounds'], result['after_snapshot']['window_bounds'])
+ if failure in ('runtime', 'stale', 'watchdog', 'file', 'held'):
+ self.assertFalse(any(call.args[0] == 'click' for call in fresh.tool.call_args_list))
+ if failure in ('unknown', 'generic', 'dispatch', 'expired_during_snapshot', 'restored_during_snapshot'):
+ self.assertIn('wrong-layout-action.json', saved)
+ self.assertNotIn('verification', saved['wrong-layout-action.json'])
+
+
+class OracleTests(unittest.TestCase):
+ def test_partial_unknown_and_exact_history_pass_without_claiming_app_effect(self):
+ for observed in (action(), {'outcome': 'unknown', 'replayed': False}):
+ result = proof.verify_fault(trace(CANCEL), record(), restoration(), observed)
+ self.assertEqual(result['result'], 'verified')
+ self.assertEqual(result['saved_document_effect'], 'unproven')
+
+ def test_missing_press_release_or_cancel_cross_lane_and_replay_fail(self):
+ cases = [ACTIVE, CANCEL[:6] + CANCEL[7:], CANCEL[:5] + CANCEL[6:]]
+ for kind in ('agent_admitted', 'agent_drag_end', 'agent_action_end', 'keyboard_key',
+ 'pointer_axis', 'pointer_enter', 'pointer_motion'):
+ cases.append(CANCEL + [(11, kind, 1, 0)])
+ cases.append(CANCEL + [(11, 'pointer_leave', 2, 0)])
+ for rows in cases:
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(rows), record(), restoration(), action())
+ candidate = record()
+ candidate['prefix'] = trace(ACTIVE[:3])
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), candidate, restoration(), action())
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), record(), restoration(), {**action(), 'replayed': True})
+
+ def test_fault_cancellation_and_release_must_precede_restoration(self):
+ for changes in ({'requested_ns': 9_000_000}, {'gate_ns': 7_000_000},
+ {'requested_ns': 300_000_000}, {'watchdog_deadline_ns': 12_000_000}):
+ with self.subTest(changes=changes), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), {**record(), **changes}, restoration(), action())
+ late = ACTIVE + [(12, 'agent_cancel', 1, 0), (13, 'pointer_button', 1, 0)]
+ with self.assertRaisesRegex(AssertionError, 'during fault'):
+ proof.verify_fault(trace(late), record(), restoration(), action())
+ late_release = ACTIVE + [(8, 'agent_cancel', 1, 0), (12, 'pointer_button', 1, 0)]
+ with self.assertRaisesRegex(AssertionError, 'delayed'):
+ proof.verify_fault(trace(late_release), record(), restoration(), action())
+
+ def test_reconnected_trace_must_be_complete_and_preserve_prefix(self):
+ for key, value in (('overflow', True), ('timed_out', True), ('hook', False), ('active', False), ('count', 0)):
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_fault({**trace(CANCEL), key: value}, record(), restoration(), action())
+ for page in (trace(CANCEL[5:]), trace(CANCEL)):
+ page['events'][1][1] += 1
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(page, record(), restoration(), action())
+
+ def test_primary_input_focus_and_transient_warp_fail(self):
+ for kind, value in (('pointer_button', 0), ('keyboard_key', 1), ('pointer_axis', 0), ('pointer_focus', 0)):
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL + [(11, kind, 0, value)]), record(), restoration(), action())
+ page = trace(CANCEL + [(11, 'cursor', 0, 0), (12, 'cursor', 0, 0)])
+ page['events'][-2][3] += 5
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(page, record(), restoration(), action())
+
+ def test_exact_fault_bytes_and_restoration_required(self):
+ for key, value in (('result', 'unproven'), ('kind', 'keymap'), ('config', {'sha256': 'bad'})):
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), {**record(), key: value}, restoration(), action())
+ for update in ({'result': 'not_needed'}, {'config': {'sha256': 'bad'}}, {'status': status(False)}):
+ with self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), record(), {**restoration(), **update}, action())
+
+
+class SafetyTests(unittest.TestCase):
+ def test_plan_rejects_other_faults_and_incomplete_identity(self):
+ proof.validate_plan(plan())
+ for change in ({'disposable': False}, {'fault': {'kind': 'keymap'}}, {'fault': {'kind': 'dpms'}},
+ {'fault': {'kind': 'lock'}}, {'vm': {'machine_id': 'bad', 'boot_id': 'bad'}},
+ {'config': {**plan()['config'], 'sha256': 'arbitrary config'}},
+ {'compositor': {**plan()['compositor'], 'exe': '/usr/bin/other'}},
+ {'recovery': {'pointer_stage': 'select_range'}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **change})
+
+ def test_host_bare_metal_and_wrong_process_refused_before_file_access(self):
+ for system, vm_return in (('Darwin', 0), ('Linux', 1)):
+ with patch.object(proof.platform, 'system', return_value=system), \
+ patch.object(proof.subprocess, 'run', return_value=Mock(returncode=vm_return)), \
+ patch.object(proof, 'file_identity') as files, self.assertRaises(AssertionError):
+ proof.ConfigFault(plan(), Path('/unused'))
+ files.assert_not_called()
+ with patch.object(proof.platform, 'system', return_value='Linux'), \
+ patch.object(proof.subprocess, 'run', return_value=Mock(returncode=0)), \
+ patch.object(proof.os, 'getuid', return_value=1000), \
+ patch.object(proof, '_identity', return_value={}), \
+ patch.object(proof, 'file_identity') as files, self.assertRaises(AssertionError):
+ proof.ConfigFault(plan(), Path('/unused'))
+ files.assert_not_called()
+
+ def test_status_rejects_old_signed_and_uncleared_native_state(self):
+ for enabled in (True, False):
+ with patch.object(proof, '_hypr', return_value=json.dumps(status(enabled))):
+ proof.production_status('exact', enabled)
+ mutations = [('protocol', 0), ('test_only', True), ('seat_lifetime', 'action'), ('transport_ready', True)]
+ for key, value in mutations:
+ candidate = status(False)
+ candidate['input'][key] = value
+ with patch.object(proof, '_hypr', return_value=json.dumps(candidate)), self.assertRaises(AssertionError):
+ proof.production_status('exact', False)
+ for key, value in (('held_button', True), ('held_keys', 1), ('drag_active', True), ('lease_active', True)):
+ candidate = status(False)
+ candidate['input']['lanes'][1][key] = value
+ with patch.object(proof, '_hypr', return_value=json.dumps(candidate)), self.assertRaises(AssertionError):
+ proof.production_status('exact', False)
+ candidate = status(False)
+ candidate['experiment'] = candidate.pop('input')
+ with patch.object(proof, '_hypr', return_value=json.dumps(candidate)), self.assertRaises(AssertionError):
+ proof.production_status('exact', False)
+
+ def prepare_files(self, directory, kind='config_disable'):
+ config = {'kind': kind, 'path': str(directory / 'input.lua'), 'files': {}}
+ original, changed = proof.fixed_bytes(kind)
+ for name, data in (('original', original), ('disabled', changed), ('restored', original)):
+ path = Path(config['path']) if name == 'original' else directory / (name + '.stage')
+ path.write_bytes(data.encode())
+ path.chmod(0o600)
+ config['files'][name] = {'path': str(path), 'identity': proof.file_identity(path)}
+ return config
+
+ def test_atomic_fixed_transition_restores_exact_bytes_and_is_idempotent(self):
+ with tempfile.TemporaryDirectory() as root, patch.object(proof, '_guard'):
+ config = self.prepare_files(Path(root).resolve())
+ proof._replace(config, False)
+ self.assertEqual(Path(config['path']).read_bytes(), proof.DISABLED.encode())
+ self.assertEqual(proof.file_identity(config['path']), config['files']['disabled']['identity'])
+ proof._replace(config, True)
+ proof._replace(config, True)
+ self.assertEqual(Path(config['path']).read_bytes(), proof.ENABLED.encode())
+ self.assertEqual(proof.file_identity(config['path']), config['files']['restored']['identity'])
+
+ def test_keymap_atomic_replacement_restoration_and_guarded_failures(self):
+ for failure in (None, 'unrelated', 'wrong_stage', 'reload'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ config = self.prepare_files(Path(root).resolve(), 'keymap')
+ config['instance'] = 'exact'
+ stack.enter_context(patch.object(proof, '_guard'))
+ stack.enter_context(patch.object(proof, '_locked', side_effect=lambda _: nullcontext()))
+ stack.enter_context(patch.object(proof, '_reload', side_effect=TimeoutError('lost') if failure == 'reload' else lambda *_: keymap_status(3)))
+ readback = stack.enter_context(patch.object(proof, 'keymap_options', return_value=options()))
+ proof._replace(config, False)
+ self.assertEqual(Path(config['path']).read_bytes(), proof.KEYMAP_DE.encode())
+ if failure == 'unrelated':
+ Path(config['path']).write_bytes(proof.DISABLED.encode())
+ if failure == 'wrong_stage':
+ Path(config['files']['restored']['path']).write_bytes(proof.ENABLED.encode())
+ if failure:
+ with self.assertRaises((AssertionError, TimeoutError)):
+ proof.restore_config(config)
+ readback.assert_not_called()
+ else:
+ restored = proof.restore_config(config)
+ self.assertEqual(restored['keymap_options'], options())
+ self.assertEqual(Path(config['path']).read_bytes(), proof.KEYMAP_US.encode())
+ proof._replace(config, True)
+
+ def test_unrelated_bytes_inode_symlink_and_stage_change_preserved(self):
+ for change in ('bytes', 'inode', 'link', 'stage'):
+ with self.subTest(change=change), tempfile.TemporaryDirectory() as root, patch.object(proof, '_guard'):
+ config = self.prepare_files(Path(root).resolve())
+ proof._replace(config, False)
+ path = Path(config['path'])
+ if change == 'bytes':
+ path.write_bytes(b'unrelated')
+ elif change == 'inode':
+ replacement = path.with_name('replacement')
+ replacement.write_bytes(proof.DISABLED.encode())
+ replacement.chmod(0o600)
+ os.replace(replacement, path)
+ elif change == 'link':
+ path.unlink()
+ path.symlink_to(config['files']['restored']['path'])
+ else:
+ Path(config['files']['restored']['path']).write_bytes(b'unrelated')
+ with patch.object(proof.os, 'replace') as replace, self.assertRaises(AssertionError):
+ proof._replace(config, True)
+ replace.assert_not_called()
+
+ def test_group_writable_and_hardlinked_config_are_rejected(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root).resolve() / 'input.lua'
+ path.write_bytes(proof.ENABLED.encode())
+ path.chmod(0o666)
+ with self.assertRaises(AssertionError):
+ proof.file_identity(path)
+ path.chmod(0o600)
+ os.link(path, path.with_name('alias'))
+ with self.assertRaises(AssertionError):
+ proof.file_identity(path)
+
+ def test_constructor_stages_only_fixed_bytes_and_close_preserves_original(self):
+ with tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ directory = Path(root).resolve()
+ path = directory / 'input.lua'
+ path.write_bytes(proof.ENABLED.encode())
+ path.chmod(0o600)
+ candidate = plan()
+ candidate['config'] = {'path': str(path), **proof.file_identity(path)}
+ candidate['compositor']['uid'] = os.getuid()
+ identity = {k: v for k, v in candidate['compositor'].items() if k != 'instance'}
+ stack.enter_context(patch.object(proof.platform, 'system', return_value='Linux'))
+ stack.enter_context(patch.object(proof.subprocess, 'run', return_value=Mock(returncode=0)))
+ stack.enter_context(patch.object(proof, '_identity', return_value=identity))
+ stack.enter_context(patch.object(proof, '_guard'))
+ stack.enter_context(patch.object(proof, 'production_status', return_value=status()))
+ reload = stack.enter_context(patch.object(proof, '_reload'))
+ fault = proof.ConfigFault(candidate, directory)
+ original = proof.file_identity(path)
+ for name, data in (('disabled', proof.DISABLED), ('restored', proof.ENABLED)):
+ staged = Path(fault.config['files'][name]['path'])
+ self.assertEqual(staged.read_bytes(), data.encode())
+ self.assertEqual(staged.suffix, '.stage')
+ fault.close()
+ self.assertEqual(proof.file_identity(path), original)
+ self.assertEqual(set(directory.iterdir()), {path, directory / 'pre-fault-status.json'})
+ reload.assert_not_called()
+
+ def test_final_active_gate_failure_prevents_atomic_replacement(self):
+ with tempfile.TemporaryDirectory() as root, patch.object(proof, '_guard'):
+ config = self.prepare_files(Path(root).resolve())
+ with patch.object(proof.os, 'replace') as replace, self.assertRaisesRegex(AssertionError, 'stale'):
+ proof._replace(config, False, before_replace=Mock(side_effect=AssertionError('stale')))
+ replace.assert_not_called()
+ self.assertEqual(Path(config['path']).read_bytes(), proof.ENABLED.encode())
+
+ def test_restore_readback_failure_preserves_cleanup_obligation(self):
+ with tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ config = self.prepare_files(Path(root).resolve())
+ stack.enter_context(patch.object(proof, '_guard'))
+ stack.enter_context(patch.object(proof, '_locked', side_effect=lambda _: nullcontext()))
+ stack.enter_context(patch.object(proof, '_reload', side_effect=TimeoutError('lost reload reply')))
+ proof._replace(config, False)
+ with self.assertRaises(TimeoutError):
+ proof.restore_config(config)
+ self.assertEqual(Path(config['path']).read_bytes(), proof.ENABLED.encode())
+ # Restored bytes alone are not acknowledgment; retry must reload.
+ with self.assertRaises(TimeoutError):
+ proof.restore_config(config)
+
+ def test_stale_vm_prevents_compositor_commands(self):
+ with patch.object(proof.platform, 'system', return_value='Linux'), \
+ patch.object(proof, 'guest_identity', return_value={}), \
+ patch.object(proof, '_same_compositor') as compositor, self.assertRaises(AssertionError):
+ proof._guard({'vm': plan()['vm']})
+ compositor.assert_not_called()
+
+ def test_trace_reconnection_binds_exact_compositor_peer_and_protocol(self):
+ for peer, protocol in (((50, 1000, 1000), 3), ((51, 1000, 1000), 3),
+ ((50, 1001, 1000), 3), ((50, 1000, 1000), 0)):
+ connection = Mock(hello={'protocol': protocol})
+ connection.socket.getsockopt.return_value = struct.pack('3i', *peer)
+ with patch.object(proof, '_guard') as guard, patch.object(proof.socket, 'SO_PEERCRED', 17, create=True):
+ if peer[:2] == (50, 1000) and protocol == 3:
+ proof.verify_trace_peer(connection, {'compositor': plan()['compositor']})
+ guard.assert_called_once()
+ else:
+ with self.assertRaises(AssertionError):
+ proof.verify_trace_peer(connection, {'compositor': plan()['compositor']})
+ guard.assert_not_called()
+
+ def controller(self):
+ fault = object.__new__(proof.ConfigFault)
+ fault.config = {'path': '/unused', 'deadline_ns': 10_000_000_000}
+ fault.child = Mock(poll=Mock(return_value=None))
+ fault.cancel_fd = 8
+ fault.record = {'result': 'unproven', 'kind': 'config_disable'}
+ fault.restoration = None
+ fault.mutated = False
+ return fault
+
+ def test_watchdog_has_fixed_bounded_budget_for_each_fault(self):
+ for kind, seconds in (('config_disable', 12), ('keymap', 30)):
+ with self.subTest(kind=kind), ExitStack() as stack:
+ fault = self.controller()
+ fault.config['kind'] = kind
+ fault.child = None
+ child = Mock()
+ child.stdout.readline.return_value = 'ARMED\n'
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', return_value=100))
+ stack.enter_context(patch.object(proof.os, 'pipe', return_value=(7, 8)))
+ close = stack.enter_context(patch.object(proof.os, 'close'))
+ launch = stack.enter_context(patch.object(proof.subprocess, 'Popen', return_value=child))
+ stack.enter_context(patch.object(proof.select, 'select', return_value=([child.stdout], [], [])))
+ fault.arm()
+ self.assertEqual(fault.config['deadline_ns'], 100 + seconds * 1_000_000_000)
+ self.assertLess(seconds * 1000, proof.PRIMARY_LIFETIME_MS)
+ self.assertEqual(json.loads(launch.call_args.args[0][3])['deadline_ns'], fault.config['deadline_ns'])
+ close.assert_called_once_with(7)
+ with self.assertRaises(AssertionError):
+ fault.arm()
+
+ def test_injection_requires_pending_press_fresh_gate_live_watchdog(self):
+ for failure in (None, 'done', 'stale', 'watchdog', 'deadline', 'lost_reply'):
+ fault = self.controller()
+ if failure == 'watchdog':
+ fault.child.poll.return_value = 0
+ if failure == 'deadline':
+ fault.config['deadline_ns'] = 1
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(proof, '_locked', side_effect=lambda _: nullcontext()))
+ stack.enter_context(patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2})))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[5, 300_000_006 if failure == 'stale' else 6, 7]))
+ replace = stack.enter_context(patch.object(proof, '_replace', side_effect=lambda *_args, **kwargs: kwargs['before_replace']()))
+ stack.enter_context(patch.object(proof, '_reload', side_effect=TimeoutError('lost') if failure == 'lost_reply' else lambda *_: status(False)))
+ stack.enter_context(patch.object(proof, 'file_identity', return_value={'sha256': proof.digest(proof.DISABLED.encode())}))
+ if failure:
+ with self.assertRaises((AssertionError, TimeoutError)):
+ fault.inject(Mock(), trace(ACTIVE[:1]), Mock(done=Mock(return_value=failure == 'done')), Mock())
+ else:
+ fault.inject(Mock(), trace(ACTIVE[:1]), Mock(done=Mock(return_value=False)), Mock())
+ self.assertEqual(fault.record['result'], 'observed')
+ self.assertEqual(replace.call_count, int(failure != 'watchdog'))
+ self.assertEqual(fault.mutated, failure in (None, 'lost_reply'))
+ if failure == 'lost_reply':
+ self.assertTrue(fault.mutated)
+
+ def test_keymap_injection_checks_active_native_gate_and_observed_generation(self):
+ for failure in (None, 'gate_changed', 'gate_released', 'not_compiled', 'wrong_options'):
+ with self.subTest(failure=failure), ExitStack() as stack:
+ fault = self.controller()
+ fault.config.update(kind='keymap', instance='exact')
+ fault.record = {'kind': 'keymap', 'result': 'unproven', 'before': keymap_status(1)}
+ gate = keymap_status(2 if failure == 'gate_changed' else 1)
+ gate['input']['lanes'][0].update(drag_active=True, lease_active=True,
+ held_button=0 if failure == 'gate_released' else 272)
+ stack.enter_context(patch.object(proof, 'production_status', return_value=gate))
+ stack.enter_context(patch.object(proof, 'keymap_options', side_effect=[options(),
+ AssertionError('wrong options') if failure == 'wrong_options' else options(False)]))
+ stack.enter_context(patch.object(proof, '_locked', side_effect=lambda _: nullcontext()))
+ stack.enter_context(patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2})))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[5, 6, 7]))
+ replace = stack.enter_context(patch.object(proof, '_replace', side_effect=lambda *_args, **kwargs: kwargs['before_replace']()))
+ stack.enter_context(patch.object(proof, '_reload', return_value=keymap_status(1 if failure == 'not_compiled' else 2)))
+ stack.enter_context(patch.object(proof, 'file_identity', return_value={'sha256': proof.digest(proof.KEYMAP_DE.encode())}))
+ if failure:
+ with self.assertRaises(AssertionError):
+ fault.inject(Mock(), trace(ACTIVE[:1]), Mock(done=Mock(return_value=False)), Mock())
+ else:
+ fault.inject(Mock(), trace(ACTIVE[:1]), Mock(done=Mock(return_value=False)), Mock())
+ self.assertEqual(fault.record['result'], 'observed')
+ self.assertEqual(fault.record['keymap_after'], options(False))
+ self.assertEqual(replace.call_count, int(failure not in ('gate_changed', 'gate_released')))
+ self.assertEqual(fault.mutated, failure not in ('gate_changed', 'gate_released'))
+
+ def test_failed_restore_never_cancels_watchdog_or_deletes_backup(self):
+ fault = self.controller()
+ fault.mutated = True
+ fault._clean_staged = Mock()
+ with patch.object(proof, 'restore_config', side_effect=RuntimeError('unowned config')), \
+ patch.object(proof.os, 'write') as write, patch.object(proof.os, 'close') as close:
+ with self.assertRaises(RuntimeError):
+ fault.close()
+ write.assert_not_called()
+ close.assert_called_once_with(8)
+ fault._clean_staged.assert_not_called()
+
+ def test_watchdog_eof_and_timeout_restore_cancel_does_not(self):
+ for ready, data in (([], b''), ([8], b''), ([8], b'C')):
+ with tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ config = {'deadline_ns': 1, 'record': str(Path(root) / 'watchdog.json')}
+ stack.enter_context(patch.object(proof, '_guard'))
+ stack.enter_context(patch.object(proof.select, 'select', return_value=(ready, [], [])))
+ stack.enter_context(patch.object(proof.os, 'read', return_value=data))
+ restore = stack.enter_context(patch.object(proof, 'restore_config', return_value=restoration()))
+ stack.enter_context(patch('builtins.print'))
+ proof.watchdog(config, 8)
+ self.assertEqual(restore.call_count, int(data != b'C'))
+ self.assertTrue(Path(config['record']).exists())
+
+
+class RunnerTests(unittest.TestCase):
+ def test_invalid_plan_fails_before_native_controller_or_allocation(self):
+ with tempfile.TemporaryDirectory() as root:
+ directory = Path(root)
+ path = directory / 'plan.json'
+ path.write_text(json.dumps({**plan(), 'disposable': False}))
+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence')
+ with patch.object(proof, 'ConfigFault') as controller, patch.object(proof, 'DirectMCP') as launch, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ controller.assert_not_called()
+ launch.assert_not_called()
+
+ def test_reconnect_without_reset_restore_before_snapshot_and_new_action(self):
+ cases = [(kind, failure) for kind in ('config_disable', 'keymap') for failure in (None, 'inject', 'restore', 'recovery')]
+ cases += [('keymap', 'refusal'), ('keymap', 'cancel')]
+ for kind, failure in cases:
+ with self.subTest(kind=kind, failure=failure), tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ directory = Path(root)
+ path = directory / 'plan.json'
+ path.write_text(json.dumps(plan(kind)))
+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence', driver=Path('/driver'),
+ primary_grab=Path('/grab'), foreground_journal=Path('/journal'), trace_socket=Path('/cua-input-v3.sock'))
+ order = []
+ fault = Mock(record=keymap_record() if kind == 'keymap' else record())
+ def inject(*_):
+ order.append('inject')
+ if failure == 'inject':
+ raise AssertionError('injection failed')
+ return trace(ACTIVE), 1
+ fault.inject.side_effect = inject
+ def restore():
+ order.append('restore')
+ if failure == 'restore':
+ raise AssertionError('restore failed')
+ return keymap_restoration() if kind == 'keymap' else restoration()
+ fault.restore.side_effect = restore
+ stack.enter_context(patch.object(proof, 'ConfigFault', return_value=fault))
+ stack.enter_context(patch.object(proof, 'provenance', return_value={'files': {}}))
+ agent, observer, fresh, refused = client(100), client(101), client(102), client(103)
+ agent.tool.return_value = {}
+ observer.tool.return_value = {'structuredContent': {'screen_width': 1920, 'screen_height': 1080}}
+ stack.enter_context(patch.object(proof, 'DirectMCP', side_effect=[agent, observer, refused, fresh] if kind == 'keymap' else [agent, observer, fresh]))
+ def snapshot(*_args, **_kwargs):
+ order.append('snapshot')
+ return {'window_bounds': dict(BOUNDS)}
+ stack.enter_context(patch.object(proof, 'grounded_snapshot', side_effect=snapshot))
+ stack.enter_context(patch.object(proof, 'prepare_drag', return_value={}))
+ stack.enter_context(patch.object(proof, 'call_drag', return_value=action()))
+ grab = Mock(poll=Mock(return_value=None))
+ grab.terminate.side_effect = lambda: setattr(grab.poll, 'return_value', 0)
+ stack.enter_context(patch.object(proof.subprocess, 'Popen', return_value=grab))
+ stack.enter_context(patch.object(proof, 'stop_process'))
+ stack.enter_context(patch.object(proof, 'primary_acknowledgement', return_value='HELD\n'))
+ stack.enter_context(patch.object(proof, 'wait_for', return_value=True))
+ stack.enter_context(patch.object(proof, 'wm', return_value={'pid': 10}))
+ stack.enter_context(patch.object(proof, 'state', return_value={'held': True, 'clicks': 0, 'keys': 0, 'scroll': 0}))
+ stack.enter_context(patch.object(proof, 'require_primary_active'))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[0, 0, 0, 11_500_000]))
+ first = Mock(hello={'protocol': 3}, collect=Mock(side_effect=[trace(ACTIVE[:1]), trace(ACTIVE if failure == 'cancel' else CANCEL)]))
+ page = trace(CANCEL + [(14, 'agent_admitted', 1, 0), (15, 'pointer_button', 1, 1),
+ (16, 'pointer_button', 1, 0), (17, 'agent_action_end', 1, 0)])
+ last = proof.stopped_prefix(page if failure is None else trace(CANCEL))
+ second = Mock(hello={'protocol': 3}, collect=Mock(side_effect=[trace(CANCEL), trace(CANCEL), last]))
+ stack.enter_context(patch.object(proof, 'connect_trace', side_effect=[first, second]))
+ def refuse(*args):
+ order.append('refusal')
+ self.assertEqual(agent.process.poll(), 0)
+ if failure == 'refusal':
+ raise AssertionError('wrong layout did not refuse')
+ return layout_refusal()
+ probe = stack.enter_context(patch.object(proof, 'refuse_new_action', side_effect=refuse))
+ def recover(*args):
+ order.append('recovery')
+ if failure == 'recovery':
+ raise AssertionError('recovery failed')
+ args[-1]['result'] = 'verified'
+ return page
+ stack.enter_context(patch.object(proof, 'recover', side_effect=recover))
+ stack.enter_context(patch.object(proof, 'close_owned', side_effect=lambda c: setattr(c.process.poll, 'return_value', 0)))
+ stack.enter_context(patch('builtins.print'))
+ self.assertEqual(proof.run(args), int(failure is not None))
+ fault.close.assert_called_once()
+ first.exchange.assert_any_call('TRACE_START')
+ self.assertFalse(any(call.args == ('TRACE_START',) for call in second.exchange.call_args_list))
+ self.assertEqual(agent.process.poll(), 0)
+ self.assertEqual(observer.process.poll(), 0)
+ if failure not in ('inject', 'restore', 'refusal', 'cancel'):
+ self.assertLess(order.index('restore'), len(order) - 1 - order[::-1].index('snapshot'))
+ self.assertLess(order.index('restore'), order.index('recovery'))
+ self.assertTrue((args.evidence / 'pre-recovery-prefix.json').is_file())
+ if kind == 'keymap' and failure not in ('inject', 'cancel'):
+ self.assertLess(order.index('refusal'), order.index('restore'))
+ self.assertEqual(refused.process.poll(), 0)
+ if kind == 'config_disable' or failure in ('inject', 'cancel'):
+ probe.assert_not_called()
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertFalse(report['full_desktop_matrix'])
+ self.assertFalse(report['physical_hardware'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.py
new file mode 100644
index 0000000000..8072ad8f90
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.py
@@ -0,0 +1,433 @@
+"""Signer-free v3 geometry fault episode on a disposable native Hyprland VM.
+
+Use the same CLI flags as production_cancel_proof.py. A plan has purpose
+geometry_fault, disposable=true, compositor={pid,instance}, foreground,
+primary_point, package_versions, and exactly one agents entry: app, name,
+target={pid,window_id}, bounds, pointer_stage (select_range or move_rectangle),
+drag={}. fault={kind:move|resize,to:[x,y]} gives absolute position or size;
+floating resize preserves the center, and this integer-frame proof requires
+even size deltas so the expected position does not depend on pixel rounding.
+recovery={pointer_stage:click_a1|click_b2|scroll_down} chooses a NEW action.
+The prepared synthetic document must already be floating. Run separate move
+and resize episodes with freshly observed plans; never replay a failed drag.
+
+Only normal direct Driver calls send application input. Exact compositor IPC
+injects/restores geometry, never replaces app input. A pass requires observed
+mid-drag mutation, cancellation, own-seat release, continuous foreground
+isolation, and a freshly grounded new-runtime recovery. Portable tests are
+synthetic orchestration evidence, not native or physical-hardware proof.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import subprocess
+import time
+
+from driver_input_live import state, wait_for, wm
+from primary_trace import Trace, analyze
+from production_cancel_proof import (GROUNDING_DISPATCH_RESERVE_NS, MAX_GROUNDING_ATTEMPTS,
+ MAX_GROUNDING_AGE_NS, POINTER_STAGES, PROFILE,
+ RECOVERY_STAGES, active_drags, call_drag, close_owned, grounded_snapshot,
+ poll_active, prepare_drag, stopped_prefix, verify_recovery_cleanup, verify_recovery_trace)
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity,
+ check_response, primary_acknowledgement, provenance, require_primary_active, trace_interval)
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'geometry_fault' and plan['disposable'] is True
+ assert len(plan['agents']) == 1, 'geometry episode owns one synthetic lane'
+ spec = plan['agents'][0]
+ assert spec['app'] in POINTER_STAGES
+ assert spec['pointer_stage'] == POINTER_STAGES[spec['app']] and spec['drag'] == {}
+ assert isinstance(spec['name'], str) and spec['name']
+ assert spec.get('profile', PROFILE) == PROFILE
+ for target in (spec['target'], plan['foreground']):
+ assert set(target) == {'pid', 'window_id'}
+ assert all(type(v) is int and v > 1 for v in target.values())
+ assert spec['target']['pid'] != plan['foreground']['pid']
+ bounds = spec['bounds']
+ assert set(bounds) == {'x', 'y', 'width', 'height'}
+ assert all(type(v) is int for v in bounds.values())
+ assert bounds['width'] > 0 and bounds['height'] > 0
+ fault = plan['fault']
+ assert set(fault) == {'kind', 'to'} and fault['kind'] in ('move', 'resize')
+ assert len(fault['to']) == 2 and all(type(v) is int for v in fault['to'])
+ keys = ('x', 'y') if fault['kind'] == 'move' else ('width', 'height')
+ old = [bounds[key] for key in keys]
+ assert old != fault['to'] and all(abs(a - b) <= 128 for a, b in zip(old, fault['to'])), 'need bounded changed geometry'
+ assert fault['kind'] != 'resize' or min(fault['to']) > 0
+ expected_geometry(bounds, fault)
+ assert set(plan['recovery']) == {'pointer_stage'}
+ assert plan['recovery']['pointer_stage'] in RECOVERY_STAGES[spec['app']]
+ assert len(plan['primary_point']) == 2 and all(type(v) is int for v in plan['primary_point'])
+ compositor = plan['compositor']
+ assert set(compositor) == {'pid', 'instance'} and type(compositor['pid']) is int and compositor['pid'] > 1
+ assert isinstance(compositor['instance'], str) and re.fullmatch(r'[A-Za-z0-9_.-]+', compositor['instance'])
+
+
+def process_identity(pid):
+ root = Path('/proc') / str(pid)
+ return {'pid': pid, 'uid': root.stat().st_uid,
+ 'starttime': (root / 'stat').read_text().rsplit(')', 1)[1].split()[19],
+ 'exe': str((root / 'exe').resolve(strict=True))}
+
+
+def window_bounds(window):
+ return dict(zip(('x', 'y', 'width', 'height'), [*window['at'], *window['size']]))
+
+
+def expected_geometry(bounds, fault):
+ """Hyprland's floating resize translates the origin by minus half the delta."""
+ expected = dict(bounds)
+ if fault['kind'] == 'move':
+ expected.update(zip(('x', 'y'), fault['to']))
+ else:
+ assert fault['kind'] == 'resize'
+ for position, size, target in zip(('x', 'y'), ('width', 'height'), fault['to']):
+ delta = target - bounds[size]
+ assert delta % 2 == 0, 'integer-frame resize proof requires even size deltas'
+ expected[position] -= delta // 2
+ expected[size] = target
+ return expected
+
+
+class GeometryFault:
+ """Only the reviewed native window may be mutated or restored; never kill it."""
+ def __init__(self, plan):
+ assert plan['disposable'] is True and platform.system() == 'Linux'
+ assert subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode == 0
+ self.spec, self.fault = plan['agents'][0], plan['fault']
+ self.instance = plan['compositor']['instance']
+ assert os.environ.get('HYPRLAND_INSTANCE_SIGNATURE') == self.instance, 'wrong compositor session'
+ self.compositor = process_identity(plan['compositor']['pid'])
+ assert self.compositor['uid'] == os.getuid() and Path(self.compositor['exe']).name == 'Hyprland'
+ self.owner = process_identity(self.spec['target']['pid'])
+ assert self.owner['uid'] == os.getuid(), 'target is not owned by test user'
+ app_process_identity(self.spec['app'], self.owner['pid'])
+ self.expected = expected_geometry(self.spec['bounds'], self.fault)
+ self.mutated = False
+ self.record = {'result': 'unproven', 'kind': self.fault['kind'], 'target': self.spec['target'],
+ 'before_bounds': self.spec['bounds'], 'expected_bounds': self.expected}
+ before = self.snapshot()
+ assert before['bounds'] == self.spec['bounds'], 'reviewed geometry is stale'
+ self.record['before'] = before
+
+ def hypr(self, *arguments):
+ return subprocess.check_output(['hyprctl', '-i', self.instance, *arguments], text=True, timeout=2).strip()
+
+ def snapshot(self):
+ assert process_identity(self.compositor['pid']) == self.compositor, 'compositor identity changed'
+ assert process_identity(self.owner['pid']) == self.owner, 'target identity changed'
+ instances = json.loads(self.hypr('-j', 'instances'))
+ assert sum(row.get('instance') == self.instance and row.get('pid') == self.compositor['pid']
+ for row in instances) == 1, 'wrong compositor instance'
+ windows = json.loads(self.hypr('-j', 'clients'))
+ matches = [w for w in windows if w.get('pid') == self.owner['pid']]
+ assert len(matches) == 1, 'target is not one exact window'
+ window = matches[0]
+ assert re.fullmatch(r'0x[0-9a-fA-F]+', window.get('address', ''))
+ assert int(window['address'], 16) == self.spec['target']['window_id'], 'target address changed'
+ assert window.get('xwayland') is False and window.get('floating') is True, 'need prepared floating native target'
+ assert f'cua-smoke-{self.spec["app"]}' in window.get('title', ''), 'wrong synthetic document'
+ return {'observed_ns': time.monotonic_ns(), 'bounds': window_bounds(window), 'window': window}
+
+ def dispatch(self, to):
+ assert len(to) == 2 and all(type(v) is int for v in to)
+ address = hex(self.spec['target']['window_id'])
+ # Current Lua dispatcher explicitly supports absolute x/y plus window.
+ command = (f'hl.dsp.window.{self.fault["kind"]}({{ window = "address:{address}", '
+ f'x = {to[0]}, y = {to[1]}, relative = false }})')
+ assert self.hypr('dispatch', command) == 'ok', 'geometry dispatcher refused'
+
+ def inject(self, trace, previous, pending, guard):
+ before = self.snapshot()
+ assert before['bounds'] == self.spec['bounds'], 'target moved before fault gate'
+ page, lanes = poll_active(trace, previous, None, [pending])
+ gate_ns = time.monotonic_ns()
+ lane = next(iter(lanes))
+ before = self.snapshot()
+ assert before['bounds'] == self.spec['bounds'], 'target changed at fault gate'
+ guard()
+ assert not pending.done(), 'drag returned before geometry dispatch'
+ self.record.update(prefix=page, lane=lane, gate_ns=gate_ns, gate_observation=before)
+ requested = time.monotonic_ns()
+ assert 0 <= requested - gate_ns <= 250_000_000, 'stale fault gate'
+ self.record['requested_ns'] = requested
+ self.mutated = True # A lost IPC reply can still mean the mutation happened.
+ self.dispatch(self.fault['to'])
+ self.record['acknowledged_ns'] = time.monotonic_ns()
+ def changed():
+ observation = self.snapshot()
+ self.record['last_observation'] = observation
+ return observation if observation['bounds'] == self.expected else None
+ self.record['after'] = wait_for(changed, timeout=2)
+ guard()
+ self.record['result'] = 'observed'
+ return page, lane
+
+ def restore(self):
+ if not self.mutated:
+ return {'result': 'not_needed'}
+ observed = self.snapshot()
+ assert observed['bounds'] in (self.expected, self.spec['bounds']), 'unowned geometry change; restoration refused'
+ if observed['bounds'] != self.spec['bounds']:
+ keys = ('x', 'y') if self.fault['kind'] == 'move' else ('width', 'height')
+ self.dispatch([self.spec['bounds'][key] for key in keys])
+ restored = wait_for(lambda: (row if (row := self.snapshot())['bounds'] == self.spec['bounds'] else None), timeout=2)
+ self.mutated = False
+ return {'result': 'restored', 'before': observed, 'after': restored}
+
+
+def fault_outcome(action):
+ assert action.get('replayed') is False
+ if action['outcome'] == 'unknown':
+ return {'kind': 'unknown', 'app_effect_verified': False}
+ assert action['outcome'] == 'response'
+ response = action['response']
+ content = response.get('structuredContent', {})
+ if (content.get('delivery') or {}).get('mode') == 'unknown':
+ kind = 'unknown'
+ elif content.get('effect') == 'partial':
+ kind = 'partial'
+ else:
+ # A refusal after an observed press cannot truthfully claim zero delivery.
+ reason = (content.get('refusal') or {}).get('code', content.get('reason'))
+ check_response(response, {'kind': 'refused', 'reason': reason})
+ raise AssertionError('refusal conflicts with trace-observed drag delivery')
+ check_response(response, {'kind': kind})
+ if kind == 'partial':
+ assert content['delivery']['delivered_count'] > 0, 'partial result hid observed delivery'
+ return {'kind': kind, 'app_effect_verified': False}
+
+
+def verify_fault(boundary, record, action):
+ assert record['result'] == 'observed' and record['after']['bounds'] == record['expected_bounds']
+ assert record['before_bounds'] != record['expected_bounds']
+ prefix, lane = record['prefix'], record['lane']
+ assert set(active_drags(prefix)) == {lane}
+ tail = trace_interval(prefix, boundary)
+ assert record['gate_ns'] <= record['requested_ns'] <= record['acknowledged_ns'] <= record['after']['observed_ns']
+ assert 0 <= record['requested_ns'] - record['gate_ns'] <= 250_000_000
+ assert prefix['events'][-1][1] <= record['requested_ns'], 'trace clock is incompatible'
+ synthetic = [row for row in tail if row[5] in (1, 2)]
+ assert all(row[5] == lane for row in synthetic), 'cleanup crossed lanes'
+ cancelled = [row for row in synthetic if row[2] == 'agent_cancel']
+ assert len(cancelled) == 1 and cancelled[0][1] >= record['requested_ns'], 'no post-fault cancellation'
+ assert not any(row[2] in ('agent_admitted', 'agent_drag_start', 'agent_drag_end', 'agent_action_end',
+ 'keyboard_key', 'pointer_axis') for row in synthetic), 'extra action or false completion'
+ releases = [row for row in synthetic if row[2] == 'pointer_button']
+ assert len(releases) == 1 and releases[0][6] == 0 and releases[0][0] > cancelled[0][0], 'missing own-seat release'
+ assert not any(row[2] in ('pointer_motion', 'pointer_enter') and row[0] > cancelled[0][0]
+ for row in synthetic), 'input continued after cancellation'
+ stopped = stopped_prefix(boundary)
+ isolation = analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ return {'result': 'verified', 'outcome': fault_outcome(action), 'continuous_isolation': isolation,
+ 'synthetic_cleanup': 'verified', 'saved_document_effect': 'unproven'}
+
+
+def prepare_recovery(client, spec, stage, guard, save):
+ """Refresh an expired successful observation once, before any input.
+
+ Preserve both snapshots and the real observation start. Failed observations
+ and unknown actions are never retried; actual dispatch still checks 5 s.
+ """
+ for attempt in range(1, MAX_GROUNDING_ATTEMPTS + 1):
+ guard()
+ app_process_identity(spec['app'], spec['target']['pid'])
+ before = grounded_snapshot(client, spec['target'], spec)
+ prepared_ns = before['proof_observation_started_ns']
+ assert type(prepared_ns) is int and prepared_ns > 0, 'invalid recovery observation timestamp'
+ arguments, oracle = pointer_grounding.action(before, pointer_grounding.read_pixels(before['proof_image']), spec['app'], stage)
+ checked_ns = time.monotonic_ns()
+ age = checked_ns - prepared_ns
+ assert age >= 0, 'recovery observation is in the future'
+ ready = age <= MAX_GROUNDING_AGE_NS - GROUNDING_DISPATCH_RESERVE_NS
+ prepared = {'snapshot': before, 'arguments': arguments, 'oracle': oracle, 'prepared_ns': prepared_ns,
+ 'attempt': attempt, 'checked_ns': checked_ns, 'grounding_age_ns': age,
+ 'dispatch_reserve_ns': GROUNDING_DISPATCH_RESERVE_NS, 'ready': ready, 'input_attempted': False}
+ save(f'recovery-grounding-attempt-{attempt}.json', prepared)
+ save('recovery-grounding.json', prepared)
+ if ready:
+ return prepared
+ raise AssertionError('recovery grounding expired; no input sent')
+
+
+def recover(client, observer, victim, spec, stage, trace, boundary, lane, guard, save, result):
+ assert victim.process.poll() is not None, 'old runtime must be reaped before recovery'
+ assert victim.process.pid not in assert_distinct_runtimes([client, observer]), 'reused old runtime'
+ assert stage in RECOVERY_STAGES[spec['app']]
+ fresh = {**spec, 'name': spec['name'] + '-recovery', 'pointer_stage': stage}
+ result.update(runtime_pid=client.process.pid, previous_runtime_pid=victim.process.pid, replayed=False)
+ assert not client.tool('start_session', {'session': fresh['name']}).get('isError')
+ prepared = prepare_recovery(client, fresh, stage, guard, save)
+ prepared_ns, arguments, oracle = prepared['prepared_ns'], prepared['arguments'], prepared['oracle']
+ tool = pointer_grounding.STAGES[spec['app']][stage]
+ assert tool in ('click', 'scroll')
+ guard()
+ dispatch_ns = time.monotonic_ns()
+ assert 0 <= dispatch_ns - prepared_ns <= MAX_GROUNDING_AGE_NS, 'recovery grounding expired'
+ result['action'] = {'outcome': 'unknown', 'replayed': False, 'dispatch_ns': dispatch_ns}
+ try:
+ response = client.tool(tool, {**arguments, **spec['target'], 'session': fresh['name'], 'delivery_mode': 'background'})
+ except Exception as error:
+ result['action']['error'] = str(error)
+ else:
+ result['action'].update(outcome='response', response=response)
+ save('recovery-action.json', result['action'])
+ after = grounded_snapshot(observer, spec['target'], fresh, session=False)
+ save('recovery-after.json', after)
+ assert result['action']['outcome'] == 'response', 'recovery delivery unknown; no replay'
+ check_response(response, {'kind': 'dispatched'})
+ result['app_effect'] = pointer_grounding.verify(after, pointer_grounding.read_pixels(after['proof_image']), oracle)
+ page = trace.collect()
+ result['trace'] = verify_recovery_trace(boundary, page, lane, tool)
+ guard()
+ result['result'] = 'verified'
+ return page
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ report = {'result': 'failed', 'scope': 'native-geometry-fault', 'fault': 'unproven',
+ 'recovery': {'result': 'unproven'}, 'full_desktop_matrix': False, 'physical_hardware': False}
+ clients, observer, grab, trace, fault, pool, future = [], None, None, None, None, None, None
+ prefix = primary_before = baseline = deadline = None
+ def guard():
+ require_primary_active(grab, deadline)
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ assert args.trace_socket.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')
+ fault = GeometryFault(plan)
+ origin = provenance(args, plan)
+ for name in ('production_geometry_fault_proof.py', 'production_geometry_fault_proof_test.py', 'production_cancel_proof.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ save('provenance.json', origin)
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ return DirectMCP(args.driver, directory, PROFILE)
+ spec = plan['agents'][0]
+ clients.append(launch('agent'))
+ assert not clients[0].tool('start_session', {'session': spec['name']}).get('isError')
+ observer = launch('observer')
+ report['driver_processes'] = assert_distinct_runtimes([clients[0], observer])
+ foreground = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError')
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < foreground['width'] and 0 < y < foreground['height']
+ x, y = foreground['x'] + x, foreground['y'] + y
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid'] and baseline['held']
+ trace = Trace(args.trace_socket)
+ assert trace.hello['protocol'] == 3
+ start_ns = time.monotonic_ns()
+ trace.exchange('TRACE_START')
+ initial = trace.collect()
+ assert start_ns <= initial['events'][0][1] <= time.monotonic_ns(), 'incompatible trace clock'
+ assert not active_drags(initial) and not any(r[5] in (1, 2) for r in initial['events'])
+ prepared = prepare_drag(clients[0], spec)
+ save('drag-grounding.json', prepared)
+ guard()
+ pool = ThreadPoolExecutor(max_workers=1)
+ future = pool.submit(call_drag, clients[0], spec, prepared, guard)
+ _, lane = fault.inject(trace, initial, future, guard)
+ save('fault.json', fault.record)
+ report['action'] = future.result(timeout=5)
+ save('drag-action.json', report['action'])
+ boundary = trace.collect()
+ save('fault-prefix.json', boundary)
+ report['fault'] = verify_fault(boundary, fault.record, report['action'])
+ changed = {**spec, 'bounds': fault.expected}
+ after = grounded_snapshot(observer, spec['target'], changed, session=False)
+ save('interrupted-state.json', {'snapshot': after, 'action': report['action'], 'replayed': False,
+ 'saved_document_effect': 'unproven'})
+ close_owned(clients[0])
+ teardown = trace.collect()
+ report['runtime_teardown'] = verify_recovery_cleanup(boundary, stopped_prefix(teardown))
+ boundary = teardown # Seat teardown is included before new admission.
+ save('pre-recovery-prefix.json', boundary)
+ clients.append(launch('recovery'))
+ prefix = recover(clients[-1], observer, clients[0], changed, plan['recovery']['pointer_stage'],
+ trace, boundary, lane, guard, save, report['recovery'])
+ save('recovery-prefix.json', prefix)
+ guard()
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = [(f'close_agent_{index}', lambda c=client: close_owned(c)) for index, client in enumerate(clients)]
+ if future:
+ def preserve_action():
+ try:
+ report['action'] = future.result(timeout=5)
+ except Exception as error:
+ report['action'] = {'outcome': 'unknown', 'error': str(error), 'replayed': False}
+ save('drag-action.json', report['action'])
+ operations.append(('preserve_action', preserve_action))
+ if pool:
+ operations.append(('shutdown_pool', lambda: pool.shutdown(wait=False, cancel_futures=True)))
+ if fault:
+ operations.append(('preserve_fault', lambda: save('fault.json', fault.record)))
+ operations.append(('restore_geometry', lambda: save('restoration.json', fault.restore())))
+ if trace:
+ def finish_trace():
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('trace.json', stopped)
+ guard()
+ isolation = verify_recovery_cleanup(prefix, stopped) if prefix else analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ report['continuous_isolation'] = isolation
+ assert wm() == primary_before, 'primary cursor/focus/workspace changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), current
+ guard()
+ operations += [('finish_trace', finish_trace), ('close_trace', trace.close)]
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release_primary))
+ if observer:
+ operations.append(('close_observer', lambda: close_owned(observer)))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.py
new file mode 100644
index 0000000000..5323d6ff2f
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.py
@@ -0,0 +1,418 @@
+"""Portable synthetic tests; these do not exercise or certify a native desktop."""
+from contextlib import ExitStack
+from copy import deepcopy
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_geometry_fault_proof as proof
+
+
+BOUNDS = {'x': 10, 'y': 20, 'width': 800, 'height': 600}
+PARTIAL = {'structuredContent': {'effect': 'partial', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background', 'delivered_count': 1}}}
+DELIVERED = {'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background'}}}
+
+
+def plan(kind='move', app='calc'):
+ return {'purpose': 'geometry_fault', 'disposable': True, 'compositor': {'pid': 50, 'instance': 'test_1'},
+ 'foreground': {'pid': 10, 'window_id': 100}, 'primary_point': [20, 20],
+ 'agents': [{'app': app, 'name': 'geometry', 'target': {'pid': 20, 'window_id': 200},
+ 'bounds': dict(BOUNDS), 'pointer_stage': proof.POINTER_STAGES[app], 'drag': {}}],
+ 'fault': {'kind': kind, 'to': [30, 40] if kind == 'move' else [820, 620]},
+ 'recovery': {'pointer_stage': 'click_b2' if app == 'calc' else 'scroll_down'}}
+
+
+def trace(rows, active=True):
+ return {'hook': True, 'active': active, 'overflow': False, 'timed_out': False, 'count': len(rows),
+ 'events': [[i + 1, ms * 1_000_000, kind, 100, 100, lane, value]
+ for i, (ms, kind, lane, value) in enumerate(rows)]}
+
+
+ACTIVE = [(0, 'start', 0, 0), (1, 'agent_admitted', 1, 0), (2, 'agent_drag_start', 1, 0),
+ (3, 'pointer_button', 1, 1), (4, 'pointer_motion', 1, 0)]
+CANCEL = ACTIVE + [(8, 'agent_cancel', 1, 0), (9, 'pointer_button', 1, 0), (10, 'pointer_leave', 1, 0)]
+
+
+def record():
+ return {'result': 'observed', 'lane': 1, 'prefix': trace(ACTIVE), 'gate_ns': 5_000_000,
+ 'requested_ns': 6_000_000, 'acknowledged_ns': 7_000_000,
+ 'after': {'bounds': {**BOUNDS, 'x': 30, 'y': 40}, 'observed_ns': 11_000_000},
+ 'before_bounds': dict(BOUNDS), 'expected_bounds': {**BOUNDS, 'x': 30, 'y': 40}}
+
+
+def action(response=PARTIAL):
+ return {'outcome': 'response', 'response': deepcopy(response), 'replayed': False}
+
+
+def client(pid, alive=True):
+ process = Mock(pid=pid, poll=Mock(return_value=None if alive else 0))
+ process.kill.side_effect = lambda: setattr(process.poll, 'return_value', -9)
+ return Mock(process=process)
+
+
+class OracleTests(unittest.TestCase):
+ def test_partial_and_unknown_preserve_delivery_uncertainty(self):
+ for observed in (action(), {'outcome': 'unknown', 'error': 'lost reply', 'replayed': False},
+ action({'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'unknown'}}})):
+ self.assertEqual(proof.verify_fault(trace(CANCEL), record(), observed)['result'], 'verified')
+ for response in (DELIVERED, {'isError': True, 'structuredContent': {
+ 'effect': 'refused', 'reason': 'cancelled'}}, {**PARTIAL, 'structuredContent': {
+ **PARTIAL['structuredContent'], 'delivery': {'mode': 'background', 'delivered_count': 0}}}):
+ with self.subTest(response=response), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), record(), action(response))
+ with self.assertRaises(AssertionError):
+ proof.fault_outcome({**action(), 'replayed': True})
+
+ def test_incomplete_and_discontinuous_telemetry_cannot_pass(self):
+ for key, value in [('hook', False), ('active', False), ('overflow', True), ('timed_out', True), ('count', 0)]:
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_fault({**trace(CANCEL), key: value}, record(), action())
+ changed = trace(CANCEL)
+ changed['events'][1][1] += 1
+ with self.assertRaisesRegex(AssertionError, 'history'):
+ proof.verify_fault(changed, record(), action())
+
+ def test_primary_warp_and_input_leak_fail_even_with_equal_endpoints(self):
+ for kind, lane, value in [('cursor', 0, 0), ('pointer_focus', 0, 0), ('pointer_button', 0, 0),
+ ('keyboard_key', 0, 1), ('pointer_axis', 0, 0)]:
+ rows = trace(CANCEL + [(12, kind, lane, value), (13, 'pointer_leave', 1, 0)])
+ if kind == 'cursor':
+ rows['events'][-2][3] += 1
+ rows['events'][-1][2] = 'cursor' # Warp back: endpoint-only checks would miss it.
+ rows['events'][-1][5] = 0
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ proof.verify_fault(rows, record(), action())
+
+ def test_own_lane_cancellation_release_and_no_continuation_required(self):
+ mutations = [ACTIVE, CANCEL[:5] + CANCEL[6:], CANCEL[:6] + CANCEL[7:],
+ ACTIVE + [(8, 'agent_cancel', 2, 0), (9, 'pointer_button', 1, 0)],
+ ACTIVE + [(5, 'agent_cancel', 1, 0), (9, 'pointer_button', 1, 0)],
+ ACTIVE + [(8, 'pointer_button', 1, 0), (9, 'agent_cancel', 1, 0)]]
+ for kind in ('agent_drag_end', 'agent_drag_start', 'agent_admitted', 'agent_action_end',
+ 'pointer_motion', 'pointer_enter', 'keyboard_key', 'pointer_axis'):
+ mutations.append(CANCEL + [(12, kind, 1, 0)])
+ for rows in mutations:
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(rows), record(), action())
+
+ def test_unchanged_geometry_stale_gate_and_invalid_timestamps_fail(self):
+ for field, value in [('result', 'unproven'), ('requested_ns', 300_000_000),
+ ('acknowledged_ns', 4_000_000), ('gate_ns', 7_000_000),
+ ('after', {'bounds': BOUNDS, 'observed_ns': 11_000_000}),
+ ('before_bounds', record()['expected_bounds'])]:
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(CANCEL), {**record(), field: value}, action())
+
+
+class OwnershipTests(unittest.TestCase):
+ def test_resize_keeps_center_not_top_left_and_inverse_restores_exact_frame(self):
+ before = {'x': 983, 'y': 576, 'width': 480, 'height': 480}
+ smaller = {'x': 987, 'y': 580, 'width': 472, 'height': 472}
+ fault = {'kind': 'resize', 'to': [472, 472]}
+ self.assertEqual(proof.expected_geometry(before, fault), smaller)
+ self.assertEqual(proof.expected_geometry(smaller, {'kind': 'resize', 'to': [480, 480]}), before)
+ self.assertEqual(proof.expected_geometry(BOUNDS, plan('resize')['fault']),
+ {'x': 0, 'y': 10, 'width': 820, 'height': 620})
+ self.assertEqual(proof.expected_geometry(BOUNDS, plan()['fault']),
+ {**BOUNDS, 'x': 30, 'y': 40})
+
+ def test_resize_with_fractional_center_shift_is_rejected_before_dispatch(self):
+ for size in ([819, 620], [820, 619]):
+ candidate = plan('resize')
+ candidate['fault']['to'] = size
+ with self.subTest(size=size), self.assertRaisesRegex(AssertionError, 'even'):
+ proof.validate_plan(candidate)
+
+ def test_plan_confines_targets_geometry_and_new_action(self):
+ for kind in ('move', 'resize'):
+ for app in ('calc', 'inkscape'):
+ candidate = plan(kind, app)
+ proof.validate_plan(candidate)
+ bad = deepcopy(candidate)
+ bad['agents'][0]['drag'] = {'pid': 999}
+ with self.assertRaises(AssertionError):
+ proof.validate_plan(bad)
+ for update in ({'disposable': False}, {'agents': []}, {'fault': {'kind': 'close', 'to': [1, 2]}},
+ {'fault': {'kind': 'move', 'to': [10, 20]}},
+ {'fault': {'kind': 'move', 'to': [9999, 20]}},
+ {'recovery': {'pointer_stage': 'select_range'}},
+ {'compositor': {'pid': 50, 'instance': 'x;bad'}}):
+ with self.subTest(update=update), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **update})
+
+ def controller(self, kind='move'):
+ fault = object.__new__(proof.GeometryFault)
+ candidate = plan(kind)
+ fault.spec, fault.fault = candidate['agents'][0], candidate['fault']
+ fault.instance = 'test_1'
+ fault.owner = {'pid': 20, 'uid': 1000, 'starttime': '1', 'exe': '/usr/bin/app'}
+ fault.compositor = {'pid': 50, 'uid': 1000, 'starttime': '2', 'exe': '/usr/bin/Hyprland'}
+ fault.expected = proof.expected_geometry(BOUNDS, candidate['fault'])
+ fault.mutated, fault.record = False, {'result': 'unproven'}
+ return fault
+
+ def test_snapshot_revalidates_exact_pid_address_native_floating_and_synthetic_title(self):
+ window = {'pid': 20, 'address': '0xc8', 'floating': True, 'xwayland': False,
+ 'title': 'cua-smoke-calc.ods', 'at': [10, 20], 'size': [800, 600]}
+ for change in (None, {'pid': 21}, {'address': '0xc9'}, {'floating': False},
+ {'xwayland': True}, {'title': 'unowned.ods'}):
+ fault = self.controller()
+ fault.hypr = Mock(side_effect=[json.dumps([{'pid': 50, 'instance': 'test_1'}]),
+ json.dumps([{**window, **(change or {})}])])
+ with patch.object(proof, 'process_identity', side_effect=[fault.compositor, fault.owner]):
+ if change:
+ with self.assertRaises(AssertionError):
+ fault.snapshot()
+ else:
+ self.assertEqual(fault.snapshot()['bounds'], BOUNDS)
+ fault = self.controller()
+ with patch.object(proof, 'process_identity', return_value={}), self.assertRaises(AssertionError):
+ fault.snapshot()
+
+ def test_exact_dispatch_has_no_focus_or_input_operation(self):
+ for kind in ('move', 'resize'):
+ fault = self.controller(kind)
+ fault.hypr = Mock(return_value='ok')
+ fault.dispatch(fault.fault['to'])
+ x, y = fault.fault['to']
+ fault.hypr.assert_called_once_with('dispatch',
+ f'hl.dsp.window.{kind}({{ window = "address:0xc8", x = {x}, y = {y}, relative = false }})')
+
+ def test_injection_requires_active_pending_and_fresh_owned_geometry(self):
+ for failure in (None, 'done', 'stale', 'changed', 'reply_lost', 'unchanged'):
+ fault = self.controller()
+ before = {'bounds': dict(BOUNDS), 'observed_ns': 1}
+ after = {'bounds': fault.expected, 'observed_ns': 10}
+ fault.snapshot = Mock(side_effect=[before, {**before, 'bounds': fault.expected} if failure == 'changed' else before, after])
+ fault.dispatch = Mock(side_effect=TimeoutError('lost IPC reply') if failure == 'reply_lost' else None)
+ pending = Mock(done=Mock(return_value=failure == 'done'))
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2})))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[5, 300_000_006 if failure == 'stale' else 6, 7]))
+ stack.enter_context(patch.object(proof, 'wait_for', side_effect=AssertionError('unchanged') if failure == 'unchanged' else lambda check, timeout: check()))
+ if failure:
+ with self.assertRaises((AssertionError, TimeoutError)):
+ fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock())
+ else:
+ _, lane = fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock())
+ self.assertEqual(lane, 1)
+ self.assertEqual(fault.record['result'], 'observed')
+ self.assertEqual(fault.dispatch.call_count, int(failure not in ('done', 'stale', 'changed')))
+ if failure == 'reply_lost':
+ self.assertTrue(fault.mutated, 'unknown dispatch must retain cleanup obligation')
+
+ def test_restore_only_owned_expected_geometry_and_preserve_identity_failure(self):
+ for kind in ('move', 'resize'):
+ fault = self.controller(kind)
+ fault.snapshot, fault.dispatch = Mock(), Mock()
+ self.assertEqual(fault.restore(), {'result': 'not_needed'})
+ fault.snapshot.assert_not_called()
+ for current in (fault.expected, BOUNDS, {**BOUNDS, 'x': 99}):
+ fault.mutated = True
+ fault.snapshot = Mock(side_effect=[{'bounds': current}, {'bounds': BOUNDS}])
+ fault.dispatch = Mock()
+ with patch.object(proof, 'wait_for', side_effect=lambda check, timeout: check()):
+ if current not in (fault.expected, BOUNDS):
+ with self.assertRaisesRegex(AssertionError, 'unowned geometry'):
+ fault.restore()
+ fault.dispatch.assert_not_called()
+ else:
+ self.assertEqual(fault.restore()['result'], 'restored')
+ self.assertEqual(fault.dispatch.call_count, int(current != BOUNDS))
+
+
+class RecoveryTests(unittest.TestCase):
+ def test_expired_observation_refresh_is_bounded_and_never_sends_input(self):
+ budget = proof.MAX_GROUNDING_AGE_NS - proof.GROUNDING_DISPATCH_RESERVE_NS
+ for second_age in (1, budget, budget + 1, proof.MAX_GROUNDING_AGE_NS + 1):
+ with self.subTest(second_age=second_age), ExitStack() as stack:
+ snapshots = [{'proof_image': str(i) + '.png', 'proof_observation_started_ns': i * 10_000_000_000}
+ for i in (1, 2)]
+ observe = stack.enter_context(patch.object(proof, 'grounded_snapshot', side_effect=snapshots))
+ stack.enter_context(patch.object(proof, 'app_process_identity'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1}, {'stage': 'click_b2'})))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[
+ 10_000_000_000 + proof.MAX_GROUNDING_AGE_NS + 1, 20_000_000_000 + second_age]))
+ fresh, save = Mock(), Mock()
+ if second_age > budget:
+ with self.assertRaisesRegex(AssertionError, 'recovery grounding expired'):
+ proof.prepare_recovery(fresh, plan()['agents'][0], 'click_b2', Mock(), save)
+ else:
+ prepared = proof.prepare_recovery(fresh, plan()['agents'][0], 'click_b2', Mock(), save)
+ self.assertEqual(prepared['prepared_ns'], 20_000_000_000)
+ self.assertIs(prepared['snapshot'], snapshots[1])
+ self.assertEqual(observe.call_count, 2)
+ fresh.tool.assert_not_called()
+ attempts = [c.args[1] for c in save.call_args_list if '-attempt-' in c.args[0]]
+ self.assertEqual([p['attempt'] for p in attempts], [1, 2])
+ self.assertEqual([p['ready'] for p in attempts], [False, second_age <= budget])
+ self.assertTrue(all(p['input_attempted'] is False for p in attempts))
+
+ def test_observation_failure_is_not_retried(self):
+ with patch.object(proof, 'app_process_identity'), \
+ patch.object(proof, 'grounded_snapshot', side_effect=TimeoutError('observation failed')) as observe:
+ fresh = Mock()
+ with self.assertRaises(TimeoutError):
+ proof.prepare_recovery(fresh, plan()['agents'][0], 'click_b2', Mock(), Mock())
+ observe.assert_called_once()
+ fresh.tool.assert_not_called()
+
+ def test_invalid_timestamp_never_gets_a_new_freshness_budget(self):
+ for timestamp in (None, 0, True, -1, 101):
+ with self.subTest(timestamp=timestamp), ExitStack() as stack:
+ snapshot = {'proof_image': 'before.png', 'proof_observation_started_ns': timestamp}
+ observe = stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value=snapshot))
+ stack.enter_context(patch.object(proof, 'app_process_identity'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({}, {})))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', return_value=100))
+ fresh = Mock()
+ with self.assertRaises(AssertionError):
+ proof.prepare_recovery(fresh, plan()['agents'][0], 'click_b2', Mock(), Mock())
+ observe.assert_called_once()
+ fresh.tool.assert_not_called()
+
+ def test_fresh_runtime_fresh_grounding_single_new_action_and_unknown_never_replayed(self):
+ for app in ('calc', 'inkscape'):
+ for failure in (None, 'slow_discovery', 'alive', 'reused', 'stale', 'unknown', 'guard', 'effect'):
+ with self.subTest(app=app, failure=failure), ExitStack() as stack:
+ spec = plan(app=app)['agents'][0]
+ stage = plan(app=app)['recovery']['pointer_stage']
+ tool = 'click' if app == 'calc' else 'scroll'
+ fresh, observer, victim = client(101), client(102), client(100, failure == 'alive')
+ if failure == 'reused':
+ fresh.process.pid = 100
+ fresh.tool.side_effect = [{}, TimeoutError('lost reply') if failure == 'unknown' else DELIVERED]
+ before, after = {'proof_image': 'before.png', 'proof_observation_started_ns': 100}, {'proof_image': 'after.png'}
+ dispatch_ns = 101
+ if failure == 'slow_discovery':
+ before['proof_observation_started_ns'] = proof.MAX_GROUNDING_AGE_NS + 200
+ dispatch_ns = proof.MAX_GROUNDING_AGE_NS + 301
+ stack.enter_context(patch.object(proof, 'grounded_snapshot', side_effect=[before, after]))
+ stack.enter_context(patch.object(proof, 'app_process_identity'))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[dispatch_ns - 1, proof.MAX_GROUNDING_AGE_NS + 101 if failure == 'stale' else dispatch_ns]))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({'x': 20, 'y': 30}, {'stage': stage})))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'verify', side_effect=AssertionError('effect') if failure == 'effect' else None))
+ stack.enter_context(patch.object(proof, 'verify_recovery_trace', return_value={'result': 'verified'}))
+ result, save = {}, Mock()
+ guard = Mock(side_effect=AssertionError('primary expired') if failure == 'guard' else None)
+ if failure not in (None, 'slow_discovery'):
+ with self.assertRaises(AssertionError):
+ proof.recover(fresh, observer, victim, spec, stage, Mock(), trace(CANCEL), 1, guard, save, result)
+ else:
+ proof.recover(fresh, observer, victim, spec, stage, Mock(), trace(CANCEL), 1, guard, save, result)
+ self.assertEqual(result['result'], 'verified')
+ self.assertEqual(result['action']['dispatch_ns'], dispatch_ns)
+ grounding = next(call.args[1] for call in save.call_args_list
+ if call.args[0] == 'recovery-grounding.json')
+ self.assertEqual(grounding['prepared_ns'],
+ before.get('proof_observation_started_ns', 100))
+ inputs = [call for call in fresh.tool.call_args_list if call.args[0] != 'start_session']
+ self.assertEqual(len(inputs), int(failure not in ('alive', 'reused', 'stale', 'guard')))
+ if inputs:
+ self.assertEqual(inputs[0].args[0], tool)
+ if failure == 'unknown':
+ self.assertEqual(result['action']['outcome'], 'unknown')
+ self.assertFalse(result['action']['replayed'])
+ victim.tool.assert_not_called()
+
+ def test_invalid_plan_failure_preserves_cleanup_and_fails(self):
+ with tempfile.TemporaryDirectory() as root:
+ directory = Path(root)
+ plan_path = directory / 'plan.json'
+ plan_path.write_text(json.dumps({**plan(), 'disposable': False}))
+ args = SimpleNamespace(evidence=directory / 'evidence', plan=plan_path)
+ with patch.object(proof, 'GeometryFault') as constructor:
+ self.assertEqual(proof.run(args), 1)
+ constructor.assert_not_called()
+ result = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(result['result'], 'failed')
+ self.assertEqual(json.loads((args.evidence / 'cleanup.json').read_text()), {'errors': []})
+
+ def test_orchestration_always_preserves_trace_reaps_owned_runtimes_and_restores(self):
+ for failure in (None, 'inject', 'recovery', 'restore', 'expired'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ directory = Path(root)
+ plan_path = directory / 'plan.json'
+ plan_path.write_text(json.dumps(plan()))
+ args = SimpleNamespace(evidence=directory / 'evidence', plan=plan_path, driver=Path('/driver'),
+ primary_grab=Path('/grab'), foreground_journal=Path('/journal'),
+ trace_socket=Path('/cua-input-v3.sock'))
+ fault = Mock(record=record(), expected=record()['expected_bounds'])
+ fault.inject.side_effect = AssertionError('injection failed') if failure == 'inject' else None
+ fault.inject.return_value = (trace(ACTIVE), 1)
+ fault.restore.side_effect = AssertionError('restoration refused') if failure == 'restore' else None
+ fault.restore.return_value = {'result': 'restored'}
+ stack.enter_context(patch.object(proof, 'GeometryFault', return_value=fault))
+ stack.enter_context(patch.object(proof, 'provenance', return_value={'files': {}}))
+ agent, observer, fresh = client(101), client(102), client(103)
+ observer.tool.return_value = {'structuredContent': {'screen_width': 1600, 'screen_height': 900}}
+ agent.tool.return_value = {}
+ stack.enter_context(patch.object(proof, 'DirectMCP', side_effect=[agent, observer, fresh]))
+ stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value={'window_bounds': BOUNDS}))
+ stack.enter_context(patch.object(proof, 'prepare_drag', return_value={'grounding': 'fresh'}))
+ stack.enter_context(patch.object(proof, 'call_drag', return_value=action()))
+ grab = Mock(poll=Mock(return_value=None))
+ grab.terminate.side_effect = lambda: setattr(grab.poll, 'return_value', 0)
+ stack.enter_context(patch.object(proof.subprocess, 'Popen', return_value=grab))
+ stack.enter_context(patch.object(proof, 'stop_process'))
+ stack.enter_context(patch.object(proof, 'primary_acknowledgement', return_value='HELD\n'))
+ stack.enter_context(patch.object(proof, 'wait_for', return_value=True))
+ stack.enter_context(patch.object(proof, 'wm', return_value={'pid': 10}))
+ stack.enter_context(patch.object(proof, 'state', return_value={'held': True, 'clicks': 0, 'keys': 0, 'scroll': 0}))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', return_value=0))
+ stopped = False
+ def exchange(command):
+ nonlocal stopped
+ if command == 'TRACE_STOP':
+ stopped = True
+ def guard(*_args):
+ if stopped and failure == 'expired':
+ raise AssertionError('primary deadline expired')
+ stack.enter_context(patch.object(proof, 'require_primary_active', side_effect=guard))
+ recovery = trace(CANCEL + [(11, 'agent_admitted', 1, 0), (12, 'pointer_button', 1, 1),
+ (13, 'pointer_button', 1, 0), (14, 'agent_action_end', 1, 0)])
+ final = proof.stopped_prefix(recovery if failure not in ('inject', 'recovery') else trace(CANCEL))
+ pages = [trace(ACTIVE[:1])]
+ if failure != 'inject':
+ pages += [trace(CANCEL), trace(CANCEL)]
+ pages += [final]
+ tracer = Mock(hello={'protocol': 3}, exchange=Mock(side_effect=exchange), collect=Mock(side_effect=pages))
+ stack.enter_context(patch.object(proof, 'Trace', return_value=tracer))
+ def recover(*args):
+ if failure == 'recovery':
+ raise AssertionError('recovery failed')
+ args[-1]['result'] = 'verified'
+ return recovery
+ stack.enter_context(patch.object(proof, 'recover', side_effect=recover))
+ def close(client):
+ client.process.poll.return_value = 0
+ closer = stack.enter_context(patch.object(proof, 'close_owned', side_effect=close))
+ stack.enter_context(patch('builtins.print'))
+ self.assertEqual(proof.run(args), int(failure is not None))
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['result'], 'failed' if failure else 'passed')
+ self.assertFalse(report['physical_hardware'])
+ self.assertTrue((args.evidence / 'fault.json').exists())
+ self.assertTrue((args.evidence / 'trace.json').exists())
+ fault.restore.assert_called_once()
+ tracer.close.assert_called_once()
+ self.assertEqual(agent.process.poll(), 0)
+ self.assertEqual(observer.process.poll(), 0)
+ if failure != 'inject':
+ self.assertEqual(fresh.process.poll(), 0)
+ self.assertGreaterEqual(closer.call_count, 2)
+ if failure in ('restore', 'expired'):
+ self.assertTrue(json.loads((args.evidence / 'cleanup.json').read_text())['errors'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_handshake_probe.py b/libs/cua-driver/hyprland-plugin/tests/production_handshake_probe.py
new file mode 100644
index 0000000000..5dd298ed85
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_handshake_probe.py
@@ -0,0 +1,278 @@
+"""Opt-in native v3 HELLO-deadline probe; no application input is sent.
+
+Run in a clean disposable Linux Hyprland session with the production plugin
+enabled, no Driver/trace/operator clients, and both input endpoints available:
+
+ python3 production_handshake_probe.py --clean-session \
+ --compositor-pid PID --input-directory "$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE"
+
+The controller must verify candidate/artifact provenance and capture stdout as
+private evidence. This focused probe does not certify the desktop matrix or
+the post-HELLO idle timeout. Portable unit tests are not native evidence.
+"""
+
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import select
+import socket
+import stat
+import struct
+import subprocess
+import sys
+import time
+
+
+ENDPOINTS = ("cua-input-v3.sock", "cua-input-v3-2.sock")
+CAPACITY = 8
+CLOSE_BOUND = 6.5
+IO_TIMEOUT = 0.5
+CLOSED = object()
+
+
+class ProbeFailure(Exception):
+ """Only fixed, path-free reason codes are exposed in evidence."""
+
+
+def require(condition, reason):
+ if not condition:
+ raise ProbeFailure(reason)
+
+
+def validate_path(path, *, directory=False, private=True):
+ metadata = path.lstat()
+ require(path.is_absolute() and path == path.resolve(strict=True), "noncanonical_path")
+ require(metadata.st_uid == os.getuid(), "wrong_path_owner")
+ if directory:
+ # The private runtime directory confines descendants. Hyprland may
+ # create readable child directories; they must not be writable by peers.
+ require(stat.S_ISDIR(metadata.st_mode) and not metadata.st_mode & (0o077 if private else 0o022),
+ "nonprivate_directory")
+ else:
+ require(stat.S_ISSOCK(metadata.st_mode) and stat.S_IMODE(metadata.st_mode) == 0o600,
+ "invalid_socket_type_or_mode")
+
+
+def ctl(*arguments):
+ try:
+ return json.loads(subprocess.check_output(
+ ["hyprctl", "-j", *arguments], text=True, stderr=subprocess.DEVNULL,
+ timeout=IO_TIMEOUT))
+ except (OSError, subprocess.SubprocessError, ValueError):
+ raise ProbeFailure("compositor_unresponsive") from None
+
+
+def preflight(args):
+ require(sys.platform == "linux" and args.clean_session, "clean_linux_session_required")
+ require(args.compositor_pid > 0, "invalid_compositor_pid")
+ instance = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "")
+ require(bool(re.fullmatch(r"[a-zA-Z0-9_.-]+", instance)) and instance not in (".", ".."),
+ "invalid_instance_signature")
+ runtime = Path(os.environ.get("XDG_RUNTIME_DIR", ""))
+ expected = runtime / "hypr" / instance
+ require(args.input_directory == expected, "wrong_instance_directory")
+ for directory in (runtime, runtime / "hypr", expected):
+ validate_path(directory, directory=True, private=directory == runtime)
+ instances = ctl("instances")
+ require(isinstance(instances, list), "invalid_instances_reply")
+ matches = [row for row in instances if isinstance(row, dict) and row.get("instance") == instance]
+ require(len(matches) == 1 and matches[0].get("pid") == args.compositor_pid,
+ "wrong_compositor_instance")
+ process = Path(f"/proc/{args.compositor_pid}")
+ require(process.stat().st_uid == os.getuid()
+ and (process / "exe").resolve(strict=True).name == "Hyprland",
+ "wrong_compositor_process")
+ paths = [expected / name for name in ENDPOINTS]
+ for path in paths:
+ validate_path(path)
+ return paths
+
+
+def validate_reply(value, *, hello=False):
+ require(isinstance(value, dict), "reply_not_object")
+ if hello:
+ require(value.get("ok") is True and type(value.get("protocol")) is int
+ and value["protocol"] == 3 and isinstance(value.get("epoch"), str)
+ and bool(re.fullmatch(r"[0-9a-f]{32}", value["epoch"])), "invalid_hello_reply")
+ else:
+ require(value.get("ok") is False and value.get("code") == "invalid_request",
+ "invalid_prehello_refusal")
+
+
+class NativeRuntime:
+ clock = staticmethod(time.monotonic)
+ sleep = staticmethod(time.sleep)
+
+ def __init__(self, pid):
+ self.pid = pid
+
+ def health(self):
+ require(isinstance(ctl("version"), dict), "invalid_version_reply")
+
+ def connect(self, path):
+ validate_path(path)
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+ try:
+ client.settimeout(IO_TIMEOUT)
+ client.connect(str(path))
+ pid, uid, _ = struct.unpack("3i", client.getsockopt(
+ socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")))
+ require(pid == self.pid and uid == os.getuid(), "wrong_socket_peer")
+ return client
+ except BaseException:
+ client.close()
+ raise
+
+ def exchange(self, client, packet):
+ try:
+ require(client.send(packet) == len(packet), "short_packet_send")
+ reply = client.recv(2049)
+ except (BrokenPipeError, ConnectionResetError):
+ return CLOSED
+ except TimeoutError:
+ raise ProbeFailure("reply_timeout") from None
+ if not reply:
+ return CLOSED
+ require(len(reply) <= 2048, "oversized_reply")
+ try:
+ return json.loads(reply)
+ except (ValueError, UnicodeError):
+ raise ProbeFailure("malformed_reply") from None
+
+ def closed(self, client):
+ if not select.select([client], [], [], 0)[0]:
+ return False
+ try:
+ packet = client.recv(2049)
+ except ConnectionResetError:
+ return True
+ require(not packet, "unsolicited_reply")
+ return True
+
+
+def probe_endpoint(path, runtime, evidence):
+ """Fill every slot, observe hard expiry, then retain eight fresh HELLOs.
+
+ runtime is injectable for portable failure-path tests. Times are observed
+ from local connect, not a claim to know the server's precise accept time.
+ All sockets are closed in finally, including failures and interrupts.
+ """
+ sockets = []
+ started = runtime.clock()
+ rows = evidence.setdefault("clients", [])
+ evidence.update(result="failed", capacity=CAPACITY, close_bound_seconds=CLOSE_BOUND,
+ health_checks=[], recovery_hello_count=0, cleanup_complete=False)
+
+ def health():
+ before = runtime.clock()
+ runtime.health()
+ evidence["health_checks"].append({"at_seconds": round(before - started, 3),
+ "duration_seconds": round(runtime.clock() - before, 3)})
+
+ def refusal(client, row):
+ value = runtime.exchange(client, b"CLAIM")
+ if value is CLOSED:
+ return False
+ validate_reply(value)
+ row["refusal_seconds"].append(round(runtime.clock() - row["opened"], 3))
+ return True
+
+ def mark_closed(row):
+ elapsed = runtime.clock() - row["opened"]
+ row["closed_seconds"] = round(elapsed, 3)
+ require(4.75 <= elapsed <= CLOSE_BOUND, "closure_outside_deadline_window")
+ require(len(row["refusal_seconds"]) >= 4 and row["refusal_seconds"][-1] >= 3,
+ "insufficient_continued_prehello_traffic")
+
+ try:
+ health()
+ for index in range(CAPACITY):
+ opened = runtime.clock()
+ client = runtime.connect(path)
+ sockets.append(client)
+ row = {"slot": index, "opened": opened, "refusal_seconds": []}
+ rows.append(row)
+ require(refusal(client, row), "initial_connection_refused")
+ require(runtime.clock() - rows[0]["opened"] <= 1, "slow_initial_admission")
+ pending = list(zip(sockets, rows))
+ next_health = runtime.clock()
+ while pending:
+ if runtime.clock() >= next_health:
+ health()
+ next_health = runtime.clock() + 1
+ for client, row in list(pending):
+ elapsed = runtime.clock() - row["opened"]
+ require(elapsed <= CLOSE_BOUND, "hard_hello_deadline_exceeded")
+ if runtime.closed(client):
+ mark_closed(row)
+ pending.remove((client, row))
+ elif elapsed >= len(row["refusal_seconds"]):
+ if not refusal(client, row):
+ mark_closed(row)
+ pending.remove((client, row))
+ if pending:
+ runtime.sleep(0.025)
+ health()
+ epochs = set()
+ for _ in range(CAPACITY):
+ client = runtime.connect(path)
+ sockets.append(client)
+ reply = runtime.exchange(client, b"HELLO")
+ require(reply is not CLOSED, "capacity_recovery_failed")
+ validate_reply(reply, hello=True)
+ epochs.add(reply["epoch"])
+ evidence["recovery_hello_count"] += 1
+ require(len(epochs) == 1, "endpoint_epoch_changed")
+ health()
+ evidence["result"] = "passed"
+ finally:
+ cleanup_failed = False
+ for client in sockets:
+ try:
+ client.close()
+ except OSError:
+ cleanup_failed = True
+ for row in rows:
+ row["opened_seconds"] = round(row.pop("opened") - started, 3)
+ evidence["cleanup_complete"] = not cleanup_failed
+ evidence["duration_seconds"] = round(runtime.clock() - started, 3)
+ if cleanup_failed:
+ evidence["result"] = "failed"
+ raise ProbeFailure("socket_cleanup_failed")
+
+
+def run(args):
+ result = {"result": "failed", "native_run": True, "full_desktop_matrix": False,
+ "post_hello_idle_tested": False, "endpoints": []}
+ try:
+ paths = preflight(args)
+ runtime = NativeRuntime(args.compositor_pid)
+ for path in paths:
+ evidence = {"endpoint": path.name}
+ result["endpoints"].append(evidence)
+ probe_endpoint(path, runtime, evidence)
+ result["result"] = "passed"
+ except ProbeFailure as error:
+ result["failure"] = str(error)
+ except (OSError, ValueError, RuntimeError):
+ result["failure"] = "native_io_failure"
+ except KeyboardInterrupt:
+ result["failure"] = "interrupted"
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--clean-session", action="store_true",
+ help="confirm a disposable session without other input endpoint clients")
+ parser.add_argument("--compositor-pid", type=int, required=True)
+ parser.add_argument("--input-directory", type=Path, required=True)
+ result = run(parser.parse_args())
+ print(json.dumps(result, indent=2, sort_keys=True))
+ return 0 if result["result"] == "passed" else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_handshake_probe_test.py b/libs/cua-driver/hyprland-plugin/tests/production_handshake_probe_test.py
new file mode 100644
index 0000000000..8f81251569
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_handshake_probe_test.py
@@ -0,0 +1,258 @@
+"""Portable helper tests; these do not exercise or certify native Hyprland."""
+
+import json
+import os
+from pathlib import Path
+import socket
+import stat
+import struct
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+from production_handshake_probe import (
+ CAPACITY, CLOSED, ENDPOINTS, NativeRuntime, ProbeFailure, preflight,
+ probe_endpoint, run, validate_path, validate_reply,
+)
+
+
+REFUSAL = {"ok": False, "code": "invalid_request"}
+HELLO = {"ok": True, "protocol": 3, "epoch": "a" * 32}
+
+
+class FakeClient:
+ def __init__(self, opened, path):
+ self.opened = opened
+ self.path = path
+ self.closed = False
+ self.packets = []
+
+ def close(self):
+ self.closed = True
+
+
+class FakeRuntime:
+ def __init__(self, expiry=5.05, refusal=REFUSAL, hello=HELLO, recovery_limit=8):
+ self.now = 10
+ self.expiry = expiry
+ self.refusal = refusal
+ self.hello = hello
+ self.recovery_limit = recovery_limit
+ self.clients = []
+ self.hellos = 0
+ self.health_checks = 0
+
+ def clock(self):
+ return self.now
+
+ def sleep(self, seconds):
+ self.now += seconds
+
+ def health(self):
+ self.health_checks += 1
+
+ def connect(self, path):
+ if self.clients and self.clients[-1].path != path:
+ assert all(client.closed for client in self.clients)
+ client = FakeClient(self.now, path)
+ self.clients.append(client)
+ return client
+
+ def closed(self, client):
+ return self.now - client.opened >= self.expiry
+
+ def exchange(self, client, packet):
+ client.packets.append(packet)
+ if packet == b"CLAIM":
+ return CLOSED if self.closed(client) else self.refusal
+ assert packet == b"HELLO" and client.packets == [b"HELLO"]
+ self.hellos += 1
+ return self.hello if self.hellos <= self.recovery_limit else CLOSED
+
+
+class DeadlineTests(unittest.TestCase):
+ def attempt(self, runtime, failure=None):
+ evidence = {}
+ if failure:
+ with self.assertRaisesRegex(ProbeFailure, failure):
+ probe_endpoint(Path(ENDPOINTS[0]), runtime, evidence)
+ else:
+ probe_endpoint(Path(ENDPOINTS[0]), runtime, evidence)
+ self.assertTrue(evidence["cleanup_complete"])
+ self.assertTrue(all(client.closed for client in runtime.clients))
+ self.assertNotIn("opened", json.dumps(evidence).replace("opened_seconds", ""))
+ return evidence
+
+ def test_fixed_deadline_despite_traffic_and_full_capacity_recovery(self):
+ runtime = FakeRuntime()
+ evidence = self.attempt(runtime)
+ self.assertEqual(evidence["result"], "passed")
+ self.assertEqual(evidence["recovery_hello_count"], CAPACITY)
+ self.assertEqual(len(runtime.clients), 2 * CAPACITY)
+ for row in evidence["clients"]:
+ self.assertGreaterEqual(len(row["refusal_seconds"]), 5)
+ self.assertGreaterEqual(row["refusal_seconds"][-1], 4)
+ self.assertLess(row["closed_seconds"], 5.1)
+ self.assertGreaterEqual(runtime.health_checks, 7)
+ self.assertTrue(all(set(client.packets) == {b"CLAIM"}
+ for client in runtime.clients[:CAPACITY]))
+ self.assertTrue(all(client.packets == [b"HELLO"]
+ for client in runtime.clients[CAPACITY:]))
+
+ def test_old_activity_based_timeout_fails_boundedly(self):
+ runtime = FakeRuntime(expiry=float("inf"))
+ evidence = self.attempt(runtime, "hard_hello_deadline_exceeded")
+ self.assertLess(evidence["duration_seconds"], 6.6)
+ self.assertEqual(evidence["recovery_hello_count"], 0)
+
+ def test_early_close_cannot_pass_as_deadline_expiry(self):
+ self.attempt(FakeRuntime(expiry=2), "closure_outside_deadline_window")
+
+ def test_initial_capacity_unavailable_fails(self):
+ self.attempt(FakeRuntime(expiry=0), "initial_connection_refused")
+
+ def test_wrong_refusal_does_not_pass(self):
+ for reply in ({"ok": True}, {"ok": False, "code": "lane_busy"}, None, []):
+ with self.subTest(reply=reply):
+ self.attempt(FakeRuntime(refusal=reply), "reply_not_object|invalid_prehello_refusal")
+
+ def test_wrong_hello_protocol_and_epoch_fail(self):
+ for reply in ({**HELLO, "protocol": 0}, {**HELLO, "protocol": True},
+ {**HELLO, "epoch": "bad"}, {**HELLO, "ok": 1}, None):
+ with self.subTest(reply=reply):
+ self.attempt(FakeRuntime(hello=reply), "reply_not_object|invalid_hello_reply")
+
+ def test_partial_capacity_recovery_fails_and_closes_every_client(self):
+ evidence = self.attempt(FakeRuntime(recovery_limit=7), "capacity_recovery_failed")
+ self.assertEqual(evidence["recovery_hello_count"], 7)
+
+ def test_changed_epoch_during_recovery_fails(self):
+ runtime = FakeRuntime()
+ exchange = runtime.exchange
+
+ def changing(client, packet):
+ reply = exchange(client, packet)
+ return {**reply, "epoch": "b" * 32} if runtime.hellos == 2 else reply
+
+ runtime.exchange = changing
+ self.attempt(runtime, "endpoint_epoch_changed")
+
+ def test_unresponsive_compositor_fails_and_cleans_up(self):
+ runtime = FakeRuntime()
+ runtime.health = Mock(side_effect=[None, ProbeFailure("compositor_unresponsive")])
+ self.attempt(runtime, "compositor_unresponsive")
+
+ def test_exchange_timeout_is_not_reported_as_closure(self):
+ runtime = FakeRuntime()
+ runtime.exchange = Mock(side_effect=ProbeFailure("reply_timeout"))
+ evidence = self.attempt(runtime, "reply_timeout")
+ self.assertNotIn("closed_seconds", evidence["clients"][0])
+
+ def test_both_endpoints_run_sequentially_with_cleanup(self):
+ runtime = FakeRuntime(recovery_limit=16)
+ paths = [Path(name) for name in ENDPOINTS]
+ with patch("production_handshake_probe.preflight", return_value=paths), \
+ patch("production_handshake_probe.NativeRuntime", return_value=runtime):
+ result = run(SimpleNamespace(compositor_pid=123))
+ self.assertEqual(result["result"], "passed")
+ self.assertEqual([row["endpoint"] for row in result["endpoints"]], list(ENDPOINTS))
+ self.assertTrue(all(row["cleanup_complete"] for row in result["endpoints"]))
+ self.assertFalse(result["post_hello_idle_tested"])
+
+ def test_cleanup_failure_does_not_skip_remaining_sockets_or_report_pass(self):
+ runtime = FakeRuntime()
+ connect = runtime.connect
+
+ def bad_close(path):
+ client = connect(path)
+ if len(runtime.clients) == 1:
+ client.close = Mock(side_effect=OSError("synthetic close failure"))
+ return client
+
+ runtime.connect = bad_close
+ evidence = {}
+ with self.assertRaisesRegex(ProbeFailure, "socket_cleanup_failed"):
+ probe_endpoint(Path(ENDPOINTS[0]), runtime, evidence)
+ self.assertEqual(evidence["result"], "failed")
+ self.assertFalse(evidence["cleanup_complete"])
+ self.assertTrue(all(client.closed for client in runtime.clients[1:]))
+
+
+class ValidationTests(unittest.TestCase):
+ def test_explicit_linux_clean_session_required(self):
+ with patch("production_handshake_probe.sys.platform", "linux"):
+ with self.assertRaisesRegex(ProbeFailure, "clean_linux_session_required"):
+ preflight(SimpleNamespace(clean_session=False))
+
+ def test_private_canonical_directory_and_socket_metadata(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory).resolve()
+ path.chmod(0o700)
+ validate_path(path, directory=True)
+ path.chmod(0o755)
+ with self.assertRaisesRegex(ProbeFailure, "nonprivate_directory"):
+ validate_path(path, directory=True)
+ validate_path(path, directory=True, private=False)
+ path.chmod(0o775)
+ with self.assertRaisesRegex(ProbeFailure, "nonprivate_directory"):
+ validate_path(path, directory=True, private=False)
+ path.chmod(0o700)
+ with self.assertRaisesRegex(ProbeFailure, "invalid_socket_type_or_mode"):
+ validate_path(path)
+ metadata = SimpleNamespace(st_uid=os.getuid() + 1, st_mode=stat.S_IFSOCK | 0o600)
+ with patch.object(Path, "lstat", return_value=metadata):
+ with self.assertRaisesRegex(ProbeFailure, "wrong_path_owner"):
+ validate_path(path)
+
+ def test_socket_permissions_and_symlinks_fail_closed(self):
+ path = Path("/synthetic/input.sock")
+ for mode in (stat.S_IFREG | 0o600, stat.S_IFSOCK | 0o666, stat.S_IFLNK | 0o600):
+ with self.subTest(mode=mode), \
+ patch.object(Path, "lstat", return_value=SimpleNamespace(st_uid=os.getuid(), st_mode=mode)), \
+ patch.object(Path, "resolve", return_value=path):
+ with self.assertRaisesRegex(ProbeFailure, "invalid_socket_type_or_mode"):
+ validate_path(path)
+ with patch.object(Path, "lstat", return_value=SimpleNamespace(st_uid=os.getuid(), st_mode=stat.S_IFSOCK | 0o600)), \
+ patch.object(Path, "resolve", return_value=Path("/synthetic/other.sock")):
+ with self.assertRaisesRegex(ProbeFailure, "noncanonical_path"):
+ validate_path(path)
+
+ def test_exact_peer_pid_and_uid_required_and_failed_connect_is_closed(self):
+ for pid, uid in ((456, os.getuid()), (123, os.getuid() + 1)):
+ peer = Mock()
+ peer.getsockopt.return_value = struct.pack("3i", pid, uid, 1)
+ with patch("production_handshake_probe.validate_path"), \
+ patch("production_handshake_probe.socket.socket", return_value=peer), \
+ patch.object(socket, "SO_PEERCRED", 17, create=True):
+ with self.assertRaisesRegex(ProbeFailure, "wrong_socket_peer"):
+ NativeRuntime(123).connect(Path("/synthetic/input.sock"))
+ peer.close.assert_called_once()
+
+ def test_exchange_eof_reset_timeout_and_invalid_json_are_distinct(self):
+ runtime = NativeRuntime(123)
+ for response, error in ((b"", None), (ConnectionResetError(), None),
+ (TimeoutError(), "reply_timeout"), (b"garbage", "malformed_reply"),
+ (b"x" * 2049, "oversized_reply")):
+ with self.subTest(response=type(response).__name__):
+ peer = Mock()
+ peer.send.return_value = 5
+ if isinstance(response, Exception):
+ peer.recv.side_effect = response
+ else:
+ peer.recv.return_value = response
+ if error:
+ with self.assertRaisesRegex(ProbeFailure, error):
+ runtime.exchange(peer, b"CLAIM")
+ else:
+ self.assertIs(runtime.exchange(peer, b"CLAIM"), CLOSED)
+ peer = Mock()
+ peer.send.return_value = 5
+ peer.recv.return_value = b"null"
+ self.assertIsNone(runtime.exchange(peer, b"CLAIM"))
+ with self.assertRaisesRegex(ProbeFailure, "reply_not_object"):
+ validate_reply(None)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.py
new file mode 100644
index 0000000000..e7bda7c480
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.py
@@ -0,0 +1,329 @@
+"""Opt-in production idle-peer regression in a prepared disposable Hyprland desktop.
+
+Two new, grounded Calc clicks share one DirectMCP runtime and named session.
+Between them only read-only compositor status is polled, for at most 85 seconds.
+Neither a primary grab nor a trace spans the real 60-second input-peer expiry.
+No transport reset, test input packet, timeout override, or action retry is used.
+"""
+import argparse
+import hashlib
+import json
+import math
+from pathlib import Path
+import subprocess
+import time
+
+from driver_input_live import state, wait_for, wm
+from primary_trace import Trace
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, close_owned,
+ grounded_snapshot, verify_recovery_cleanup,
+ verify_recovery_trace)
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as grounding
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity,
+ capacity_lane, check_response, primary_acknowledgement,
+ provenance, read_input_status, require_primary_active)
+from realapp_proof import cleanup_all
+
+
+IDLE_SECONDS = 60
+EXPIRY_DEADLINE_SECONDS = 85
+# read_input_status uses a five-second subprocess timeout. Reserve its entire
+# budget before starting another read, so a stalled hyprctl cannot extend 85s.
+STATUS_READ_BUDGET_NS = 5_000_000_000
+STAGES = ('click_b2', 'click_a1')
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'idle_reconnect'
+ assert len(plan['agents']) == 1, 'one persistent input runtime is required'
+ spec = plan['agents'][0]
+ assert spec['app'] == 'calc' and spec.get('profile', PROFILE) == PROFILE
+ assert isinstance(spec['name'], str) and spec['name']
+ assert Path(spec['document']).name == 'cua-smoke-calc.ods', 'only the synthetic document is allowed'
+ assert set(spec['bounds']) == {'x', 'y', 'width', 'height'}
+ assert all(type(v) in (int, float) and math.isfinite(v) for v in spec['bounds'].values())
+ assert spec['bounds']['width'] > 0 and spec['bounds']['height'] > 0
+ for target in (spec['target'], plan['foreground']):
+ assert set(target) == {'pid', 'window_id'}
+ assert all(type(v) is int and v > 0 for v in target.values())
+ assert spec['target']['pid'] != plan['foreground']['pid']
+ assert len(plan['primary_point']) == 2 and all(type(v) is int for v in plan['primary_point'])
+ assert not any(key in plan for key in ('phases', 'recovery', 'idle_timeout', 'moving_primary'))
+
+
+def process_birth(pid, proc_root=Path('/proc')):
+ # comm may contain spaces or parentheses; field 22 follows the final ')'.
+ return int((proc_root / str(pid) / 'stat').read_text().rsplit(')', 1)[1].split()[19])
+
+
+def calc_identity(spec):
+ pid = spec['target']['pid']
+ identity = app_process_identity('calc', pid)
+ document = Path(spec['document']).resolve(strict=True)
+ assert str(document).encode() in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0'), \
+ 'Calc process is not bound to the synthetic document'
+ return {key: identity[key] for key in ('pid', 'executable', 'sha256')} | {
+ 'start_ticks': process_birth(pid), 'document': str(document)}
+
+
+def require_runtime(client, runtime):
+ assert client.process is runtime['process'] and client.process.pid == runtime['pid'], 'Driver process changed'
+ assert client.process.poll() is None and not client.failed and not client.closed, 'Driver runtime did not survive'
+
+
+def lane_states(status):
+ assert status['state'] == 'input_v3_candidate'
+ data = status['input']
+ assert data['protocol'] == 3 and data['test_only'] is False and data['transport_ready'] is True
+ assert len(data['lanes']) == 2 and {row['lane'] for row in data['lanes']} == {0, 1}
+ lanes = {row['lane'] + 1: row for row in data['lanes']}
+ for row in lanes.values():
+ for key in ('reserved', 'lease_active', 'drag_active', 'pointer_focus', 'keyboard_focus'):
+ assert type(row[key]) is bool, 'malformed lane state'
+ assert row['lease_active'] is False and row['drag_active'] is False
+ assert row['held_button'] == 0 and row['held_keys'] == 0 and row['keyboard_focus'] is False
+ assert type(row['dispatches']) is int and row['dispatches'] >= 0
+ assert isinstance(row['epoch'], str) and row['epoch']
+ assert type(row['desktop_generation']) is int
+ return lanes
+
+
+def unchanged_lanes(before, after):
+ for lane in before:
+ for key in ('epoch', 'desktop_generation', 'dispatches'):
+ assert before[lane][key] == after[lane][key], f'lane {key} changed during idle'
+
+
+def wait_for_idle_expiry(client, runtime, occupied_status, lane, dispatch_ns, save,
+ *, read_status=read_input_status, now=time.monotonic_ns, sleep=time.sleep):
+ """Status is read through hyprctl, never through the idle input connection."""
+ original = lane_states(occupied_status)
+ assert original[lane]['reserved'] is True and original[lane]['pointer_focus'] is True
+ assert not original[3 - lane]['reserved'] and not original[3 - lane]['pointer_focus']
+ counter = client.counter
+ deadline = dispatch_ns + EXPIRY_DEADLINE_SECONDS * 1_000_000_000
+ samples = []
+ while now() + STATUS_READ_BUDGET_NS <= deadline:
+ require_runtime(client, runtime)
+ assert client.counter == counter, 'idle runtime received another MCP request'
+ status = read_status()
+ observed_ns = now()
+ assert observed_ns <= deadline, 'idle expiry observation exceeded 85 seconds'
+ current = lane_states(status)
+ unchanged_lanes(original, current)
+ assert not current[3 - lane]['reserved'] and not current[3 - lane]['pointer_focus'], 'another input owner appeared'
+ samples.append({'observed_ns': observed_ns, 'status': status})
+ save('idle-observations.json', samples)
+ require_runtime(client, runtime)
+ assert client.counter == counter, 'idle runtime received another MCP request'
+ if not current[lane]['reserved']:
+ assert observed_ns - dispatch_ns >= IDLE_SECONDS * 1_000_000_000, 'lane disappeared before real idle timeout'
+ assert current[lane]['pointer_focus'] is True, 'idle expiry unnecessarily cleared inert hover'
+ return {'verified': True, 'elapsed_ns': observed_ns - dispatch_ns, 'status': status,
+ 'runtime_pid': runtime['pid'], 'mcp_counter': counter, 'lane': lane}
+ assert current[lane]['pointer_focus'] is True, 'passive focus disappeared before peer expiry'
+ sleep(min(1, max(0, (deadline - now()) / 1_000_000_000)))
+ raise AssertionError('input peer did not expire within 85 seconds; no second action')
+
+
+def grid_digest(snapshot, pixels):
+ x, y, width, height = grounding.calc_table(snapshot, pixels)
+ digest = hashlib.sha256()
+ for row in range(y, y + height):
+ offset = row * pixels.stride + x * pixels.channels
+ digest.update(bytes(pixels.data[offset:offset + width * pixels.channels]))
+ return digest.hexdigest()
+
+
+def click_once(client, observer, spec, stage, runtime, identity, trace, boundary, save, result, guard):
+ """Exactly one click invocation; unknown outcomes remain failures without replay."""
+ assert stage in STAGES
+ require_runtime(client, runtime)
+ assert calc_identity(spec) == identity, 'Calc process identity changed'
+ fresh = {**spec, 'pointer_stage': stage}
+ before = grounded_snapshot(client, spec['target'], fresh)
+ pixels = grounding.read_pixels(before['proof_image'])
+ arguments, oracle = grounding.action(before, pixels, 'calc', stage)
+ before_digest = grid_digest(before, pixels)
+ result.update(stage=stage, session=spec['name'], target=dict(spec['target']), runtime_pid=runtime['pid'],
+ grounding=before, arguments=arguments, oracle=oracle, replayed=False)
+ save(stage + '-grounding.json', result)
+ guard()
+ require_runtime(client, runtime)
+ assert process_birth(spec['target']['pid']) == identity['start_ticks'], 'Calc process identity changed'
+ dispatch_ns = time.monotonic_ns()
+ assert 0 <= dispatch_ns - before['proof_observation_started_ns'] <= MAX_GROUNDING_AGE_NS, \
+ 'snapshot grounding expired; no input sent'
+ result['action'] = {'outcome': 'unknown', 'dispatch_ns': dispatch_ns, 'attempts': 1, 'replayed': False}
+ try:
+ response = client.tool('click', {**arguments, **spec['target'], 'session': spec['name'],
+ 'delivery_mode': 'background'})
+ except Exception as error:
+ result['action']['error'] = str(error)
+ else:
+ result['action'].update(outcome='response', response=response)
+ save(stage + '-action.json', result['action'])
+ after = grounded_snapshot(observer, spec['target'], fresh, session=False)
+ save(stage + '-after.json', after)
+ assert result['action']['outcome'] == 'response', 'click outcome unknown; no replay'
+ check_response(response, {'kind': 'dispatched'})
+ after_pixels = grounding.read_pixels(after['proof_image'])
+ result['app_effect'] = grounding.verify(after, after_pixels, oracle)
+ after_digest = grid_digest(after, after_pixels)
+ assert before_digest != after_digest, 'Calc grid pixels did not change'
+ result['pixels'] = {'before': before_digest, 'after': after_digest, 'changed': True}
+ assert calc_identity(spec) == identity, 'Calc process identity changed'
+ require_runtime(client, runtime)
+ page = trace.collect()
+ lane = capacity_lane(boundary, page, 'click')
+ result['trace'] = verify_recovery_trace(boundary, page, lane, 'click')
+ guard()
+ result['result'] = 'verified'
+ return page, lane
+
+
+def episode(args, plan, client, observer, runtime, identity, stage, save, result, *, final=False):
+ """A new held foreground grab and trace, both bounded below their 60s limit."""
+ grab = trace = prefix = baseline = primary_before = None
+ deadline = None
+ def guard():
+ require_primary_active(grab, deadline)
+ try:
+ fg = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError'), desktop
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < fg['width'] and 0 < y < fg['height']
+ x, y = fg['x'] + x, fg['y'] + y
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)],
+ stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'])
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid'] and baseline['held']
+ trace = Trace(args.trace_socket)
+ assert trace.hello['protocol'] == 3
+ trace.exchange('TRACE_START')
+ boundary = trace.collect()
+ save(stage + '-boundary.json', boundary)
+ prefix, lane = click_once(client, observer, plan['agents'][0], stage, runtime, identity,
+ trace, boundary, save, result, guard)
+ save(stage + '-prefix.json', prefix)
+ result['occupied_status'] = read_input_status()
+ occupied = lane_states(result['occupied_status'])
+ assert occupied[lane]['reserved'] and occupied[lane]['pointer_focus']
+ assert not occupied[3 - lane]['reserved'] and not occupied[3 - lane]['pointer_focus']
+ result['lane'] = lane
+ result['client_survived'] = True
+ finally:
+ operations = []
+ if final:
+ operations.append(('close_input_runtime', lambda: close_owned(client)))
+ if trace:
+ def finish_trace():
+ guard()
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save(stage + '-trace.json', stopped)
+ assert prefix is not None, 'click did not produce a complete trace prefix'
+ result['continuous_isolation'] = verify_recovery_cleanup(prefix, stopped)
+ assert wm() == primary_before, 'primary cursor/focus changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), current
+ if final:
+ status = read_input_status()
+ save('closed-input-status.json', status)
+ closed = lane_states(status)
+ assert all(not row['reserved'] for row in closed.values())
+ assert closed[lane]['pointer_focus'] and not closed[3 - lane]['pointer_focus']
+ result['synthetic_cleanup'] = 'verified'
+ guard()
+ operations += [('finish_trace', finish_trace), ('close_trace', trace.close)]
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'])
+ operations.append(('release_primary', release_primary))
+ errors = cleanup_all(operations)
+ result['cleanup_errors'] = errors
+ save(stage + '-result.json', result)
+ assert not errors, errors
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ save('plan.json', plan)
+ report = {'result': 'failed', 'scope': 'native-production-idle-reconnect',
+ 'full_desktop_matrix': False, 'actions': []}
+ clients = []
+ try:
+ assert args.trace_socket.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')
+ origin = provenance(args, plan)
+ for name in ('production_idle_reconnect_proof.py', 'production_idle_reconnect_proof_test.py',
+ 'production_cancel_proof.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ save('provenance.json', origin)
+ spec = plan['agents'][0]
+ identity = calc_identity(spec)
+ report['app_identity'] = identity
+ initial = read_input_status()
+ save('initial-input-status.json', initial)
+ assert all(not row['reserved'] and not row['pointer_focus'] for row in lane_states(initial).values())
+ for name in ('input-runtime', 'observer'):
+ directory = args.evidence / name
+ directory.mkdir()
+ clients.append(DirectMCP(args.driver, directory, PROFILE))
+ client, observer = clients
+ report['driver_processes'] = assert_distinct_runtimes(clients)
+ runtime = {'process': client.process, 'pid': client.process.pid}
+ response = client.tool('start_session', {'session': spec['name']})
+ assert not response.get('isError'), response
+ first = {}
+ report['actions'].append(first)
+ episode(args, plan, client, observer, runtime, identity, STAGES[0], save, first)
+ report['expiry'] = wait_for_idle_expiry(client, runtime, first['occupied_status'], first['lane'],
+ first['action']['dispatch_ns'], save)
+ second = {}
+ report['actions'].append(second)
+ episode(args, plan, client, observer, runtime, identity, STAGES[1], save, second, final=True)
+ assert second['lane'] == first['lane'], 'fresh action did not reacquire the same lane'
+ before = lane_states(report['expiry']['status'])
+ after = lane_states(second['occupied_status'])
+ for lane in before:
+ for key in ('epoch', 'desktop_generation'):
+ assert before[lane][key] == after[lane][key], 'plugin identity changed before reacquisition'
+ assert after[lane]['dispatches'] == before[lane]['dispatches'] + (lane == second['lane']), \
+ 'fresh action dispatch count differs; possible replay'
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ errors = cleanup_all([(f'close_runtime_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)])
+ report['cleanup_errors'] = errors
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.py
new file mode 100644
index 0000000000..2b41cfbc2d
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.py
@@ -0,0 +1,277 @@
+"""Mocked proof-contract tests only; these do not certify a native desktop."""
+from contextlib import ExitStack
+import copy
+import io
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_idle_reconnect_proof as proof
+
+
+BOUNDS = {'x': 0, 'y': 0, 'width': 800, 'height': 600}
+RESPONSE = {'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background'}}}
+
+
+def plan():
+ return {'purpose': 'idle_reconnect', 'package_versions': {},
+ 'foreground': {'pid': 10, 'window_id': 100}, 'primary_point': [100, 100],
+ 'agents': [{'app': 'calc', 'name': 'idle-proof', 'target': {'pid': 20, 'window_id': 200},
+ 'bounds': dict(BOUNDS), 'document': '/synthetic/cua-smoke-calc.ods',
+ 'profile': dict(proof.PROFILE)}]}
+
+
+def status(reserved=True, dispatches=1):
+ return {'state': 'input_v3_candidate', 'input': {
+ 'protocol': 3, 'test_only': False, 'transport_ready': True,
+ 'lanes': [{'lane': lane, 'epoch': f'epoch-{lane}', 'desktop_generation': 2,
+ 'reserved': reserved if lane == 0 else False,
+ 'pointer_focus': dispatches > 0 if lane == 0 else False,
+ 'lease_active': False, 'drag_active': False, 'held_button': 0,
+ 'held_keys': 0, 'keyboard_focus': False, 'dispatches': dispatches if lane == 0 else 0}
+ for lane in (0, 1)]}}
+
+
+def client(pid=99):
+ value = Mock(counter=7, failed=False, closed=False)
+ value.process.pid = pid
+ value.process.poll.return_value = None
+ value.tool.return_value = copy.deepcopy(RESPONSE)
+ return value
+
+
+def runtime(value):
+ return {'process': value.process, 'pid': value.process.pid}
+
+
+class Clock:
+ def __init__(self, seconds=0):
+ self.ns = seconds * 1_000_000_000
+
+ def now(self):
+ return self.ns
+
+ def sleep(self, seconds):
+ self.ns += int(seconds * 1_000_000_000)
+
+
+class ExpiryTests(unittest.TestCase):
+ def poll(self, read_status, value=None, seconds=0):
+ value = value or client()
+ clock = Clock(seconds)
+ return proof.wait_for_idle_expiry(value, runtime(value), status(), 1, 0, Mock(),
+ read_status=read_status(clock, value),
+ now=clock.now, sleep=clock.sleep)
+
+ def test_actual_sixty_second_expiry_does_not_call_runtime(self):
+ value = client()
+ result = self.poll(lambda clock, _: lambda: status(clock.ns < 60_000_000_000), value)
+ self.assertEqual(result['elapsed_ns'], 60_000_000_000)
+ self.assertEqual(result['runtime_pid'], 99)
+ value.tool.assert_not_called()
+ value.close.assert_not_called()
+
+ def test_expiry_timeout_is_bounded_and_never_sends_input(self):
+ value = client()
+ clock = Clock()
+ with self.assertRaisesRegex(AssertionError, '85 seconds'):
+ proof.wait_for_idle_expiry(value, runtime(value), status(), 1, 0, Mock(),
+ read_status=lambda: status(), now=clock.now, sleep=clock.sleep)
+ self.assertLessEqual(clock.ns + proof.STATUS_READ_BUDGET_NS - 1_000_000_000, 85_000_000_000)
+ self.assertGreaterEqual(clock.ns, 60_000_000_000)
+ value.tool.assert_not_called()
+
+ def test_early_disconnect_and_ambiguous_expiry_fail_closed(self):
+ cases = []
+ early = status(False)
+ cases.append((early, 59))
+ for field, changed in [('pointer_focus', False), ('epoch', 'replacement'),
+ ('desktop_generation', 3), ('dispatches', 2), ('held_button', 272),
+ ('lease_active', True), ('reserved', 'false')]:
+ malformed = status(False)
+ malformed['input']['lanes'][0][field] = changed
+ cases.append((malformed, 61))
+ for observed, seconds in cases:
+ with self.subTest(status=observed, seconds=seconds), self.assertRaises(AssertionError):
+ self.poll(lambda _clock, _client: lambda: observed, seconds=seconds)
+
+ def test_runtime_exit_or_mcp_activity_during_idle_is_not_expiry(self):
+ def exited(_clock, value):
+ def read():
+ value.process.poll.return_value = 1
+ return status(False)
+ return read
+ with self.assertRaisesRegex(AssertionError, 'survive'):
+ self.poll(exited, seconds=61)
+ def activity(_clock, value):
+ def read():
+ value.counter += 1
+ return status()
+ return read
+ with self.assertRaisesRegex(AssertionError, 'another MCP'):
+ self.poll(activity)
+
+
+class ClickTests(unittest.TestCase):
+ def setUp(self):
+ self.stack = ExitStack()
+ self.addCleanup(self.stack.close)
+ self.client, self.observer = client(), client(100)
+ self.spec = plan()['agents'][0]
+ self.identity = {'pid': 20, 'start_ticks': 300}
+ self.snapshot = {'proof_observation_started_ns': 1_000_000_000,
+ 'proof_image': 'synthetic.png', 'window_bounds': BOUNDS}
+ def mock(name, **kwargs):
+ return self.stack.enter_context(patch.object(proof, name, **kwargs))
+ self.identity_mock = mock('calc_identity', return_value=self.identity)
+ self.birth = mock('process_birth', return_value=300)
+ self.snapshot_mock = mock('grounded_snapshot', side_effect=[self.snapshot, self.snapshot])
+ self.clock = self.stack.enter_context(patch.object(proof.time, 'monotonic_ns', return_value=2_000_000_000))
+ self.stack.enter_context(patch.object(proof.grounding, 'read_pixels', return_value=object()))
+ self.stack.enter_context(patch.object(proof.grounding, 'action', return_value=(
+ {'x': 20, 'y': 30}, {'app': 'calc', 'stage': 'click_b2', 'selection': 'B2'})))
+ self.verify = self.stack.enter_context(patch.object(proof.grounding, 'verify', return_value={'verified': True}))
+ self.digest = mock('grid_digest', side_effect=['before-pixels', 'after-pixels'])
+ mock('capacity_lane', return_value=1)
+ mock('verify_recovery_trace', return_value={'result': 'verified'})
+ self.trace, self.result = Mock(), {}
+
+ def call(self):
+ return proof.click_once(self.client, self.observer, self.spec, 'click_b2', runtime(self.client),
+ self.identity, self.trace, {}, Mock(), self.result, Mock())
+
+ def test_one_normal_action_in_same_named_session(self):
+ self.call()
+ self.client.tool.assert_called_once_with('click', {
+ 'x': 20, 'y': 30, 'pid': 20, 'window_id': 200, 'session': 'idle-proof',
+ 'delivery_mode': 'background'})
+ self.assertEqual(self.result['action']['attempts'], 1)
+ self.assertFalse(self.result['replayed'])
+ self.assertEqual(self.snapshot_mock.call_args_list[0].args[0], self.client)
+ self.assertEqual(self.snapshot_mock.call_args_list[1].args[0], self.observer)
+
+ def test_unknown_outcome_is_observed_but_never_replayed(self):
+ self.client.tool.side_effect = RuntimeError('closed after possible delivery')
+ with self.assertRaisesRegex(AssertionError, 'unknown; no replay'):
+ self.call()
+ self.client.tool.assert_called_once()
+ self.assertEqual(self.snapshot_mock.call_count, 2)
+ self.assertEqual(self.result['action']['outcome'], 'unknown')
+ self.verify.assert_not_called()
+
+ def test_partial_unknown_and_nonsynthetic_responses_fail_without_retry(self):
+ for content in ({'effect': 'partial', 'route': 'synthetic_events'},
+ {'effect': 'unverifiable', 'route': 'synthetic_events', 'delivery': {'mode': 'unknown'}},
+ {'effect': 'confirmed', 'route': 'primary'}):
+ with self.subTest(content=content):
+ self.snapshot_mock.side_effect = [self.snapshot, self.snapshot]
+ self.digest.side_effect = ['before', 'after']
+ self.client.tool.reset_mock()
+ self.client.tool.return_value = {'structuredContent': content}
+ with self.assertRaises(AssertionError):
+ self.call()
+ self.client.tool.assert_called_once()
+
+ def test_freshness_is_anchored_to_observation_start_and_fixed_at_five_seconds(self):
+ self.clock.return_value = self.snapshot['proof_observation_started_ns'] + 5_000_000_001
+ with self.assertRaisesRegex(AssertionError, 'grounding expired'):
+ self.call()
+ self.client.tool.assert_not_called()
+
+ def test_app_process_change_fails_before_dispatch(self):
+ self.identity_mock.return_value = {'pid': 20, 'start_ticks': 301}
+ with self.assertRaisesRegex(AssertionError, 'process identity changed'):
+ self.call()
+ self.client.tool.assert_not_called()
+
+ def test_pid_reuse_after_snapshot_fails_before_dispatch(self):
+ self.birth.return_value = 301
+ with self.assertRaisesRegex(AssertionError, 'process identity changed'):
+ self.call()
+ self.client.tool.assert_not_called()
+
+ def test_unchanged_grid_is_not_a_pass(self):
+ self.digest.side_effect = ['same', 'same']
+ with self.assertRaisesRegex(AssertionError, 'pixels did not change'):
+ self.call()
+ self.client.tool.assert_called_once()
+
+
+class IdentityAndPlanTests(unittest.TestCase):
+ def test_target_and_geometry_checks_use_real_snapshot_helper(self):
+ spec = {**plan()['agents'][0], 'pointer_stage': 'click_b2'}
+ for window, bounds in [({'pid': 20, 'window_id': 201}, BOUNDS),
+ ({'pid': 21, 'window_id': 200}, BOUNDS),
+ ({'pid': 20, 'window_id': 200}, {**BOUNDS, 'x': 1})]:
+ value = client()
+ value.tool.side_effect = [
+ {'structuredContent': {'windows': [window]}},
+ {'structuredContent': {'window_bounds': bounds, 'screenshot_width': 800, 'screenshot_height': 600}}]
+ with self.subTest(window=window, bounds=bounds), self.assertRaises(AssertionError):
+ proof.grounded_snapshot(value, spec['target'], spec)
+ self.assertTrue(all(call.args[0] != 'click' for call in value.tool.call_args_list))
+
+ def test_runtime_object_pid_and_liveness_are_fixed(self):
+ original = client()
+ expected = runtime(original)
+ proof.require_runtime(original, expected)
+ for replacement in (client(), client(101)):
+ with self.assertRaisesRegex(AssertionError, 'process changed'):
+ proof.require_runtime(replacement, expected)
+ original.process.poll.return_value = 0
+ with self.assertRaisesRegex(AssertionError, 'survive'):
+ proof.require_runtime(original, expected)
+
+ def test_plan_accepts_only_fixed_synthetic_calc_scenario(self):
+ proof.validate_plan(plan())
+ for key, value in [('app', 'inkscape'), ('document', '/private/work.ods'),
+ ('profile', {'mode': 'standard'}), ('name', '')]:
+ modified = plan()
+ modified['agents'][0][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.validate_plan(modified)
+ with self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), 'idle_timeout': 1})
+
+
+class RunnerTests(unittest.TestCase):
+ def test_same_client_and_session_across_expiry_and_expiry_failure_blocks_second_action(self):
+ for expires in (True, False):
+ with self.subTest(expires=expires), tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ args = SimpleNamespace(plan=Mock(), evidence=Path(directory) / 'proof',
+ driver=Path('/synthetic/cua-driver'),
+ trace_socket=Path('/synthetic/cua-input-v3.sock'))
+ import json
+ args.plan.read_text.return_value = json.dumps(plan())
+ first_client, observer = client(), client(100)
+ stack.enter_context(patch.object(proof, 'DirectMCP', side_effect=[first_client, observer]))
+ stack.enter_context(patch.object(proof, 'provenance', return_value={'files': {}}))
+ stack.enter_context(patch.object(proof, 'calc_identity', return_value={'start_ticks': 300}))
+ stack.enter_context(patch.object(proof, 'read_input_status', return_value=status(False, 0)))
+ stack.enter_context(patch.object(proof, 'close_owned'))
+ stack.enter_context(patch('sys.stdout', new_callable=io.StringIO))
+ events = []
+ def episode(*values, final=False):
+ events.append(values[6])
+ self.assertIs(values[2], first_client)
+ self.assertEqual(values[1]['agents'][0]['name'], 'idle-proof')
+ values[8].update(lane=1, action={'dispatch_ns': 0}, occupied_status=status(True, 2 if final else 1))
+ episodes = stack.enter_context(patch.object(proof, 'episode', side_effect=episode))
+ def expiry(*values):
+ events.append('expiry')
+ self.assertIs(values[0], first_client)
+ if not expires:
+ raise AssertionError('no expiry')
+ return {'status': status(False)}
+ stack.enter_context(patch.object(proof, 'wait_for_idle_expiry', side_effect=expiry))
+ self.assertEqual(proof.run(args), 0 if expires else 1)
+ self.assertEqual(episodes.call_count, 2 if expires else 1)
+ self.assertEqual(events, ['click_b2', 'expiry', 'click_a1'] if expires else ['click_b2', 'expiry'])
+ first_client.tool.assert_called_once_with('start_session', {'session': 'idle-proof'})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_lock_refusal_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_lock_refusal_proof.py
new file mode 100644
index 0000000000..c5fc13e219
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_lock_refusal_proof.py
@@ -0,0 +1,514 @@
+"""TEST ONLY: settled ext-session-lock refusal and fresh-runtime Calc recovery.
+
+Use geometry-proof CLI flags plus --lock-fixture. The exact disposable guest
+plan uses purpose=lock_refusal, fault={kind:lock}, the session-fault identity,
+monitor and foreground_fixture fields, and lock_fixture={path,device,inode,uid,
+sha256,source_sha256}. Hash the reviewed binary and repository C source. The
+fixture is not a real authentication screen. Only its acknowledged protocol
+unlock restores the test desktop. The controller requests it by closing stdin;
+an unsolicited EOF/deadline unlock is cleanup, never proof.
+
+A normal Driver screenshot BEFORE lock grounds one denied click in a NEW
+runtime AFTER acknowledged lock. No active-lock cancellation is exercised.
+Lock/unlock and deliberate foreground-grab setup are outside action traces:
+continuous isolation across these transitions is explicitly UNPROVEN. Each
+settled action has an unfiltered strict trace. Recovery is one newly grounded
+click, with visible Calc effect under the restored foreground fixture grab.
+No product wake/unlock policy, replay, source fixture edit, or native setup.
+Portable tests are orchestration checks, never native certification.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import select
+import stat
+import subprocess
+import time
+
+from desktop_faults import _identity
+from driver_input_live import state, wait_for, wm
+from primary_trace import analyze
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, close_owned,
+ grounded_snapshot, stopped_prefix, verify_recovery_cleanup, verify_recovery_trace)
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+from production_desktop_fault_proof import idle_lanes
+import production_pointer_grounding as pointer_grounding
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, capacity_lane, check_response,
+ primary_acknowledgement, provenance, require_primary_active, trace_interval)
+from production_session_fault_proof import (PROCESS_KEYS, SessionFault, connect_trace,
+ guard_guest, lanes, power, production_status, validate_plan as session_plan)
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+LOCK_MS = 20000
+# Measured lock/settle/fresh-runtime setup takes about one second.
+REFUSAL_SETUP_RESERVE_NS = 1_250_000_000
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'lock_refusal' and plan['fault'] == {'kind': 'lock'}
+ session_plan({**plan, 'purpose': 'session_fault', 'fault': {'kind': 'dpms'}})
+ fixture = plan['lock_fixture']
+ assert set(fixture) == {'path', 'device', 'inode', 'uid', 'sha256', 'source_sha256'}
+ assert Path(fixture['path']).is_absolute() and Path(fixture['path']).name == 'session_lock_fixture'
+ assert all(type(fixture[k]) is int and fixture[k] >= 0 for k in ('device', 'inode', 'uid'))
+ assert fixture['uid'] == plan['compositor']['uid']
+ assert all(re.fullmatch(r'[0-9a-f]{64}', fixture[k]) for k in ('sha256', 'source_sha256'))
+ assert plan['identities']['foreground']['uid'] == plan['identities']['target']['uid'] == fixture['uid']
+ assert len({plan['compositor']['pid'], *(p['pid'] for p in plan['identities'].values())}) == 3
+
+
+def stable_status(before, after, *, advanced=False):
+ # Only a pre-transition idle baseline may contain an inert pointer.
+ old = idle_lanes(before) if advanced else lanes(before, cleared=True)
+ new = lanes(after, cleared=True)
+ assert set(old) == set(new)
+ for lane in old:
+ assert old[lane].get('reserved') is False and new[lane].get('reserved') is False
+ assert old[lane]['epoch'] == new[lane]['epoch'], 'compositor lane replaced'
+ assert old[lane]['dispatches'] == new[lane]['dispatches'], 'unexpected dispatch'
+ a, b = old[lane]['desktop_generation'], new[lane]['desktop_generation']
+ assert b > a if advanced else b == a, 'unexpected desktop generation'
+
+
+def verify_runtimes(clients):
+ assert len({client.process.pid for client in clients}) == len(clients), 'reused prior runtime PID'
+ for client in clients:
+ if client.closed:
+ assert client.process.poll() is not None, 'closed runtime was not reaped'
+ assert_distinct_runtimes([client for client in clients if not client.closed])
+
+
+def settle_locked(fixture):
+ """Observe a quiet locked primary for 100ms before the strict action trace."""
+ samples = fixture.record['settling'] = []
+ stable_since = None
+ previous = None
+ def sample():
+ nonlocal stable_since, previous
+ fixture.locked()
+ current = {'primary': wm(), 'status': production_status(fixture.config)}
+ stable_status(fixture.record['after'], current['status'])
+ now = time.monotonic_ns()
+ samples.append({**current, 'observed_ns': now})
+ if current != previous:
+ stable_since = now
+ previous = current
+ return current if now - stable_since >= 100_000_000 else None
+ return wait_for(sample, timeout=2)
+
+
+class LockFixture(SessionFault):
+ """Reuse exact guest/boot/compositor/window/file guards, without DPMS IPC."""
+ def __init__(self, plan, args):
+ self.plan, self.args = plan, args
+ self.config = {'disposable': plan['disposable'], 'vm': plan['vm'],
+ 'compositor': {key: plan['compositor'][key] for key in PROCESS_KEYS},
+ 'instance': plan['compositor']['instance'], 'monitors': plan['monitors']}
+ self.child = None
+ self.buffer = b''
+ self.events = []
+ self.record = {'result': 'unproven', 'events': self.events}
+ self.requested = False
+ self.restored = False
+ self.check_targets()
+ power(self.config, True)
+ self.check_binary()
+
+ def check_binary(self):
+ expected, path = self.plan['lock_fixture'], self.args.lock_fixture
+ assert str(path) == expected['path'] and path.resolve(strict=True) == path
+ info = path.lstat()
+ assert stat.S_ISREG(info.st_mode) and os.access(path, os.X_OK)
+ assert [info.st_dev, info.st_ino, info.st_uid] == [expected[k] for k in ('device', 'inode', 'uid')]
+ assert hashlib.sha256(path.read_bytes()).hexdigest() == expected['sha256']
+ source = self.args.source / 'libs/cua-driver/hyprland-plugin/tests/session_lock_fixture.c'
+ assert source.resolve(strict=True) == source
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == expected['source_sha256']
+
+ def check_running_binary(self):
+ # A pathname alone cannot distinguish a replaced executable between
+ # preflight and exec. Bind the actual mapped executable before LOCK.
+ expected = self.plan['lock_fixture']
+ assert self.child.poll() is None and _identity(self.child.pid) == self.identity
+ with Path(f'/proc/{self.child.pid}/exe').open('rb') as stream:
+ info = os.fstat(stream.fileno())
+ assert stat.S_ISREG(info.st_mode)
+ assert [info.st_dev, info.st_ino, info.st_uid] == [expected[k] for k in ('device', 'inode', 'uid')]
+ assert hashlib.sha256(stream.read()).hexdigest() == expected['sha256']
+ assert self.child.poll() is None and _identity(self.child.pid) == self.identity
+
+ def read_event(self):
+ if b'\n' not in self.buffer:
+ if not select.select([self.child.stdout], [], [], 0)[0]:
+ return None
+ chunk = os.read(self.child.stdout.fileno(), 4096)
+ assert chunk, 'fixture EOF without expected protocol acknowledgement'
+ self.buffer += chunk
+ assert len(self.buffer) <= 16384, 'oversized fixture event'
+ if b'\n' not in self.buffer:
+ return None
+ line, self.buffer = self.buffer.split(b'\n', 1)
+ event = json.loads(line)
+ assert set(event) == {'event', 'observed_ns'}
+ assert event['event'] in ('ready', 'locked', 'finished', 'unlocked')
+ assert type(event['observed_ns']) is int and 0 < event['observed_ns'] <= time.monotonic_ns()
+ assert not self.events or self.events[-1]['observed_ns'] <= event['observed_ns']
+ self.events.append(event)
+ return event
+
+ def event(self, expected, timeout=2):
+ event = wait_for(self.read_event, timeout=timeout)
+ assert event['event'] == expected, f'unexpected fixture protocol event: {event}'
+ return event
+
+ def lock(self):
+ self.check_targets()
+ self.check_binary()
+ assert self.child is None
+ self.record['before'] = production_status(self.config)
+ (self.args.evidence / 'pre-fault-status.json').write_text(json.dumps(self.record['before']))
+ idle_lanes(self.record['before'])
+ with (self.args.evidence / 'lock-fixture.stderr').open('wb') as log:
+ self.child = subprocess.Popen([str(self.args.lock_fixture), str(LOCK_MS),
+ str(self.config['compositor']['pid'])], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=log, start_new_session=True)
+ self.identity = _identity(self.child.pid)
+ assert self.identity['uid'] == self.config['compositor']['uid']
+ assert self.identity['exe'] == str(self.args.lock_fixture)
+ self.record['identity'] = self.identity
+ self.event('ready')
+ self.check_running_binary()
+ self.check_targets()
+ self.record['requested_ns'] = time.monotonic_ns()
+ self.deadline_ns = self.record['requested_ns'] + LOCK_MS * 1_000_000
+ self.requested = True # Lost response may still mean lock ownership.
+ self.child.stdin.write(b'LOCK\n')
+ self.child.stdin.flush()
+ self.record['ack'] = self.event('locked')
+ assert self.record['requested_ns'] <= self.record['ack']['observed_ns'] < self.deadline_ns
+ self.record['after'] = production_status(self.config)
+ stable_status(self.record['before'], self.record['after'], advanced=True)
+ self.locked()
+ self.record['result'] = 'acknowledged'
+
+ def locked(self):
+ self.check_targets()
+ power(self.config, True)
+ assert self.child.poll() is None and _identity(self.child.pid) == self.identity
+ assert time.monotonic_ns() + 1_000_000_000 < self.deadline_ns, 'lock deadline too near'
+ assert self.read_event() is None, 'lock ended before explicit restoration'
+ assert self.events[-1]['event'] == 'locked'
+
+ def restore(self, *, cleanup=False):
+ if not self.child or self.restored:
+ return {'result': 'not_needed'}
+ record = {'result': 'unproven', 'cleanup': cleanup, 'started_ns': time.monotonic_ns()}
+ self.record['restoration'] = record
+ # EOF is the fixture's bounded protocol-unlock request. Never signal or
+ # kill the lock client, including when proof collection failed.
+ try:
+ if self.child.stdin and not self.child.stdin.closed:
+ try:
+ if not cleanup:
+ self.locked()
+ finally:
+ self.child.stdin.close()
+ if self.requested:
+ while not self.events or self.events[-1]['event'] != 'unlocked':
+ event = wait_for(self.read_event, timeout=3)
+ assert event['event'] == 'unlocked' or (cleanup and event['event'] == 'locked')
+ record['ack'] = event
+ record.setdefault('ack', self.events[-1])
+ finally:
+ # Even malformed/missing acknowledgements must reap an exited
+ # child. If lock acquisition is still pending, allow its own
+ # deadline plus sync grace to finish; never signal the lock client.
+ remaining = (getattr(self, 'deadline_ns', time.monotonic_ns()) - time.monotonic_ns()) / 1_000_000_000
+ timeout = max(3, min(LOCK_MS / 1000 + 3, remaining + 3))
+ record['exit_code'] = self.child.wait(timeout=timeout)
+ self.child.stdout.close()
+ assert record['exit_code'] == 0, 'fixture failed graceful restoration'
+ self.restored = True
+ guard_guest(self.config)
+ record.update(after=production_status(self.config), observed_ns=time.monotonic_ns())
+ if not cleanup:
+ assert self.requested and record['started_ns'] <= record['ack']['observed_ns'] < self.deadline_ns
+ stable_status(self.record['after'], record['after'], advanced=True)
+ record['result'] = 'restored'
+ return record
+
+
+def verify_refusal(record):
+ assert record['outcome'] == 'response' and record['replayed'] is False
+ check_response(record['response'], {'kind': 'refused', 'reason': 'session_unavailable'})
+ assert record['prepared_ns'] <= record['lock_ack_ns'] <= record['runtime_started_ns'] <= record['dispatch_ns'] <= record['observed_ns'] < record['deadline_ns']
+ assert record['dispatch_ns'] - record['prepared_ns'] <= MAX_GROUNDING_AGE_NS
+ stable_status(record['before'], record['after'])
+ assert not any(row[5] in (1, 2) for row in trace_interval(record['trace_before'], record['trace_after'])), 'refused action emitted synthetic events'
+ isolation = analyze(stopped_prefix(record['trace_after']))
+ assert isolation['result'] == 'passed', isolation
+ return {'result': 'verified', 'reason': 'session_unavailable', 'zero_dispatch': True, 'isolation': isolation}
+
+
+def verify_refusal_cleanup(prefix, stopped):
+ trace_interval(prefix, prefix)
+ isolation = analyze(stopped)
+ assert isolation['result'] == 'passed', isolation
+ assert stopped['events'][:prefix['count']] == prefix['events'], 'refusal trace history changed'
+ assert not any(row[5] in (1, 2) for row in stopped['events']), 'refused action emitted synthetic events'
+ return isolation
+
+
+def click_once(client, arguments, record, save, name):
+ """Persist the attempt before transport; an exception never permits replay."""
+ assert record['outcome'] == 'unknown' and record['replayed'] is False
+ record['request'] = arguments
+ save(name, record)
+ try:
+ record['dispatch_ns'] = time.monotonic_ns()
+ assert 0 <= record['dispatch_ns'] - record['prepared_ns'] <= MAX_GROUNDING_AGE_NS, 'grounding expired; no input sent'
+ response = client.tool('click', arguments)
+ record.update(outcome='response', response=response)
+ return response
+ except Exception as error:
+ record['error'] = str(error)
+ raise
+ finally:
+ record['observed_ns'] = time.monotonic_ns()
+ save(name, record)
+
+
+def prepare_click(client, spec, *, session=True):
+ """Keep the full observation's original age, excluding earlier discovery."""
+ snapshot = grounded_snapshot(client, spec['target'], spec, session=session)
+ prepared_ns = snapshot['proof_observation_started_ns']
+ assert type(prepared_ns) is int and 0 < prepared_ns <= time.monotonic_ns()
+ arguments, oracle = pointer_grounding.action(snapshot,
+ pointer_grounding.read_pixels(snapshot['proof_image']), 'calc', spec['pointer_stage'])
+ return {'snapshot': snapshot, 'arguments': arguments, 'oracle': oracle,
+ 'prepared_ns': prepared_ns}
+
+
+def prepare_refusal_click(observer, spec, save):
+ """Refresh successful grounding at most once, before starting the lock."""
+ first = prepare_click(observer, spec, session=False)
+ save('refusal-grounding-attempt-1.json', first)
+ checked_ns = time.monotonic_ns()
+ age_ns = checked_ns - first['prepared_ns']
+ assert age_ns >= 0, 'future refusal grounding'
+ refresh = age_ns + REFUSAL_SETUP_RESERVE_NS > MAX_GROUNDING_AGE_NS
+ decision = {'checked_ns': checked_ns, 'initial_age_ns': age_ns,
+ 'reserve_ns': REFUSAL_SETUP_RESERVE_NS, 'max_age_ns': MAX_GROUNDING_AGE_NS,
+ 'refresh_requested': refresh, 'selected_attempt': None if refresh else 1}
+ first.update(attempt=1, prelock_decision=decision)
+ save('refusal-grounding-attempt-1.json', first)
+ selected = first
+ if refresh:
+ # This is a new read-only observation, never an input or failure retry.
+ selected = prepare_click(observer, spec, session=False)
+ decision.update(selected_attempt=2, refresh_finished_ns=time.monotonic_ns())
+ selected.update(attempt=2, prelock_decision=decision)
+ save('refusal-grounding-attempt-2.json', selected)
+ save('refusal-grounding-attempt-1.json', first)
+ save('refusal-grounding.json', selected)
+ return selected
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ report = {'result': 'failed', 'scope': 'settled-session-lock-refusal',
+ 'active_lock_cancellation': 'unproven', 'continuous_isolation_across_transitions': 'unproven',
+ 'physical_hardware': False, 'full_desktop_matrix': False, 'runtime_pids': [],
+ 'recovery': {'result': 'unproven'}}
+ clients, fixture, trace, grab, deadline = [], None, None, None, None
+ tracing = False
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ client = DirectMCP(args.driver, directory, PROFILE)
+ clients.append(client)
+ verify_runtimes(clients)
+ report['runtime_pids'].append(client.process.pid)
+ return client
+ def start_trace():
+ nonlocal tracing
+ started = time.monotonic_ns()
+ tracing = True # A lost acknowledgement may still have started tracing.
+ trace.exchange('TRACE_START')
+ page = trace.collect()
+ trace_interval(page, page)
+ assert page['count'] == 1 and started <= page['events'][0][1] <= time.monotonic_ns()
+ return page
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ fixture = LockFixture(plan, args)
+ origin = provenance(args, plan)
+ for name in (Path(__file__).name, 'production_lock_refusal_proof_test.py', 'session_lock_fixture.c',
+ 'production_session_fault_proof.py', 'desktop_faults.py', 'production_cancel_proof.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ origin['lock_fixture'] = plan['lock_fixture']
+ save('provenance.json', origin)
+ observer = launch('observer')
+ trace = connect_trace(args.trace_socket, fixture.config)
+ spec = {**plan['agents'][0], 'pointer_stage': plan['recovery']['pointer_stage']}
+ assert state(args.foreground_journal)['held'] is False, 'lock setup requires released primary fixture'
+ probe = prepare_refusal_click(observer, spec, save)
+ arguments, prepared_ns = probe['arguments'], probe['prepared_ns']
+ fixture.lock()
+ settle_locked(fixture)
+ locked_primary, locked_foreground = wm(), state(args.foreground_journal)
+ refusal = report['refusal'] = {**probe, 'outcome': 'unknown', 'replayed': False,
+ 'lock_ack_ns': fixture.record['ack']['observed_ns'], 'deadline_ns': fixture.deadline_ns,
+ 'before': production_status(fixture.config)}
+ stable_status(fixture.record['after'], refusal['before'])
+ refusal['trace_before'] = start_trace()
+ tracing = True
+ refusal['runtime_started_ns'] = time.monotonic_ns()
+ actor = launch('refusal')
+ refusal['runtime_pid'] = actor.process.pid
+ assert not actor.tool('start_session', {'session': spec['name']}).get('isError')
+ fixture.locked()
+ refusal['dispatch_ns'] = time.monotonic_ns()
+ assert refusal['dispatch_ns'] - prepared_ns <= MAX_GROUNDING_AGE_NS, 'refusal grounding expired'
+ click_once(actor, {**arguments, **spec['target'],
+ 'session': spec['name'], 'delivery_mode': 'background'}, refusal, save, 'refusal.json')
+ close_owned(actor)
+ fixture.locked()
+ refusal.update(after=production_status(fixture.config), trace_after=trace.collect(), observed_ns=time.monotonic_ns())
+ refusal['verification'] = verify_refusal(refusal)
+ trace.exchange('TRACE_STOP')
+ tracing = False
+ stopped = trace.collect()
+ save('refusal-trace.json', stopped)
+ refusal['isolation'] = verify_refusal_cleanup(refusal['trace_after'], stopped)
+ refusal['primary_readback'] = {'before': locked_primary, 'after': wm(),
+ 'foreground_before': locked_foreground, 'foreground_after': state(args.foreground_journal)}
+ assert refusal['primary_readback']['after'] == locked_primary
+ assert all(refusal['primary_readback']['foreground_after'][key] == locked_foreground[key]
+ for key in ('clicks', 'keys', 'scroll', 'held'))
+ save('refusal.json', refusal)
+ restoration = fixture.restore()
+ save('restoration.json', restoration)
+ fixture.check_targets()
+ power(fixture.config, True)
+ # All intentional focus/cursor/grab setup precedes the recovery trace.
+ setup = {'before': wm(), 'started_ns': time.monotonic_ns(), 'continuous_isolation': 'unproven'}
+ foreground = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ screen_response = observer.tool('get_desktop_state', {})
+ assert not screen_response.get('isError')
+ screen = screen_response['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < foreground['width'] and 0 < y < foreground['height']
+ x, y = foreground['x'] + x, foreground['y'] + y
+ assert 0 <= x < screen['screen_width'] and 0 <= y < screen['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(screen['screen_width']),
+ str(screen['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ primary, baseline = wm(), state(args.foreground_journal)
+ assert primary['pid'] == plan['foreground']['pid'] and int(primary['address'], 16) == plan['foreground']['window_id']
+ assert primary['cursor'] == {'x': x, 'y': y} and baseline['held']
+ setup.update(after=primary, observed_ns=time.monotonic_ns())
+ save('foreground-setup.json', setup)
+ fixture.check_targets()
+ stable_status(restoration['after'], production_status(fixture.config))
+ initial = start_trace()
+ tracing = True
+ save('recovery-trace-initial.json', initial)
+ fresh = launch('recovery')
+ assert actor.process.poll() is not None and fresh.process.pid != actor.process.pid
+ recovery = report['recovery']
+ recovery.update(runtime_pid=fresh.process.pid, previous_runtime_pid=actor.process.pid, replayed=False)
+ name = spec['name'] + '-recovery'
+ assert not fresh.tool('start_session', {'session': name}).get('isError')
+ grounding = prepare_click(fresh, {**spec, 'name': name})
+ arguments, oracle, prepared_ns = (grounding[key] for key in ('arguments', 'oracle', 'prepared_ns'))
+ save('recovery-grounding.json', grounding)
+ require_primary_active(grab, deadline)
+ dispatched_ns = time.monotonic_ns()
+ assert dispatched_ns - prepared_ns <= MAX_GROUNDING_AGE_NS
+ recovery['action'] = {'outcome': 'unknown', 'replayed': False, 'dispatch_ns': dispatched_ns,
+ 'prepared_ns': prepared_ns}
+ response = click_once(fresh, {**arguments, **spec['target'], 'session': name,
+ 'delivery_mode': 'background'}, recovery['action'], save, 'recovery-action.json')
+ check_response(response, {'kind': 'dispatched'})
+ after = grounded_snapshot(observer, spec['target'], spec, session=False)
+ save('recovery-after.json', after)
+ recovery['app_effect'] = pointer_grounding.verify(after, pointer_grounding.read_pixels(after['proof_image']), oracle)
+ prefix = trace.collect()
+ save('recovery-trace-prefix.json', prefix)
+ recovery['trace'] = verify_recovery_trace(initial, prefix, capacity_lane(initial, prefix, 'click'), 'click')
+ close_owned(fresh)
+ trace.exchange('TRACE_STOP')
+ tracing = False
+ stopped = trace.collect()
+ save('recovery-trace.json', stopped)
+ recovery['isolation'] = verify_recovery_cleanup(prefix, stopped)
+ assert released_synthetic_input(stopped)
+ require_primary_active(grab, deadline)
+ assert wm() == primary
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held'))
+ save('recovery-primary-readback.json', {'before': primary, 'after': wm(), 'foreground_before': baseline, 'foreground_after': current})
+ fixture.check_targets()
+ final_status = production_status(fixture.config)
+ # Exactly the one completed recovery click may advance dispatch counts.
+ old, new = lanes(restoration['after'], cleared=True), lanes(final_status, cleared=True, allow_passive=True)
+ assert sum(new[k]['dispatches'] - old[k]['dispatches'] for k in old) == 1
+ for key in old:
+ assert new[key]['dispatches'] >= old[key]['dispatches'] and new[key].get('reserved') is False
+ assert all(new[key][field] == old[key][field] for field in ('epoch', 'desktop_generation'))
+ save('final-status.json', final_status)
+ recovery['result'] = 'verified'
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = []
+ if fixture:
+ operations.append(('graceful_unlock', lambda: fixture.restore(cleanup=True)))
+ operations += [(f'close_runtime_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)]
+ if trace:
+ if tracing:
+ def preserve_trace():
+ trace.exchange('TRACE_STOP')
+ save('failed-phase-trace.json', trace.collect())
+ operations.append(('preserve_trace', preserve_trace))
+ operations.append(('close_trace', trace.close))
+ if grab:
+ def release_primary():
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release_primary))
+ errors = cleanup_all(operations)
+ if fixture:
+ save('lock-fixture.json', fixture.record)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence',
+ 'foreground-journal', 'trace-socket', 'lock-fixture'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_lock_refusal_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_lock_refusal_proof_test.py
new file mode 100644
index 0000000000..b5113edde7
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_lock_refusal_proof_test.py
@@ -0,0 +1,509 @@
+"""Portable failure-oracle tests only; no native lock or guest certification."""
+from copy import deepcopy
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_lock_refusal_proof as proof
+from production_session_fault_proof_test import plan as session_plan, status, trace, REFUSED
+
+
+def plan():
+ return {**session_plan(), 'purpose': 'lock_refusal', 'fault': {'kind': 'lock'},
+ 'lock_fixture': {'path': '/test/session_lock_fixture', 'device': 1, 'inode': 2,
+ 'uid': 1000, 'sha256': 'b' * 64, 'source_sha256': 'c' * 64}}
+
+
+def refusal():
+ return {'outcome': 'response', 'replayed': False, 'response': deepcopy(REFUSED),
+ 'prepared_ns': 1_000_000, 'lock_ack_ns': 2_000_000, 'runtime_started_ns': 3_000_000,
+ 'dispatch_ns': 4_000_000, 'observed_ns': 5_000_000, 'deadline_ns': 10_000_000,
+ 'before': status(2), 'after': status(2),
+ 'trace_before': trace([(3, 'start', 0, 0)]), 'trace_after': trace([(3, 'start', 0, 0)])}
+
+
+class PlanTests(unittest.TestCase):
+ def test_lock_preflight_accepts_only_inert_unreserved_hover_before_launch(self):
+ for reserved in (False, True):
+ with self.subTest(reserved=reserved), tempfile.TemporaryDirectory() as directory:
+ fixture = object.__new__(proof.LockFixture)
+ fixture.args = SimpleNamespace(evidence=Path(directory), lock_fixture=Path('/test/session_lock_fixture'))
+ fixture.config = {'compositor': {'pid': 50}}
+ fixture.check_targets = Mock()
+ fixture.check_binary = Mock()
+ fixture.child = None
+ fixture.record = {}
+ before = status()
+ before['input']['lanes'][1].update(pointer_focus=True, reserved=reserved)
+ with patch.object(proof, 'production_status', return_value=before), \
+ patch.object(proof.subprocess, 'Popen', side_effect=RuntimeError('launch reached')) as launch:
+ if reserved:
+ with self.assertRaisesRegex(AssertionError, 'authority'):
+ fixture.lock()
+ launch.assert_not_called()
+ else:
+ with self.assertRaisesRegex(RuntimeError, 'launch reached'):
+ fixture.lock()
+ launch.assert_called_once()
+ self.assertEqual(json.loads((fixture.args.evidence / 'pre-fault-status.json').read_text()), before)
+
+ def test_exact_lock_disposable_calc_identity_plan(self):
+ proof.validate_plan(plan())
+ for change in ({'purpose': 'session_fault'}, {'fault': {'kind': 'dpms'}},
+ {'disposable': False}, {'fault': {'kind': 'lock', 'kill_to_unlock': True}},
+ {'recovery': {'pointer_stage': 'select_range'}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **change})
+ for field, value in (('path', '/test/arbitrary'), ('sha256', 'unknown'),
+ ('source_sha256', 'x' * 64), ('uid', 0), ('inode', True)):
+ candidate = plan()
+ candidate['lock_fixture'][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_binary_and_source_hash_inode_and_canonical_path_required(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ binary = root / 'session_lock_fixture'
+ binary.write_bytes(b'fixture')
+ binary.chmod(0o700)
+ source = root / 'libs/cua-driver/hyprland-plugin/tests/session_lock_fixture.c'
+ source.parent.mkdir(parents=True)
+ source.write_bytes(b'fixture source')
+ info = binary.stat()
+ fixture = object.__new__(proof.LockFixture)
+ fixture.args = SimpleNamespace(source=root, lock_fixture=binary)
+ fixture.plan = {'lock_fixture': {'path': str(binary), 'device': info.st_dev,
+ 'inode': info.st_ino, 'uid': info.st_uid,
+ 'sha256': hashlib.sha256(binary.read_bytes()).hexdigest(),
+ 'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest()}}
+ fixture.check_binary()
+ original = deepcopy(fixture.plan)
+ for field, value in (('inode', info.st_ino + 1), ('sha256', '0' * 64),
+ ('source_sha256', '0' * 64), ('path', str(root / 'elsewhere'))):
+ fixture.plan = deepcopy(original)
+ fixture.plan['lock_fixture'][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ fixture.check_binary()
+
+ def test_invalid_plan_preserves_failed_report_before_native_setup(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps({**plan(), 'disposable': False}))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence')
+ with patch.object(proof, 'LockFixture') as fixture, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ fixture.assert_not_called()
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['active_lock_cancellation'], 'unproven')
+ self.assertEqual(report['continuous_isolation_across_transitions'], 'unproven')
+ self.assertEqual(report['result'], 'failed')
+
+ def test_running_executable_must_match_reviewed_inode_and_bytes(self):
+ with tempfile.TemporaryDirectory() as directory:
+ binary = Path(directory) / 'session_lock_fixture'
+ binary.write_bytes(b'reviewed executable')
+ info = binary.stat()
+ fixture = object.__new__(proof.LockFixture)
+ fixture.child = Mock(pid=42, poll=Mock(return_value=None))
+ fixture.identity = {'pid': 42, 'uid': os.getuid(), 'exe': str(binary), 'starttime': '1'}
+ expected = {'device': info.st_dev, 'inode': info.st_ino, 'uid': info.st_uid,
+ 'sha256': hashlib.sha256(binary.read_bytes()).hexdigest()}
+ for change in ({}, {'inode': info.st_ino + 1}, {'sha256': '0' * 64}):
+ fixture.plan = {'lock_fixture': {**expected, **change}}
+ with binary.open('rb') as stream, \
+ patch.object(proof.Path, 'open', return_value=stream) as opened, \
+ patch.object(proof, '_identity', return_value=fixture.identity), \
+ self.subTest(change=change):
+ if change:
+ with self.assertRaises(AssertionError):
+ fixture.check_running_binary()
+ else:
+ fixture.check_running_binary()
+ opened.assert_called_once_with('rb')
+ fixture.child.poll.return_value = 1
+ with self.assertRaises(AssertionError):
+ fixture.check_running_binary()
+
+
+class OracleTests(unittest.TestCase):
+ def test_prelock_refresh_is_bounded_and_retains_actual_observations(self):
+ spec = {**plan()['agents'][0], 'pointer_stage': 'click_b2'}
+ for age in (1_000_000_000, 3_750_000_000, 3_750_000_001, 6_000_000_000):
+ with self.subTest(age=age):
+ first_ns = 1_000_000_000
+ checked_ns = first_ns + age
+ refreshed = age > 3_750_000_000
+ snapshots = [
+ {'proof_observation_started_ns': first_ns, 'proof_image': 'first.png',
+ 'tree': 'complete first tree including late toolbar'},
+ {'proof_observation_started_ns': checked_ns, 'proof_image': 'second.png',
+ 'tree': 'complete second tree including late formula table'}]
+ saved = {}
+ def save(name, value):
+ saved[name] = deepcopy(value)
+ # A 3.9s replacement is allowed despite lacking the heuristic margin.
+ clocks = [checked_ns, checked_ns, checked_ns + 3_900_000_000,
+ checked_ns + 3_900_000_000]
+ with patch.object(proof, 'grounded_snapshot', side_effect=snapshots) as observe, \
+ patch.object(proof.pointer_grounding, 'read_pixels'), \
+ patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1, 'y': 2}, {})), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=clocks):
+ selected = proof.prepare_refusal_click(Mock(), spec, save)
+ attempt = 2 if refreshed else 1
+ self.assertEqual(observe.call_count, attempt)
+ self.assertTrue(all(call.kwargs == {'session': False} for call in observe.call_args_list))
+ self.assertEqual(saved['refusal-grounding.json'], selected)
+ decision = selected['prelock_decision']
+ self.assertEqual(decision['selected_attempt'], attempt)
+ self.assertEqual(decision['checked_ns'], checked_ns)
+ self.assertEqual(decision['initial_age_ns'], age)
+ self.assertEqual(decision['refresh_requested'], refreshed)
+ self.assertEqual(decision['reserve_ns'], 1_250_000_000)
+ self.assertEqual(decision['max_age_ns'], 5_000_000_000)
+ for index in range(attempt):
+ retained = saved[f'refusal-grounding-attempt-{index + 1}.json']
+ self.assertEqual(retained['snapshot'], snapshots[index])
+ self.assertEqual(retained['prepared_ns'], snapshots[index]['proof_observation_started_ns'])
+ self.assertEqual(retained['prelock_decision']['selected_attempt'], attempt)
+ if not refreshed:
+ self.assertNotIn('refusal-grounding-attempt-2.json', saved)
+
+ def test_prelock_does_not_retry_observation_or_grounding_failures(self):
+ spec = {**plan()['agents'][0], 'pointer_stage': 'click_b2'}
+ valid = {'proof_observation_started_ns': 1, 'proof_image': 'first.png'}
+ for failing_attempt in (1, 2):
+ for phase in ('observation', 'grounding', 'missing', 'invalid', 'future'):
+ with self.subTest(attempt=failing_attempt, phase=phase):
+ bad = {'proof_image': 'bad.png'}
+ if phase in ('invalid', 'future'):
+ bad['proof_observation_started_ns'] = False if phase == 'invalid' else 9_000_000_000
+ observations = [valid] * (failing_attempt - 1) + [
+ RuntimeError('observation failed') if phase == 'observation'
+ else valid if phase == 'grounding' else bad]
+ actions = [({}, {})] * (failing_attempt - 1) + [AssertionError('grounding failed')]
+ saved = {}
+ with patch.object(proof, 'grounded_snapshot', side_effect=observations) as observe, \
+ patch.object(proof.pointer_grounding, 'read_pixels'), \
+ patch.object(proof.pointer_grounding, 'action', side_effect=actions), \
+ patch.object(proof.time, 'monotonic_ns', return_value=4_000_000_000), \
+ self.assertRaises((AssertionError, KeyError, RuntimeError)):
+ proof.prepare_refusal_click(Mock(), spec, lambda name, value: saved.update({name: deepcopy(value)}))
+ self.assertEqual(observe.call_count, failing_attempt)
+ self.assertNotIn('refusal-grounding.json', saved)
+ if failing_attempt == 2:
+ self.assertEqual(saved['refusal-grounding-attempt-1.json']['snapshot'], valid)
+ self.assertIsNone(saved['refusal-grounding-attempt-1.json']['prelock_decision']['selected_attempt'])
+
+ def test_expired_replacement_still_fails_actual_click_guard_without_third_observation(self):
+ client = Mock()
+ observations = [{'prepared_ns': 1, 'snapshot': {'proof_image': 'first.png'}, 'arguments': {}},
+ {'prepared_ns': 4_000_000_000, 'snapshot': {'proof_image': 'second.png'}, 'arguments': {}}]
+ with patch.object(proof, 'prepare_click', side_effect=observations) as prepare, \
+ patch.object(proof.time, 'monotonic_ns', side_effect=[4_000_000_000, 9_000_000_001]):
+ selected = proof.prepare_refusal_click(client, {}, Mock())
+ self.assertEqual(prepare.call_count, 2)
+ with patch.object(proof.time, 'monotonic_ns', return_value=9_000_000_002), \
+ self.assertRaisesRegex(AssertionError, 'grounding expired'):
+ proof.click_once(client, {}, {**selected, 'outcome': 'unknown', 'replayed': False}, Mock(), 'attempt.json')
+ client.tool.assert_not_called()
+
+ def test_click_grounding_retains_original_observation_timestamp(self):
+ spec = {**plan()['agents'][0], 'pointer_stage': 'click_b2'}
+ snapshot = {'proof_observation_started_ns': 10, 'proof_image': 'fresh.png'}
+ client = Mock()
+ with patch.object(proof, 'grounded_snapshot', return_value=snapshot) as observed, \
+ patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'), \
+ patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1, 'y': 2}, {'verified': False})), \
+ patch.object(proof.time, 'monotonic_ns', return_value=500):
+ record = proof.prepare_click(client, spec, session=False)
+ observed.assert_called_once_with(client, spec['target'], spec, session=False)
+ self.assertIs(record['snapshot'], snapshot)
+ self.assertEqual(record['prepared_ns'], 10)
+ # A slow observation cannot acquire a new five-second budget.
+ with patch.object(proof.time, 'monotonic_ns', return_value=proof.MAX_GROUNDING_AGE_NS + 11), \
+ self.assertRaisesRegex(AssertionError, 'grounding expired'):
+ proof.click_once(client, record['arguments'],
+ {**record, 'outcome': 'unknown', 'replayed': False}, Mock(), 'attempt.json')
+ client.tool.assert_not_called()
+
+ def test_click_grounding_rejects_missing_invalid_or_future_observation_time(self):
+ spec = {**plan()['agents'][0], 'pointer_stage': 'click_b2'}
+ for timestamp in (None, False, 0, -1, 501):
+ snapshot = {'proof_image': 'fresh.png'}
+ if timestamp is not None:
+ snapshot['proof_observation_started_ns'] = timestamp
+ with self.subTest(timestamp=timestamp), \
+ patch.object(proof, 'grounded_snapshot', return_value=snapshot), \
+ patch.object(proof.time, 'monotonic_ns', return_value=500), \
+ self.assertRaises((AssertionError, KeyError)):
+ proof.prepare_click(Mock(), spec)
+
+ def test_click_attempt_is_saved_on_transport_failure_without_replay(self):
+ for fails in (False, True):
+ client = Mock()
+ client.tool.side_effect = TimeoutError('unknown delivery') if fails else None
+ client.tool.return_value = deepcopy(REFUSED)
+ record = {'outcome': 'unknown', 'replayed': False, 'prepared_ns': 1, 'dispatch_ns': 2}
+ saved = []
+ def save(name, value):
+ saved.append((name, deepcopy(value)))
+ with self.subTest(fails=fails), patch.object(proof.time, 'monotonic_ns', return_value=3):
+ if fails:
+ with self.assertRaises(TimeoutError):
+ proof.click_once(client, {'x': 10, 'y': 20}, record, save, 'attempt.json')
+ else:
+ self.assertEqual(proof.click_once(client, {'x': 10, 'y': 20}, record, save, 'attempt.json'), REFUSED)
+ client.tool.assert_called_once_with('click', {'x': 10, 'y': 20})
+ self.assertEqual(saved[0][1]['outcome'], 'unknown')
+ self.assertEqual(saved[-1][1]['outcome'], 'unknown' if fails else 'response')
+ self.assertEqual(saved[-1][1]['observed_ns'], 3)
+ self.assertFalse(saved[-1][1]['replayed'])
+
+ def test_saving_evidence_cannot_allow_expired_grounding_to_dispatch(self):
+ client = Mock()
+ record = {'outcome': 'unknown', 'replayed': False, 'prepared_ns': 1}
+ with patch.object(proof.time, 'monotonic_ns', return_value=proof.MAX_GROUNDING_AGE_NS + 2), \
+ self.assertRaisesRegex(AssertionError, 'grounding expired'):
+ proof.click_once(client, {}, record, Mock(), 'attempt.json')
+ client.tool.assert_not_called()
+
+ def test_new_runtime_allows_reaped_refusal_but_rejects_reuse_or_live_closed_process(self):
+ def runtime(pid, closed=False, exited=False):
+ return SimpleNamespace(closed=closed, process=Mock(pid=pid, poll=Mock(return_value=0 if exited else None)))
+ proof.verify_runtimes([runtime(10), runtime(20, closed=True, exited=True), runtime(30)])
+ for clients in ([runtime(10), runtime(10)], [runtime(10, closed=True)], [runtime(10, exited=True)]):
+ with self.subTest(clients=clients), self.assertRaises(AssertionError):
+ proof.verify_runtimes(clients)
+
+ def test_exact_refusal_without_synthetic_input_or_dispatch(self):
+ self.assertEqual(proof.verify_refusal(refusal())['result'], 'verified')
+ for change in ({'outcome': 'unknown'}, {'replayed': True},
+ {'response': {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'primary_target_busy'}}},
+ {'runtime_started_ns': 1}, {'dispatch_ns': 1}, {'prepared_ns': -6_000_000_000},
+ {'observed_ns': 11_000_000}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.verify_refusal({**refusal(), **change})
+ for key, value in (('dispatches', 1), ('desktop_generation', 3), ('epoch', 'changed'),
+ ('held_button', 272), ('held_keys', 1), ('pointer_focus', True),
+ ('lease_active', True), ('reserved', True)):
+ candidate = refusal()
+ candidate['after']['input']['lanes'][0][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_refusal(candidate)
+
+ def test_unfiltered_strict_trace_rejects_primary_and_synthetic_events(self):
+ for lane, kind in ((0, 'pointer_focus'), (0, 'keyboard_focus'), (0, 'pointer_button'),
+ (0, 'keyboard_key'), (1, 'agent_admitted'), (2, 'pointer_enter'),
+ (1, 'agent_cancel'), (1, 'pointer_button')):
+ candidate = refusal()
+ candidate['trace_after'] = trace([(3, 'start', 0, 0), (4, kind, lane, 0)])
+ with self.subTest(lane=lane, kind=kind), self.assertRaises(AssertionError):
+ proof.verify_refusal(candidate)
+ for field in ('overflow', 'timed_out'):
+ candidate = refusal()
+ candidate['trace_after'][field] = True
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.verify_refusal(candidate)
+
+ def test_each_lock_transition_advances_generation_without_dispatch(self):
+ proof.stable_status(status(1), status(2), advanced=True)
+ passive = status(1)
+ passive['input']['lanes'][0]['pointer_focus'] = True
+ proof.stable_status(passive, status(2), advanced=True)
+ with self.assertRaises(AssertionError):
+ proof.stable_status(passive, passive)
+ after = status(2)
+ after['input']['lanes'][0]['pointer_focus'] = True
+ with self.assertRaises(AssertionError):
+ proof.stable_status(passive, after, advanced=True)
+ passive['input']['lanes'][0]['reserved'] = True
+ with self.assertRaises(AssertionError):
+ proof.stable_status(passive, status(2), advanced=True)
+ for after in (status(1), status(0)):
+ with self.assertRaises(AssertionError):
+ proof.stable_status(status(1), after, advanced=True)
+ replacement = status(2)
+ replacement['input']['lanes'][1]['epoch'] = 'replaced'
+ with self.assertRaises(AssertionError):
+ proof.stable_status(status(1), replacement, advanced=True)
+
+ def test_stopped_refusal_trace_must_preserve_the_verified_prefix(self):
+ prefix = refusal()['trace_after']
+ stopped = proof.stopped_prefix(prefix)
+ self.assertEqual(proof.verify_refusal_cleanup(prefix, stopped)['result'], 'passed')
+ replacement = deepcopy(stopped)
+ replacement['events'][0][1] -= 1
+ with self.assertRaisesRegex(AssertionError, 'history changed'):
+ proof.verify_refusal_cleanup(prefix, replacement)
+ synthetic = proof.stopped_prefix(trace([(3, 'start', 0, 0), (4, 'agent_admitted', 1, 0)]))
+ with self.assertRaisesRegex(AssertionError, 'synthetic events'):
+ proof.verify_refusal_cleanup(prefix, synthetic)
+
+
+class FixtureTests(unittest.TestCase):
+ def test_lost_trace_start_ack_still_stops_and_preserves_trace(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps(plan()))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence', driver=root / 'driver',
+ trace_socket=root / 'trace', foreground_journal=root / 'journal')
+ fixture = Mock(config={}, deadline_ns=30, record={'after': status(2),
+ 'ack': {'event': 'locked', 'observed_ns': 10}})
+ client = SimpleNamespace(process=Mock(pid=42, poll=Mock(return_value=None)), closed=False)
+ trace_client = Mock()
+ def exchange(command):
+ if command == 'TRACE_START':
+ raise TimeoutError('lost start acknowledgement')
+ return {'ok': True}
+ trace_client.exchange.side_effect = exchange
+ trace_client.collect.return_value = proof.stopped_prefix(refusal()['trace_after'])
+ order = []
+ fixture.lock.side_effect = lambda: order.append('lock')
+ def observe(*args, **kwargs):
+ order.append('observe')
+ return {'proof_image': f'fresh-{len(order)}.png', 'proof_observation_started_ns': 1}
+ with patch.object(proof, 'LockFixture', return_value=fixture), \
+ patch.object(proof, 'provenance', return_value={'files': {}}), \
+ patch.object(proof, 'DirectMCP', return_value=client), \
+ patch.object(proof, 'connect_trace', return_value=trace_client), \
+ patch.object(proof, 'state', return_value={'held': False}), \
+ patch.object(proof, 'wm', return_value={}), \
+ patch.object(proof, 'production_status', return_value=status(2)), \
+ patch.object(proof, 'grounded_snapshot', side_effect=observe), \
+ patch.object(proof.pointer_grounding, 'read_pixels'), \
+ patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1, 'y': 1}, {})), \
+ patch.object(proof.time, 'monotonic_ns', return_value=4_000_000_000), \
+ patch.object(proof, 'settle_locked'), patch.object(proof, 'close_owned'), \
+ patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ self.assertEqual([call.args[0] for call in trace_client.exchange.call_args_list], ['TRACE_START', 'TRACE_STOP'])
+ self.assertEqual(order, ['observe', 'observe', 'lock'])
+ self.assertEqual(json.loads((args.evidence / 'refusal-grounding.json').read_text())['attempt'], 2)
+ self.assertTrue((args.evidence / 'failed-phase-trace.json').is_file())
+ fixture.restore.assert_called_once_with(cleanup=True)
+
+ def test_settling_restarts_on_primary_transition_and_rejects_generation_change(self):
+ fixture = Mock(record={'after': status(2)}, config={})
+ def sample_until_ready(predicate, timeout):
+ self.assertIsNone(predicate())
+ self.assertIsNone(predicate())
+ return predicate()
+ with patch.object(proof, 'wm', side_effect=[{'pid': 10}, {'pid': None}, {'pid': None}]), \
+ patch.object(proof, 'production_status', return_value=status(2)), \
+ patch.object(proof.time, 'monotonic_ns', side_effect=[1, 100_000_001, 200_000_001]), \
+ patch.object(proof, 'wait_for', side_effect=sample_until_ready):
+ self.assertEqual(proof.settle_locked(fixture)['primary'], {'pid': None})
+ with patch.object(proof, 'wm', return_value={}), \
+ patch.object(proof, 'production_status', return_value=status(3)), \
+ patch.object(proof, 'wait_for', side_effect=lambda fn, timeout: fn()), \
+ self.assertRaises(AssertionError):
+ proof.settle_locked(fixture)
+
+ def fixture(self):
+ fixture = object.__new__(proof.LockFixture)
+ fixture.child = Mock(stdin=io.BytesIO(), stdout=Mock(), wait=Mock(return_value=0))
+ fixture.events = [{'event': 'locked', 'observed_ns': 10}]
+ fixture.record = {'after': status(2)}
+ fixture.requested, fixture.restored = True, False
+ fixture.deadline_ns = 100
+ fixture.config = {}
+ fixture.locked = Mock()
+ return fixture
+
+ def test_restore_requires_protocol_ack_and_successful_exit_never_kill(self):
+ fixture = self.fixture()
+ def acknowledgement():
+ event = {'event': 'unlocked', 'observed_ns': 50}
+ fixture.events.append(event)
+ return event
+ fixture.read_event = acknowledgement
+ with patch.object(proof, 'wait_for', side_effect=lambda fn, timeout: fn()), \
+ patch.object(proof, 'guard_guest'), patch.object(proof, 'production_status', return_value=status(3)), \
+ patch.object(proof.time, 'monotonic_ns', return_value=40):
+ result = fixture.restore()
+ self.assertTrue(fixture.child.stdin.closed)
+ self.assertEqual(result['result'], 'restored')
+ fixture.child.kill.assert_not_called()
+ fixture.child.terminate.assert_not_called()
+
+ def test_missing_ack_or_deadline_unlock_cannot_pass(self):
+ for failure in ('missing_ack', 'early_ack', 'deadline', 'bad_exit'):
+ fixture = self.fixture()
+ event = {'event': 'unlocked', 'observed_ns': 30 if failure == 'early_ack' else 110 if failure == 'deadline' else 50}
+ def acknowledgement():
+ fixture.events.append(event)
+ return event
+ fixture.read_event = acknowledgement
+ if failure == 'bad_exit':
+ fixture.child.wait.return_value = 1
+ with self.subTest(failure=failure), \
+ patch.object(proof, 'wait_for', side_effect=TimeoutError('no ack') if failure == 'missing_ack' else lambda fn, timeout: fn()), \
+ patch.object(proof, 'guard_guest'), patch.object(proof, 'production_status', return_value=status(3)), \
+ patch.object(proof.time, 'monotonic_ns', return_value=40), \
+ self.assertRaises((AssertionError, TimeoutError)):
+ fixture.restore()
+ self.assertEqual(fixture.record['restoration']['result'], 'unproven')
+ fixture.child.kill.assert_not_called()
+ fixture.child.terminate.assert_not_called()
+ fixture.child.wait.assert_called_once()
+
+ def test_failed_lock_guard_still_closes_stdin_and_reaps(self):
+ fixture = self.fixture()
+ fixture.locked.side_effect = AssertionError('already unlocked')
+ with patch.object(proof.time, 'monotonic_ns', return_value=40), \
+ self.assertRaisesRegex(AssertionError, 'already unlocked'):
+ fixture.restore()
+ self.assertTrue(fixture.child.stdin.closed)
+ fixture.child.wait.assert_called_once()
+ fixture.child.kill.assert_not_called()
+ fixture.child.terminate.assert_not_called()
+
+ def test_cleanup_waits_for_independent_deadline_without_signaling(self):
+ fixture = self.fixture()
+ fixture.deadline_ns = 20_000_000_000
+ fixture.read_event = Mock()
+ fixture.child.wait.side_effect = subprocess.TimeoutExpired('session_lock_fixture', 22)
+ with patch.object(proof, 'wait_for', side_effect=TimeoutError('missing ack')), \
+ patch.object(proof.time, 'monotonic_ns', return_value=1_000_000_000), \
+ self.assertRaises(subprocess.TimeoutExpired):
+ fixture.restore(cleanup=True)
+ self.assertTrue(fixture.child.stdin.closed)
+ fixture.child.wait.assert_called_once_with(timeout=22)
+ fixture.child.kill.assert_not_called()
+ fixture.child.terminate.assert_not_called()
+ self.assertFalse(fixture.restored)
+
+ def test_event_reader_retains_protocol_evidence_and_rejects_bad_clock(self):
+ fixture = self.fixture()
+ fixture.events = []
+ fixture.buffer = b'{"event":"ready","observed_ns":10}\n'
+ with patch.object(proof.time, 'monotonic_ns', return_value=20):
+ self.assertEqual(fixture.read_event()['event'], 'ready')
+ fixture.buffer = b'{"event":"locked","observed_ns":30}\n'
+ with self.assertRaises(AssertionError):
+ fixture.read_event()
+ self.assertEqual(len(fixture.events), 1)
+
+ def test_partial_event_never_blocks_on_readline(self):
+ fixture = self.fixture()
+ fixture.events, fixture.buffer = [], b''
+ with patch.object(proof.select, 'select', side_effect=[([fixture.child.stdout], [], []), ([], [], [])]), \
+ patch.object(proof.os, 'read', return_value=b'{"event":"locked"'):
+ self.assertIsNone(fixture.read_event())
+ self.assertIsNone(fixture.read_event())
+ self.assertEqual(fixture.events, [])
+ fixture.child.stdout.readline.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_mcp.py b/libs/cua-driver/hyprland-plugin/tests/production_mcp.py
new file mode 100644
index 0000000000..2c0ee18150
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_mcp.py
@@ -0,0 +1,113 @@
+"""Normal direct-runtime MCP transport for disposable native production proofs."""
+import os
+from pathlib import Path
+import subprocess
+
+from driver_input_live import MCP
+
+
+PROFILE_ENV = (
+ 'CUA_DRIVER_PERMISSION_MODE', 'CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS',
+ 'CUA_DRIVER_CAPABILITY_MANIFEST_FILE', 'CUA_DRIVER_CAPABILITY_MANIFEST_APPROVED',
+ 'CUA_DRIVER_SESSION_POLICY_FILE', 'CUA_DRIVER_SESSION_POLICY_APPROVED',
+)
+
+
+def profile_environment(profile, inherited=None):
+ """Select a reviewed profile; retain inherited managed/user policy ceilings."""
+ mode = profile['mode']
+ assert mode in ('standard', 'bounded', 'unrestricted')
+ manifest = profile.get('manifest')
+ assert mode != 'bounded' or manifest, 'bounded needs an approved manifest'
+ assert mode != 'unrestricted' or profile.get('acknowledge_unrestricted') is True
+ assert not manifest or profile.get('approve_manifest') is True
+ env = dict(os.environ if inherited is None else inherited)
+ for name in PROFILE_ENV:
+ env.pop(name, None)
+ env['CUA_DRIVER_PERMISSION_MODE'] = mode
+ if mode == 'unrestricted':
+ env['CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS'] = '1'
+ if manifest:
+ assert Path(manifest).is_file(), 'manifest does not exist'
+ env['CUA_DRIVER_CAPABILITY_MANIFEST_FILE'] = str(Path(manifest).resolve())
+ env['CUA_DRIVER_CAPABILITY_MANIFEST_APPROVED'] = '1'
+ return env
+
+
+def stop_process(process):
+ """Reap a process owned by this run, escalating only that exact child."""
+ if process.poll() is not None:
+ process.wait(timeout=5)
+ return
+ if process.stdin:
+ try:
+ process.stdin.close()
+ except (BrokenPipeError, OSError):
+ pass
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+
+
+class DirectMCP(MCP):
+ """One process, one private runtime. Never attach to a daemon socket."""
+
+ def __init__(self, driver, directory, profile):
+ self.directory = directory
+ env = profile_environment(profile)
+ # Bounded renderer lifecycle messages distinguish a cold runtime from
+ # one that created layer surfaces. No input payloads are logged here.
+ env['CUA_OVERLAY_DEBUG'] = '1'
+ self.log = (directory / 'mcp.stderr').open('w')
+ self.process = None
+ self.counter = 0
+ self.failed = False
+ self.closed = False
+ # Direct MCP reads the immutable authorization configuration from
+ # profile_environment. Permission CLI flags are serve-only and cause
+ # MCP to exit before initialize, even when their environment agrees.
+ command = [str(driver), 'mcp', '--direct']
+ try:
+ self.process = subprocess.Popen(
+ command, env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log,
+ text=True, bufsize=1)
+ self.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {},
+ 'clientInfo': {'name': 'production-native-proof', 'version': '1'}})
+ self.process.stdin.write('{"jsonrpc":"2.0","method":"notifications/initialized"}\n')
+ self.process.stdin.flush()
+ except BaseException:
+ self.close()
+ raise
+
+ def rpc(self, method, params):
+ if self.failed or self.closed:
+ raise RuntimeError('MCP outcome unknown or transport closed; do not replay')
+ try:
+ return super().rpc(method, params)
+ except BaseException:
+ self.failed = True
+ raise
+
+ def close(self):
+ if self.closed:
+ return
+ self.closed = True
+ try:
+ if self.process:
+ stop_process(self.process)
+ finally:
+ self.log.close()
+
+
+def assert_distinct_runtimes(clients):
+ pids = [client.process.pid for client in clients]
+ assert len(pids) == len(set(pids)), 'agents share a Driver process'
+ assert all(client.process.poll() is None for client in clients), 'Driver process exited'
+ return pids
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_pointer_grounding.py b/libs/cua-driver/hyprland-plugin/tests/production_pointer_grounding.py
new file mode 100644
index 0000000000..2e3c9bbbf9
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_pointer_grounding.py
@@ -0,0 +1,370 @@
+"""Fresh-pixel grounding for bounded native Calc/Inkscape pointer proofs.
+
+No captured coordinates are reused across calls. GTK's PNG reader is needed
+only on the native test guest; the geometry algorithms have portable tests.
+These helpers inspect synthetic documents, not arbitrary application content.
+"""
+import math
+import re
+
+from production_app_smoke import (GroundingUnavailable, calc_formula_selection,
+ inkscape_selection_command, rows)
+
+
+STAGES = {
+ 'calc': {'click_b2': 'click', 'click_a1': 'click', 'scroll_down': 'scroll',
+ 'scroll_up': 'scroll', 'select_range': 'drag'},
+ 'inkscape': {'click_rectangle': 'click', 'scroll_down': 'scroll',
+ 'scroll_up': 'scroll', 'move_rectangle': 'drag'},
+}
+
+
+class Pixels:
+ def __init__(self, width, height, data, stride, channels=3):
+ self.width, self.height = width, height
+ self.data, self.stride, self.channels = data, stride, channels
+
+ def rgb(self, x, y):
+ assert 0 <= x < self.width and 0 <= y < self.height
+ offset = y * self.stride + x * self.channels
+ return tuple(self.data[offset:offset + 3])
+
+
+def read_pixels(path):
+ import gi
+ gi.require_version('GdkPixbuf', '2.0')
+ from gi.repository import GdkPixbuf
+ image = GdkPixbuf.Pixbuf.new_from_file(str(path))
+ assert image.get_bits_per_sample() == 8 and image.get_n_channels() in (3, 4)
+ assert 0 < image.get_width() <= 1568 and 0 < image.get_height() <= 1568
+ return Pixels(image.get_width(), image.get_height(), image.get_pixels(),
+ image.get_rowstride(), image.get_n_channels())
+
+
+def checked_snapshot(snapshot, image, app):
+ elements = rows(snapshot)
+ bounds = snapshot['window_bounds']
+ assert (image.width, image.height) == (snapshot['screenshot_width'], snapshot['screenshot_height'])
+ assert (image.width, image.height) == (bounds['width'], bounds['height']), 'only native 1:1 pixels qualified'
+ assert f'cua-smoke-{app}' in snapshot['window_title'], 'wrong synthetic document'
+ return elements
+
+
+def local_frame(row, bounds, image):
+ frame = row.get('frame', {})
+ if set(frame) != {'x', 'y', 'w', 'h'} or not all(type(value) is int for value in frame.values()):
+ raise GroundingUnavailable('missing integer pixel frame')
+ x, y, w, h = frame['x'] - bounds['x'], frame['y'] - bounds['y'], frame['w'], frame['h']
+ if not (0 <= x < x + w <= image.width and 0 <= y < y + h <= image.height):
+ raise GroundingUnavailable('accessible frame is clipped or outside the snapshot')
+ return x, y, w, h
+
+
+def calc_table(snapshot, image):
+ elements = checked_snapshot(snapshot, image, 'calc')
+ tables = [row for row in elements if row.get('role') == 'table' and row.get('label') == 'Sheet Smoke']
+ if len(tables) != 1:
+ raise GroundingUnavailable('need exactly one synthetic Calc sheet')
+ return local_frame(tables[0], snapshot['window_bounds'], image)
+
+
+def calc_scroll(snapshot, image):
+ candidates = []
+ for row in rows(snapshot):
+ if row.get('role') != 'scroll bar' or not row.get('frame'):
+ continue
+ frame = row['frame']
+ if not (0 < frame.get('w', 0) < 30 and frame.get('h', 0) > 100):
+ continue
+ local_frame(row, snapshot['window_bounds'], image)
+ candidates.append(float(row['value']))
+ if len(candidates) != 1 or not math.isfinite(candidates[0]) or candidates[0] < 0:
+ raise GroundingUnavailable('need one visible finite vertical scrollbar')
+ return candidates[0]
+
+
+def calc_cells(snapshot, image):
+ x, y, w, h = calc_table(snapshot, image)
+ if calc_scroll(snapshot, image) != 0:
+ raise GroundingUnavailable('cell proof requires the top of the sheet')
+ # The table frame excludes headers. First establish uniform columns from
+ # their full-height lines. A short range selection can obscure the upper
+ # part of these lines without hiding their positions below the selection.
+ columns = [px for px in range(x, x + w)
+ if sum(image.rgb(px, py) == (204, 204, 204) for py in range(y, y + h)) >= h * .70]
+ if len(columns) < 3:
+ raise GroundingUnavailable('cannot resolve visible spreadsheet grid')
+ columns = [x - 1, *columns]
+
+ def uniform(positions, minimum):
+ gaps = [b - a for a, b in zip(positions, positions[1:])]
+ if min(gaps) < minimum or max(gaps) - min(gaps) > 2:
+ raise GroundingUnavailable('spreadsheet grid is ambiguous or irregular')
+
+ uniform(columns, 30)
+ # Inspect each complete column interior independently at the same 70%
+ # coverage. A highlighted A1:B3 leaves C and D available to corroborate
+ # the early row boundaries even when a full-width scan cannot see them.
+ # Keep every observed boundary: conflicting strips must fail, not be
+ # discarded in favor of a majority or an extrapolated hidden grid.
+ support = {}
+ for left, right in zip(columns, columns[1:]):
+ for py in range(y, y + h):
+ if sum(image.rgb(px, py) == (204, 204, 204)
+ for px in range(left + 1, right)) >= (right - left - 1) * .70:
+ support[py] = support.get(py, 0) + 1
+ if len(support) < 4:
+ raise GroundingUnavailable('cannot resolve visible spreadsheet grid')
+ lines = [y - 1, *sorted(support)]
+ uniform(lines, 8)
+ if min(support.values()) < 2:
+ raise GroundingUnavailable('spreadsheet rows need two independent column strips')
+ return {'A1': ((columns[0] + columns[1]) // 2, (lines[0] + lines[1]) // 2),
+ 'B2': ((columns[1] + columns[2]) // 2, (lines[1] + lines[2]) // 2),
+ 'B3': ((columns[1] + columns[2]) // 2, (lines[2] + lines[3]) // 2)}
+
+
+def calc_selection(snapshot):
+ """Resolve a positive name-field value from the complete fixture toolbar.
+
+ A bounded tree without the field is unknown, not evidence that a desired
+ range is unselected. The following Standard toolbar proves the Formula
+ Tool Bar section was not cut short by the snapshot's node budget.
+ """
+ elements = rows(snapshot)
+ lines = snapshot.get('tree_markdown', '').splitlines()
+ headers = [index for index, line in enumerate(lines)
+ if line.strip() == '- tool bar = "Formula Tool Bar"']
+ if len(headers) != 1:
+ raise GroundingUnavailable('need one complete Calc formula toolbar')
+ start = headers[0]
+ indent = len(lines[start]) - len(lines[start].lstrip())
+ following = next((line for line in lines[start + 1:]
+ if line.strip() and len(line) - len(line.lstrip()) <= indent), None)
+ if (following is None or following.strip() != '- tool bar = "Standard"'
+ or len(following) - len(following.lstrip()) != indent):
+ raise GroundingUnavailable('Calc formula toolbar may be truncated')
+ values = [row['label'] for row in elements
+ if row.get('role') == 'text' and isinstance(row.get('label'), str) and row['label']
+ and calc_formula_selection(snapshot, elements, row['label'])]
+ if len(values) != 1:
+ raise GroundingUnavailable('need one positively identified Calc selection')
+ return values[0]
+
+
+def inkscape_geometry(snapshot, *, allow_transform_center=False):
+ elements = rows(snapshot)
+ lines = [line.strip() for line in snapshot.get('tree_markdown', '').splitlines()]
+ objects = [row for row in elements if row.get('role') == 'table cell' and row.get('label') == 'smoke-rectangle']
+ selected = '- label = "Rectangle in root. Click selection again to toggle scale/rotation handles."'
+ center = ('- label = "Center of transformation: drag to reposition; scaling, rotation '
+ 'and skew with Shift also uses this center"')
+ # Inkscape replaces its idle selection message while the synthetic pointer
+ # hovers over the rotation center. This does not deselect the rectangle.
+ # Admit this exact idle hint for fresh grounding/scroll only; a drag's
+ # committed-effect check still requires the ordinary selection message.
+ hints = lines.count(selected) + lines.count(center)
+ if (len(objects) != 1 or hints != 1 or
+ (lines.count(center) and not allow_transform_center)):
+ raise GroundingUnavailable('the synthetic rectangle is not uniquely selected')
+ values = {}
+ for axis in ('X', 'Y', 'W', 'H'):
+ matches = []
+ for index, line in enumerate(lines):
+ if index == 0 or lines[index - 1] != f'- label = "{axis}:"':
+ continue
+ match = re.match(r'^- \[(\d+)\] spin button "([-\d.]+)" value="([-\d.]+)" ', line)
+ if not match:
+ continue
+ controls = [row for row in elements if row.get('element_index') == int(match[1])
+ and row.get('role') == 'spin button' and row.get('label') == match[2]
+ and row.get('value') == match[3] and row.get('enabled') is True
+ and row.get('frame', {}).get('h', 0) > 0
+ and 0 <= row.get('frame', {}).get('y', -1) - snapshot['window_bounds']['y'] < 90]
+ if len(controls) == 1 and math.isclose(float(match[2]), float(match[3]), abs_tol=.001):
+ matches.append(float(match[3]))
+ if len(matches) != 1 or not math.isfinite(matches[0]):
+ raise GroundingUnavailable('selection geometry differs between semantic projections')
+ values[axis] = matches[0]
+ if values['W'] != 80 or values['H'] != 50:
+ raise GroundingUnavailable('synthetic rectangle size changed')
+ return values
+
+
+def blue_rectangle(snapshot, image):
+ checked_snapshot(snapshot, image, 'inkscape')
+ # Only the synthetic canvas rectangle has this large solid color region.
+ # Exclude toolbar and palette strips, then require one contiguous rectangle.
+ points = {(x, y) for y in range(90, image.height - 90) for x in range(35, image.width - 10)
+ if image.rgb(x, y) == (51, 102, 153)}
+ if not points:
+ raise GroundingUnavailable('synthetic blue rectangle is not visible')
+ left, right = min(x for x, _ in points), max(x for x, _ in points)
+ top, bottom = min(y for _, y in points), max(y for _, y in points)
+ width, height = right - left + 1, bottom - top + 1
+ if width < 40 or height < 25 or len(points) < .95 * width * height:
+ raise GroundingUnavailable('blue pixels are clipped, obscured, or ambiguous')
+ if not (left > 35 and top > 90 and right < image.width - 11 and bottom < image.height - 91):
+ raise GroundingUnavailable('blue rectangle touches the canvas inspection boundary')
+ return {'x': left, 'y': top, 'w': width, 'h': height,
+ 'center': [(left + right) // 2, (top + bottom) // 2]}
+
+
+def action(snapshot, image, app, stage):
+ checked_snapshot(snapshot, image, app)
+ if stage not in STAGES[app]:
+ raise GroundingUnavailable('unknown pointer qualification stage')
+ oracle = {'app': app, 'stage': stage}
+ if app == 'calc':
+ if stage.startswith('scroll_'):
+ x, y, w, h = calc_table(snapshot, image)
+ point = [x + w // 2, y + h // 2]
+ oracle['scroll'] = calc_scroll(snapshot, image)
+ else:
+ cells = calc_cells(snapshot, image)
+ point = cells['B2' if stage == 'click_b2' else 'A1']
+ oracle['selection'] = {'click_b2': 'B2', 'click_a1': 'A1', 'select_range': 'A1:B3'}[stage]
+ if calc_selection(snapshot) == oracle['selection']:
+ raise GroundingUnavailable('selection already matches; this would not prove a pointer effect')
+ else:
+ oracle['rectangle'] = blue_rectangle(snapshot, image)
+ if stage == 'click_rectangle':
+ if not inkscape_selection_command(snapshot, rows(snapshot)):
+ raise GroundingUnavailable('click proof needs the unselected synthetic rectangle')
+ oracle['geometry'] = None
+ else:
+ oracle['geometry'] = inkscape_geometry(snapshot, allow_transform_center=True)
+ point = oracle['rectangle']['center']
+ if stage == 'move_rectangle':
+ # The center is an interactive pivot in rotation mode. Ground the
+ # drag inside the same observed rectangle, away from every handle.
+ rectangle = oracle['rectangle']
+ point = [rectangle['x'] + rectangle['w'] // 4,
+ rectangle['y'] + rectangle['h'] // 4]
+ if stage.startswith('scroll_'):
+ args = {'x': point[0], 'y': point[1], 'direction': stage.split('_')[1], 'amount': 1, 'by': 'line'}
+ elif STAGES[app][stage] == 'drag':
+ end = cells['B3'] if app == 'calc' else [point[0] + 40, point[1] + 30]
+ assert 0 < end[0] < image.width and 0 < end[1] < image.height
+ args = {'from_x': point[0], 'from_y': point[1], 'to_x': end[0], 'to_y': end[1],
+ 'duration_ms': 1500, 'steps': 30}
+ oracle['delta'] = [end[0] - point[0], end[1] - point[1]]
+ else:
+ args = {'x': point[0], 'y': point[1]}
+ return args, oracle
+
+
+def visible_inkscape_scroll_stage(snapshot, image):
+ """Choose one recovery scroll before input, with room for its pixel oracle.
+
+ The pinned fixture scrolls about 80 pixels per line. Reserve 100 pixels
+ inside the existing inspection region, not a guarantee for arbitrary apps.
+ After-action pixel and document-size checks remain unchanged.
+ """
+ rectangle = blue_rectangle(snapshot, image)
+ inkscape_geometry(snapshot, allow_transform_center=True)
+ margins = {'scroll_down': rectangle['y'] - 90,
+ 'scroll_up': image.height - 90 - (rectangle['y'] + rectangle['h'])}
+ stage = max(margins, key=margins.get)
+ if margins[stage] < 100:
+ raise GroundingUnavailable('recovery scroll needs 100 pixels of visible canvas margin')
+ return stage
+
+
+def verify(snapshot, image, oracle):
+ app, stage = oracle['app'], oracle['stage']
+ elements = checked_snapshot(snapshot, image, app)
+ if app == 'calc':
+ if 'selection' in oracle:
+ assert calc_selection(snapshot) == oracle['selection'], 'Calc selection did not change as expected'
+ else:
+ value = calc_scroll(snapshot, image)
+ assert value > oracle['scroll'] if stage == 'scroll_down' else value < oracle['scroll'], 'Calc viewport did not scroll'
+ else:
+ rectangle = blue_rectangle(snapshot, image)
+ geometry = inkscape_geometry(snapshot, allow_transform_center=stage.startswith('scroll_'))
+ previous = oracle['rectangle']
+ assert abs(rectangle['w'] - previous['w']) <= 1 and abs(rectangle['h'] - previous['h']) <= 1, 'rectangle resized'
+ delta = [a - b for a, b in zip(rectangle['center'], previous['center'])]
+ if stage == 'move_rectangle':
+ # Inkscape 1.4.4 select-tool.cpp anchors _seltrans->grab(p) at the
+ # first processed motion, NOT at button press. Do not equate object
+ # translation with the complete pointer delta. Require a committed
+ # selection and matching pixel/document translation here, then match
+ # that translation to an actual motion anchor in verify_drag_trace.
+ assert all(2 < a <= b + 2 for a, b in zip(delta, oracle['delta'])), 'rectangle did not follow drag direction'
+ assert geometry['X'] > oracle['geometry']['X'] and geometry['Y'] > oracle['geometry']['Y']
+ semantic_pixels = [(geometry[axis] - oracle['geometry'][axis]) * previous[size] / oracle['geometry'][extent]
+ for axis, size, extent in (('X', 'w', 'W'), ('Y', 'h', 'H'))]
+ assert all(abs(a - b) <= 2 for a, b in zip(delta, semantic_pixels)), 'pixel/document translation disagrees'
+ else:
+ if oracle['geometry'] is not None:
+ assert geometry == oracle['geometry'], 'pointer operation changed document geometry'
+ if stage.startswith('scroll_'):
+ assert abs(delta[0]) <= 1 and (delta[1] < -2 if stage == 'scroll_down' else delta[1] > 2), 'canvas did not scroll'
+ else:
+ assert all(abs(value) <= 1 for value in delta), 'click unexpectedly moved rectangle'
+ result = {'verified': True, 'scope': 'fresh-snapshot-pointer-effect', **oracle}
+ if app == 'inkscape' and stage == 'move_rectangle':
+ result.update(observed_delta=delta, observed_geometry=geometry, pointer_delivery='requires_trace')
+ return result
+
+
+def verify_drag_trace(trace, arguments, effect, *, expected_lane=None):
+ """Prove the wire endpoint independently of a client's drag threshold.
+
+ Surface coordinates come from the Wayland protocol logger, not actuator
+ intent or primary-cursor coordinates. Historical seven-field traces cannot
+ satisfy this oracle. This bounded episode must have one unambiguous stroke.
+ An expected lane binds cancellation proofs to the known surviving agent.
+ """
+ from primary_trace import analyze
+ assert expected_lane is None or (type(expected_lane) is int and expected_lane in (1, 2)), \
+ 'invalid expected drag lane'
+ assert analyze(trace).get('telemetry_complete') is True, 'incomplete pointer trace'
+ start = [arguments['from_x'], arguments['from_y']]
+ end = [arguments['to_x'], arguments['to_y']]
+ matched = []
+ for lane in ((expected_lane,) if expected_lane is not None else (1, 2)):
+ events = [row for row in trace['events'] if row[5] == lane]
+ for index, row in enumerate(events):
+ if row[2] != 'agent_drag_start':
+ continue
+ preceding = [r for r in events[:index] if r[2] == 'pointer_motion']
+ assert preceding and len(preceding[-1]) == 9, 'missing synthetic start coordinates'
+ if math.dist(preceding[-1][7:9], start) > .01:
+ continue
+ ends = [i for i in range(index + 1, len(events)) if events[i][2] in ('agent_drag_end', 'agent_cancel')]
+ assert ends and events[ends[0]][2] == 'agent_drag_end', 'drag did not complete'
+ stroke = events[index + 1:ends[0]]
+ assert not any(r[2] in ('pointer_leave', 'agent_drag_start') for r in stroke), 'drag focus changed'
+ buttons = [r for r in stroke if r[2] == 'pointer_button']
+ assert len(buttons) == 2 and [r[6] for r in buttons] == [1, 0], 'unbalanced drag buttons'
+ motion = [r for r in stroke if r[2] == 'pointer_motion']
+ assert len(motion) >= 2 and all(len(r) == 9 for r in motion), 'missing synthetic motion coordinates'
+ assert buttons[0][0] < motion[0][0] < motion[-1][0] < buttons[1][0], 'motion outside button hold'
+ assert math.dist(motion[-1][7:9], end) <= .01, 'synthetic pointer missed endpoint'
+ vector = [b - a for a, b in zip(start, end)]
+ norm = sum(v * v for v in vector)
+ assert norm > 0
+ last = 0.0
+ for sample in motion:
+ t = sum((p - a) * v for p, a, v in zip(sample[7:9], start, vector)) / norm
+ assert last - .001 <= t <= 1.001, 'synthetic path reversed or overshot'
+ assert math.dist(sample[7:9], [a + t * v for a, v in zip(start, vector)]) <= .01, 'synthetic path deviated'
+ last = t
+ if effect['app'] == 'inkscape':
+ delta = effect['observed_delta']
+ # Source: INKSCAPE_1_4_4/src/ui/tools/select-tool.cpp,
+ # root_handler(MotionEvent), _seltrans->grab(p)/moveTo(p).
+ # Coalescing may skip events. The translation must still match
+ # endpoint minus a motion the client could actually receive.
+ anchors = [r[0] for r in motion[:-1] if all(abs((e - p) - d) <= 2
+ for e, p, d in zip(end, r[7:9], delta))]
+ assert anchors, 'object translation matches no delivered motion anchor'
+ else:
+ anchors = []
+ matched.append({'lane': lane, 'start': start, 'end': end, 'motion_events': len(motion),
+ 'compatible_anchor_events': anchors})
+ assert len(matched) == 1, 'missing or ambiguous matching drag'
+ return {'verified': True, 'scope': 'wire-pointer-endpoint-and-app-effect', **matched[0]}
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_pointer_grounding_test.py b/libs/cua-driver/hyprland-plugin/tests/production_pointer_grounding_test.py
new file mode 100644
index 0000000000..7c3f1cd327
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_pointer_grounding_test.py
@@ -0,0 +1,383 @@
+"""Synthetic pixels and semantic projections; no native operation is performed."""
+import copy
+import unittest
+
+import production_pointer_grounding as pointer
+from production_app_smoke_test import INKSCAPE, INKSCAPE_SELECTED
+from primary_trace_test import START, STOP, trace
+
+
+class Image:
+ width = height = 500
+
+ def __init__(self):
+ self.points = {}
+
+ def rgb(self, x, y):
+ assert 0 <= x < self.width and 0 <= y < self.height
+ return self.points.get((x, y), (255, 255, 255))
+
+ def rectangle(self, x, y, w, h):
+ self.points.update({(a, b): (51, 102, 153) for a in range(x, x + w) for b in range(y, y + h)})
+
+
+def snapshot(app):
+ return {'window_title': f'cua-smoke-{app}', 'window_bounds': {'x': 600, 'y': 400, 'width': 500, 'height': 500},
+ 'screenshot_width': 500, 'screenshot_height': 500}
+
+
+def calc(selection='A2', scroll=0):
+ state = snapshot('calc')
+ state.update(elements=[
+ {'role': 'panel', 'element_index': 1, 'enabled': True},
+ {'role': 'text', 'element_index': 2, 'parent_index': 1, 'label': selection, 'enabled': True},
+ {'role': 'combo box', 'element_index': 3, 'parent_index': 1, 'enabled': True},
+ {'role': 'table', 'element_index': 4, 'label': 'Sheet Smoke',
+ 'frame': {'x': 645, 'y': 569, 'w': 340, 'h': 270}},
+ {'role': 'scroll bar', 'value': str(scroll), 'frame': {'x': 990, 'y': 569, 'w': 14, 'h': 270}}],
+ tree_markdown='\n'.join(['- tool bar = "Formula Tool Bar"',
+ ' - [1] panel "" [actions=[]]',
+ f' - [2] text "{selection}" [actions=[]]',
+ '- tool bar = "Standard"']))
+ image = Image()
+ for x in (129, 214, 299, 384):
+ image.points.update({(x, y): (204, 204, 204) for y in range(169, 439)})
+ for y in range(186, 439, 18):
+ image.points.update({(x, y): (204, 204, 204) for x in range(45, 385)})
+ return state, image
+
+
+def highlighted_calc():
+ state, image = calc('A1:B3')
+ # Selection tint replaces both white interiors and gray grid pixels in
+ # A1:B3. C and D retain independent evidence for the first two row lines.
+ image.points.update({(x, y): (205, 226, 247)
+ for x in range(45, 215) for y in range(169, 222)})
+ return state, image
+
+
+def ink(selected=True, dx=0, dy=0, scroll_y=0):
+ state = {**snapshot('inkscape'), **copy.deepcopy(INKSCAPE_SELECTED if selected else INKSCAPE)}
+ if selected:
+ for row in state['elements']:
+ if row['role'] == 'spin button':
+ row['frame'] = {'x': 700, 'y': 435, 'w': 100, 'h': 34}
+ for index, value in ((2, 40 + dx * .8), (3, 60 + dy * .8)):
+ row = next(row for row in state['elements'] if row['element_index'] == index)
+ state['tree_markdown'] = state['tree_markdown'].replace(
+ f'[{index}] spin button "{row["label"]}" value="{row["value"]}"',
+ f'[{index}] spin button "{value:.3f}" value="{value:.1f}"')
+ row.update(label=f'{value:.3f}', value=f'{value:.1f}')
+ image = Image()
+ image.rectangle(120 + dx, 150 + dy + scroll_y, 100, 60)
+ return state, image
+
+
+class PointerGroundingTests(unittest.TestCase):
+ def test_recovery_scroll_chooses_visible_space_before_input(self):
+ for offset, expected, movement in ((21, 'scroll_up', 80), (160, 'scroll_down', -80)):
+ with self.subTest(offset=offset):
+ before, image = ink(scroll_y=offset)
+ stage = pointer.visible_inkscape_scroll_stage(before, image)
+ self.assertEqual(stage, expected)
+ args, oracle = pointer.action(before, image, 'inkscape', stage)
+ self.assertEqual(args['amount'], 1)
+ self.assertTrue(pointer.verify(*ink(scroll_y=offset + movement), oracle)['verified'])
+ # Reproduce a top-toolbar clip while document W/H remain unchanged.
+ _, oracle = pointer.action(*ink(scroll_y=21), 'inkscape', 'scroll_down')
+ after, clipped = ink(scroll_y=-59)
+ clipped.points = {point: color for point, color in clipped.points.items() if point[1] >= 94}
+ with self.assertRaisesRegex(AssertionError, 'rectangle resized'):
+ pointer.verify(after, clipped, oracle)
+
+ def test_recovery_scroll_refuses_insufficient_margin_or_ambiguous_state(self):
+ state, image = ink()
+ image.height = 350
+ state['screenshot_height'] = state['window_bounds']['height'] = 350
+ with self.assertRaisesRegex(pointer.GroundingUnavailable, '100 pixels'):
+ pointer.visible_inkscape_scroll_stage(state, image)
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.visible_inkscape_scroll_stage(*ink(False))
+ state, image = ink()
+ image.points.clear()
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.visible_inkscape_scroll_stage(state, image)
+
+ def test_calc_selection_requires_positive_complete_semantic_evidence(self):
+ for failure in ('missing_toolbar', 'truncated_toolbar', 'missing_field', 'wrong_parent',
+ 'duplicate_field', 'duplicate_toolbar', 'disabled', 'wrong_terminator_depth'):
+ with self.subTest(failure=failure):
+ state, image = calc('B2')
+ if failure == 'missing_toolbar':
+ state['tree_markdown'] = ''
+ elif failure == 'truncated_toolbar':
+ state['tree_markdown'] = state['tree_markdown'].rsplit('\n', 1)[0]
+ elif failure == 'missing_field':
+ state['elements'] = [row for row in state['elements'] if row.get('role') != 'text']
+ elif failure == 'wrong_parent':
+ state['elements'][1]['parent_index'] = 999
+ elif failure == 'duplicate_field':
+ state['elements'].append(copy.deepcopy(state['elements'][1]))
+ elif failure == 'duplicate_toolbar':
+ state['tree_markdown'] += '\n- tool bar = "Formula Tool Bar"'
+ elif failure == 'disabled':
+ state['elements'][1]['enabled'] = False
+ else:
+ state['tree_markdown'] = state['tree_markdown'].replace(
+ '- tool bar = "Standard"', ' - tool bar = "Standard"')
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.action(state, image, 'calc', 'select_range')
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.verify(state, image, {'app': 'calc', 'stage': 'click_b2', 'selection': 'B2'})
+
+ def test_calc_points_are_derived_from_the_current_grid(self):
+ state, image = calc()
+ self.assertEqual(pointer.calc_cells(state, image), {'A1': (86, 177), 'B2': (171, 195), 'B3': (171, 213)})
+ args, oracle = pointer.action(state, image, 'calc', 'click_b2')
+ self.assertEqual(args, {'x': 171, 'y': 195})
+ self.assertTrue(pointer.verify(*calc('B2'), oracle)['verified'])
+ with self.assertRaises(AssertionError):
+ pointer.verify(*calc('A2'), oracle)
+ args, oracle = pointer.action(*calc('B2'), 'calc', 'select_range')
+ self.assertEqual(args, {'from_x': 86, 'from_y': 177, 'to_x': 171, 'to_y': 213,
+ 'duration_ms': 1500, 'steps': 30})
+ self.assertTrue(pointer.verify(*calc('A1:B3'), oracle)['verified'])
+
+ def test_calc_highlighted_range_uses_unobscured_column_strips(self):
+ state, image = highlighted_calc()
+ # This is the native failure: neither early line meets full-width 70%.
+ for y in (186, 204):
+ self.assertLess(sum(image.rgb(x, y) == (204, 204, 204)
+ for x in range(45, 385)), 340 * .70)
+ self.assertEqual(pointer.calc_cells(state, image), pointer.calc_cells(*calc()))
+ args, oracle = pointer.action(state, image, 'calc', 'click_b2')
+ self.assertEqual(args, {'x': 171, 'y': 195})
+ self.assertTrue(pointer.verify(*calc('B2'), oracle)['verified'])
+ with self.assertRaisesRegex(pointer.GroundingUnavailable, 'selection already matches'):
+ pointer.action(state, image, 'calc', 'select_range')
+
+ def test_calc_highlight_does_not_hide_irregular_or_ambiguous_grid_evidence(self):
+ for failure in ('extra_row', 'conflicting_strips', 'missing_row', 'one_strip', 'irregular_column'):
+ with self.subTest(failure=failure):
+ state, image = highlighted_calc()
+ if failure == 'extra_row':
+ image.points.update({(x, 195): (204, 204, 204) for x in range(215, 384)})
+ elif failure == 'conflicting_strips':
+ # One clear strip disagrees with the other by one pixel.
+ image.points.update({(x, 186): (255, 255, 255) for x in range(215, 299)})
+ image.points.update({(x, 187): (204, 204, 204) for x in range(215, 299)})
+ elif failure == 'missing_row':
+ image.points.update({(x, 186): (255, 255, 255) for x in range(215, 384)})
+ elif failure == 'one_strip':
+ image.points.update({(x, y): (205, 226, 247)
+ for x in range(215, 300) for y in range(169, 222)})
+ else:
+ image.points.update({(140, y): (204, 204, 204) for y in range(222, 439)})
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.action(state, image, 'calc', 'click_b2')
+
+ def test_calc_grid_and_scroll_refuse_ambiguous_or_clipped_state(self):
+ for failure in ('blank', 'duplicate', 'clipped', 'scrolled', 'irregular', 'already_selected', 'scaled'):
+ with self.subTest(failure=failure):
+ state, image = calc('B2' if failure == 'already_selected' else 'A2')
+ if failure == 'blank':
+ image.points.clear()
+ elif failure == 'duplicate':
+ state['elements'].append(copy.deepcopy(state['elements'][3]))
+ elif failure == 'clipped':
+ state['elements'][3]['frame']['x'] = 900
+ elif failure == 'scrolled':
+ state['elements'][4]['value'] = '5'
+ elif failure == 'irregular':
+ image.points.update({(140, y): (204, 204, 204) for y in range(169, 439)})
+ elif failure == 'scaled':
+ state['screenshot_width'] = 250
+ with self.assertRaises((AssertionError, pointer.GroundingUnavailable)):
+ pointer.action(state, image, 'calc', 'click_b2')
+
+ def test_calc_scroll_requires_an_observed_value_change(self):
+ args, oracle = pointer.action(*calc(), 'calc', 'scroll_down')
+ self.assertEqual(args['amount'], 1)
+ self.assertTrue(pointer.verify(*calc(scroll=3), oracle)['verified'])
+ with self.assertRaises(AssertionError):
+ pointer.verify(*calc(), oracle)
+ _, oracle = pointer.action(*calc(scroll=3), 'calc', 'scroll_up')
+ self.assertTrue(pointer.verify(*calc(), oracle)['verified'])
+
+ def test_inkscape_click_requires_an_actual_selection_transition(self):
+ args, oracle = pointer.action(*ink(False), 'inkscape', 'click_rectangle')
+ self.assertEqual(args, {'x': 169, 'y': 179})
+ self.assertTrue(pointer.verify(*ink(), oracle)['verified'])
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.verify(*ink(False), oracle)
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.action(*ink(), 'inkscape', 'click_rectangle')
+
+ def test_inkscape_drag_and_scroll_need_pixels_and_semantics_to_agree(self):
+ args, oracle = pointer.action(*ink(), 'inkscape', 'move_rectangle')
+ self.assertEqual([args['from_x'], args['from_y']], [145, 165])
+ self.assertEqual([args['to_x'] - args['from_x'], args['to_y'] - args['from_y']], [40, 30])
+ self.assertTrue(pointer.verify(*ink(dx=40, dy=30), oracle)['verified'])
+ # A client may anchor at a processed motion after button press.
+ self.assertTrue(pointer.verify(*ink(dx=35, dy=27), oracle)['verified'])
+ with self.assertRaises(AssertionError):
+ pointer.verify(*ink(), oracle)
+ state, image = ink(dx=35, dy=27)
+ for row in state['elements']:
+ if row.get('element_index') == 2:
+ old = row['value']
+ row.update(label='100.000', value='100.0')
+ state['tree_markdown'] = state['tree_markdown'].replace(
+ f'[{2}] spin button "68.000" value="{old}"', '[2] spin button "100.000" value="100.0"')
+ with self.assertRaisesRegex(AssertionError, 'pixel/document'):
+ pointer.verify(state, image, oracle)
+ _, oracle = pointer.action(*ink(), 'inkscape', 'scroll_down')
+ self.assertTrue(pointer.verify(*ink(scroll_y=-20), oracle)['verified'])
+ for state in (ink(), ink(scroll_y=20), ink(dx=10, dy=10)):
+ with self.assertRaises(AssertionError):
+ pointer.verify(*state, oracle)
+
+ def test_inkscape_idle_pivot_hover_can_ground_a_new_action_without_replaying_drag(self):
+ selected = 'Rectangle in root. Click selection again to toggle scale/rotation handles.'
+ center = ('Center of transformation: drag to reposition; scaling, rotation '
+ 'and skew with Shift also uses this center')
+ state, image = ink()
+ state['tree_markdown'] = state['tree_markdown'].replace(selected, center)
+ args, _ = pointer.action(state, image, 'inkscape', 'move_rectangle')
+ self.assertEqual([args['from_x'], args['from_y']], [145, 165])
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.inkscape_geometry(state)
+ _, oracle = pointer.action(state, image, 'inkscape', 'scroll_down')
+ after, after_image = ink(scroll_y=-20)
+ after['tree_markdown'] = after['tree_markdown'].replace(selected, center)
+ self.assertTrue(pointer.verify(after, after_image, oracle)['verified'])
+ with self.assertRaises(AssertionError):
+ pointer.verify(state, image, oracle)
+ # An interrupted drag is never reclassified as a committed move merely
+ # because the later snapshot exposes an idle hover hint.
+ _, drag = pointer.action(*ink(), 'inkscape', 'move_rectangle')
+ after, after_image = ink(dx=35, dy=27)
+ after['tree_markdown'] = after['tree_markdown'].replace(selected, center)
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.verify(after, after_image, drag)
+
+ def test_inkscape_hover_does_not_admit_ambiguous_unselected_or_in_progress_state(self):
+ selected = 'Rectangle in root. Click selection again to toggle scale/rotation handles.'
+ center = ('Center of transformation: drag to reposition; scaling, rotation '
+ 'and skew with Shift also uses this center')
+ for failure in ('duplicate_hint', 'duplicate_object', 'no_object', 'in_progress',
+ 'unselected', 'wrong_geometry', 'disabled_geometry'):
+ with self.subTest(failure=failure):
+ state, image = ink()
+ state['tree_markdown'] = state['tree_markdown'].replace(selected, center)
+ if failure == 'duplicate_hint':
+ state['tree_markdown'] += f'\n- label = "{selected}"'
+ elif failure == 'duplicate_object':
+ state['elements'].append(copy.deepcopy(state['elements'][0]))
+ elif failure == 'no_object':
+ state['elements'].pop(0)
+ elif failure == 'in_progress':
+ state['tree_markdown'] = state['tree_markdown'].replace(center, 'Move by 1 px, 1 px')
+ elif failure == 'unselected':
+ state, image = ink(False)
+ elif failure == 'wrong_geometry':
+ state['elements'][3]['value'] = '120.0'
+ else:
+ state['elements'][3]['enabled'] = False
+ with self.assertRaises(pointer.GroundingUnavailable):
+ pointer.action(state, image, 'inkscape', 'scroll_down')
+
+ def test_wrong_or_ambiguous_blue_pixels_do_not_ground(self):
+ for failure in ('wrong_title', 'dialog', 'blank', 'two_rectangles', 'clipped', 'semantic_mismatch'):
+ with self.subTest(failure=failure):
+ state, image = ink()
+ if failure == 'wrong_title':
+ state['window_title'] = 'another.svg'
+ elif failure == 'dialog':
+ state['elements'].append({'role': 'dialog'})
+ elif failure == 'blank':
+ image.points.clear()
+ elif failure == 'two_rectangles':
+ image.rectangle(300, 250, 80, 50)
+ elif failure == 'clipped':
+ image.points.clear()
+ image.rectangle(120, 80, 100, 60)
+ else:
+ state['elements'][1]['value'] = '999.0'
+ with self.assertRaises((AssertionError, pointer.GroundingUnavailable)):
+ pointer.action(state, image, 'inkscape', 'move_rectangle')
+
+ def test_rgb_accessor_honors_stride_and_alpha(self):
+ image = pointer.Pixels(2, 2, bytes([10, 20, 30, 255, 40, 50, 60, 255, 0, 0,
+ 70, 80, 90, 255, 100, 110, 120, 255]), 10, 4)
+ self.assertEqual(image.rgb(1, 1), (100, 110, 120))
+ with self.assertRaises(AssertionError):
+ image.rgb(2, 1)
+
+ def test_drag_trace_proves_endpoint_separately_from_client_anchor(self):
+ args, oracle = pointer.action(*ink(), 'inkscape', 'move_rectangle')
+ effect = pointer.verify(*ink(dx=35, dy=27), oracle)
+ data = trace(START, ('pointer_motion', 100, 200, 2, 0),
+ ('agent_drag_start', 100, 200, 2, 0), ('pointer_button', 100, 200, 2, 1),
+ ('pointer_motion', 100, 200, 2, 0), ('pointer_motion', 100, 200, 2, 0),
+ ('pointer_motion', 100, 200, 2, 0), ('pointer_button', 100, 200, 2, 0),
+ ('agent_drag_end', 100, 200, 2, 0), ('pointer_leave', 100, 200, 2, 0), STOP)
+ for index, xy in ((1, [145, 165]), (4, [149, 168]), (5, [165, 180]), (6, [185, 195])):
+ data['events'][index].extend(xy)
+ result = pointer.verify_drag_trace(data, args, effect)
+ self.assertEqual(result['lane'], 2)
+ self.assertEqual(result['compatible_anchor_events'], [5])
+ for expected_lane in (True, False, 0, 3, 1.0, '2', [], {}):
+ with self.subTest(expected_lane=expected_lane), self.assertRaisesRegex(AssertionError, 'invalid expected'):
+ pointer.verify_drag_trace(data, args, effect, expected_lane=expected_lane)
+ with self.assertRaisesRegex(AssertionError, 'missing or ambiguous'):
+ pointer.verify_drag_trace(data, args, effect, expected_lane=1)
+ for canceled in (False, True):
+ other = copy.deepcopy(data['events'][1:-1])
+ for row in other:
+ row[5] = 1
+ if canceled and row[2] == 'agent_drag_end':
+ row[2] = 'agent_cancel'
+ both = copy.deepcopy(data)
+ both['events'][1:1] = other
+ for sequence, row in enumerate(both['events'], 1):
+ row[0], row[1] = sequence, sequence * 1_000_000
+ both['count'] = len(both['events'])
+ with self.subTest(canceled=canceled):
+ self.assertEqual(pointer.verify_drag_trace(both, args, effect, expected_lane=2)['lane'], 2)
+ with self.assertRaisesRegex(AssertionError, 'drag did not complete' if canceled else 'missing or ambiguous'):
+ pointer.verify_drag_trace(both, args, effect)
+ if canceled:
+ with self.assertRaisesRegex(AssertionError, 'drag did not complete'):
+ pointer.verify_drag_trace(both, args, effect, expected_lane=1)
+ for failure in ('missing_endpoint', 'wrong_start', 'missing_coords', 'reversed', 'off_path',
+ 'cancelled', 'leave_during_drag', 'unreleased', 'no_anchor', 'incomplete'):
+ with self.subTest(failure=failure):
+ bad, changed_effect = copy.deepcopy(data), copy.deepcopy(effect)
+ if failure == 'missing_endpoint':
+ bad['events'][6][7:9] = [184, 194.25]
+ elif failure == 'wrong_start':
+ bad['events'][1][7] = 999
+ elif failure == 'missing_coords':
+ bad['events'][4] = bad['events'][4][:7]
+ elif failure == 'reversed':
+ bad['events'][5][7:9] = [147, 166.5]
+ elif failure == 'off_path':
+ bad['events'][5][8] += 2
+ elif failure == 'cancelled':
+ bad['events'][8][2] = 'agent_cancel'
+ elif failure == 'leave_during_drag':
+ bad['events'][5] = bad['events'][5][:7]
+ bad['events'][5][2] = 'pointer_leave'
+ elif failure == 'unreleased':
+ bad['events'][7][6] = 1
+ elif failure == 'no_anchor':
+ changed_effect['observed_delta'] = [10, 25]
+ else:
+ bad['overflow'] = True
+ with self.assertRaises(AssertionError):
+ pointer.verify_drag_trace(bad, args, changed_effect)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py
new file mode 100644
index 0000000000..be91930477
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py
@@ -0,0 +1,395 @@
+"""Shared-policy native proof cells, using normal direct Driver MCP.
+
+Run one cell per prepared disposable Hyprland desktop/document. The controller
+must open a fresh document from production_app_smoke.create_documents and supply
+its exact target, then restore a distinct foreground client before starting.
+Every action refuses if its target is the primary client. This runner never
+launches apps, installs policy, signs grants,
+or sends plugin input. It uses the existing process-startup managed-policy path;
+an inherited managed/user policy is a blocker, never silently replaced.
+
+Plan: {"case": "no_manifest_allow|resource_allow|resource_wrong_pid|resource_wrong_window|
+managed_allow|managed_deny", "mode": "unrestricted", "app": "calc|inkscape",
+"target": {"pid": 20, "window_id": 200}, "document": "/disposable/document",
+"disposable": true}. Mode defaults to unrestricted (the direct-MCP equivalent
+of --dangerously-bypass-approvals); standard/bounded are explicit policy cells.
+For each denial the same initial action is attempted in a fresh permitted
+runtime, followed by the remaining fixed app smoke steps and saved-file oracle.
+All steps have Driver before/after snapshots. Denial observations and window
+discovery use a separate unrestricted observer: exact window scope cannot
+observe excluded windows or enumerate the whole application.
+
+CLI requires --plan, --evidence, --driver, --plugin, --source, --source-sha,
+--trace-socket. Import verify_evidence to recheck raw records and saved documents.
+Run the five manifest cells for each app/profile and no_manifest_allow for
+standard/unrestricted to build a matrix; each needs a fresh
+synthetic document. These cells prove shared policy at the native dispatch
+boundary, not cached authorization, concurrency, hostile same-user isolation,
+managed deployment/immutability, or the complete desktop certification matrix.
+"""
+import argparse
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import time
+import xml.etree.ElementTree as ET
+import zipfile
+
+from driver_input_live import wait_for, wm
+from primary_trace import Trace, analyze
+from production_app_smoke import NS, ground, provenance, rectangle, verify_calc, verify_inkscape
+from production_mcp import DirectMCP
+from production_realapp_proof import (
+ SMOKE_STEPS, app_process_identity, assert_no_dispatch, capacity_lane,
+ check_response, document_root, trace_interval,
+)
+
+
+CASES = ('no_manifest_allow', 'resource_allow', 'resource_wrong_pid', 'resource_wrong_window',
+ 'managed_allow', 'managed_deny')
+DENIALS = frozenset(('resource_wrong_pid', 'resource_wrong_window', 'managed_deny'))
+TOOLS = ['get_window_state', 'press_key', 'hotkey']
+MANAGED_ENV = 'CUA_DRIVER_MANAGED_POLICY_FILE'
+POLICY_ENV = (MANAGED_ENV, 'CUA_DRIVER_POLICY_FILE')
+# Bound Inkscape observations except before select and move: their grounding
+# needs trailing menu nodes and selection status that the cap can omit. Keep
+# default depth and images, and fail closed if either grounding check is unavailable.
+POLICY_SNAPSHOT_LIMITS = {'inkscape': {'max_elements': 2500}}
+
+
+def validate_plan(plan):
+ assert set(plan) <= {'case', 'mode', 'app', 'target', 'document', 'disposable'}
+ assert plan.get('disposable') is True, 'requires a prepared disposable desktop'
+ assert plan['case'] in CASES and plan['app'] in SMOKE_STEPS
+ assert plan.get('mode', 'unrestricted') in ('standard', 'bounded', 'unrestricted')
+ assert plan['case'] != 'no_manifest_allow' or plan.get('mode', 'unrestricted') != 'bounded', \
+ 'bounded cannot admit an action without a manifest'
+ assert set(plan['target']) == {'pid', 'window_id'}
+ assert type(plan['target']['pid']) is int and 0 < plan['target']['pid'] <= 2**31 - 1
+ assert type(plan['target']['window_id']) is int and 0 < plan['target']['window_id'] <= 2**64 - 1
+ assert isinstance(plan['document'], str) and Path(plan['document']).is_absolute()
+ expected_name = 'cua-smoke-calc.ods' if plan['app'] == 'calc' else 'cua-smoke-inkscape.svg'
+ assert Path(plan['document']).name == expected_name, 'requires the canonical synthetic document'
+
+
+def documents_for_case(plan, *, control=False):
+ """JSON is valid YAML; only exact, synthetic typed window resources are used."""
+ validate_plan(plan)
+ if plan['case'] == 'no_manifest_allow':
+ return None, None
+ target = dict(plan['target'])
+ if not control and plan['case'] == 'resource_wrong_pid':
+ target['pid'] = target['pid'] + 1 if target['pid'] < 2**31 - 1 else 1
+ if not control and plan['case'] == 'resource_wrong_window':
+ target['window_id'] = target['window_id'] + 1 if target['window_id'] < 2**64 - 1 else 1
+ manifest = {'version': 3, 'expires_after': '5m', 'idle_timeout': '2m',
+ 'allow': {'tools': list(TOOLS)}, 'resources': {'desktop': {'windows': [target]}}}
+ managed = None
+ if plan['case'].startswith('managed_'):
+ managed = {'allow': {'tools': list(TOOLS)}}
+ if not control and plan['case'] == 'managed_deny':
+ tool = next(iter(SMOKE_STEPS[plan['app']].values()))[0]
+ managed['deny'] = {'tools': [tool]}
+ return manifest, managed
+
+
+def expected_refusal(plan):
+ assert plan['case'] in DENIALS
+ if plan['case'] == 'managed_deny':
+ tool = next(iter(SMOKE_STEPS[plan['app']].values()))[0]
+ return {'code': 'permission_denied',
+ 'message': f"Permission denied: managed policy: tool '{tool}' is explicitly denied"}
+ target = plan['target']
+ return {'code': 'bounded_resource_outside_manifest',
+ 'message': 'protected resource is outside the capability manifest: '
+ f"desktop pid {target['pid']} window {target['window_id']} "
+ 'is outside the capability manifest'}
+
+
+def check_refusal(result, expected):
+ """Accept exact common core/MCP admission envelopes, never plugin errors."""
+ assert result.get('isError') is True, 'denial must be an MCP error'
+ content = result.get('structuredContent')
+ text = [{'type': 'text', 'text': expected['message']}]
+ if expected['code'] == 'permission_denied' and content == {'code': 'permission_denied'}:
+ assert result.get('content') == text, 'wrong MCP permission refusal'
+ return 'mcp-tool-admission'
+ assert content == {'status': 'refused', 'refusal': expected}, 'wrong common policy refusal'
+ assert result.get('content', text) == text, 'conflicting refusal text'
+ return 'core-resource-admission' if expected['code'] != 'permission_denied' else 'core-admission'
+
+
+def start_client(driver, directory, mode, manifest=None, managed=None):
+ """Serial CLI-only setup: inject only during child spawn and restore on error.
+
+ Do not call this helper from a multi-threaded embedding. Run this module as
+ a child process instead. DirectMCP snapshots its environment in __init__.
+ No installed file or pre-existing ceiling is changed, even transiently.
+ """
+ assert not any(name in os.environ for name in POLICY_ENV), \
+ 'inherited managed/user policy: use a clean disposable process environment'
+ profile = {'mode': mode, 'acknowledge_unrestricted': mode == 'unrestricted'}
+ if manifest is not None:
+ path = directory / 'manifest.yaml'
+ with path.open('x') as stream:
+ json.dump(manifest, stream, indent=2)
+ profile.update(manifest=str(path), approve_manifest=True)
+ if managed is not None:
+ path = directory / 'managed.yaml'
+ with path.open('x') as stream:
+ json.dump(managed, stream, indent=2)
+ os.environ[MANAGED_ENV] = str(path.resolve(strict=True))
+ try:
+ return DirectMCP(driver, directory, profile)
+ finally:
+ if managed is not None:
+ os.environ.pop(MANAGED_ENV, None)
+
+
+def check_snapshot(snapshot, plan):
+ assert not snapshot.get('isError'), 'Driver observation failed'
+ content = snapshot['structuredContent']
+ assert all(type(content.get(key)) is int and content[key] == value
+ for key, value in plan['target'].items()), 'snapshot target identity differs'
+ assert content.get('screenshot_width', 0) > 0 and content.get('screenshot_height', 0) > 0
+ assert Path(plan['document']).name in content.get('window_title', ''), 'wrong synthetic document'
+ assert isinstance(content.get('window_bounds'), dict), 'missing target geometry'
+ assert content.get('snapshot_id'), 'missing fresh snapshot identity'
+ return content
+
+
+def check_primary(primary, target):
+ assert type(primary.get('pid')) is int and primary['pid'] > 0, 'missing primary client'
+ assert isinstance(primary.get('address'), str) and int(primary['address'], 16) > 0
+ assert primary['pid'] != target['pid'] and int(primary['address'], 16) != target['window_id'], \
+ 'target is the primary client; restore the separate foreground fixture first'
+
+
+def snapshot(client, plan, observer=None, *, stage=None, before=False):
+ # list_windows(pid) attests an application resource, which is deliberately
+ # outside a window-only manifest. Keep discovery on the explicit observer.
+ windows = (observer or client).tool('list_windows', {'pid': plan['target']['pid']})
+ assert not windows.get('isError'), 'cannot resolve exact target'
+ matches = [row for row in windows['structuredContent']['windows']
+ if row.get('pid') == plan['target']['pid']]
+ assert len(matches) == 1 and matches[0].get('window_id') == plan['target']['window_id'], \
+ 'target is stale or ambiguous'
+ limits = ({} if before and stage in ('select', 'move') else
+ POLICY_SNAPSHOT_LIMITS.get(plan['app'], {}))
+ result = client.tool('get_window_state', {**plan['target'], 'session': 'policy-proof',
+ **limits})
+ check_snapshot(result, plan)
+ return result
+
+
+def validate_initial_document(app, before):
+ if app == 'calc':
+ root = document_root(before, {'zip_member': 'content.xml'})
+ initial = root.find('.//table:table-row/table:table-cell', NS)
+ assert initial is not None and not ''.join(initial.itertext()).strip(), 'initial A1 is not blank'
+ assert initial.get(f"{{{NS['office']}}}value-type") is None, 'initial A1 contains a value'
+ assert initial.get(f"{{{NS['table']}}}formula") is None, 'initial A1 contains a formula'
+ else:
+ node, point = rectangle(before)
+ assert point == (40, 60) and float(node.get('width')) == 80 and float(node.get('height')) == 50, \
+ 'initial rectangle differs from the synthetic fixture'
+
+
+def document_effect(app, before, after):
+ validate_initial_document(app, before)
+ return (verify_calc if app == 'calc' else verify_inkscape)(before, after)
+
+
+def saved_document(document, app, before):
+ """Wait only for the existing save to finish; never repeat input."""
+ def read_saved():
+ value = document.read_bytes()
+ try:
+ document_effect(app, before, value)
+ except (AssertionError, ET.ParseError, zipfile.BadZipFile):
+ return None
+ return value
+ return wait_for(read_saved, timeout=5)
+
+
+def verify_evidence(plan, evidence):
+ """Recompute from raw results, full trace prefixes, and document bytes.
+
+ This rejects contradictory/tampered artifacts, not a malicious same-user
+ author who can rewrite all evidence coherently. No self-reported pass flag
+ or app_effect_verified field is accepted as proof.
+ """
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ validate_plan(plan)
+ complete = evidence['trace']
+ assert analyze(complete).get('telemetry_complete') is True, 'incomplete final trace'
+ rows = evidence['actions']
+ stages = list(SMOKE_STEPS[plan['app']])
+ expected_stages = ([stages[0]] if plan['case'] in DENIALS else []) + stages
+ assert len(rows) == len(expected_stages), 'missing or extra action'
+ previous_time, previous_count = 0, 0
+ control_pids = set()
+ for index, (row, stage) in enumerate(zip(rows, expected_stages)):
+ denied = plan['case'] in DENIALS and index == 0
+ tool, args = SMOKE_STEPS[plan['app']][stage]
+ assert row['stage'] == stage and row['tool'] == tool
+ assert row['arguments'] == {**args, **plan['target'], 'session': 'policy-proof',
+ 'delivery_mode': 'background'}, 'action ownership changed'
+ assert type(row['runtime_pid']) is int and row['runtime_pid'] > 0
+ assert row['phase'] == ('deny' if denied else 'control')
+ assert row['mode'] == plan.get('mode', 'unrestricted'), 'wrong runtime profile'
+ check_primary(row['primary_before'], plan['target'])
+ assert row['configuration'] == list(documents_for_case(plan, control=not denied)), \
+ 'wrong reviewed policy configuration'
+ times = row['times_ns']
+ assert len(times) == 4 and all(type(t) is int for t in times)
+ assert previous_time < times[0] <= times[1] <= times[2] <= times[3], 'unordered observations'
+ previous_time = times[3]
+ before, after = (check_snapshot(row[key], plan) for key in ('before', 'after'))
+ assert before['snapshot_id'] != after['snapshot_id'], 'after observation reused before state'
+ assert before['window_bounds'] == after['window_bounds'], 'target geometry changed'
+ ground(before, plan['app'], stage)
+ for key in ('trace_before', 'trace_after'):
+ page = row[key]
+ trace_interval(page, page)
+ assert page['count'] >= previous_count, 'trace intervals reordered'
+ assert complete['events'][:page['count']] == page['events'], 'trace prefix changed'
+ previous_count = page['count']
+ if denied:
+ check_refusal(row['response'], expected_refusal(plan))
+ assert_no_dispatch(row['trace_before'], row['trace_after'])
+ else:
+ control_pids.add(row['runtime_pid'])
+ check_response(row['response'], {'kind': 'dispatched'})
+ capacity_lane(row['trace_before'], row['trace_after'], tool)
+ assert len(control_pids) == 1, 'positive control changed runtime'
+ if plan['case'] in DENIALS:
+ assert rows[0]['runtime_pid'] not in control_pids, 'policy changed inside cached runtime'
+ assert_no_dispatch(rows[0]['trace_before'], rows[1]['trace_before'])
+ before = base64.b64decode(evidence['document_before'], validate=True)
+ after = base64.b64decode(evidence['document_after'], validate=True)
+ effect = document_effect(plan['app'], before, after)
+ return {'result': 'passed', 'case': plan['case'], 'mode': plan.get('mode', 'unrestricted'),
+ 'app': plan['app'], 'positive_control': effect,
+ 'denial': expected_refusal(plan) if plan['case'] in DENIALS else None,
+ 'same_user_security_boundary': False, 'full_desktop_matrix': False}
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ assert not any(name in os.environ for name in POLICY_ENV), 'inherited managed/user policy'
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ report = {'result': 'failed', 'plan': plan, 'actions': [], 'full_desktop_matrix': False}
+ clients, trace, started = [], None, False
+ def save():
+ (args.evidence / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
+ def client(name, manifest=None, managed=None, mode=None):
+ directory = args.evidence / name
+ directory.mkdir()
+ value = start_client(args.driver, directory, mode or plan.get('mode', 'unrestricted'),
+ manifest, managed)
+ clients.append(value)
+ return value
+ try:
+ report['provenance'] = provenance(args)
+ report['provenance']['policy_runner_sha256'] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
+ report['provenance']['app_process'] = app_process_identity(plan['app'], plan['target']['pid'])
+ windows = json.loads(subprocess.check_output(['hyprctl', '-j', 'clients'], text=True, timeout=10))
+ matches = [row for row in windows if row.get('pid') == plan['target']['pid']]
+ assert len(matches) == 1 and matches[0].get('xwayland') is False, 'requires a native app window'
+ assert int(matches[0]['address'], 16) == plan['target']['window_id'], 'native window identity differs'
+ report['provenance']['native_window'] = matches[0]
+ document = Path(plan['document']).resolve(strict=True)
+ document_before = document.read_bytes()
+ validate_initial_document(plan['app'], document_before)
+ report['document_before'] = base64.b64encode(document_before).decode('ascii')
+ observer = client('observer', mode='unrestricted')
+ trace = Trace(args.trace_socket)
+ assert trace.collect().get('active') is False, 'another proof owns the trace'
+ trace.exchange('TRACE_START')
+ started = True
+
+ def action(actor, phase, stage, configuration):
+ tool, arguments = SMOKE_STEPS[plan['app']][stage]
+ observer_for_step = observer if phase == 'deny' else actor
+ row = {'phase': phase, 'stage': stage, 'tool': tool, 'configuration': list(configuration),
+ 'mode': plan.get('mode', 'unrestricted'),
+ 'runtime_pid': actor.process.pid, 'arguments': {**arguments, **plan['target'],
+ 'session': 'policy-proof', 'delivery_mode': 'background'}}
+ report['actions'].append(row)
+ row['before'] = snapshot(observer_for_step, plan, observer, stage=stage, before=True)
+ ground(row['before']['structuredContent'], plan['app'], stage)
+ row['primary_before'] = wm()
+ check_primary(row['primary_before'], plan['target'])
+ row['times_ns'] = [time.monotonic_ns()]
+ row['trace_before'] = trace.collect()
+ row['times_ns'].append(time.monotonic_ns())
+ try:
+ row['response'] = actor.tool(tool, row['arguments'])
+ finally:
+ row['times_ns'].append(time.monotonic_ns())
+ # Independent observer survives an actor's poisoned MCP connection.
+ row['after'] = snapshot(observer if actor.failed else observer_for_step,
+ plan, observer, stage=stage)
+ row['times_ns'].append(time.monotonic_ns())
+ row['trace_after'] = trace.collect()
+ save()
+ if phase == 'deny':
+ check_refusal(row['response'], expected_refusal(plan))
+ assert_no_dispatch(row['trace_before'], row['trace_after'])
+ else:
+ check_response(row['response'], {'kind': 'dispatched'})
+ capacity_lane(row['trace_before'], row['trace_after'], tool)
+
+ if plan['case'] in DENIALS:
+ config = documents_for_case(plan)
+ denied = client('denied', *config)
+ action(denied, 'deny', next(iter(SMOKE_STEPS[plan['app']])), config)
+ denied.close()
+ config = documents_for_case(plan, control=True)
+ permitted = client('control', *config)
+ for stage in SMOKE_STEPS[plan['app']]:
+ action(permitted, 'control', stage, config)
+ report['document_after'] = base64.b64encode(
+ saved_document(document, plan['app'], document_before)).decode('ascii')
+ except Exception as error:
+ report['error'] = {'type': type(error).__name__, 'message': str(error)}
+ finally:
+ for value in reversed(clients):
+ try:
+ value.close()
+ except Exception as error:
+ report.setdefault('cleanup_errors', []).append(str(error))
+ if trace is not None:
+ try:
+ if started:
+ trace.exchange('TRACE_STOP')
+ report['trace'] = trace.collect()
+ except Exception as error:
+ report.setdefault('cleanup_errors', []).append(str(error))
+ finally:
+ trace.close()
+ if 'error' not in report and 'cleanup_errors' not in report:
+ try:
+ report['verification'] = verify_evidence(plan, report)
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = {'type': type(error).__name__, 'message': str(error)}
+ save()
+ print(json.dumps({'result': report['result'], 'evidence': str(args.evidence)}), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('plan', 'evidence', 'driver', 'plugin', 'source', 'trace-socket'):
+ parser.add_argument('--' + name, type=Path, required=True)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py
new file mode 100644
index 0000000000..6db277048e
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py
@@ -0,0 +1,480 @@
+"""Synthetic policy/oracle tests only: no native input or managed host policy."""
+import base64
+import copy
+import json
+import os
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+from production_app_smoke import GroundingUnavailable, create_documents
+from production_app_smoke_test import CALC, INKSCAPE, INKSCAPE_SELECTED, changed_ods
+from production_policy_proof import (
+ CASES, DENIALS, MANAGED_ENV, SMOKE_STEPS, check_refusal, documents_for_case,
+ expected_refusal, run, snapshot, start_client, validate_plan, verify_evidence,
+)
+
+
+def plan(case='resource_wrong_window', app='calc', mode='unrestricted'):
+ suffix = 'calc.ods' if app == 'calc' else 'inkscape.svg'
+ return {'case': case, 'app': app, 'mode': mode, 'disposable': True,
+ 'target': {'pid': 20, 'window_id': 200},
+ 'document': '/disposable/cua-smoke-' + suffix}
+
+
+def page(events, active=True):
+ return {'active': active, 'hook': True, 'overflow': False, 'timed_out': False,
+ 'count': len(events), 'events': copy.deepcopy(events)}
+
+
+def window(candidate, stage, identity):
+ source = CALC if candidate['app'] == 'calc' else (
+ INKSCAPE_SELECTED if stage == 'move' else INKSCAPE)
+ return {'structuredContent': {**copy.deepcopy(source),
+ **candidate['target'],
+ 'window_title': Path(candidate['document']).name,
+ 'snapshot_id': f'snapshot-{identity}', 'screenshot_width': 800,
+ 'screenshot_height': 600, 'window_bounds': {'x': 0, 'y': 0, 'width': 800, 'height': 600}}}
+
+
+def evidence(candidate):
+ events = [[1, 0, 'start', 100, 100, 0, 0]]
+ result = {'actions': []}
+ stages = list(SMOKE_STEPS[candidate['app']])
+ stages = ([stages[0]] if candidate['case'] in DENIALS else []) + stages
+ for index, stage in enumerate(stages):
+ denied = index == 0 and candidate['case'] in DENIALS
+ tool, args = SMOKE_STEPS[candidate['app']][stage]
+ before = page(events)
+ if not denied:
+ for kind, pressed in [('agent_admitted', 0), ('keyboard_key', 1),
+ ('keyboard_key', 0), ('agent_action_end', 0)]:
+ events.append([len(events) + 1, len(events), kind, 100, 100, 1, pressed])
+ response = ({'isError': True, 'structuredContent': {
+ 'status': 'refused', 'refusal': expected_refusal(candidate)}} if denied else
+ {'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background'}}})
+ result['actions'].append({'stage': stage, 'tool': tool, 'phase': 'deny' if denied else 'control',
+ 'mode': candidate.get('mode', 'unrestricted'),
+ 'primary_before': {'pid': 10, 'address': '0x64'},
+ 'configuration': list(documents_for_case(candidate, control=not denied)),
+ 'runtime_pid': 100 if denied else 101,
+ 'arguments': {**args, **candidate['target'], 'session': 'policy-proof',
+ 'delivery_mode': 'background'},
+ 'times_ns': list(range(index * 4 + 1, index * 4 + 5)),
+ 'before': window(candidate, stage, index * 2),
+ 'after': window(candidate, stage, index * 2 + 1),
+ 'trace_before': before, 'trace_after': page(events), 'response': response})
+ events.append([len(events) + 1, len(events), 'stop', 100, 100, 0, 0])
+ result['trace'] = page(events, active=False)
+ with tempfile.TemporaryDirectory() as temporary:
+ documents = create_documents(Path(temporary))
+ before = documents[candidate['app']].read_bytes()
+ after = changed_ods(before) if candidate['app'] == 'calc' else before.replace(b'x="40"', b'x="42"')
+ result.update(document_before=base64.b64encode(before).decode(),
+ document_after=base64.b64encode(after).decode())
+ return result
+
+
+class PolicyTests(unittest.TestCase):
+ def test_native_window_addresses_use_u64_not_pid_range(self):
+ for window_id in (0x55ABCDEF1234, 2**64 - 1):
+ candidate = plan('resource_wrong_window')
+ candidate['target']['window_id'] = window_id
+ self.assertEqual(verify_evidence(candidate, evidence(candidate))['result'], 'passed')
+ excluded = documents_for_case(candidate)[0]['resources']['desktop']['windows'][0]
+ self.assertNotEqual(excluded['window_id'], window_id)
+ self.assertLessEqual(excluded['window_id'], 2**64 - 1)
+ for window_id in (True, 0, -1, 2**64):
+ candidate = plan()
+ candidate['target']['window_id'] = window_id
+ with self.subTest(window_id=window_id), self.assertRaises(AssertionError):
+ validate_plan(candidate)
+
+ def test_exact_resource_and_managed_matrix_all_profiles(self):
+ for mode in ('standard', 'bounded', 'unrestricted'):
+ for app in ('calc', 'inkscape'):
+ for case in CASES:
+ candidate = plan(case, app, mode)
+ with self.subTest(case=case, app=app, mode=mode):
+ if case == 'no_manifest_allow' and mode == 'bounded':
+ with self.assertRaisesRegex(AssertionError, 'bounded'):
+ validate_plan(candidate)
+ continue
+ self.assertEqual(verify_evidence(candidate, evidence(candidate))['result'], 'passed')
+ manifest, managed = documents_for_case(candidate)
+ if case == 'no_manifest_allow':
+ self.assertIsNone(manifest)
+ self.assertIsNone(managed)
+ continue
+ target = manifest['resources']['desktop']['windows'][0]
+ self.assertEqual(target['pid'], 21 if case == 'resource_wrong_pid' else 20)
+ self.assertEqual(target['window_id'], 201 if case == 'resource_wrong_window' else 200)
+ self.assertEqual('deny' in (managed or {}), case == 'managed_deny')
+ self.assertEqual(manifest['version'], 3)
+ self.assertTrue(manifest['expires_after'] and manifest['idle_timeout'])
+
+ def test_plan_rejects_scope_escape_and_non_synthetic_document(self):
+ mutations = [lambda p: p.update(disposable=False), lambda p: p.update(case='arbitrary'),
+ lambda p: p.update(mode='autonomous'), lambda p: p.update(app='terminal'),
+ lambda p: p.update(profile={'manifest': '/host-policy'}),
+ lambda p: p.update(arguments={'scope': 'desktop'}),
+ lambda p: p.update(document='/business/file.ods'),
+ lambda p: p.update(document='cua-smoke-calc.ods'),
+ lambda p: p['target'].update(pid=True), lambda p: p['target'].update(window_id=0),
+ lambda p: p['target'].update(delivery_mode='foreground')]
+ for mutate in mutations:
+ candidate = plan()
+ mutate(candidate)
+ with self.subTest(candidate=candidate), self.assertRaises(AssertionError):
+ validate_plan(candidate)
+
+ def test_source_exact_envelope_and_admission_boundary(self):
+ for case in DENIALS:
+ expected = expected_refusal(plan(case))
+ core = {'isError': True, 'structuredContent': {'status': 'refused', 'refusal': expected}}
+ check_refusal(core, expected)
+ invalid = [dict(core, isError=False),
+ dict(core, structuredContent={'effect': 'refused', 'reason': expected['code']}),
+ dict(core, structuredContent={**core['structuredContent'], 'delivery': {'mode': 'background'}}),
+ dict(core, structuredContent={'status': 'refused', 'refusal': {**expected, 'code': 'lane_busy'}}),
+ dict(core, content=[{'type': 'text', 'text': 'Permission denied'}])]
+ for result in invalid:
+ with self.subTest(case=case, result=result), self.assertRaises(AssertionError):
+ check_refusal(result, expected)
+ expected = expected_refusal(plan('managed_deny'))
+ flat = {'isError': True, 'structuredContent': {'code': 'permission_denied'},
+ 'content': [{'type': 'text', 'text': expected['message']}]}
+ self.assertEqual(check_refusal(flat, expected), 'mcp-tool-admission')
+ flat['content'][0]['text'] = expected['message'].replace('managed', 'user')
+ with self.assertRaises(AssertionError):
+ check_refusal(flat, expected)
+
+ def test_policy_injection_is_process_local_restored_and_never_overwrites_host_ceiling(self):
+ candidate = plan('managed_deny')
+ manifest, managed = documents_for_case(candidate)
+ with tempfile.TemporaryDirectory() as temporary, patch.dict(os.environ, {}, clear=True):
+ directory = Path(temporary)
+ def spawned(driver, path, profile):
+ self.assertEqual(os.environ[MANAGED_ENV], str((directory / 'managed.yaml').resolve()))
+ self.assertEqual(json.loads((directory / 'managed.yaml').read_text()), managed)
+ self.assertEqual(json.loads(Path(profile['manifest']).read_text()), manifest)
+ self.assertEqual(profile['mode'], 'unrestricted')
+ self.assertTrue(profile['acknowledge_unrestricted'] and profile['approve_manifest'])
+ raise RuntimeError('synthetic spawn failure')
+ with patch('production_policy_proof.DirectMCP', side_effect=spawned):
+ with self.assertRaisesRegex(RuntimeError, 'spawn failure'):
+ start_client(Path('/driver'), directory, 'unrestricted', manifest, managed)
+ self.assertNotIn(MANAGED_ENV, os.environ)
+ for name in (MANAGED_ENV, 'CUA_DRIVER_POLICY_FILE'):
+ with patch.dict(os.environ, {name: '/never-read-host-policy'}), \
+ patch('production_policy_proof.DirectMCP') as spawn:
+ with self.assertRaisesRegex(AssertionError, 'inherited'):
+ start_client(Path('/driver'), directory, 'unrestricted', manifest, managed)
+ spawn.assert_not_called()
+ self.assertEqual(os.environ[name], '/never-read-host-policy')
+
+
+class OracleTests(unittest.TestCase):
+ def test_only_inkscape_snapshots_bound_visited_nodes_and_keep_images_and_depth(self):
+ for app in ('calc', 'inkscape'):
+ for stage in SMOKE_STEPS[app]:
+ for before in (True, False):
+ with self.subTest(app=app, stage=stage, before=before):
+ candidate = plan(app=app)
+ client = Mock()
+ expected = window(candidate, stage, 1)
+ client.tool.side_effect = [
+ {'structuredContent': {'windows': [candidate['target']]}}, expected]
+ self.assertEqual(snapshot(client, candidate, stage=stage, before=before), expected)
+ arguments = {**candidate['target'], 'session': 'policy-proof'}
+ if app == 'inkscape' and not (stage in ('select', 'move') and before):
+ arguments['max_elements'] = 2500
+ client.tool.assert_called_with('get_window_state', arguments)
+
+ def test_bounded_projection_cannot_omit_selection_grounding(self):
+ candidate = plan('resource_allow', app='inkscape')
+ for stage in ('select', 'move'):
+ value = evidence(candidate)
+ row = next(row for row in value['actions'] if row['stage'] == stage)
+ row['before']['structuredContent']['tree_markdown'] = ''
+ with self.subTest(stage=stage), self.assertRaises(GroundingUnavailable):
+ verify_evidence(candidate, value)
+
+ def test_rejects_tampered_result_trace_snapshots_configuration_and_output(self):
+ mutations = {
+ 'dropped_action': lambda e: e['actions'].pop(),
+ 'wrong_target': lambda e: e['actions'][0]['arguments'].update(window_id=201),
+ 'wrong_tool': lambda e: e['actions'][0].update(tool='click'),
+ 'wrong_profile': lambda e: e['actions'][0]['configuration'][0]['resources']['desktop'].update(windows=[]),
+ 'wrong_mode': lambda e: e['actions'][0].update(mode='standard'),
+ 'refusal_code': lambda e: e['actions'][0]['response']['structuredContent']['refusal'].update(code='permission_denied'),
+ 'refusal_message': lambda e: e['actions'][0]['response']['structuredContent']['refusal'].update(message='denied'),
+ 'false_error_success': lambda e: e['actions'][1]['response'].update(isError=True),
+ 'partial': lambda e: e['actions'][1]['response']['structuredContent'].update(effect='partial'),
+ 'other_route': lambda e: e['actions'][1]['response']['structuredContent'].update(route='accessibility'),
+ 'same_runtime': lambda e: e['actions'][0].update(runtime_pid=101),
+ 'changed_runtime': lambda e: e['actions'][2].update(runtime_pid=102),
+ 'stale_snapshot': lambda e: e['actions'][0].update(after=e['actions'][0]['before']),
+ 'wrong_document': lambda e: e['actions'][0]['before']['structuredContent'].update(window_title='other'),
+ 'wrong_snapshot_pid': lambda e: e['actions'][0]['before']['structuredContent'].update(pid=21),
+ 'wrong_snapshot_window': lambda e: e['actions'][0]['after']['structuredContent'].update(window_id=201),
+ 'foreground_target': lambda e: e['actions'][0]['primary_before'].update(pid=20),
+ 'missing_image': lambda e: e['actions'][0]['before']['structuredContent'].update(screenshot_width=0),
+ 'unordered_time': lambda e: e['actions'][0]['times_ns'].__setitem__(3, 0),
+ 'trace_overflow': lambda e: e['trace'].update(overflow=True),
+ 'trace_timeout': lambda e: e['actions'][0]['trace_after'].update(timed_out=True),
+ 'trace_incomplete': lambda e: e['trace']['events'].pop(),
+ 'changed_prefix': lambda e: e['actions'][1]['trace_after']['events'][1].__setitem__(3, 500),
+ 'no_saved_effect': lambda e: e.update(document_after=e['document_before']),
+ }
+ candidate = plan()
+ good = evidence(candidate)
+ for name, mutate in mutations.items():
+ bad = copy.deepcopy(good)
+ mutate(bad)
+ with self.subTest(name=name), self.assertRaises(AssertionError):
+ verify_evidence(candidate, bad)
+
+ def test_synthetic_dispatch_in_denial_rejected_even_with_consistent_trace_prefixes(self):
+ candidate = plan()
+ bad = evidence(candidate)
+ # Move the quiet interval boundary past the first positive-control
+ # admission, preserving a complete internally consistent trace.
+ bad['actions'][0]['trace_after'] = page(bad['trace']['events'][:2])
+ with self.assertRaisesRegex(AssertionError, 'denied call reached'):
+ verify_evidence(candidate, bad)
+
+ def test_no_dispatch_flag_cannot_replace_raw_trace(self):
+ candidate = plan()
+ bad = evidence(candidate)
+ bad['actions'][0].update(no_dispatch='verified', trace_after={})
+ with self.assertRaises(AssertionError):
+ verify_evidence(candidate, bad)
+
+ def test_calc_preexisting_expected_text_cannot_pass_as_an_input_effect(self):
+ candidate = plan('resource_allow')
+ bad = evidence(candidate)
+ # A rewrite of container bytes must not be enough if A1 already had a.
+ bad['document_before'] = bad['document_after']
+ with self.assertRaisesRegex(AssertionError, 'initial A1 is not blank'):
+ verify_evidence(candidate, bad)
+
+ def test_exact_window_discovery_precedes_snapshot(self):
+ client = Mock()
+ client.tool.return_value = {'structuredContent': {'windows': [
+ {'pid': 20, 'window_id': 200}, {'pid': 20, 'window_id': 201}]}}
+ with self.assertRaisesRegex(AssertionError, 'stale or ambiguous'):
+ snapshot(client, plan())
+ self.assertEqual([call.args[0] for call in client.tool.call_args_list], ['list_windows'])
+
+ def test_failed_provenance_cannot_start_native_process_or_trace(self):
+ with tempfile.TemporaryDirectory() as temporary, patch.dict(os.environ, {}, clear=True):
+ directory = Path(temporary)
+ path = directory / 'plan.json'
+ path.write_text(json.dumps(plan()))
+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence')
+ with patch('production_policy_proof.provenance', side_effect=AssertionError('source differs')), \
+ patch('production_policy_proof.DirectMCP') as spawn, \
+ patch('production_policy_proof.Trace') as trace:
+ self.assertEqual(run(args), 1)
+ spawn.assert_not_called()
+ trace.assert_not_called()
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['result'], 'failed')
+ self.assertIn('source differs', report['error']['message'])
+
+
+class OrchestrationTests(unittest.TestCase):
+ def exercise(self, directory, failure=None, *, app='calc', case='managed_deny',
+ missing_grounding=None):
+ candidate = plan(case, app=app)
+ document = create_documents(directory)[app]
+ candidate['document'] = str(document.resolve())
+ path = directory / 'plan.json'
+ path.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence', driver=Path('/driver'),
+ trace_socket=Path('/disposable/trace'))
+ events, clients, calls = [], [], []
+
+ class FakeTrace:
+ active = False
+ closed = False
+
+ def collect(self):
+ return page(events, self.active)
+
+ def exchange(self, command):
+ calls.append(('trace', command))
+ self.active = command == 'TRACE_START'
+ events.append([len(events) + 1, len(events),
+ 'start' if self.active else 'stop', 100, 100, 0, 0])
+
+ def close(self):
+ self.closed = True
+
+ class FakeClient:
+ def __init__(self, driver, path, profile):
+ self.directory, self.name, self.profile = path, path.name, profile
+ self.process = SimpleNamespace(pid=100 + len(clients))
+ self.failed, self.closed, self.counter = False, False, 0
+ self.snapshots = []
+ clients.append(self)
+
+ def tool(self, tool, arguments):
+ calls.append((self.name, tool))
+ self.counter += 1
+ if tool == 'list_windows':
+ assert self.name == 'observer', 'window-only manifest cannot enumerate application'
+ return {'structuredContent': {'windows': [candidate['target']]}}
+ if tool == 'get_window_state':
+ stage = list(SMOKE_STEPS[app])[
+ len(self.snapshots) // 2 if self.name == 'control' else 0]
+ self.snapshots.append(dict(arguments))
+ result = window(candidate, stage, f'{self.name}-{self.counter}')
+ if missing_grounding == (self.name, stage):
+ if stage == 'move':
+ content = result['structuredContent']
+ content['tree_markdown'] = '\n'.join(
+ line for line in content['tree_markdown'].splitlines()
+ if 'Rectangle in root.' not in line)
+ else:
+ result['structuredContent'].update(elements=[], tree_markdown='')
+ return result
+ if failure == 'unknown':
+ self.failed = True
+ raise RuntimeError('unknown outcome; no replay')
+ if self.name == 'denied':
+ if failure == 'unexpected_dispatch':
+ events.append([len(events) + 1, len(events), 'agent_admitted', 100, 100, 1, 0])
+ return {'isError': True, 'structuredContent': {'code': 'permission_denied'},
+ 'content': [{'type': 'text', 'text': expected_refusal(candidate)['message']}]}
+ for kind, pressed in [('agent_admitted', 0), ('keyboard_key', 1),
+ ('keyboard_key', 0), ('agent_action_end', 0)]:
+ events.append([len(events) + 1, len(events), kind, 100, 100, 1, pressed])
+ if tool == 'hotkey' and arguments['keys'] == ['ctrl', 's']:
+ before = document.read_bytes()
+ document.write_bytes(changed_ods(before) if app == 'calc' else
+ before.replace(b'x="40"', b'x="42"'))
+ return {'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background'}}}
+
+ def close(self):
+ self.closed = True
+
+ trace = FakeTrace()
+ with patch.dict(os.environ, {}, clear=True), \
+ patch('production_policy_proof.provenance', return_value={}), \
+ patch('production_policy_proof.app_process_identity', return_value={}), \
+ patch('production_policy_proof.wm', return_value={
+ 'pid': 20 if failure == 'foreground_target' else 10, 'address': '0x64'}), \
+ patch('production_policy_proof.subprocess.check_output',
+ return_value=json.dumps([{'pid': 20, 'address': '0xc8', 'xwayland': False}])), \
+ patch('production_policy_proof.Trace', return_value=trace), \
+ patch('production_policy_proof.DirectMCP', FakeClient):
+ status = run(args)
+ self.assertNotIn(MANAGED_ENV, os.environ)
+ self.assertTrue(trace.closed and not trace.active)
+ self.assertTrue(all(client.closed for client in clients))
+ return status, json.loads((args.evidence / 'result.json').read_text()), calls, clients
+
+ def test_inkscape_select_and_move_use_default_snapshots_in_denial_and_control(self):
+ for case in ('managed_deny', 'resource_allow'):
+ with self.subTest(case=case), tempfile.TemporaryDirectory() as temporary:
+ status, report, calls, clients = self.exercise(
+ Path(temporary), app='inkscape', case=case)
+ self.assertEqual(status, 0, report.get('error'))
+ default = {**report['plan']['target'], 'session': 'policy-proof'}
+ bounded = {**default, 'max_elements': 2500}
+ observed = {client.name: client.snapshots for client in clients}
+ self.assertEqual(observed['control'],
+ [default, bounded, default, bounded, bounded, bounded])
+ self.assertEqual(observed['observer'],
+ [default, bounded] if case == 'managed_deny' else [])
+ for index, (name, tool) in enumerate(calls):
+ if tool not in ('press_key', 'hotkey'):
+ continue
+ observer = 'observer' if name == 'denied' else name
+ self.assertEqual(calls[index - 1], (observer, 'get_window_state'))
+ self.assertEqual(calls[index + 1:index + 3],
+ [('observer', 'list_windows'), (observer, 'get_window_state')])
+
+ def test_inkscape_missing_grounding_stops_before_dispatch_without_retry(self):
+ for missing, expected_actions in ((('observer', 'select'), []),
+ (('control', 'select'), [('denied', 'hotkey')]),
+ (('control', 'move'), [('denied', 'hotkey'), ('control', 'hotkey')])):
+ with self.subTest(missing=missing), tempfile.TemporaryDirectory() as temporary:
+ status, report, calls, clients = self.exercise(
+ Path(temporary), app='inkscape', missing_grounding=missing)
+ self.assertEqual(status, 1)
+ self.assertEqual(report['error']['type'], 'GroundingUnavailable')
+ self.assertEqual([(name, tool) for name, tool in calls
+ if tool in ('press_key', 'hotkey')], expected_actions)
+ self.assertNotIn('response', report['actions'][-1])
+
+ def test_inkscape_missing_selection_status_refuses_before_right_without_retry(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ status, report, calls, clients = self.exercise(
+ Path(temporary), app='inkscape', case='resource_allow',
+ missing_grounding=('control', 'move'))
+ self.assertEqual(status, 1)
+ self.assertEqual(report['error'], {
+ 'type': 'GroundingUnavailable',
+ 'message': 'cannot prove the single rectangle is selected before Right'})
+ self.assertEqual([(name, tool) for name, tool in calls
+ if tool in ('press_key', 'hotkey')], [('control', 'hotkey')])
+ default = {**report['plan']['target'], 'session': 'policy-proof'}
+ control = next(client for client in clients if client.name == 'control')
+ self.assertEqual(control.snapshots,
+ [default, {**default, 'max_elements': 2500}, default])
+ move = report['actions'][-1]
+ self.assertEqual(move['stage'], 'move')
+ self.assertEqual(move['before']['structuredContent']['elements'],
+ INKSCAPE_SELECTED['elements'])
+ self.assertIn('spin button', move['before']['structuredContent']['tree_markdown'])
+ self.assertNotIn('response', move)
+
+ def test_normal_direct_cell_checks_denial_then_saved_effect_and_closes_every_runtime(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ status, report, calls, clients = self.exercise(Path(temporary))
+ self.assertEqual(status, 0, report.get('error'))
+ self.assertEqual(report['verification']['positive_control']['text'], 'a')
+ self.assertEqual([client.name for client in clients], ['observer', 'denied', 'control'])
+ self.assertTrue(all(client.profile['mode'] == 'unrestricted' for client in clients))
+ actions = [(name, tool) for name, tool in calls if tool in ('press_key', 'hotkey')]
+ self.assertEqual(actions, [('denied', 'press_key'), ('control', 'press_key'),
+ ('control', 'press_key'), ('control', 'hotkey')])
+ for index, (name, tool) in enumerate(calls):
+ if tool not in ('press_key', 'hotkey'):
+ continue
+ observer = 'observer' if name == 'denied' else name
+ self.assertEqual(calls[index - 1], (observer, 'get_window_state'))
+ self.assertEqual(calls[index + 1:index + 3],
+ [('observer', 'list_windows'), (observer, 'get_window_state')])
+
+ def test_unknown_or_wrong_refusal_stops_before_control_and_retains_after_snapshot(self):
+ for failure in ('unknown', 'unexpected_dispatch'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as temporary:
+ status, report, calls, clients = self.exercise(Path(temporary), failure)
+ self.assertEqual(status, 1)
+ self.assertEqual([client.name for client in clients], ['observer', 'denied'])
+ self.assertEqual(sum(tool == 'press_key' for _, tool in calls), 1)
+ self.assertIn('after', report['actions'][0])
+ self.assertEqual(calls[-1], ('trace', 'TRACE_STOP'))
+ if failure == 'unknown':
+ self.assertIn('unknown outcome', report['error']['message'])
+ else:
+ self.assertIn('denied call reached', report['error']['message'])
+
+ def test_foreground_target_refuses_before_any_input(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ status, report, calls, clients = self.exercise(Path(temporary), 'foreground_target')
+ self.assertEqual(status, 1)
+ self.assertFalse(any(tool in ('press_key', 'hotkey') for _, tool in calls))
+ self.assertIn('target is the primary client', report['error']['message'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.py
new file mode 100644
index 0000000000..4695b8beb6
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.py
@@ -0,0 +1,399 @@
+"""Prepare one native v3 initial-primary-conflict/refusal and fresh recovery cell.
+
+CLI: --plan --evidence --driver --plugin --source --source-sha --trace-socket
+--primary-grab --foreground-journal, as for production_geometry_fault_proof.py.
+Run with python3.11 on the exact prepared disposable VM. No app launch, config
+edit, signing, policy installation, plugin input, or automatic action replay.
+
+Integration boundary: use the geometry plan's one-agent shape (app, name,
+target, bounds, pointer_stage=select_range|move_rectangle, drag={}), foreground,
+primary_point, recovery and package_versions. Set purpose=primary_conflict,
+case=initial_refusal. Include vm={machine_id,boot_id}, compositor={pid,instance,
+uid,starttime,exe}, and processes={target,foreground}, each exact /proc identity
+{pid,uid,starttime,exe}. The controller must leave the synthetic target as the
+PRIMARY KEYBOARD client before launch, with no held foreground fixture input.
+The runner first attempts one freshly image-grounded drag through DirectMCP.
+It requires primary_target_busy, zero synthetic events, and idle lane status.
+
+After that runtime is reaped and its strict trace stopped, the independent
+primary-grab fixture deliberately moves to/holds the separate foreground client.
+Only then does a distinct runtime attempt a NEW freshly grounded click/scroll.
+The predeclared oracle is strict unchanged primary state within EACH action
+phase, including runtime cleanup. No primary events are filtered. Setup between
+phases has no agent runtime/action and is recorded as an intentional transition,
+NOT unchanged isolation. Active-drag primary-transition cancellation and
+continuous isolation across setup are explicitly UNPROVEN by this narrow cell.
+Portable tests are preparation only; native execution is a separate gate.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import socket
+import stat
+import struct
+import subprocess
+import time
+
+from desktop_faults import _identity, _same_compositor, _hypr
+from driver_input_live import state, wait_for
+from primary_trace import Trace, analyze
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, close_owned,
+ grounded_snapshot, prepare_drag, verify_fresh_observation, verify_recovery_cleanup, verify_recovery_trace)
+from production_desktop_fault_proof import guest_identity, verify_status
+from production_geometry_fault_proof import validate_plan as geometry_plan, window_bounds
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity,
+ assert_no_dispatch, capacity_lane, check_response, primary_acknowledgement,
+ provenance, require_primary_active, trace_interval)
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+def validate_identity(identity):
+ assert set(identity) == {'pid', 'uid', 'starttime', 'exe'}
+ assert type(identity['pid']) is int and identity['pid'] > 1
+ assert type(identity['uid']) is int and identity['uid'] >= 0
+ assert re.fullmatch(r'[0-9]+', identity['starttime'])
+ assert Path(identity['exe']).is_absolute()
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'primary_conflict' and plan['case'] == 'initial_refusal'
+ assert 'fault' not in plan, 'active faults are not covered by this runner'
+ bounds = plan['agents'][0]['bounds']
+ geometry_plan({**plan, 'purpose': 'geometry_fault',
+ 'compositor': {key: plan['compositor'][key] for key in ('pid', 'instance')},
+ 'fault': {'kind': 'move', 'to': [bounds['x'] + 1, bounds['y']]}})
+ assert set(plan['vm']) == {'machine_id', 'boot_id'}
+ assert re.fullmatch(r'[0-9a-f]{32}', plan['vm']['machine_id'])
+ assert re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', plan['vm']['boot_id'])
+ assert set(plan['compositor']) == {'pid', 'instance', 'uid', 'starttime', 'exe'}
+ validate_identity({k: v for k, v in plan['compositor'].items() if k != 'instance'})
+ assert Path(plan['compositor']['exe']).name == 'Hyprland'
+ assert set(plan['processes']) == {'target', 'foreground'}
+ targets = {'target': plan['agents'][0]['target'], 'foreground': plan['foreground']}
+ assert len({target['window_id'] for target in targets.values()}) == 2
+ for name, identity in plan['processes'].items():
+ validate_identity(identity)
+ assert identity['pid'] == targets[name]['pid']
+ assert identity['uid'] == plan['compositor']['uid']
+ assert len({plan['compositor']['pid'], *(p['pid'] for p in plan['processes'].values())}) == 3
+
+
+def clear_status(status, *, unreserved=False, allow_passive=False):
+ """Trace balance alone cannot exclude state held before tracing started."""
+ verify_status(status, True)
+ for row in status['input']['lanes']:
+ assert all(type(row.get(key)) is int and row[key] == 0 for key in ('held_button', 'held_keys'))
+ assert all(row.get(key) is False for key in ('drag_active', 'lease_active', 'keyboard_focus'))
+ if unreserved:
+ assert row.get('reserved') is False
+ assert type(row.get('pointer_focus')) is bool
+ if not allow_passive:
+ assert row['pointer_focus'] is False
+ return status
+
+
+def verify_refusal_status(status, response):
+ """CLAIM survives TARGET refusal until EOF, but grants no input authority."""
+ clear_status(status)
+ check_response(response, {'kind': 'refused', 'reason': 'primary_target_busy'})
+ lane = response['structuredContent'].get('lane')
+ assert type(lane) is int and lane in (0, 1), 'missing refused connection lane'
+ for row in status['input']['lanes']:
+ assert row.get('reserved') is (row['lane'] == lane), 'unexpected refusal reservation'
+ assert row.get('pointer_focus') is False, 'refused connection retained pointer focus'
+ return status
+
+
+class ExactDesktop:
+ """Read-only attestation; primary input belongs solely to the test fixture."""
+ def __init__(self, plan):
+ self.plan = plan
+ self.instance = plan['compositor']['instance']
+ self.compositor = {k: v for k, v in plan['compositor'].items() if k != 'instance'}
+ self.guard()
+ assert subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode == 0
+
+ def guard(self):
+ assert platform.system() == 'Linux' and guest_identity() == self.plan['vm'], 'wrong VM boot'
+ assert os.environ.get('HYPRLAND_INSTANCE_SIGNATURE') == self.instance, 'wrong compositor session'
+ assert self.compositor['uid'] == os.getuid(), 'wrong desktop owner'
+ _same_compositor(self.compositor, self.instance)
+ for identity in self.plan['processes'].values():
+ assert _identity(identity['pid']) == identity, 'target/foreground process changed'
+ windows = json.loads(_hypr(self.instance, '-j', 'clients'))
+ spec = self.plan['agents'][0]
+ for name, target in (('target', spec['target']), ('foreground', self.plan['foreground'])):
+ matches = [w for w in windows if w.get('pid') == target['pid']]
+ assert len(matches) == 1, 'ambiguous client'
+ window = matches[0]
+ assert int(window['address'], 16) == target['window_id'] and window.get('xwayland') is False
+ if name == 'target':
+ assert f'cua-smoke-{spec["app"]}' in window.get('title', '')
+ assert window_bounds(window) == spec['bounds'], 'target geometry changed'
+ return windows
+
+ def primary(self, target):
+ self.guard()
+ active = json.loads(_hypr(self.instance, '-j', 'activewindow'))
+ assert active.get('pid') == target['pid'] and int(active.get('address', '0'), 16) == target['window_id'], \
+ 'wrong primary client'
+ return {'pid': active['pid'], 'window_id': int(active['address'], 16),
+ 'cursor': json.loads(_hypr(self.instance, '-j', 'cursorpos')),
+ 'workspace': json.loads(_hypr(self.instance, '-j', 'activeworkspace'))['id']}
+
+ def status(self, *, unreserved=False, allow_passive=False):
+ return clear_status(self.raw_status(), unreserved=unreserved, allow_passive=allow_passive)
+
+ def raw_status(self):
+ self.guard()
+ return json.loads(_hypr(self.instance, '-j', 'cua:status'))
+
+ def trace(self, path):
+ self.guard()
+ assert path.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')
+ expected = Path(os.environ['XDG_RUNTIME_DIR']) / 'hypr' / self.instance / path.name
+ assert path.is_absolute() and path == expected and path.resolve(strict=True) == path
+ info = path.lstat()
+ assert stat.S_ISSOCK(info.st_mode) and info.st_uid == self.compositor['uid']
+ trace = Trace(path)
+ try:
+ peer = struct.unpack('3i', trace.socket.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
+ assert peer[:2] == (self.compositor['pid'], self.compositor['uid']), 'wrong trace peer'
+ assert trace.hello['protocol'] == 3
+ self.guard()
+ assert trace.collect().get('active') is False, 'another proof owns the trace'
+ return trace
+ except BaseException:
+ trace.close()
+ raise
+
+
+def verify_refusal(before, after, response):
+ check_response(response, {'kind': 'refused', 'reason': 'primary_target_busy'})
+ assert_no_dispatch(before, after)
+ # Include the initial prefix too, not just the call delta.
+ assert not any(row[5] in (1, 2) for row in after['events']), 'synthetic input before refusal'
+
+
+def action(actor, observer, spec, phase, trace, guard, save, record):
+ """One normal Driver input call; always retain its raw after-observation."""
+ assert phase in ('refusal', 'recovery')
+ prepared = prepare_drag(actor, spec) # Also grounds click/scroll pointer stages.
+ tool = pointer_grounding.STAGES[spec['app']][spec['pointer_stage']]
+ assert tool == 'drag' if phase == 'refusal' else tool in ('click', 'scroll')
+ arguments = {**prepared['arguments'], **spec['target'], 'session': spec['name'], 'delivery_mode': 'background'}
+ record.update(runtime_pid=actor.process.pid, grounding=prepared, tool=tool, arguments=arguments,
+ outcome='not_attempted', replayed=False)
+ save(phase + '-action.json', record)
+ record['trace_before'] = trace.collect()
+ trace_interval(record.get('initial_trace', record['trace_before']), record['trace_before'])
+ assert not any(row[5] in (1, 2) for row in record['trace_before']['events']), \
+ 'synthetic activity before the single planned action'
+ guard()
+ assert_distinct_runtimes([actor, observer])
+ record['dispatch_ns'] = time.monotonic_ns()
+ assert 0 <= record['dispatch_ns'] - prepared['prepared_ns'] <= MAX_GROUNDING_AGE_NS, 'stale grounding'
+ record['outcome'] = 'unknown'
+ try:
+ record['response'] = actor.tool(tool, arguments)
+ record['outcome'] = 'response'
+ except Exception as error:
+ record['error'] = str(error)
+ finally:
+ record['observed_ns'] = time.monotonic_ns()
+ save(phase + '-action.json', record)
+ try:
+ record['after'] = grounded_snapshot(observer, spec['target'], spec, session=False)
+ except Exception as error:
+ record['observation_error'] = str(error)
+ raise
+ finally:
+ # A failed screenshot must not discard independent dispatch evidence.
+ try:
+ record['trace_after'] = trace.collect()
+ finally:
+ save(phase + '-action.json', record)
+ guard()
+ assert_distinct_runtimes([actor, observer])
+ assert record['dispatch_ns'] <= record['observed_ns'], 'action returned before dispatch'
+ verify_fresh_observation(prepared['snapshot'], record['after'], observer, after_ns=record['observed_ns'])
+ assert record['outcome'] == 'response', 'delivery unknown; never replay'
+ if phase == 'refusal':
+ verify_refusal(record['trace_before'], record['trace_after'], record['response'])
+ else:
+ check_response(record['response'], {'kind': 'dispatched'})
+ record['app_effect'] = pointer_grounding.verify(record['after'],
+ pointer_grounding.read_pixels(record['after']['proof_image']), prepared['oracle'])
+ lane = capacity_lane(record['trace_before'], record['trace_after'], tool)
+ record['trace_verification'] = verify_recovery_trace(record['trace_before'], record['trace_after'], lane, tool)
+ save(phase + '-action.json', record)
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2) + '\n')
+ report = {'result': 'failed', 'scope': 'initial-primary-client-refusal-and-new-action-recovery',
+ 'active_drag_cancellation': 'unproven', 'continuous_isolation_across_setup': 'unproven',
+ 'full_desktop_matrix': False, 'physical_hardware': False, 'phases': {}}
+ clients, observer, desktop, trace, grab = [], None, None, None, None
+ tracing, phase, primary, baseline, deadline = False, None, None, None, None
+ def guard():
+ wanted = spec['target'] if phase == 'refusal' else plan['foreground']
+ assert desktop.primary(wanted) == primary, 'primary cursor/focus/workspace changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), 'foreground input changed'
+ if phase == 'recovery':
+ require_primary_active(grab, deadline)
+ def finish_trace():
+ nonlocal tracing
+ trace.exchange('TRACE_STOP')
+ tracing = False
+ stopped = trace.collect()
+ save(phase + '-trace.json', stopped)
+ checked = analyze(stopped)
+ assert checked['result'] == 'passed' and released_synthetic_input(stopped), checked
+ assert [row[2] for row in stopped['events'] if row[2] in ('start', 'stop')] == ['start', 'stop'], \
+ 'trace restarted within an action phase'
+ boundary = report['phases'][phase]['trace_after']
+ assert stopped['events'][:boundary['count']] == boundary['events'], 'final trace history changed'
+ if phase == 'refusal':
+ assert not any(row[5] in (1, 2) for row in stopped['events']), 'refusal dispatched or teardown sent input'
+ else:
+ checked = verify_recovery_cleanup(report['phases'][phase]['trace_after'], stopped)
+ guard()
+ report['phases'][phase]['final_status'] = desktop.status(unreserved=True, allow_passive=phase == 'recovery')
+ report['phases'][phase]['isolation'] = checked
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ value = DirectMCP(args.driver, directory, PROFILE)
+ clients.append(value)
+ return value
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ spec = plan['agents'][0]
+ desktop = ExactDesktop(plan)
+ app_process_identity(spec['app'], spec['target']['pid'])
+ origin = provenance(args, plan)
+ for name in (Path(__file__).name, 'production_primary_conflict_proof_test.py',
+ 'desktop_faults.py', 'production_cancel_proof.py',
+ 'production_desktop_fault_proof.py', 'production_geometry_fault_proof.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ origin['ownership'] = {'vm': plan['vm'], 'compositor': plan['compositor'], 'processes': plan['processes']}
+ save('provenance.json', origin)
+ observer = launch('observer')
+ trace = desktop.trace(args.trace_socket)
+ for phase in ('refusal', 'recovery'):
+ row = report['phases'][phase] = {}
+ row['initial_status'] = desktop.status(unreserved=True)
+ if phase == 'recovery':
+ assert refused.process.poll() is not None, 'refused runtime is still active'
+ assert not tracing
+ transition = report['setup_transition'] = {'purpose': 'independent-primary-fixture-setup',
+ 'agent_runtime_reaped': refused.process.pid, 'active_agent_actions': 0,
+ 'continuous_isolation': 'unproven', 'before': desktop.primary(spec['target'])}
+ foreground = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ result = observer.tool('get_desktop_state', {})
+ assert not result.get('isError')
+ screen = result['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < foreground['width'] and 0 < y < foreground['height']
+ x, y = foreground['x'] + x, foreground['y'] + y
+ assert 0 <= x < screen['screen_width'] and 0 <= y < screen['screen_height']
+ transition.update(expected_target=plan['foreground'], expected_cursor={'x': x, 'y': y},
+ requested_ns=time.monotonic_ns())
+ save('setup-transition.json', transition)
+ desktop.guard()
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(screen['screen_width']),
+ str(screen['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ transition['after'] = desktop.primary(plan['foreground'])
+ transition['observed_ns'] = time.monotonic_ns()
+ save('setup-transition.json', transition)
+ assert transition['after']['cursor'] == transition['expected_cursor'], 'primary fixture missed planned point'
+ require_primary_active(grab, deadline)
+ row['post_setup_status'] = desktop.status(unreserved=True)
+ wanted = spec['target'] if phase == 'refusal' else plan['foreground']
+ primary, baseline = desktop.primary(wanted), state(args.foreground_journal)
+ assert baseline['held'] is (phase == 'recovery')
+ row.update(primary_before=primary, foreground_before=baseline)
+ started_ns = time.monotonic_ns()
+ # A lost acknowledgement can still mean tracing started; retain
+ # the cleanup obligation before issuing the test-only command.
+ tracing = True
+ trace.exchange('TRACE_START')
+ initial = trace.collect()
+ row['initial_trace'] = initial
+ trace_interval(initial, initial)
+ assert initial['count'] == 1 and started_ns <= initial['events'][0][1] <= time.monotonic_ns()
+ actor = launch(phase)
+ assert_distinct_runtimes([actor, observer])
+ if phase == 'refusal':
+ refused = actor
+ current_spec = spec
+ else:
+ assert actor.process.pid != refused.process.pid, 'reused refused runtime'
+ current_spec = {**spec, 'name': spec['name'] + '-recovery',
+ 'pointer_stage': plan['recovery']['pointer_stage']}
+ assert not actor.tool('start_session', {'session': current_spec['name']}).get('isError')
+ action(actor, observer, current_spec, phase, trace, guard, save, row)
+ # Retain the observed status before validation can raise. A live
+ # refused connection still owns its CLAIM; EOF must clear it below.
+ row['post_action_status'] = desktop.raw_status()
+ save(phase + '-action.json', row)
+ if phase == 'refusal':
+ verify_refusal_status(row['post_action_status'], row['response'])
+ else:
+ clear_status(row['post_action_status'])
+ close_owned(actor)
+ wait_for(lambda: desktop.status(unreserved=True, allow_passive=phase == 'recovery'), timeout=2)
+ finish_trace()
+ row['result'] = 'verified'
+ save(phase + '-action.json', row)
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = {'type': type(error).__name__, 'message': str(error)}
+ finally:
+ operations = [(f'close_runtime_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients) if c is not observer]
+ if trace:
+ if tracing:
+ operations.append(('finish_trace', finish_trace))
+ operations.append(('close_trace', trace.close))
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release_primary))
+ if observer:
+ operations.append(('close_observer', lambda: close_owned(observer)))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.py
new file mode 100644
index 0000000000..cf8eea6cd2
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.py
@@ -0,0 +1,423 @@
+"""Portable adversarial orchestration tests; no native desktop is certified."""
+from contextlib import ExitStack
+from copy import deepcopy
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_primary_conflict_proof as proof
+
+
+BOUNDS = {'x': 10, 'y': 20, 'width': 800, 'height': 600}
+REFUSED = {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'primary_target_busy', 'lane': 0}}
+DELIVERED = {'structuredContent': {'effect': 'unverifiable', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background'}}}
+
+
+def identity(pid, name='app'):
+ return {'pid': pid, 'uid': 1000, 'starttime': '123', 'exe': '/usr/bin/' + name}
+
+
+def plan(app='calc'):
+ return {'purpose': 'primary_conflict', 'case': 'initial_refusal', 'disposable': True,
+ 'vm': {'machine_id': 'a' * 32, 'boot_id': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'},
+ 'compositor': {**identity(50, 'Hyprland'), 'instance': 'test_1'},
+ 'processes': {'target': identity(20), 'foreground': identity(10)},
+ 'foreground': {'pid': 10, 'window_id': 100}, 'primary_point': [20, 20], 'package_versions': {},
+ 'agents': [{'app': app, 'name': 'primary-conflict', 'target': {'pid': 20, 'window_id': 200},
+ 'bounds': dict(BOUNDS), 'pointer_stage': 'select_range' if app == 'calc' else 'move_rectangle', 'drag': {}}],
+ 'recovery': {'pointer_stage': 'click_b2' if app == 'calc' else 'scroll_down'}}
+
+
+def trace(events=(), active=True):
+ rows = [(0, 'start', 0, 0), *events]
+ if not active:
+ rows += [(20, 'stop', 0, 0)]
+ return {'hook': True, 'active': active, 'overflow': False, 'timed_out': False, 'count': len(rows),
+ 'events': [[i + 1, timestamp, kind, 30, 40, lane, value]
+ for i, (timestamp, kind, lane, value) in enumerate(rows)]}
+
+
+RECOVERY = [(1, 'agent_admitted', 1, 0), (2, 'pointer_button', 1, 1),
+ (3, 'pointer_button', 1, 0), (4, 'agent_action_end', 1, 0)]
+
+
+def status():
+ return {'configured': True, 'transport': {'ready': True}, 'input': {
+ 'protocol': 3, 'test_only': False, 'transport_ready': True,
+ 'seat_lifetime': 'compositor', 'upgrade': 'desktop_restart', 'lanes': [
+ {'lane': lane, 'held_button': 0, 'held_keys': 0, 'drag_active': False,
+ 'lease_active': False, 'keyboard_focus': False, 'pointer_focus': False, 'reserved': False}
+ for lane in (0, 1)]}}
+
+
+def client(pid):
+ return Mock(directory=Path.cwd(), process=Mock(pid=pid, poll=Mock(return_value=None)))
+
+
+class OracleTests(unittest.TestCase):
+ def test_refusal_keeps_only_its_connection_reservation_without_authority(self):
+ for lane in (0, 1):
+ response = {**REFUSED, 'structuredContent': {**REFUSED['structuredContent'], 'lane': lane}}
+ current = status()
+ current['input']['lanes'][lane]['reserved'] = True
+ self.assertIs(proof.verify_refusal_status(current, response), current)
+ for index, field, value in ((lane, 'reserved', False), (1 - lane, 'reserved', True),
+ (lane, 'pointer_focus', True), (1 - lane, 'pointer_focus', True),
+ (lane, 'keyboard_focus', True), (lane, 'lease_active', True),
+ (lane, 'drag_active', True), (lane, 'held_button', 272), (lane, 'held_keys', 1)):
+ candidate = deepcopy(current)
+ candidate['input']['lanes'][index][field] = value
+ with self.subTest(lane=lane, index=index, field=field), self.assertRaises(AssertionError):
+ proof.verify_refusal_status(candidate, response)
+ # The same reservation is forbidden after the runtime reaches EOF.
+ with self.assertRaises(AssertionError):
+ proof.clear_status(current, unreserved=True)
+ for invalid in (None, True, -1, 2):
+ with self.subTest(invalid=invalid), self.assertRaises(AssertionError):
+ proof.verify_refusal_status(current, {**response, 'structuredContent': {
+ **response['structuredContent'], 'lane': invalid}})
+
+ def test_exact_refusal_and_zero_synthetic_events_required(self):
+ proof.verify_refusal(trace(), trace(), REFUSED)
+ for response in (DELIVERED, {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'policy_denied'}},
+ {**REFUSED, 'structuredContent': {**REFUSED['structuredContent'], 'delivery': {'mode': 'unknown'}}}):
+ with self.subTest(response=response), self.assertRaises(AssertionError):
+ proof.verify_refusal(trace(), trace(), response)
+ for kind in ('agent_admitted', 'agent_cancel', 'pointer_enter', 'pointer_leave', 'pointer_button',
+ 'pointer_motion', 'keyboard_key', 'agent_drag_start', 'agent_action_end'):
+ for lane in (1, 2):
+ with self.subTest(kind=kind, lane=lane), self.assertRaises(AssertionError):
+ proof.verify_refusal(trace(), trace([(1, kind, lane, 0)]), REFUSED)
+ # A pre-call synthetic event must not disappear into a baseline.
+ before = trace([(1, kind, lane, 0)])
+ with self.assertRaises(AssertionError):
+ proof.verify_refusal(before, before, REFUSED)
+
+ def test_incomplete_or_rewritten_trace_cannot_pass(self):
+ for key, value in (('hook', False), ('active', False), ('overflow', True), ('timed_out', True), ('count', 9)):
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_refusal(trace(), {**trace(), key: value}, REFUSED)
+ changed = trace()
+ changed['events'][0][3] += 1
+ with self.assertRaisesRegex(AssertionError, 'history'):
+ proof.verify_refusal(trace(), changed, REFUSED)
+
+ def test_trace_oracle_never_ignores_primary_input_or_warp_and_return(self):
+ for kind in ('pointer_focus', 'keyboard_focus', 'pointer_button', 'keyboard_key', 'pointer_axis'):
+ self.assertEqual(proof.analyze(trace([(1, kind, 0, 0)], active=False))['result'], 'failed')
+ warped = trace([(1, 'cursor', 0, 0), (2, 'cursor', 0, 0)], active=False)
+ warped['events'][1][3] += 20
+ self.assertEqual(proof.analyze(warped)['result'], 'failed')
+
+ def test_current_held_state_and_preexisting_reservations_are_checked(self):
+ proof.clear_status(status(), unreserved=True)
+ for field, value in (('held_button', 272), ('held_keys', 1), ('held_keys', False),
+ ('drag_active', True), ('lease_active', True), ('keyboard_focus', True),
+ ('reserved', True), ('pointer_focus', True)):
+ row = status()
+ row['input']['lanes'][1][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.clear_status(row, unreserved=True)
+ passive = status()
+ passive['input']['lanes'][0].update(pointer_focus=True, reserved=True)
+ proof.clear_status(passive) # A live owner can retain passive focus.
+ with self.assertRaises(AssertionError):
+ proof.clear_status(passive, unreserved=True, allow_passive=True)
+ passive['input']['lanes'][0]['reserved'] = False
+ proof.clear_status(passive, unreserved=True, allow_passive=True)
+ for field, value in (('held_button', 272), ('held_keys', 1), ('drag_active', True),
+ ('lease_active', True), ('keyboard_focus', True), ('pointer_focus', 1)):
+ altered = deepcopy(passive)
+ altered['input']['lanes'][0][field] = value
+ with self.subTest(passive_field=field), self.assertRaises(AssertionError):
+ proof.clear_status(altered, unreserved=True, allow_passive=True)
+
+
+class OwnershipTests(unittest.TestCase):
+ def test_trace_requires_exact_socket_peer_and_unowned_trace(self):
+ path = Path('/run/user/1000/hypr/test_1/cua-input-v3.sock')
+ for failure in (None, 'peer', 'protocol', 'active', 'owner', 'alias'):
+ desktop = object.__new__(proof.ExactDesktop)
+ desktop.instance, desktop.compositor = 'test_1', identity(50, 'Hyprland')
+ desktop.guard = Mock()
+ tracer = Mock(hello={'protocol': 2 if failure == 'protocol' else 3})
+ tracer.collect.return_value = {'active': failure == 'active'}
+ tracer.socket.getsockopt.return_value = proof.struct.pack('3i', 51 if failure == 'peer' else 50, 1000, 1000)
+ with self.subTest(failure=failure), ExitStack() as stack:
+ stack.enter_context(patch.object(proof.socket, 'SO_PEERCRED', 17, create=True))
+ stack.enter_context(patch.dict(proof.os.environ, {'XDG_RUNTIME_DIR': '/run/user/1000'}))
+ stack.enter_context(patch.object(Path, 'resolve', return_value=Path('/different') if failure == 'alias' else path))
+ stack.enter_context(patch.object(Path, 'lstat', return_value=SimpleNamespace(
+ st_mode=proof.stat.S_IFSOCK | 0o600, st_uid=1001 if failure == 'owner' else 1000)))
+ factory = stack.enter_context(patch.object(proof, 'Trace', return_value=tracer))
+ if failure:
+ with self.assertRaises(AssertionError):
+ desktop.trace(path)
+ if failure in ('peer', 'protocol', 'active'):
+ tracer.close.assert_called_once()
+ else:
+ factory.assert_not_called()
+ else:
+ self.assertIs(desktop.trace(path), tracer)
+ tracer.exchange.assert_not_called()
+
+ def test_plan_requires_exact_vm_processes_and_narrow_case(self):
+ for app in ('calc', 'inkscape'):
+ proof.validate_plan(plan(app))
+ updates = ({'case': 'active_drag'}, {'disposable': False}, {'fault': {'kind': 'primary'}},
+ {'recovery': {'pointer_stage': 'select_range'}},
+ {'vm': {'machine_id': 'unknown', 'boot_id': 'unknown'}})
+ for update in updates:
+ with self.subTest(update=update), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **update})
+ for owner, key, value in (('target', 'pid', 21), ('target', 'uid', 1001),
+ ('foreground', 'starttime', ''), ('foreground', 'exe', 'relative')):
+ candidate = plan()
+ candidate['processes'][owner][key] = value
+ with self.subTest(owner=owner, key=key), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_guard_revalidates_boot_pid_and_window_before_control(self):
+ windows = [{'pid': 20, 'address': '0xc8', 'xwayland': False, 'title': 'cua-smoke-calc.ods',
+ 'at': [10, 20], 'size': [800, 600]}, {'pid': 10, 'address': '0x64', 'xwayland': False}]
+ for failure in (None, 'boot', 'process', 'address', 'geometry', 'native', 'document', 'ambiguous'):
+ candidate = plan()
+ desktop = object.__new__(proof.ExactDesktop)
+ desktop.plan, desktop.instance = candidate, 'test_1'
+ desktop.compositor = identity(50, 'Hyprland')
+ rows = deepcopy(windows)
+ if failure == 'address':
+ rows[0]['address'] = '0xc9'
+ elif failure == 'geometry':
+ rows[0]['size'][0] += 1
+ elif failure == 'native':
+ rows[0]['xwayland'] = True
+ elif failure == 'document':
+ rows[0]['title'] = 'unowned'
+ elif failure == 'ambiguous':
+ rows.append(rows[0])
+ with self.subTest(failure=failure), ExitStack() as stack:
+ stack.enter_context(patch.object(proof.platform, 'system', return_value='Linux'))
+ stack.enter_context(patch.object(proof, 'guest_identity', return_value={} if failure == 'boot' else candidate['vm']))
+ stack.enter_context(patch.dict(proof.os.environ, {'HYPRLAND_INSTANCE_SIGNATURE': 'test_1'}))
+ stack.enter_context(patch.object(proof.os, 'getuid', return_value=1000))
+ stack.enter_context(patch.object(proof, '_same_compositor'))
+ stack.enter_context(patch.object(proof, '_identity', side_effect=lambda pid: {} if failure == 'process' else identity(pid)))
+ stack.enter_context(patch.object(proof, '_hypr', return_value=json.dumps(rows)))
+ if failure:
+ with self.assertRaises(AssertionError):
+ desktop.guard()
+ else:
+ self.assertEqual(desktop.guard(), windows)
+
+
+class ActionTests(unittest.TestCase):
+ def test_single_normal_call_fresh_snapshot_unknown_never_replayed(self):
+ for phase in ('refusal', 'recovery'):
+ for failure in (None, 'guard', 'stale', 'unknown', 'same_snapshot', 'same_artifact', 'cached',
+ 'before_return', 'same_runtime', 'effect', 'pre_activity',
+ 'dead_before', 'dead_after', 'observation'):
+ if phase == 'refusal' and failure == 'effect':
+ continue
+ with self.subTest(phase=phase, failure=failure), ExitStack() as stack:
+ spec = plan()['agents'][0]
+ if phase == 'recovery':
+ spec['pointer_stage'] = 'click_b2'
+ actor, observer = client(101), client(102)
+ if failure == 'same_runtime':
+ observer = actor
+ if failure == 'dead_before':
+ actor.process.poll.return_value = 1
+ elif failure == 'dead_after':
+ actor.process.poll.side_effect = [None, 1]
+ actor.tool.side_effect = TimeoutError('lost reply') if failure == 'unknown' else None
+ actor.tool.return_value = REFUSED if phase == 'refusal' else DELIVERED
+ before = {'snapshot_id': 's00000001', 'proof_image': 'before.png',
+ 'proof_runtime': {'pid': 101, 'directory': str(Path.cwd())},
+ 'proof_observation_started_ns': 10, 'proof_observation_finished_ns': 20}
+ after = {**before, 'proof_runtime': {'pid': 102, 'directory': str(Path.cwd())},
+ 'proof_image': 'after.png', 'proof_observation_started_ns': 50, 'proof_observation_finished_ns': 60}
+ if failure == 'same_snapshot':
+ after = dict(before)
+ elif failure == 'same_artifact':
+ after['proof_image'] = before['proof_image']
+ elif failure == 'cached':
+ after.update(proof_observation_started_ns=10, proof_observation_finished_ns=20)
+ elif failure == 'before_return':
+ after['proof_observation_started_ns'] = 39
+ prepared = {'snapshot': before, 'arguments': {'x': 20, 'y': 30}, 'oracle': {'stage': 'click_b2'},
+ 'prepared_ns': 10}
+ stack.enter_context(patch.object(proof, 'prepare_drag', return_value=prepared))
+ snapshots = stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value=after,
+ side_effect=AssertionError('snapshot unavailable') if failure == 'observation' else None))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=
+ [proof.MAX_GROUNDING_AGE_NS + 11] if failure == 'stale' else [30, 40, 70]))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels'))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'verify', side_effect=AssertionError('effect missing') if failure == 'effect' else None))
+ tracer = Mock(collect=Mock(side_effect=[trace(RECOVERY) if failure == 'pre_activity' else trace(),
+ trace() if phase == 'refusal' else trace(RECOVERY)]))
+ guard = Mock(side_effect=AssertionError('primary changed') if failure == 'guard' else None)
+ save, record = Mock(), {}
+ if failure:
+ with self.assertRaises(AssertionError):
+ proof.action(actor, observer, spec, phase, tracer, guard, save, record)
+ else:
+ proof.action(actor, observer, spec, phase, tracer, guard, save, record)
+ attempted = failure not in ('stale', 'guard', 'pre_activity', 'dead_before', 'same_runtime')
+ self.assertEqual(actor.tool.call_count, int(attempted))
+ self.assertFalse(record['replayed'])
+ if attempted:
+ snapshots.assert_called_once_with(observer, spec['target'], spec, session=False)
+ self.assertEqual(actor.tool.call_args.args[1]['delivery_mode'], 'background')
+ self.assertEqual(actor.tool.call_args.args[1]['pid'], 20)
+ self.assertEqual(actor.tool.call_args.args[0], 'drag' if phase == 'refusal' else 'click')
+ if failure == 'unknown':
+ self.assertEqual(record['outcome'], 'unknown')
+ self.assertIn('after', record)
+ self.assertEqual(record['observed_ns'], 40)
+ self.assertTrue(save.call_count >= 3)
+ if failure == 'observation':
+ self.assertEqual(record['observation_error'], 'snapshot unavailable')
+ self.assertIn('trace_after', record)
+ self.assertEqual(record['outcome'], 'response')
+ self.assertTrue(save.call_count >= 3)
+
+
+class RunTests(unittest.TestCase):
+ def test_invalid_plan_preserves_raw_plan_and_cleanup_without_native_calls(self):
+ with tempfile.TemporaryDirectory() as root:
+ directory = Path(root)
+ path = directory / 'plan.json'
+ candidate = {**plan(), 'disposable': False}
+ path.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence')
+ with patch.object(proof, 'ExactDesktop') as desktop, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ desktop.assert_not_called()
+ self.assertEqual(json.loads((args.evidence / 'plan.json').read_text()), candidate)
+ self.assertEqual(json.loads((args.evidence / 'cleanup.json').read_text()), {'errors': []})
+
+ def test_run_separates_setup_reaps_all_children_and_retains_failure_evidence(self):
+ for failure in (None, 'refusal', 'recovery', 'close', 'release', 'primary_event', 'held',
+ 'reused', 'start_lost', 'restarted_trace', 'reserved_refusal', 'reserved_after_close'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as root, ExitStack() as stack:
+ directory = Path(root)
+ path = directory / 'plan.json'
+ path.write_text(json.dumps(plan()))
+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence', driver=Path('/driver'),
+ primary_grab=Path('/grab'), trace_socket=Path('/cua-input-v3.sock'), foreground_journal=Path('/journal'))
+ desktop = Mock()
+ desktop.status.return_value = status()
+ desktop.raw_status.return_value = status()
+ desktop.primary.side_effect = lambda target: {**target, 'cursor': {'x': 30, 'y': 40}, 'workspace': 1}
+ stack.enter_context(patch.object(proof, 'ExactDesktop', return_value=desktop))
+ stack.enter_context(patch.object(proof, 'app_process_identity'))
+ stack.enter_context(patch.object(proof, 'provenance', return_value={'files': {}}))
+ observer, refused, fresh = client(101), client(102), client(102 if failure == 'reused' else 103)
+ observer.tool.return_value = {'structuredContent': {'screen_width': 1600, 'screen_height': 900}}
+ for actor in (refused, fresh):
+ actor.tool.return_value = {}
+ launched = []
+ def launch(*_args):
+ value = (observer, refused, fresh)[len(launched)]
+ launched.append(value)
+ return value
+ stack.enter_context(patch.object(proof, 'DirectMCP', side_effect=launch))
+ stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value={'window_bounds': BOUNDS}))
+ grab = Mock(poll=Mock(return_value=None))
+ grabbed = [False]
+ def start_grab(*_args, **_kwargs):
+ self.assertIsNotNone(refused.process.poll())
+ self.assertEqual(len(launched), 2, 'new actor launched before intentional setup')
+ self.assertFalse(tracing[0], 'setup inside action trace')
+ grabbed[0] = True
+ return grab
+ stack.enter_context(patch.object(proof.subprocess, 'Popen', side_effect=start_grab))
+ grab.terminate.side_effect = lambda: setattr(grab.poll, 'return_value', 0)
+ stack.enter_context(patch.object(proof, 'stop_process', side_effect=RuntimeError('release failed') if failure == 'release' else None))
+ stack.enter_context(patch.object(proof, 'primary_acknowledgement', return_value='HELD\n'))
+ stack.enter_context(patch.object(proof, 'wait_for', side_effect=lambda check, **kwargs: check()))
+ stack.enter_context(patch.object(proof, 'state', side_effect=lambda _: {
+ 'held': grabbed[0] and grab.poll() is None, 'clicks': 0, 'keys': 0, 'scroll': 0}))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', return_value=0))
+ starts, tracing, action_done = [0], [False], [False]
+ def exchange(command):
+ if command == 'TRACE_START':
+ self.assertFalse(tracing[0])
+ starts[0] += 1
+ tracing[0], action_done[0] = True, False
+ if failure == 'start_lost':
+ raise TimeoutError('trace start acknowledgement lost')
+ elif command == 'TRACE_STOP':
+ tracing[0] = False
+ def collect():
+ events = RECOVERY if starts[0] == 2 and action_done[0] else []
+ if not tracing[0] and failure == 'primary_event':
+ events = [*events, (10, 'keyboard_key', 0, 1)]
+ if not tracing[0] and failure == 'held':
+ events = [*events, (10, 'pointer_button', 1, 1)]
+ if not tracing[0] and failure == 'restarted_trace':
+ events = [*events, (10, 'start', 0, 0)]
+ return trace(events, active=tracing[0])
+ tracer = Mock(exchange=Mock(side_effect=exchange), collect=Mock(side_effect=collect))
+ desktop.trace.return_value = tracer
+ def do_action(actor, obs, spec, phase, trace_obj, guard, save, record):
+ guard()
+ action_done[0] = True
+ record.update(trace_after=collect(), outcome='response', replayed=False,
+ response=REFUSED if phase == 'refusal' else DELIVERED)
+ current = status()
+ if phase == 'refusal':
+ current['input']['lanes'][0]['reserved'] = True
+ if failure == 'reserved_refusal':
+ current['input']['lanes'][1]['reserved'] = True
+ desktop.raw_status.return_value = current
+ save(phase + '-action.json', record)
+ if failure == 'reserved_after_close':
+ def reserved_status(*, unreserved=False, allow_passive=False):
+ value = status()
+ value['input']['lanes'][0]['reserved'] = True
+ return proof.clear_status(value, unreserved=unreserved, allow_passive=allow_passive)
+ desktop.status.side_effect = reserved_status
+ if failure == phase:
+ raise AssertionError(phase + ' failed')
+ stack.enter_context(patch.object(proof, 'action', side_effect=do_action))
+ def close(value):
+ value.process.poll.return_value = 0
+ if failure == 'close' and value is fresh:
+ raise RuntimeError('close failed')
+ stack.enter_context(patch.object(proof, 'close_owned', side_effect=close))
+ stack.enter_context(patch('builtins.print'))
+ self.assertEqual(proof.run(args), 0 if failure is None else 1)
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['active_drag_cancellation'], 'unproven')
+ self.assertEqual(report['continuous_isolation_across_setup'], 'unproven')
+ self.assertTrue((args.evidence / 'refusal-trace.json').exists())
+ self.assertTrue((args.evidence / 'provenance.json').exists())
+ self.assertTrue(all(value.process.poll() is not None for value in launched))
+ tracer.close.assert_called_once()
+ if failure in ('release', 'close', 'primary_event', 'held'):
+ self.assertTrue(report.get('error') or json.loads((args.evidence / 'cleanup.json').read_text())['errors'])
+ if failure is None:
+ self.assertEqual(starts[0], 2)
+ self.assertTrue((args.evidence / 'setup-transition.json').exists())
+ self.assertTrue((args.evidence / 'recovery-trace.json').exists())
+ self.assertEqual(set(report['phases']), {'refusal', 'recovery'})
+ files = json.loads((args.evidence / 'provenance.json').read_text())['files']
+ for name in ('desktop_faults.py', 'production_cancel_proof.py',
+ 'production_desktop_fault_proof.py', 'production_geometry_fault_proof.py'):
+ self.assertEqual(len(files[name]['sha256']), 64)
+ if failure == 'reserved_refusal':
+ self.assertEqual(len(launched), 2, 'recovery followed a non-idle refusal')
+ self.assertTrue(report['phases']['refusal']['post_action_status']['input']['lanes'][1]['reserved'])
+ self.assertEqual(report['error']['message'], 'unexpected refusal reservation')
+ if failure == 'reserved_after_close':
+ self.assertEqual(len(launched), 2, 'recovery followed an unreleased reservation')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py
new file mode 100644
index 0000000000..953bd48267
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py
@@ -0,0 +1,907 @@
+"""Reviewed native Calc/Inkscape plans through normal direct Driver MCP.
+
+Run only in a prepared disposable Hyprland desktop. This runner never signs a
+grant, sends TARGET/input packets, or installs policy. A trace socket is optional
+for package smoke and mandatory for continuous isolation/no-dispatch proof.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import select
+import subprocess
+import threading
+import time
+import xml.etree.ElementTree as ET
+import zipfile
+
+from driver_input_live import state, wait_for, wm
+from primary_trace import Trace, analyze
+from production_app_smoke import EXECUTABLES, ground, package_owner, provenance as runtime_provenance
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as pointer_grounding
+from realapp_proof import cleanup_all, rect_position, released_synthetic_input
+
+
+TOOLS = {'click', 'press_key', 'hotkey', 'scroll', 'drag'}
+RESERVED = {'pid', 'window_id', 'session', 'delivery_mode'}
+POINTER_EPISODES = ('clicks', 'scroll-away', 'scroll-back', 'drags', 'save')
+PRIMARY_LIFETIME_MS = 60000
+SMOKE_STEPS = {
+ 'calc': {'insert': ('press_key', {'key': 'a'}),
+ 'commit': ('press_key', {'key': 'Return'}),
+ 'save': ('hotkey', {'keys': ['ctrl', 's']})},
+ 'inkscape': {'select': ('hotkey', {'keys': ['ctrl', 'a']}),
+ 'move': ('press_key', {'key': 'Right'}),
+ 'save': ('hotkey', {'keys': ['ctrl', 's']})},
+}
+
+
+def manifest_tool_messages(tool):
+ # authorization.rs -> AuthorizationError::Denied -> permission_denied_result.
+ return {f"Permission denied: capability manifest denies tool '{tool}'",
+ f"Permission denied: tool '{tool}' is outside the capability manifest"}
+
+
+def validate_plan(plan):
+ assert plan['purpose'] in ('apps', 'policy', 'policy_cache', 'negative_control', 'capacity')
+ assert type(plan.get('moving_primary', False)) is bool
+ assert not (plan.get('moving_primary') and plan['purpose'] == 'negative_control'), \
+ 'negative control requires a parked primary'
+ capacity = plan['purpose'] == 'capacity'
+ policy_cache = plan['purpose'] == 'policy_cache'
+ episode = plan.get('pointer_episode')
+ if 'pointer_episode' in plan:
+ assert plan['purpose'] == 'apps' and isinstance(episode, dict), 'invalid pointer episode'
+ assert set(episode) == {'name', 'index', 'count'}, 'invalid pointer episode metadata'
+ assert type(episode['count']) is int and episode['count'] == len(POINTER_EPISODES)
+ assert type(episode['index']) is int and 0 <= episode['index'] < len(POINTER_EPISODES)
+ assert episode['name'] == POINTER_EPISODES[episode['index']], 'pointer episode order mismatch'
+ assert type(plan.get('require_overlap', False)) is bool
+ assert plan.get('require_overlap', False) == (episode['name'] == 'drags'), \
+ 'only the drag episode requires overlap'
+ assert not plan.get('moving_primary') or episode['name'] == 'drags', \
+ 'only the drag episode may move the primary'
+ assert (len(plan['agents']) == 3 if capacity else 1 <= len(plan['agents']) <= 2)
+ if policy_cache:
+ assert len(plan['agents']) == 1, 'policy_cache needs one persistent runtime'
+ assert not plan.get('moving_primary') and not plan.get('require_overlap'), \
+ 'policy_cache requires serial actions and a parked primary'
+ spec = plan['agents'][0]
+ assert spec['app'] in ('calc', 'inkscape')
+ assert isinstance(spec['name'], str) and spec['name'], 'policy_cache needs a fixed session'
+ profile = spec['profile']
+ assert profile['mode'] in ('standard', 'bounded', 'unrestricted')
+ assert profile.get('manifest') and profile.get('approve_manifest') is True
+ assert profile['mode'] != 'unrestricted' or profile.get('acknowledge_unrestricted') is True
+ assert len(plan['phases']) == 3, 'policy_cache needs allow, deny, fresh allow'
+ for index, step in enumerate(plan['phases']):
+ assert 'parallel' not in step and step.get('agent') == 0, 'policy_cache must reuse agent 0 serially'
+ expected = step.get('expect', {'kind': 'dispatched'})
+ if index == 1:
+ assert expected.get('kind') == 'refused' and expected.get('reason') == 'permission_denied'
+ assert expected.get('message') in manifest_tool_messages(step['tool']), \
+ 'policy_cache needs an exact manifest tool-ceiling refusal'
+ else:
+ assert expected == {'kind': 'dispatched'}, 'policy_cache permitted calls must dispatch'
+ tools = [step['tool'] for step in plan['phases']]
+ assert tools[0] == tools[2] and tools[0] != tools[1], 'policy_cache needs a distinct denied tool'
+ if capacity:
+ assert not plan.get('moving_primary'), 'capacity requires a parked primary'
+ assert not plan.get('require_overlap'), 'capacity establishes persistent lanes serially'
+ assert {spec['app'] for spec in plan['agents'][:2]} == {'calc', 'inkscape'}
+ assert all(spec['app'] in ('calc', 'inkscape') for spec in plan['agents'])
+ assert len(plan['phases']) == 3, 'capacity needs two admissions and one refusal'
+ for index, step in enumerate(plan['phases']):
+ assert 'parallel' not in step and step.get('agent') == index, 'capacity must run agents 0, 1, 2 serially'
+ expected = {'kind': 'dispatched'} if index < 2 else {'kind': 'refused', 'reason': 'lane_busy'}
+ assert step.get('expect', {'kind': 'dispatched'}) == expected, 'incorrect capacity expectation'
+ if plan['purpose'] == 'apps':
+ assert len(plan['agents']) == 2
+ assert {spec['app'] for spec in plan['agents']} == {'calc', 'inkscape'}
+ if episode and episode['name'] != 'save':
+ assert plan.get('outputs', []) == [], 'intermediate pointer episodes do not save outputs'
+ else:
+ assert len(plan['outputs']) == 2 and {oracle['agent'] for oracle in plan['outputs']} == {0, 1}
+ targets = [spec['target'] for spec in plan['agents']]
+ assert len({target['pid'] for target in targets}) == len(targets), 'apps must be distinct processes'
+ assert plan['foreground']['pid'] not in {target['pid'] for target in targets}
+ for target in targets:
+ assert set(target) == {'pid', 'window_id'}
+ assert type(target['pid']) is int and target['pid'] > 0
+ if capacity or policy_cache:
+ assert type(target['window_id']) is int and target['window_id'] > 0
+ assert plan['phases'], 'empty plan cannot pass'
+ for phase in plan['phases']:
+ if phase.get('negative_control'):
+ assert plan['purpose'] == 'negative_control'
+ continue
+ assert plan['purpose'] != 'negative_control'
+ steps = phase.get('parallel', [phase])
+ indexes = [step['agent'] for step in steps]
+ assert len(indexes) == len(set(indexes)), 'concurrent calls need separate runtimes'
+ assert all(type(i) is int and 0 <= i < len(targets) for i in indexes)
+ for step in steps:
+ assert step['tool'] in TOOLS
+ assert not RESERVED.intersection(step['arguments']), 'action overrides reviewed ownership'
+ if 'smoke_stage' in step:
+ app = plan['agents'][step['agent']].get('app')
+ stage = step['smoke_stage']
+ assert app in SMOKE_STEPS and isinstance(stage, str) and stage in SMOKE_STEPS[app], \
+ 'invalid app smoke stage'
+ assert (step['tool'], step['arguments']) == SMOKE_STEPS[app][stage], \
+ 'smoke stage must match its exact keyboard action'
+ if 'pointer_stage' in step:
+ app = plan['agents'][step['agent']].get('app')
+ stage = step['pointer_stage']
+ assert 'smoke_stage' not in step and plan['purpose'] == 'apps'
+ assert app in pointer_grounding.STAGES and stage in pointer_grounding.STAGES[app]
+ assert step['tool'] == pointer_grounding.STAGES[app][stage] and step['arguments'] == {}, \
+ 'pointer stages derive their exact arguments from the fresh image'
+ assert step.get('expect', {'kind': 'dispatched'}) == {'kind': 'dispatched'}
+ expected = step.get('expect', {'kind': 'dispatched'})
+ assert expected['kind'] in ('dispatched', 'refused', 'partial', 'unknown')
+ if expected['kind'] == 'refused':
+ assert expected['reason']
+ assert len(steps) == 1, 'no-dispatch proof needs a quiet measurement interval'
+ if plan['purpose'] == 'policy':
+ assert expected['kind'] == 'refused', 'policy plans measure denial, not app effects'
+ for oracle in plan.get('outputs', []):
+ assert 0 <= oracle['agent'] < len(targets)
+ assert oracle.get('attributes') or oracle.get('rect_translation') or 'text' in oracle
+ if 'rect_translation' in oracle:
+ assert len(oracle['rect_translation']) == 2
+ assert all(len(bounds) == 2 and bounds[0] <= bounds[1] for bounds in oracle['rect_translation'])
+
+
+def check_response(result, expected):
+ """Classify delivery independently from app effect; never retry any case."""
+ content = result.get('structuredContent', {})
+ kind = expected['kind']
+ delivery = content.get('delivery')
+ if kind == 'refused':
+ policy_refusal = content.get('status') == 'refused' and isinstance(content.get('refusal'), dict)
+ reason = content['refusal'].get('code') if policy_refusal else content.get('reason')
+ assert result.get('isError') is True and reason == expected['reason'], result
+ assert content.get('effect') == 'refused' or (policy_refusal and 'effect' not in content), result
+ assert delivery is None, 'refusal must not imply acknowledged delivery'
+ elif kind == 'partial':
+ assert content.get('effect') == 'partial', result
+ assert isinstance(delivery, dict) and type(delivery.get('delivered_count')) is int, result
+ assert delivery['delivered_count'] >= 0
+ elif kind == 'unknown':
+ assert isinstance(delivery, dict) and delivery.get('mode') == 'unknown', result
+ assert content.get('effect') in ('partial', 'unverifiable'), result
+ else:
+ assert not result.get('isError') and content.get('effect') in ('confirmed', 'unverifiable'), result
+ assert delivery is None or delivery.get('mode') == 'background', result
+ if kind != 'refused':
+ assert content.get('route') == 'synthetic_events', 'not plugin input evidence'
+ return {'expected': kind, 'observed': content, 'app_effect_verified': False}
+
+
+def trace_interval(before, after):
+ """Validate complete active prefixes before interpreting their difference."""
+ for page in (before, after):
+ assert isinstance(page, dict), 'missing dispatch telemetry'
+ assert page.get('hook') is True and page.get('active') is True
+ assert page.get('overflow') is False and page.get('timed_out') is False
+ rows = page.get('events')
+ assert isinstance(rows, list) and rows, 'empty dispatch telemetry'
+ assert type(page.get('count')) is int and page['count'] == len(rows), 'incomplete dispatch telemetry'
+ assert isinstance(rows[-1], list) and len(rows[-1]) in (7, 9), 'malformed dispatch telemetry'
+ # Reuse the canonical row/order validator with a local end sentinel;
+ # the real stopped trace is still required during cleanup.
+ last = rows[-1]
+ assert type(last[0]) is int, 'malformed trace sequence'
+ stopped = {**page, 'active': False, 'count': len(rows) + 1,
+ 'events': rows + [[last[0] + 1, last[1], 'stop', *last[3:5], 0, 0]]}
+ assert analyze(stopped).get('telemetry_complete') is True, 'incomplete dispatch telemetry'
+ assert not any(row[2] == 'stop' for row in rows), 'trace already stopped'
+ assert after['events'][:before['count']] == before['events'], 'trace history changed'
+ return after['events'][before['count']:]
+
+
+def assert_no_dispatch(before, after):
+ """Zero completions alone is insufficient: reject every synthetic event."""
+ events = trace_interval(before, after)
+ assert not any(row[5] in (1, 2) or row[2] == 'agent_admitted' for row in events), \
+ 'denied call reached a synthetic lane'
+
+
+def passive_focus_evidence(before, after, complete_trace):
+ """Pair compositor state with wire presence; passive focus grants no input."""
+ page = before['trace']
+ trace_interval(page, page)
+ assert analyze(complete_trace).get('telemetry_complete') is True
+ assert complete_trace['events'][:page['count']] == page['events'], 'focus trace history changed'
+ presence = {'pointer_enter', 'pointer_motion'}
+ lanes = {row[5] for row in page['events'] if row[2] in presence and row[5] in (1, 2)}
+ assert lanes, 'no passive pointer was observed'
+ states = []
+ for checkpoint in (before, after):
+ status = checkpoint['status']
+ assert status['state'] == 'input_v3_candidate' and status['input']['protocol'] == 3
+ assert status['input']['test_only'] is False and status['input']['transport_ready'] is True
+ values = status['input']['lanes']
+ assert len(values) == 2 and {value['lane'] for value in values} == {0, 1}
+ values = {value['lane'] + 1: value for value in values}
+ for lane in lanes:
+ value = values[lane]
+ assert value['lease_active'] is False and value['drag_active'] is False
+ assert value['held_button'] == 0 and value['held_keys'] == 0 and value['keyboard_focus'] is False
+ states.append(values)
+ for lane in lanes:
+ assert states[0][lane]['pointer_focus'] is True and states[0][lane]['reserved'] is True
+ assert states[1][lane]['pointer_focus'] is True and states[1][lane]['reserved'] is False
+ assert states[0][lane]['epoch'] == states[1][lane]['epoch']
+ assert states[0][lane]['desktop_generation'] == states[1][lane]['desktop_generation']
+ own = [row for row in page['events'] if row[5] == lane]
+ leaves = [row for row in own if row[2] == 'pointer_leave']
+ if leaves:
+ # A previous episode may leave an inert pointer on this lane.
+ # Its one retirement must precede this episode's first admission
+ # and pointer use. Never ignore leave/re-enter during an action.
+ admitted = [row for row in own if row[2] == 'agent_admitted']
+ used = [row for row in own if row[2] in presence]
+ assert len(leaves) == 1 and own[0] == leaves[0] and admitted and \
+ leaves[0][0] < admitted[0][0] < used[0][0], 'same-target action churned pointer focus'
+ tail = [row for row in complete_trace['events'][page['count']:] if row[5] == lane]
+ assert not tail, 'runtime close changed inert pointer presence or sent new input'
+ return {'verified': True, 'scope': 'passive-focus-without-authority-and-runtime-close', 'lanes': sorted(lanes)}
+
+
+def read_input_status():
+ return json.loads(subprocess.run(['hyprctl', '-j', 'cua:status'], check=True,
+ capture_output=True, text=True, timeout=5).stdout)
+
+
+def capacity_lane(before, after, tool):
+ """Identify one admitted, exercised, completed compositor lane, not a PID."""
+ events = trace_interval(before, after)
+ synthetic = [row for row in events if row[5] in (1, 2)]
+ lanes = {row[5] for row in synthetic}
+ assert len(lanes) == 1, 'capacity action must exercise exactly one compositor lane'
+ input_kind = {'click': 'pointer_button', 'drag': 'pointer_button',
+ 'scroll': 'pointer_axis', 'press_key': 'keyboard_key', 'hotkey': 'keyboard_key'}[tool]
+ completion = 'agent_drag_end' if tool == 'drag' else 'agent_action_end'
+ admissions = [row[0] for row in synthetic if row[2] == 'agent_admitted']
+ inputs = [row[0] for row in synthetic if row[2] == input_kind]
+ completions = [row[0] for row in synthetic if row[2] == completion]
+ assert admissions and inputs and completions, 'capacity needs admission, input, and completion evidence'
+ assert min(admissions) < min(inputs) <= max(inputs) < max(completions), 'unordered capacity dispatch'
+ return lanes.pop()
+
+
+def verify_capacity(actions):
+ assert len(actions) == 3 and [row['agent'] for row in actions] == [0, 1, 2], 'incomplete capacity actions'
+ assert all(row['expected'] == 'dispatched' for row in actions[:2])
+ for row in actions[:2]:
+ check_response({'structuredContent': row['observed']}, {'kind': 'dispatched'})
+ assert {row.get('compositor_lane') for row in actions[:2]} == {1, 2}, 'capacity needs distinct compositor lanes'
+ refusal = actions[2]
+ assert refusal['expected'] == 'refused' and refusal.get('no_dispatch') == 'verified'
+ check_response({'isError': True, 'structuredContent': refusal['observed']},
+ {'kind': 'refused', 'reason': 'lane_busy'})
+ return {'result': 'verified', 'lanes': [row['compositor_lane'] for row in actions[:2]],
+ 'refused_agent': 2, 'reason': 'lane_busy'}
+
+
+def check_manifest_refusal(response, expected, tool):
+ content = response.get('structuredContent', {})
+ assert expected['kind'] == 'refused' and response.get('isError') is True
+ assert expected['reason'] == 'permission_denied'
+ assert expected['message'] in manifest_tool_messages(tool)
+ assert 'delivery' not in content, 'refusal must not imply acknowledged delivery'
+ if content == {'code': 'permission_denied'}:
+ # server.rs checks tool admission before provider dispatch. Its error
+ # uses a flat code and the exact message in MCP text content, unlike
+ # tool.rs's later common admission refusal envelope. Preserve both.
+ assert response.get('content') == [{'type': 'text', 'text': expected['message']}], \
+ 'wrong MCP manifest tool-ceiling refusal'
+ boundary = 'mcp-tool-admission'
+ else:
+ check_response(response, expected)
+ assert content.get('status') == 'refused' and isinstance(content.get('refusal'), dict), \
+ 'policy_cache needs a common authorization refusal, not a plugin error'
+ assert content['refusal'].get('message') == expected['message'], 'wrong manifest tool-ceiling refusal'
+ boundary = 'core-admission'
+ return {'expected': 'refused', 'observed': content, 'mcp_content': response.get('content', []),
+ 'refusal_boundary': boundary, 'app_effect_verified': False}
+
+
+def verify_policy_cache(actions):
+ assert len(actions) == 3 and [row['agent'] for row in actions] == [0, 0, 0]
+ assert [row['expected'] for row in actions] == ['dispatched', 'refused', 'dispatched']
+ assert actions[0]['tool'] == actions[2]['tool'] != actions[1]['tool']
+ assert len({row['runtime_pid'] for row in actions}) == 1, 'policy_cache runtime changed'
+ assert len({row['session'] for row in actions}) == 1, 'policy_cache session changed'
+ lanes = [actions[index].get('compositor_lane') for index in (0, 2)]
+ assert lanes[0] in (1, 2) and lanes[0] == lanes[1], 'policy_cache compositor lane changed'
+ for index in (0, 2):
+ check_response({'structuredContent': actions[index]['observed']}, {'kind': 'dispatched'})
+ denied = actions[1]
+ assert denied.get('no_dispatch') == 'verified'
+ check_manifest_refusal({'isError': True, 'structuredContent': denied['observed'],
+ 'content': denied.get('mcp_content', [])},
+ denied['expect'], denied['tool'])
+ return {'result': 'verified', 'runtime_pid': actions[0]['runtime_pid'],
+ 'session': actions[0]['session'], 'compositor_lane': lanes[0],
+ 'reason': denied['expect']['reason'], 'message': denied['expect']['message'],
+ 'scope': 'cached-connection-manifest-tool-ceiling'}
+
+
+def primary_trajectory(bounds, point, desktop):
+ """The independent primary-grab helper follows the historical 160px square."""
+ offsets = ([(x, 0) for x in range(20, 161, 20)] + [(160, y) for y in range(20, 161, 20)]
+ + [(x, 160) for x in range(140, -1, -20)] + [(0, y) for y in range(140, -1, -20)])
+ positions = [[int(bounds['x'] + point[0] + dx), int(bounds['y'] + point[1] + dy)]
+ for dx, dy in offsets]
+ for x, y in positions:
+ assert bounds['x'] < x < bounds['x'] + bounds['width'], 'primary trajectory leaves foreground'
+ assert bounds['y'] < y < bounds['y'] + bounds['height'], 'primary trajectory leaves foreground'
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height'], \
+ 'primary trajectory leaves desktop'
+ return positions
+
+
+def primary_acknowledgement(stream):
+ """Bound partial lines too: select followed by readline can block forever."""
+ deadline, data = time.monotonic() + 2, b''
+ while not data.endswith(b'\n'):
+ remaining = deadline - time.monotonic()
+ assert remaining > 0 and select.select([stream], [], [], remaining)[0], \
+ f'primary command acknowledgement missing or incomplete: {data!r}'
+ chunk = os.read(stream.fileno(), 128)
+ assert chunk, f'primary command acknowledgement ended early: {data!r}'
+ data += chunk
+ assert len(data) <= 128, 'oversized primary command acknowledgement'
+ return data.decode('ascii')
+
+
+def move_primary(grab, trajectory, done, ready, commands, mark):
+ """Send independent primary-seat commands, retaining every issued command."""
+ while not done.wait(0.1):
+ x, y = trajectory[len(commands) % len(trajectory)]
+ row = {'sequence': len(commands) + 1, 'x': x, 'y': y,
+ 'command_ns': time.monotonic_ns(), 'acknowledgement': None, 'ack_ns': None}
+ commands.append(row)
+ mark('primary_motion_command', **row)
+ grab.stdin.write(f'MOVE {x} {y}\n')
+ grab.stdin.flush()
+ row['acknowledgement'] = primary_acknowledgement(grab.stdout)
+ row['ack_ns'] = time.monotonic_ns()
+ mark('primary_motion_acknowledgement', **row)
+ assert row['acknowledgement'] == f'MOVED {x} {y}\n', 'malformed primary command acknowledgement'
+ ready.set()
+
+
+def expected_primary_motion(commands, trajectory):
+ """Only a complete, ordered command/acknowledgement log can define motion."""
+ assert isinstance(commands, list) and commands, 'missing primary command log'
+ expected, previous_ack = [], 0
+ for index, row in enumerate(commands):
+ assert isinstance(row, dict), 'malformed primary command log'
+ assert type(row.get('sequence')) is int and row['sequence'] == index + 1, \
+ 'incomplete or reordered primary command log'
+ assert all(type(row.get(key)) is int for key in ('x', 'y', 'command_ns', 'ack_ns')), \
+ 'incomplete primary command acknowledgement'
+ point = [row['x'], row['y']]
+ assert point == trajectory[index % len(trajectory)], 'primary command differs from trajectory'
+ assert previous_ack < row['command_ns'] <= row['ack_ns'], 'unordered primary command timestamps'
+ assert row.get('acknowledgement') == f'MOVED {point[0]} {point[1]}\n', \
+ 'malformed primary command acknowledgement'
+ previous_ack = row['ack_ns']
+ expected.append(point)
+ return expected
+
+
+def assert_primary_state(before, after, moving):
+ keys = ('pid', 'address', 'workspace') if moving else before.keys()
+ assert all(after[key] == before[key] for key in keys), 'primary cursor/focus/workspace changed'
+
+
+def document_root(content, oracle):
+ if oracle.get('zip_member'):
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
+ content = archive.read(oracle['zip_member'])
+ return ET.fromstring(content)
+
+
+def verify_output(before, after, oracle):
+ assert before != after, 'application did not save a changed file'
+ node = document_root(after, oracle).find(oracle['xpath'], oracle.get('namespaces', {}))
+ assert node is not None, 'saved document lacks expected node'
+ for key, expected in oracle.get('attributes', {}).items():
+ assert node.get(key) == expected, (key, node.attrib)
+ if 'text' in oracle:
+ assert ''.join(node.itertext()) == oracle['text']
+ if 'rect_translation' in oracle:
+ original = document_root(before, oracle).find(oracle['xpath'], oracle.get('namespaces', {}))
+ assert original is not None
+ delta = [b - a for a, b in zip(rect_position(original), rect_position(node))]
+ assert all(low <= value <= high for value, (low, high) in zip(delta, oracle['rect_translation'])), delta
+ assert all(node.get(key) == original.get(key) for key in ('width', 'height'))
+ return {'agent': oracle['agent'], 'file': Path(oracle['path']).name, 'verified': True}
+
+
+def app_process_identity(app, pid, proc_root=Path('/proc')):
+ process = proc_root / str(pid)
+ executable = (process / 'exe').resolve(strict=True)
+ gtk_maps = []
+ if app in EXECUTABLES:
+ assert executable == EXECUTABLES[app], 'noncanonical running executable'
+ package_owner(executable, 'libreoffice-fresh' if app == 'calc' else 'inkscape')
+ maps = (process / 'maps').read_text()
+ assert '/libgtk-3.so' in maps, 'running app did not load GTK3'
+ if app == 'calc':
+ assert '/libvclplug_gtk3lo.so' in maps, 'Calc did not load its GTK3 backend'
+ gtk_maps = [line for line in maps.splitlines()
+ if '/libgtk-3.so' in line or '/libvclplug_gtk3lo.so' in line]
+ return {'pid': pid, 'executable': str(executable),
+ 'sha256': hashlib.sha256(executable.read_bytes()).hexdigest(),
+ 'gtk3_maps': gtk_maps}
+
+
+def parallel_actions(steps, action):
+ """Retain every outcome and wake siblings if one fails before the barrier.
+
+ A grounding failure on the second agent must not become the first agent's
+ empty BrokenBarrierError. No action is replayed, and successful siblings
+ remain evidence even when the phase fails.
+ """
+ barrier = threading.Barrier(len(steps))
+ def guarded(step):
+ try:
+ return action(step, barrier)
+ except BaseException:
+ barrier.abort()
+ raise
+ results, errors = [], []
+ with ThreadPoolExecutor(max_workers=len(steps)) as pool:
+ futures = [pool.submit(guarded, step) for step in steps]
+ for step, future in zip(steps, futures):
+ try:
+ results.append(future.result())
+ except Exception as error:
+ errors.append({'agent': step['agent'], 'tool': step['tool'],
+ 'error_type': type(error).__name__, 'message': str(error)})
+ return results, errors
+
+
+def provenance(args, plan):
+ # Reuse exact-source, canonical ALPM and active mapped-plugin checks.
+ # Hashing a file alone does not prove which module the compositor loaded.
+ origin = runtime_provenance(args)
+ assert plan['package_versions'] == origin['packages'], 'package qualification mismatch'
+ files = {'primary-grab': args.primary_grab}
+ for name in ('production_realapp_proof.py', 'production_mcp.py', 'driver_input_live.py',
+ 'realapp_proof.py', 'primary_trace.py', 'production_pointer_grounding.py'):
+ files[name] = Path(__file__).with_name(name)
+ windows = json.loads(subprocess.check_output(
+ ['hyprctl', '-j', 'clients'], text=True, timeout=10))
+ identities = {}
+ for index, spec in enumerate(plan['agents']):
+ pid = spec['target']['pid']
+ matches = [window for window in windows if window.get('pid') == pid]
+ assert len(matches) == 1 and matches[0].get('xwayland') is False, 'need one exact native window per app'
+ identities[str(index)] = {**app_process_identity(spec.get('app'), pid),
+ 'hyprland_window': matches[0]}
+ origin['files'].update({name: {'path': str(path.resolve()),
+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ for name, path in files.items()})
+ origin['app_processes'] = identities
+ return origin
+
+
+def require_primary_active(grab, deadline_ns, now_ns=None):
+ """Do not dispatch or accept a proof after its bounded primary grab ends."""
+ assert grab is not None and grab.poll() is None, 'primary grab helper exited'
+ now_ns = time.monotonic_ns() if now_ns is None else now_ns
+ assert deadline_ns is not None and now_ns < deadline_ns, 'primary grab deadline expired'
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ capacity = plan['purpose'] == 'capacity'
+ policy_cache = plan['purpose'] == 'policy_cache'
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ save('plan.json', plan)
+ clients, recorder, grab, trace = [], None, None, None
+ primary_deadline_ns = None
+ moving = plan.get('moving_primary', False)
+ mover = None
+ motion_done, motion_ready = threading.Event(), threading.Event()
+ commands, motion_errors, action_intervals = [], [], []
+ capacity_traces = []
+ policy_cache_traces = []
+ trajectory = None
+ recording = False
+ focus_before = None
+ baseline_outputs = {}
+ report = {'result': 'failed', 'scope': 'native-production-input-proof',
+ 'full_desktop_matrix': False, 'actions': [], 'outputs': [],
+ 'continuous_isolation': 'unproven', 'synthetic_cleanup': 'unproven',
+ 'primary_mode': 'moving' if moving else 'parked'}
+ if capacity:
+ report['capacity'] = {'result': 'unproven'}
+ if policy_cache:
+ report['policy_cache'] = {'result': 'unproven'}
+ timeline_lock = threading.Lock()
+ observer_lock = threading.Lock()
+ def mark(event, **fields):
+ with timeline_lock, (args.evidence / 'timeline.jsonl').open('a') as stream:
+ stream.write(json.dumps({'monotonic_ns': time.monotonic_ns(), 'event': event, **fields}) + '\n')
+ def client(name, profile):
+ directory = args.evidence / name
+ directory.mkdir()
+ return DirectMCP(args.driver, directory, profile)
+ def snapshot(mcp, target, session=None, full=False, pixels=False):
+ if capacity or policy_cache or full:
+ windows = mcp.tool('list_windows', {})
+ assert not windows.get('isError'), windows
+ matches = [window for window in windows['structuredContent']['windows']
+ if window.get('pid') == target['pid']]
+ assert len(matches) == 1 and matches[0].get('window_id') == target['window_id'], \
+ 'reviewed PID/window identity is stale or ambiguous'
+ result = mcp.tool('get_window_state', {**target,
+ **({} if full else {'max_elements': 100, 'max_depth': 6}),
+ **({'session': session} if session else {})})
+ assert not result.get('isError'), result
+ content = result['structuredContent']
+ assert content.get('screenshot_width', 0) > 0, 'missing grounding image'
+ if pixels:
+ images = [row for row in result.get('content', []) if row.get('type') == 'image']
+ assert len(images) == 1 and images[0].get('image_file'), 'missing exact snapshot image file'
+ path = mcp.directory / images[0]['image_file']
+ assert path.resolve(strict=True).parent == mcp.directory.resolve(strict=True)
+ # Evidence-only path; never sent back to Driver or inserted into its
+ # persisted snapshot. Pixels come from this exact MCP response.
+ content = {**content, 'proof_image': str(path)}
+ return content
+ def action(step, barrier=None):
+ index = step['agent']
+ spec, mcp = plan['agents'][index], clients[index]
+ if policy_cache:
+ assert assert_distinct_runtimes(clients) == report['driver_processes'], 'policy_cache runtime changed'
+ current_trace = trace.collect()
+ trace_before = policy_cache_traces[-1] if policy_cache_traces else current_trace
+ assert_no_dispatch(trace_before, current_trace)
+ smoke_stage = step.get('smoke_stage')
+ pointer_stage = step.get('pointer_stage')
+ full = smoke_stage is not None or pointer_stage is not None
+ before = snapshot(mcp, spec['target'], spec['name'], full=full, pixels=pointer_stage is not None)
+ assert before['window_bounds'] == spec['bounds'], 'reviewed geometry is stale'
+ if smoke_stage is not None:
+ ground(before, spec['app'], smoke_stage)
+ arguments = step['arguments']
+ if pointer_stage is not None:
+ before_request = mcp.counter
+ arguments, pointer_oracle = pointer_grounding.action(
+ before, pointer_grounding.read_pixels(before['proof_image']), spec['app'], pointer_stage)
+ save(f'pointer-agent-{index}-{mcp.counter}.json',
+ {'snapshot_image': before['proof_image'], 'tool': step['tool'],
+ 'arguments': arguments, 'oracle': pointer_oracle})
+ if policy_cache:
+ # Keep the full interval quiet through fresh grounding, including
+ # delayed events after the preceding denied response.
+ assert_no_dispatch(trace_before, trace.collect())
+ expected = step.get('expect', {'kind': 'dispatched'})
+ if capacity:
+ assert_distinct_runtimes(clients)
+ if not policy_cache:
+ trace_before = trace.collect() if trace and (capacity or expected['kind'] == 'refused') else None
+ if capacity:
+ assert_no_dispatch(capacity_traces[-1] if capacity_traces else trace_before, trace_before)
+ if barrier:
+ barrier.wait(timeout=20)
+ require_primary_active(grab, primary_deadline_ns)
+ mark('action_start', agent=index, tool=step['tool'], runtime_pid=mcp.process.pid)
+ action_start = time.monotonic_ns()
+ try:
+ response = mcp.tool(step['tool'], {**arguments, **spec['target'],
+ 'session': spec['name'], 'delivery_mode': 'background'})
+ except Exception:
+ # A transport failure poisons that runtime. Preserve a fresh independent
+ # after-snapshot when available without retrying the mutation.
+ with observer_lock:
+ snapshot(recorder, spec['target'], full=full, pixels=pointer_stage is not None)
+ raise
+ action_intervals.append((action_start, time.monotonic_ns()))
+ mark('action_response', agent=index, response=response.get('structuredContent'), error=response.get('isError', False))
+ after = snapshot(mcp, spec['target'], spec['name'], full=full, pixels=pointer_stage is not None)
+ require_primary_active(grab, primary_deadline_ns)
+ result = (check_manifest_refusal(response, expected, step['tool'])
+ if policy_cache and expected['kind'] == 'refused' else check_response(response, expected))
+ if smoke_stage is not None:
+ ground(after, spec['app'], 'after')
+ result['smoke_stage'] = smoke_stage
+ if pointer_stage is not None:
+ try:
+ result['pointer_effect'] = pointer_grounding.verify(
+ after, pointer_grounding.read_pixels(after['proof_image']), pointer_oracle)
+ except (AssertionError, pointer_grounding.GroundingUnavailable) as error:
+ # Preserve later read-only state to distinguish application
+ # settling from a dropped release. This remains a failed cell:
+ # no extra input, changed oracle, or successful retry is allowed.
+ diagnostic = {'agent': index, 'tool': step['tool'], 'response': response,
+ 'oracle': pointer_oracle, 'initial': after,
+ 'error': str(error), 'samples': [], 'replayed': False}
+ for _ in range(2):
+ sample = {'monotonic_ns': time.monotonic_ns()}
+ diagnostic['samples'].append(sample)
+ try:
+ require_primary_active(grab, primary_deadline_ns)
+ later = snapshot(mcp, spec['target'], spec['name'], full=True, pixels=True)
+ require_primary_active(grab, primary_deadline_ns)
+ sample['snapshot'] = later
+ assert later['window_bounds'] == spec['bounds'], 'target geometry changed'
+ sample['effect'] = pointer_grounding.verify(
+ later, pointer_grounding.read_pixels(later['proof_image']), pointer_oracle)
+ except Exception as diagnostic_error:
+ sample.update(error_type=type(diagnostic_error).__name__, error=str(diagnostic_error))
+ if not isinstance(diagnostic_error, (AssertionError, pointer_grounding.GroundingUnavailable)):
+ break
+ save(f'pointer-effect-failure-agent-{index}.json', diagnostic)
+ raise
+ result.update(app_effect_verified=True, pointer_stage=pointer_stage, arguments=arguments,
+ pointer_evidence={'before_request': before_request, 'after_request': mcp.counter})
+ if policy_cache:
+ trace_after = trace.collect()
+ save(f'policy-cache-phase-{len(policy_cache_traces)}-trace.json',
+ {'before': trace_before, 'after': trace_after})
+ policy_cache_traces.append(trace_after)
+ if expected['kind'] == 'dispatched':
+ result['compositor_lane'] = capacity_lane(trace_before, trace_after, step['tool'])
+ else:
+ result = check_manifest_refusal(response, expected, step['tool'])
+ assert_no_dispatch(trace_before, trace_after)
+ result.update(no_dispatch='verified', expect=expected)
+ result.update(runtime_pid=mcp.process.pid, session=spec['name'])
+ assert assert_distinct_runtimes(clients) == report['driver_processes'], 'policy_cache runtime changed'
+ if capacity and expected['kind'] == 'dispatched':
+ trace_after = trace.collect()
+ save(f'capacity-agent-{index}-trace.json', {'before': trace_before, 'after': trace_after})
+ capacity_traces.append(trace_after)
+ result['compositor_lane'] = capacity_lane(trace_before, trace_after, step['tool'])
+ assert result['compositor_lane'] not in {row.get('compositor_lane') for row in report['actions']}, \
+ 'capacity needs distinct compositor lanes'
+ if expected['kind'] == 'refused' and not policy_cache:
+ result['no_dispatch'] = 'unproven'
+ if trace:
+ trace_after = trace.collect()
+ if capacity:
+ save(f'capacity-agent-{index}-trace.json', {'before': trace_before, 'after': trace_after})
+ capacity_traces.append(trace_after)
+ assert_no_dispatch(trace_before, trace_after)
+ result['no_dispatch'] = 'verified'
+ if capacity:
+ assert_distinct_runtimes(clients)
+ assert after['window_bounds'] == before['window_bounds']
+ assert_primary_state(primary_before, wm(), moving)
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), current
+ return {'agent': index, 'tool': step['tool'], **result}
+ try:
+ assert not moving or args.trace_socket, 'moving primary requires continuous trace'
+ assert not capacity or args.trace_socket, 'capacity requires continuous trace'
+ assert not policy_cache or args.trace_socket, 'policy_cache requires continuous trace'
+ save('provenance.json', provenance(args, plan))
+ for index, oracle in enumerate(plan.get('outputs', [])):
+ baseline_outputs[index] = Path(oracle['path']).read_bytes()
+ for index, spec in enumerate(plan['agents']):
+ mcp = client(f'agent-{index}', spec['profile'])
+ clients.append(mcp)
+ started = mcp.tool('start_session', {'session': spec['name']})
+ assert not started.get('isError'), started
+ assert snapshot(mcp, spec['target'], spec['name'])['window_bounds'] == spec['bounds']
+ report['driver_processes'] = assert_distinct_runtimes(clients)
+ recorder = client('observer', {'mode': 'unrestricted', 'acknowledge_unrestricted': True})
+ fg = snapshot(recorder, plan['foreground'])['window_bounds']
+ desktop = recorder.tool('get_desktop_state', {})['structuredContent']
+ point = plan.get('primary_point', [300, 300])
+ assert 0 < point[0] < fg['width'] and 0 < point[1] < fg['height']
+ if moving:
+ trajectory = primary_trajectory(fg, point, desktop)
+ grab_args = [str(args.primary_grab), str(fg['x'] + point[0]), str(fg['y'] + point[1]),
+ str(desktop['screen_width']), str(desktop['screen_height'])]
+ snapshot(recorder, plan['foreground'])
+ primary_deadline_ns = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen(grab_args + [str(PRIMARY_LIFETIME_MS)] + (['controlled'] if moving else []),
+ stdin=subprocess.PIPE if moving else None,
+ stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'])
+ snapshot(recorder, plan['foreground'])
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid']
+ if args.trace_socket:
+ assert args.trace_socket.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')
+ trace = Trace(args.trace_socket)
+ assert trace.hello['protocol'] == 3
+ trace.exchange('TRACE_START')
+ if args.record_video:
+ video = recorder.tool('start_recording', {'output_dir': str(args.evidence / 'video'), 'record_video': True})
+ assert not video.get('isError') and video['structuredContent']['video_active'], video
+ recording = True
+ if moving:
+ def movement():
+ try:
+ move_primary(grab, trajectory, motion_done, motion_ready, commands, mark)
+ except Exception as error:
+ motion_errors.append(str(error))
+ motion_ready.set()
+ mover = threading.Thread(target=movement, daemon=True)
+ mover.start()
+ assert motion_ready.wait(3), 'primary motion did not start'
+ assert not motion_errors, motion_errors
+ for phase in plan['phases']:
+ require_primary_active(grab, primary_deadline_ns)
+ if phase.get('negative_control'):
+ assert trace, 'warp-and-return detector requires continuous trace'
+ snapshot(recorder, plan['foreground'])
+ subprocess.run(grab_args + ['100', 'canary'], check=True, timeout=10)
+ snapshot(recorder, plan['foreground'])
+ assert wm() == primary_before, 'control failed to return to identical endpoints'
+ elif 'parallel' in phase:
+ results, errors = parallel_actions(phase['parallel'], action)
+ report['actions'].extend(results)
+ if errors:
+ report['phase_errors'] = errors
+ cause = next((row for row in errors if row['error_type'] != 'BrokenBarrierError'), errors[0])
+ raise RuntimeError(f'agent {cause["agent"]} {cause["tool"]}: '
+ f'{cause["error_type"]}: {cause["message"]}')
+ else:
+ report['actions'].append(action(phase))
+ if capacity:
+ report['capacity'] = verify_capacity(report['actions'])
+ if policy_cache:
+ report['policy_cache'] = verify_policy_cache(report['actions'])
+ for index, oracle in enumerate(plan.get('outputs', [])):
+ report['outputs'].append(verify_output(baseline_outputs[index], Path(oracle['path']).read_bytes(), oracle))
+ if trace and any(row.get('pointer_stage') for row in report['actions']):
+ focus_before = {'status': read_input_status(), 'trace': trace.collect()}
+ save('passive-focus-before.json', focus_before)
+ require_primary_active(grab, primary_deadline_ns)
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ # Preserve app files even after partial/unknown responses or failed assertions.
+ operations = []
+ if moving:
+ def stop_motion():
+ motion_done.set()
+ try:
+ if mover:
+ mover.join(timeout=3)
+ assert not mover.is_alive(), 'primary motion worker did not stop'
+ finally:
+ save('primary-motion-commands.json', commands)
+ assert not motion_errors, motion_errors
+ operations.append(('stop_primary_motion', stop_motion))
+ def preserve(index, oracle):
+ directory = args.evidence / 'saved-outputs'
+ directory.mkdir(exist_ok=True)
+ suffix = Path(oracle['path']).suffix
+ if index in baseline_outputs:
+ (directory / f'{index}-before{suffix}').write_bytes(baseline_outputs[index])
+ (directory / f'{index}-after{suffix}').write_bytes(Path(oracle['path']).read_bytes())
+ operations.extend((f'preserve_output_{i}', lambda i=i, o=o: preserve(i, o))
+ for i, o in enumerate(plan.get('outputs', [])))
+ if recording:
+ def stop_video():
+ result = recorder.tool('stop_recording', {})
+ assert not result.get('isError') and not result['structuredContent'].get('last_error'), result
+ operations.append(('stop_video', stop_video))
+ operations.extend((f'close_agent_{i}', mcp.close) for i, mcp in enumerate(clients))
+ if trace:
+ def finish_trace():
+ focus_after = None
+ focus_wait_error = None
+ if focus_before is not None:
+ samples = []
+ def released_focus():
+ status = read_input_status()
+ samples.append({'monotonic_ns': time.monotonic_ns(), 'status': status})
+ return all(not row['keyboard_focus'] and not row['reserved']
+ and not row['lease_active'] and not row['drag_active']
+ and row['held_button'] == 0 and row['held_keys'] == 0
+ for row in status['input']['lanes'])
+ try:
+ wait_for(released_focus)
+ except Exception as error:
+ focus_wait_error = error
+ finally:
+ focus_after = {'status': samples[-1]['status'] if samples else {}, 'samples': samples}
+ save('passive-focus-after.json', focus_after)
+ trace.exchange('TRACE_STOP')
+ data = trace.collect()
+ save('trace.json', data)
+ if focus_wait_error is not None:
+ raise focus_wait_error
+ require_primary_active(grab, primary_deadline_ns)
+ if capacity_traces:
+ last = capacity_traces[-1]
+ assert data['events'][:last['count']] == last['events'], 'capacity trace history changed at cleanup'
+ if policy_cache_traces:
+ last = policy_cache_traces[-1]
+ assert data['events'][:last['count']] == last['events'], 'policy_cache trace history changed at cleanup'
+ expected_motion = None
+ if moving:
+ assert not mover or not mover.is_alive(), 'primary motion worker did not stop'
+ logged = json.loads((args.evidence / 'primary-motion-commands.json').read_text())
+ expected_motion = expected_primary_motion(logged, trajectory)
+ save('expected-primary-motion.json', expected_motion)
+ overlaps = sum(any(start <= row['command_ns'] <= row['ack_ns'] <= end
+ for start, end in action_intervals) for row in logged)
+ report['primary_commands_during_actions'] = overlaps
+ assert overlaps > 0, 'no primary movement during a Driver action'
+ isolation = analyze(data, expected_motion=expected_motion)
+ save('isolation.json', isolation)
+ report['continuous_isolation'] = isolation['result']
+ if plan['purpose'] == 'negative_control':
+ assert isolation['result'] == 'failed' and isolation['uncommanded_motion_events'] > 0
+ assert data['events'][0][3:5] == data['events'][-1][3:5]
+ report['negative_control_detected'] = True
+ else:
+ assert isolation['result'] == 'passed', isolation
+ if plan.get('require_overlap'):
+ assert isolation['agent_drag_overlap_ms'] >= 100, 'no proven two-lane overlap'
+ assert released_synthetic_input(data)
+ report['synthetic_cleanup'] = 'verified'
+ if focus_before is not None:
+ report['passive_focus'] = passive_focus_evidence(focus_before, focus_after, data)
+ for action_result in report['actions']:
+ if action_result.get('pointer_stage') in ('select_range', 'move_rectangle'):
+ action_result['pointer_delivery'] = pointer_grounding.verify_drag_trace(
+ data, action_result['arguments'], action_result['pointer_effect'])
+ operations += [('finish_trace', finish_trace), ('close_trace', trace.close)]
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'])
+ operations.append(('release_primary', release_primary))
+ if mover:
+ def join_motion():
+ # Reaping the helper also unblocks a pending acknowledgement.
+ # Retain late failure evidence even when the first join failed.
+ try:
+ mover.join(timeout=3)
+ assert not mover.is_alive(), 'primary motion worker did not stop after release'
+ finally:
+ save('primary-motion-commands.json', commands)
+ operations.append(('join_primary_motion', join_motion))
+ if recorder:
+ operations.append(('close_observer', recorder.close))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ elif report['result'] == 'passed' and not trace:
+ report['scope'] = 'production-package-smoke'
+ if plan['purpose'] != 'apps' or plan.get('require_overlap'):
+ report['result'] = 'inconclusive'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ parser.add_argument('--trace-socket', type=Path)
+ parser.add_argument('--record-video', action='store_true')
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof_test.py
new file mode 100644
index 0000000000..38ff0b3f1c
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof_test.py
@@ -0,0 +1,1391 @@
+import copy
+from contextlib import ExitStack
+import io
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import threading
+import time
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+import zipfile
+
+from production_mcp import DirectMCP, assert_distinct_runtimes, profile_environment, stop_process
+from production_realapp_proof import (SMOKE_STEPS, app_process_identity, provenance,
+ assert_no_dispatch, assert_primary_state, check_response,
+ capacity_lane, verify_capacity, check_manifest_refusal,
+ manifest_tool_messages, verify_policy_cache,
+ passive_focus_evidence,
+ expected_primary_motion, move_primary, primary_acknowledgement,
+ parallel_actions, primary_trajectory, require_primary_active,
+ PRIMARY_LIFETIME_MS, POINTER_EPISODES, run, validate_plan, verify_output)
+from primary_trace import analyze
+from primary_trace_test import START, STOP, trace
+from production_app_smoke_test import INKSCAPE, INKSCAPE_SELECTED
+
+
+class PassiveFocusTests(unittest.TestCase):
+ def test_only_initial_pre_admission_retirement_is_allowed(self):
+ def evidence(kinds):
+ rows = [[1, 0, 'start', 100, 100, 0, 0]]
+ for index, kind in enumerate(kinds, 2):
+ row = [index, index - 1, kind, 100, 100, 1, 0]
+ if kind in ('pointer_enter', 'pointer_motion'):
+ row.extend((10, 20))
+ rows.append(row)
+ page = {'hook': True, 'active': True, 'overflow': False, 'timed_out': False,
+ 'count': len(rows), 'events': rows}
+ values = [{'lane': lane, 'epoch': f'lane-{lane}', 'desktop_generation': 1,
+ 'reserved': lane == 0, 'pointer_focus': lane == 0,
+ 'keyboard_focus': False, 'lease_active': False, 'drag_active': False,
+ 'held_button': 0, 'held_keys': 0} for lane in (0, 1)]
+ status = {'state': 'input_v3_candidate', 'input': {'protocol': 3, 'test_only': False,
+ 'transport_ready': True, 'lanes': values}}
+ before = {'status': status, 'trace': page}
+ after = {'status': copy.deepcopy(status)}
+ after['status']['input']['lanes'][0]['reserved'] = False
+ stopped = {**page, 'active': False, 'count': len(rows) + 1,
+ 'events': rows + [[len(rows) + 1, len(rows), 'stop', 100, 100, 0, 0]]}
+ return before, after, stopped
+
+ accepted = [
+ ['pointer_leave', 'agent_admitted', 'pointer_enter', 'pointer_motion', 'agent_action_end'],
+ ['agent_admitted', 'pointer_motion', 'agent_action_end'], # Reuse unchanged inert hover.
+ ]
+ rejected = [
+ ['agent_admitted', 'pointer_leave', 'pointer_enter', 'pointer_motion'],
+ ['pointer_leave', 'pointer_leave', 'agent_admitted', 'pointer_enter'],
+ ['pointer_enter', 'pointer_leave', 'agent_admitted', 'pointer_enter'],
+ ['pointer_leave', 'pointer_enter', 'agent_admitted', 'pointer_motion'],
+ ['pointer_leave', 'pointer_enter', 'pointer_motion'],
+ ['pointer_motion', 'pointer_leave', 'agent_admitted', 'pointer_motion'],
+ ['agent_admitted', 'pointer_enter', 'pointer_leave', 'pointer_enter'],
+ ['agent_admitted', 'agent_action_end'],
+ ]
+ for kinds in accepted:
+ with self.subTest(kinds=kinds):
+ self.assertEqual(passive_focus_evidence(*evidence(kinds))['lanes'], [1])
+ for kinds in rejected:
+ with self.subTest(kinds=kinds), self.assertRaises(AssertionError):
+ passive_focus_evidence(*evidence(kinds))
+
+ def test_passive_focus_retains_presence_without_authority_after_close(self):
+ rows = [[1, 0, 'start', 100, 100, 0, 0],
+ [2, 1, 'pointer_enter', 100, 100, 1, 0, 10, 20],
+ [3, 2, 'pointer_motion', 100, 100, 1, 0, 10, 20],
+ [4, 3, 'agent_action_end', 100, 100, 1, 0]]
+ page = {'hook': True, 'active': True, 'overflow': False, 'timed_out': False,
+ 'count': len(rows), 'events': rows}
+ values = [{'lane': lane, 'epoch': f'lane-{lane}', 'desktop_generation': 1,
+ 'reserved': lane == 0, 'pointer_focus': lane == 0,
+ 'keyboard_focus': False, 'lease_active': False, 'drag_active': False,
+ 'held_button': 0, 'held_keys': 0} for lane in (0, 1)]
+ status = {'state': 'input_v3_candidate', 'input': {'protocol': 3, 'test_only': False,
+ 'transport_ready': True, 'lanes': values}}
+ before = {'status': status, 'trace': page}
+ after = {'status': copy.deepcopy(status)}
+ after['status']['input']['lanes'][0].update(reserved=False)
+ stopped = {**page, 'active': False, 'count': len(rows) + 1,
+ 'events': rows + [[5, 4, 'stop', 100, 100, 0, 0]]}
+ def append_synthetic(t, kind):
+ t['events'].insert(-1, [5, 4, kind, 100, 100, 1, 0])
+ t['events'][-1][0] = 6
+ t['count'] += 1
+ mutations = {
+ 'grant': lambda b, a, t: b['status']['input']['lanes'][0].update(lease_active=True),
+ 'held': lambda b, a, t: b['status']['input']['lanes'][0].update(held_button=272),
+ 'keyboard': lambda b, a, t: b['status']['input']['lanes'][0].update(keyboard_focus=True),
+ 'not_retained': lambda b, a, t: b['status']['input']['lanes'][0].update(pointer_focus=False),
+ 'reservation': lambda b, a, t: a['status']['input']['lanes'][0].update(reserved=True),
+ 'hover_lost': lambda b, a, t: a['status']['input']['lanes'][0].update(pointer_focus=False),
+ 'held_after_close': lambda b, a, t: a['status']['input']['lanes'][0].update(held_keys=1),
+ 'epoch': lambda b, a, t: a['status']['input']['lanes'][0].update(epoch='replaced'),
+ 'unexpected_leave': lambda b, a, t: append_synthetic(t, 'pointer_leave'),
+ 'new_input': lambda b, a, t: append_synthetic(t, 'agent_admitted'),
+ 'incomplete': lambda b, a, t: t.update(overflow=True),
+ }
+ for mutation in (None, *mutations):
+ b, a, t = copy.deepcopy((before, after, stopped))
+ with self.subTest(mutation=mutation):
+ if mutation:
+ mutations[mutation](b, a, t)
+ with self.assertRaises(AssertionError):
+ passive_focus_evidence(b, a, t)
+ else:
+ self.assertEqual(passive_focus_evidence(b, a, t)['lanes'], [1])
+
+
+def plan():
+ return {'purpose': 'apps', 'foreground': {'pid': 10, 'window_id': 100},
+ 'agents': [{'app': 'calc', 'target': {'pid': 20, 'window_id': 200}},
+ {'app': 'inkscape', 'target': {'pid': 30, 'window_id': 300}}],
+ 'phases': [{'parallel': [{'agent': 0, 'tool': 'drag', 'arguments': {}},
+ {'agent': 1, 'tool': 'drag', 'arguments': {}}]}],
+ 'outputs': [{'agent': 0, 'attributes': {'value': '96'}},
+ {'agent': 1, 'rect_translation': [[10, 20], [30, 40]]}]}
+
+
+def capacity_plan():
+ result = {**plan(), 'purpose': 'capacity', 'outputs': []}
+ result['agents'].append({'app': 'inkscape', 'target': {'pid': 40, 'window_id': 400}})
+ for index, spec in enumerate(result['agents']):
+ spec.update(name='same-public-name', profile={'mode': 'standard'},
+ bounds={'x': 0, 'y': 0, 'width': 600, 'height': 600})
+ result['phases'] = [{'agent': index, 'tool': 'click', 'arguments': {'x': 20, 'y': 30}}
+ for index in range(3)]
+ result['phases'][2]['expect'] = {'kind': 'refused', 'reason': 'lane_busy'}
+ return result
+
+
+def capacity_events(lane):
+ return [('agent_admitted', 100, 200, lane, 0),
+ ('pointer_button', 100, 200, lane, 1),
+ ('pointer_button', 100, 200, lane, 0),
+ ('agent_action_end', 100, 200, lane, 0)]
+
+
+def policy_cache_plan():
+ result = capacity_plan()
+ result.update(purpose='policy_cache', agents=result['agents'][:1])
+ result['agents'][0]['profile'].update(manifest='reviewed.yaml', approve_manifest=True)
+ result['phases'] = [
+ {'agent': 0, 'tool': 'click', 'arguments': {'x': 20, 'y': 30}},
+ {'agent': 0, 'tool': 'press_key', 'arguments': {'key': 'ESC'},
+ 'expect': {'kind': 'refused', 'reason': 'permission_denied',
+ 'message': "Permission denied: capability manifest denies tool 'press_key'"}},
+ {'agent': 0, 'tool': 'click', 'arguments': {'x': 30, 'y': 40}},
+ ]
+ return result
+
+
+class ProvenanceTests(unittest.TestCase):
+ def test_runtime_provenance_refusal_precedes_app_inspection(self):
+ with patch('production_realapp_proof.runtime_provenance',
+ side_effect=AssertionError('loaded artifact mismatch')) as runtime, \
+ patch('production_realapp_proof.subprocess.check_output') as command:
+ args = SimpleNamespace()
+ with self.assertRaisesRegex(AssertionError, 'loaded artifact mismatch'):
+ provenance(args, {})
+ runtime.assert_called_once_with(args)
+ command.assert_not_called()
+
+ def test_reviewed_packages_must_match_runtime_provenance(self):
+ with patch('production_realapp_proof.runtime_provenance', return_value={'packages': {'a': '1'}}), \
+ patch('production_realapp_proof.subprocess.check_output') as command:
+ with self.assertRaisesRegex(AssertionError, 'package qualification mismatch'):
+ provenance(SimpleNamespace(), {'package_versions': {'a': '2'}})
+ command.assert_not_called()
+
+ def test_canonical_app_identity_requires_owner_and_native_backend(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary).resolve()
+ executable = root / 'soffice.bin'
+ executable.write_bytes(b'synthetic executable')
+ process = root / '20'
+ process.mkdir()
+ (process / 'exe').symlink_to(executable)
+ (process / 'maps').write_text('/usr/lib/libgtk-3.so\n/usr/lib/libvclplug_gtk3lo.so\n')
+ with patch('production_realapp_proof.EXECUTABLES', {'calc': executable}), \
+ patch('production_realapp_proof.package_owner') as owner:
+ identity = app_process_identity('calc', 20, root)
+ owner.assert_called_once_with(executable, 'libreoffice-fresh')
+ self.assertEqual(identity['executable'], str(executable))
+ self.assertEqual(len(identity['gtk3_maps']), 2)
+ self.assertEqual(len(identity['sha256']), 64)
+ owner.side_effect = AssertionError('unowned executable')
+ with self.assertRaisesRegex(AssertionError, 'unowned executable'):
+ app_process_identity('calc', 20, root)
+
+ with patch('production_realapp_proof.EXECUTABLES', {'calc': root / 'canonical/soffice.bin'}), \
+ patch('production_realapp_proof.package_owner') as owner:
+ with self.assertRaisesRegex(AssertionError, 'noncanonical running executable'):
+ app_process_identity('calc', 20, root)
+ owner.assert_not_called()
+
+ with patch('production_realapp_proof.EXECUTABLES', {'calc': executable}), \
+ patch('production_realapp_proof.package_owner'):
+ for maps, reason in [('', 'did not load GTK3'),
+ ('/usr/lib/libgtk-3.so', 'did not load its GTK3 backend')]:
+ (process / 'maps').write_text(maps)
+ with self.assertRaisesRegex(AssertionError, reason):
+ app_process_identity('calc', 20, root)
+
+
+class PolicyCacheTests(unittest.TestCase):
+ def test_plan_requires_one_fixed_target_session_and_exact_allow_deny_allow(self):
+ validate_plan(policy_cache_plan())
+ for mode in ('standard', 'bounded', 'unrestricted'):
+ for message in manifest_tool_messages('press_key'):
+ candidate = policy_cache_plan()
+ candidate['agents'][0]['profile'].update(mode=mode, acknowledge_unrestricted=True)
+ candidate['phases'][1]['expect']['message'] = message
+ validate_plan(candidate)
+ for mutate in (lambda p: p['agents'].append(copy.deepcopy(p['agents'][0])),
+ lambda p: p['agents'][0].update(app='fixture'),
+ lambda p: p['agents'][0].update(name=''),
+ lambda p: p['agents'][0]['target'].update(window_id=None),
+ lambda p: p['agents'][0]['profile'].pop('manifest'),
+ lambda p: p['agents'][0]['profile'].update(approve_manifest=False),
+ lambda p: p['agents'][0]['profile'].update(mode='unrestricted'),
+ lambda p: p['phases'].pop(),
+ lambda p: p['phases'][1].update(agent=1),
+ lambda p: p['phases'][1].update(parallel=[]),
+ lambda p: p['phases'][1].update(tool='click'),
+ lambda p: p['phases'][2].update(tool='scroll'),
+ lambda p: p['phases'][2].update(expect={'kind': 'unknown'}),
+ lambda p: p['phases'][1]['expect'].update(reason='lane_busy'),
+ lambda p: p['phases'][1]['expect'].update(reason='bounded_resource_outside_manifest'),
+ lambda p: p['phases'][1]['expect'].pop('message'),
+ lambda p: p['phases'][1]['expect'].update(message='Permission denied'),
+ lambda p: p['phases'][1]['arguments'].update(pid=99),
+ lambda p: p['phases'][1]['arguments'].update(session='new'),
+ lambda p: p.update(moving_primary=True),
+ lambda p: p.update(require_overlap=True)):
+ bad = policy_cache_plan()
+ mutate(bad)
+ with self.subTest(plan=bad), self.assertRaises(AssertionError):
+ validate_plan(bad)
+
+ def test_exact_common_envelope_excludes_plugin_and_other_policy_refusals(self):
+ expected = policy_cache_plan()['phases'][1]['expect']
+ content = {'status': 'refused', 'refusal': {'code': expected['reason'], 'message': expected['message']}}
+ check_manifest_refusal({'isError': True, 'structuredContent': content}, expected, 'press_key')
+ for change in ({'effect': 'refused', 'reason': 'permission_denied'},
+ {**content, 'delivery': {'mode': 'background'}},
+ {**content, 'refusal': {**content['refusal'], 'message': "Permission denied: user policy: tool 'press_key' is explicitly denied"}},
+ {**content, 'refusal': {**content['refusal'], 'code': 'bounded_resource_outside_manifest'}},
+ {**content, 'refusal': {**content['refusal'], 'message': "Permission denied: capability manifest denies tool 'click'"}}):
+ with self.subTest(content=change), self.assertRaises(AssertionError):
+ check_manifest_refusal({'isError': True, 'structuredContent': change}, expected, 'press_key')
+
+ def test_summary_requires_same_runtime_session_lane_and_fresh_success(self):
+ expected = policy_cache_plan()['phases'][1]['expect']
+ success = {'route': 'synthetic_events', 'effect': 'unverifiable', 'delivery': {'mode': 'background'}}
+ actions = [dict(agent=0, tool=step['tool'], expected='dispatched', observed=success,
+ runtime_pid=101, session='fixed', compositor_lane=1)
+ for step in policy_cache_plan()['phases']]
+ actions[1].update(expected='refused', expect=expected, no_dispatch='verified',
+ observed={'status': 'refused', 'refusal': {'code': expected['reason'], 'message': expected['message']}})
+ self.assertEqual(verify_policy_cache(actions)['result'], 'verified')
+ for mutate in (lambda a: a.pop(), lambda a: a[2].update(agent=1),
+ lambda a: a[2].update(compositor_lane=2),
+ lambda a: a[2].update(runtime_pid=102),
+ lambda a: a[2].update(session='replacement'),
+ lambda a: a[2].update(expected='unknown'),
+ lambda a: a[1].update(no_dispatch='unproven')):
+ bad = copy.deepcopy(actions)
+ mutate(bad)
+ with self.subTest(actions=bad), self.assertRaises(AssertionError):
+ verify_policy_cache(bad)
+
+ def test_mcp_tool_admission_requires_exact_code_and_retained_text(self):
+ expected = policy_cache_plan()['phases'][1]['expect']
+ response = {'isError': True, 'structuredContent': {'code': 'permission_denied'},
+ 'content': [{'type': 'text', 'text': expected['message']}]}
+ result = check_manifest_refusal(response, expected, 'press_key')
+ self.assertEqual(result['refusal_boundary'], 'mcp-tool-admission')
+ self.assertEqual(result['mcp_content'], response['content'])
+ for mutate in (lambda r: r.update(isError=False), lambda r: r.pop('content'),
+ lambda r: r['content'].append({'type': 'text', 'text': 'extra'}),
+ lambda r: r['content'][0].update(text='Permission denied'),
+ lambda r: r['content'][0].update(text=expected['message'].replace('press_key', 'hotkey')),
+ lambda r: r['structuredContent'].update(code='lane_busy'),
+ lambda r: r['structuredContent'].update(delivery={'mode': 'background'}),
+ lambda r: r['structuredContent'].update(effect='unverifiable')):
+ bad = copy.deepcopy(response)
+ mutate(bad)
+ with self.subTest(response=bad), self.assertRaises(AssertionError):
+ check_manifest_refusal(bad, expected, 'press_key')
+
+ def test_missing_trace_fails_before_process_launch(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ path = root / 'plan.json'
+ path.write_text(json.dumps(policy_cache_plan()))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence', trace_socket=None)
+ with patch('production_realapp_proof.provenance') as provenance, \
+ patch('production_realapp_proof.DirectMCP') as spawn:
+ self.assertEqual(run(args), 1)
+ provenance.assert_not_called()
+ spawn.assert_not_called()
+ result = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(result['error'], 'policy_cache requires continuous trace')
+ self.assertEqual(result['policy_cache']['result'], 'unproven')
+
+ def test_runner_persistent_runtime_quiet_denial_and_failures_without_replay(self):
+ for failure in (None, 'changed_lane', 'missing_input', 'wrong_refusal', 'plugin_refusal',
+ 'admitted_on_denial', 'input_on_denial', 'denial_before_snapshot',
+ 'denial_after_snapshot', 'next_snapshot_input', 'gap_input', 'dead_runtime', 'changed_runtime',
+ 'transport', 'partial', 'unknown', 'missing_hook', 'reset_trace',
+ 'cleanup_reset', 'foreground_input', 'cleanup_failure', 'stale_window'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ candidate = policy_cache_plan()
+ path = root / 'plan.json'
+ path.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence',
+ trace_socket=root / 'cua-input-v3.sock', driver=root / 'driver',
+ primary_grab=root / 'primary-grab', foreground_journal=root / 'journal',
+ record_video=False)
+ calls, events, held = [], [START], [True]
+ agent = Mock(process=Mock(pid=101, poll=Mock(return_value=None)))
+ observer = Mock()
+ targets = [candidate['foreground'], candidate['agents'][0]['target']]
+ action_count = 0
+ snapshot_count = 0
+
+ def tool(name, arguments):
+ nonlocal action_count, snapshot_count
+ if name == 'list_windows':
+ windows = copy.deepcopy(targets)
+ if failure == 'stale_window' and action_count == 1:
+ windows[1]['window_id'] += 1
+ return {'structuredContent': {'windows': windows}}
+ if name == 'get_window_state':
+ calls.append(('snapshot', arguments))
+ snapshot_count += 1
+ if ((failure == 'denial_before_snapshot' and snapshot_count == 7)
+ or (failure == 'next_snapshot_input' and snapshot_count == 9)
+ or (failure == 'denial_after_snapshot' and action_count == 2)):
+ events.append(('agent_admitted', 100, 200, 1, 0))
+ return {'structuredContent': {'screenshot_width': 600,
+ 'window_bounds': candidate['agents'][0]['bounds']}}
+ if name == 'get_desktop_state':
+ return {'structuredContent': {'screen_width': 800, 'screen_height': 800}}
+ if name not in ('click', 'press_key'):
+ return {'structuredContent': {}}
+ action_count += 1
+ calls.append((name, arguments))
+ self.assertEqual(arguments, {**candidate['phases'][action_count - 1]['arguments'],
+ **candidate['agents'][0]['target'], 'session': candidate['agents'][0]['name'],
+ 'delivery_mode': 'background'})
+ if failure == 'transport' and action_count == 2:
+ raise TimeoutError('unknown effect')
+ if name == 'press_key':
+ if failure == 'dead_runtime':
+ agent.process.poll.return_value = 1
+ if failure == 'changed_runtime':
+ agent.process.pid = 102
+ if failure in ('admitted_on_denial', 'input_on_denial'):
+ kind = 'agent_admitted' if failure == 'admitted_on_denial' else 'keyboard_key'
+ events.append((kind, 100, 200, 1, 0))
+ if failure == 'plugin_refusal':
+ return {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'permission_denied'}}
+ expected = candidate['phases'][1]['expect']
+ return {'isError': True, 'structuredContent': {'code': expected['reason']},
+ 'content': [{'type': 'text',
+ 'text': 'wrong reason' if failure == 'wrong_refusal' else expected['message']}]}
+ lane = 2 if failure == 'changed_lane' and action_count == 3 else 1
+ rows = capacity_events(lane)
+ events.extend([rows[0], rows[-1]] if failure == 'missing_input' else rows)
+ if failure == 'foreground_input':
+ events.append(('keyboard_key', 100, 200, 0, 0))
+ return {'structuredContent': {'route': 'synthetic_events',
+ 'effect': 'partial' if failure == 'partial' else 'unverifiable',
+ 'delivery': {'mode': 'unknown' if failure == 'unknown' else 'background'}}}
+
+ agent.tool.side_effect = observer.tool.side_effect = tool
+ trace_client = Mock(hello={'protocol': 3})
+ def exchange(command):
+ if command == 'TRACE_STOP':
+ if failure == 'cleanup_reset':
+ events[:] = [START]
+ events.append(STOP)
+ trace_client.exchange.side_effect = exchange
+ def collect():
+ if failure == 'reset_trace' and trace_client.collect.call_count == 4:
+ events[:] = [START]
+ if failure == 'gap_input' and trace_client.collect.call_count == 7:
+ events.append(('agent_admitted', 100, 200, 1, 0))
+ return {**trace(*events), 'active': events[-1] != STOP, 'hook': failure != 'missing_hook'}
+ trace_client.collect.side_effect = collect
+ if failure == 'cleanup_failure':
+ agent.close.side_effect = RuntimeError('cleanup failed')
+ grab = Mock(poll=Mock(return_value=None))
+ replacements = {'provenance': Mock(return_value={}),
+ 'DirectMCP': Mock(side_effect=[agent, observer]), 'Trace': Mock(return_value=trace_client),
+ 'subprocess.Popen': Mock(return_value=grab),
+ 'primary_acknowledgement': Mock(return_value='HELD\n'),
+ 'wait_for': lambda predicate: self.assertTrue(predicate()),
+ 'state': lambda path: {'held': held[0], 'clicks': 0, 'keys': 0, 'scroll': 0},
+ 'wm': lambda: {'pid': 10, 'address': '0x10', 'workspace': 1, 'cursor': {'x': 100, 'y': 200}},
+ 'stop_process': lambda process: held.__setitem__(0, False)}
+ for name, replacement in replacements.items():
+ stack.enter_context(patch('production_realapp_proof.' + name, replacement))
+ self.assertEqual(run(args), 0 if failure is None else 1)
+ mutations = [name for name, _ in calls if name in ('click', 'press_key')]
+ self.assertEqual(mutations, ['click', 'press_key', 'click'][:len(mutations)])
+ for index, (name, arguments) in enumerate(calls):
+ if name in ('click', 'press_key'):
+ self.assertEqual(calls[index - 1][0], 'snapshot')
+ if failure != 'stale_window':
+ self.assertEqual(calls[index + 1][0], 'snapshot')
+ agent.close.assert_called_once()
+ observer.close.assert_called_once()
+ trace_client.close.assert_called_once()
+ self.assertFalse(held[0])
+ self.assertEqual(replacements['DirectMCP'].call_count, 2)
+ self.assertEqual(replacements['DirectMCP'].call_args.args[2],
+ {'mode': 'unrestricted', 'acknowledge_unrestricted': True})
+ result = json.loads((args.evidence / 'result.json').read_text())
+ if failure is None:
+ self.assertEqual(mutations, ['click', 'press_key', 'click'])
+ self.assertEqual(result['policy_cache']['compositor_lane'], 1)
+ self.assertEqual(result['continuous_isolation'], 'passed')
+ self.assertEqual(result['synthetic_cleanup'], 'verified')
+ for index in range(3):
+ self.assertTrue((args.evidence / f'policy-cache-phase-{index}-trace.json').is_file())
+ if failure in ('transport', 'dead_runtime', 'changed_runtime', 'gap_input', 'next_snapshot_input'):
+ self.assertEqual(mutations, ['click', 'press_key'])
+
+
+class CapacityTests(unittest.TestCase):
+ def test_plan_requires_three_serial_independent_qualified_targets(self):
+ validate_plan(capacity_plan())
+ for mutate in (lambda p: p.update(phases=[]),
+ lambda p: p.update(phases=p['phases'][:2]),
+ lambda p: p.update(agents=p['agents'][:2]),
+ lambda p: p['phases'][1].update(agent=0),
+ lambda p: p['phases'][0].update(parallel=[]),
+ lambda p: p['phases'][0].update(expect={'kind': 'unknown'}),
+ lambda p: p['phases'][2].pop('expect'),
+ lambda p: p['phases'][2].update(expect={'kind': 'refused', 'reason': 'permission_denied'}),
+ lambda p: p['agents'][2].update(target=p['agents'][1]['target']),
+ lambda p: p['agents'][2]['target'].update(window_id=None),
+ lambda p: p['agents'][2].update(app='fixture'),
+ lambda p: p.update(moving_primary=True),
+ lambda p: p.update(require_overlap=True)):
+ bad = capacity_plan()
+ mutate(bad)
+ with self.subTest(plan=bad), self.assertRaises(AssertionError):
+ validate_plan(bad)
+ # Capacity does not redefine the normal reviewed permission contract.
+ for mode in ('standard', 'bounded', 'unrestricted'):
+ candidate = capacity_plan()
+ candidate['agents'][0]['profile']['mode'] = mode
+ validate_plan(candidate)
+ for purpose in ('apps', 'policy', 'negative_control'):
+ with self.assertRaises(AssertionError):
+ validate_plan({**capacity_plan(), 'purpose': purpose})
+
+ def test_lane_needs_actual_ordered_input_and_completion(self):
+ before = {**trace(START), 'active': True}
+ events = capacity_events(1)
+ after = {**trace(START, *events), 'active': True}
+ self.assertEqual(capacity_lane(before, after, 'click'), 1)
+ for rows in ([], events[:1], events[1:], events[:-1],
+ [events[0], events[-1]], list(reversed(events)),
+ [events[0], *capacity_events(2)],
+ [(kind, x, y, 0, state) for kind, x, y, lane, state in events]):
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ capacity_lane(before, {**trace(START, *rows), 'active': True}, 'click')
+ for malformed in (None, {}, {**after, 'events': []}, {**after, 'hook': False},
+ {**after, 'overflow': True}, {**after, 'count': 0},
+ {**after, 'timed_out': True}, {**after, 'events': [[1]]}):
+ with self.subTest(trace=malformed), self.assertRaises(AssertionError):
+ capacity_lane(before, malformed, 'click')
+ with self.assertRaises(AssertionError):
+ capacity_lane(before, after, 'press_key')
+
+ def test_summary_rejects_incomplete_wrong_lane_and_wrong_refusal(self):
+ observed = {'route': 'synthetic_events', 'effect': 'unverifiable', 'delivery': {'mode': 'background'}}
+ actions = [{'agent': i, 'expected': 'dispatched', 'observed': observed, 'compositor_lane': i + 1}
+ for i in range(2)] + [{'agent': 2, 'expected': 'refused', 'no_dispatch': 'verified',
+ 'observed': {'effect': 'refused', 'reason': 'lane_busy'}}]
+ self.assertEqual(verify_capacity(actions)['result'], 'verified')
+ for mutate in (lambda a: a.clear(), lambda a: a.pop(),
+ lambda a: a[1].update(compositor_lane=1),
+ lambda a: a[1].pop('compositor_lane'),
+ lambda a: a[0].update(observed={}),
+ lambda a: a[2].update(no_dispatch='unproven'),
+ lambda a: a[2]['observed'].update(reason='permission_denied'),
+ lambda a: a[2]['observed'].update(delivery={'mode': 'background'})):
+ bad = copy.deepcopy(actions)
+ mutate(bad)
+ with self.subTest(actions=bad), self.assertRaises(AssertionError):
+ verify_capacity(bad)
+
+ def test_missing_trace_fails_before_process_launch(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source_plan = root / 'plan.json'
+ source_plan.write_text(json.dumps(capacity_plan()))
+ args = SimpleNamespace(plan=source_plan, evidence=root / 'evidence', trace_socket=None)
+ with patch('production_realapp_proof.provenance') as provenance, \
+ patch('production_realapp_proof.DirectMCP') as spawn:
+ self.assertEqual(run(args), 1)
+ provenance.assert_not_called()
+ spawn.assert_not_called()
+ result = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(result['error'], 'capacity requires continuous trace')
+ self.assertEqual(result['capacity']['result'], 'unproven')
+
+ def test_runner_serial_capacity_and_failures_without_replay(self):
+ for failure in (None, 'same_lane', 'missing_input', 'wrong_refusal', 'dispatch_on_refusal',
+ 'dead_runtime', 'stale_window', 'transport', 'missing_hook', 'reset_trace'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ candidate = capacity_plan()
+ path = root / 'plan.json'
+ path.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence',
+ trace_socket=root / 'cua-input-v3.sock', driver=root / 'driver',
+ primary_grab=root / 'primary-grab', foreground_journal=root / 'journal',
+ record_video=False)
+ calls, events, held = [], [START], [True]
+ agents = [Mock(process=Mock(pid=101 + i, poll=Mock(return_value=None))) for i in range(3)]
+ observer = Mock()
+ targets = [candidate['foreground']] + [spec['target'] for spec in candidate['agents']]
+
+ def tool(index, name, arguments):
+ if name == 'list_windows':
+ windows = copy.deepcopy(targets)
+ if failure == 'stale_window':
+ windows[-1]['window_id'] += 1
+ return {'structuredContent': {'windows': windows}}
+ if name == 'get_window_state':
+ calls.append(('snapshot', index))
+ return {'structuredContent': {'screenshot_width': 600,
+ 'window_bounds': candidate['agents'][0]['bounds']}}
+ if name == 'get_desktop_state':
+ return {'structuredContent': {'screen_width': 800, 'screen_height': 800}}
+ if name != 'click':
+ return {'structuredContent': {}}
+ calls.append(('click', index))
+ self.assertEqual(arguments['delivery_mode'], 'background')
+ self.assertEqual({key: arguments[key] for key in ('pid', 'window_id')},
+ candidate['agents'][index]['target'])
+ if failure == 'transport':
+ raise TimeoutError('unknown effect')
+ if index < 2:
+ lane = 1 if failure == 'same_lane' else index + 1
+ rows = capacity_events(lane)
+ events.extend([rows[0], rows[-1]] if failure == 'missing_input' else rows)
+ if failure == 'dead_runtime':
+ agents[0].process.poll.return_value = 1
+ return {'structuredContent': {'route': 'synthetic_events', 'effect': 'unverifiable',
+ 'delivery': {'mode': 'background'}}}
+ if failure == 'dispatch_on_refusal':
+ events.extend(capacity_events(1))
+ return {'isError': True, 'structuredContent': {'effect': 'refused',
+ 'reason': 'permission_denied' if failure == 'wrong_refusal' else 'lane_busy'}}
+
+ for i, mcp in enumerate(agents + [observer]):
+ mcp.tool.side_effect = lambda name, arguments, i=i: tool(i, name, arguments)
+ trace_client = Mock(hello={'protocol': 3})
+ trace_client.exchange.side_effect = lambda command: events.append(STOP) if command == 'TRACE_STOP' else None
+ def collect():
+ if failure == 'reset_trace' and trace_client.collect.call_count == 3:
+ events[:] = [START]
+ return {**trace(*events), 'active': events[-1] != STOP, 'hook': failure != 'missing_hook'}
+ trace_client.collect.side_effect = collect
+ grab = Mock(poll=Mock(return_value=None))
+ replacements = {'provenance': Mock(return_value={}),
+ 'DirectMCP': Mock(side_effect=agents + [observer]), 'Trace': Mock(return_value=trace_client),
+ 'subprocess.Popen': Mock(return_value=grab),
+ 'primary_acknowledgement': Mock(return_value='HELD\n'),
+ 'wait_for': lambda predicate: self.assertTrue(predicate()),
+ 'state': lambda path: {'held': held[0], 'clicks': 0, 'keys': 0, 'scroll': 0},
+ 'wm': lambda: {'pid': 10, 'address': '0x10', 'workspace': 1, 'cursor': {'x': 100, 'y': 200}},
+ 'stop_process': lambda process: held.__setitem__(0, False)}
+ for name, replacement in replacements.items():
+ stack.enter_context(patch('production_realapp_proof.' + name, replacement))
+ self.assertEqual(run(args), 0 if failure is None else 1)
+ action_indexes = [index for name, index in calls if name == 'click']
+ self.assertEqual(action_indexes, list(range(len(action_indexes))))
+ if failure == 'missing_hook':
+ self.assertEqual(action_indexes, [])
+ if failure == 'reset_trace':
+ self.assertEqual(action_indexes, [0])
+ for i, call in enumerate(calls):
+ if call[0] == 'click':
+ self.assertEqual(calls[i - 1], ('snapshot', call[1]))
+ self.assertEqual(calls[i + 1][0], 'snapshot')
+ for mcp in agents:
+ mcp.close.assert_called_once()
+ if failure != 'stale_window':
+ observer.close.assert_called_once()
+ self.assertFalse(held[0])
+ result = json.loads((args.evidence / 'result.json').read_text())
+ if failure is None:
+ self.assertEqual(action_indexes, [0, 1, 2])
+ self.assertEqual(result['capacity']['lanes'], [1, 2])
+ self.assertEqual(result['continuous_isolation'], 'passed')
+ self.assertEqual(result['synthetic_cleanup'], 'verified')
+ for i in range(3):
+ self.assertTrue((args.evidence / f'capacity-agent-{i}-trace.json').is_file())
+
+
+class PlanTests(unittest.TestCase):
+ def test_smoke_stages_allow_only_the_exact_app_keyboard_steps(self):
+ for index, app in enumerate(('calc', 'inkscape')):
+ for stage, (tool, arguments) in SMOKE_STEPS[app].items():
+ with self.subTest(app=app, stage=stage):
+ candidate = plan()
+ candidate['phases'] = [{'agent': index, 'smoke_stage': stage,
+ 'tool': tool, 'arguments': arguments}]
+ validate_plan(candidate)
+ for change in ({'smoke_stage': 'after'}, {'smoke_stage': None},
+ {'smoke_stage': []}, {'tool': 'click'},
+ {'arguments': {**arguments, 'x': 1}},
+ {'arguments': {'key': 'Escape'}}):
+ bad = copy.deepcopy(candidate)
+ bad['phases'][0].update(change)
+ with self.assertRaises(AssertionError):
+ validate_plan(bad)
+ candidate['agents'][index]['app'] = 'unknown'
+ with self.assertRaises(AssertionError):
+ validate_plan(candidate)
+
+ def test_moving_primary_is_optional_boolean_and_excludes_negative_control(self):
+ validate_plan({**plan(), 'moving_primary': True})
+ for value in ('true', 1, None):
+ with self.assertRaises(AssertionError):
+ validate_plan({**plan(), 'moving_primary': value})
+ negative = {**plan(), 'purpose': 'negative_control',
+ 'phases': [{'negative_control': True}]}
+ validate_plan(negative)
+ with self.assertRaisesRegex(AssertionError, 'parked'):
+ validate_plan({**negative, 'moving_primary': True})
+
+ def test_real_apps_need_independent_processes_and_both_output_oracles(self):
+ validate_plan(plan())
+ for mutate in (lambda p: p['agents'][1].update(target=p['agents'][0]['target']),
+ lambda p: p['agents'][1].update(app='gtk-fixture'),
+ lambda p: p.update(outputs=p['outputs'][:1]),
+ lambda p: p.update(phases=[])):
+ bad = plan()
+ mutate(bad)
+ with self.assertRaises(AssertionError):
+ validate_plan(bad)
+
+ def test_public_arguments_cannot_override_reviewed_target_or_session(self):
+ for key in ('pid', 'window_id', 'session', 'delivery_mode'):
+ bad = plan()
+ bad['phases'][0]['parallel'][0]['arguments'][key] = 'other'
+ with self.assertRaises(AssertionError):
+ validate_plan(bad)
+
+ def test_one_connection_cannot_execute_parallel_calls(self):
+ bad = plan()
+ bad['phases'][0]['parallel'][1]['agent'] = 0
+ with self.assertRaises(AssertionError):
+ validate_plan(bad)
+
+ def test_parallel_denial_has_no_quiet_no_dispatch_interval(self):
+ bad = plan()
+ bad['phases'][0]['parallel'][0]['expect'] = {'kind': 'refused', 'reason': 'permission_denied'}
+ with self.assertRaises(AssertionError):
+ validate_plan(bad)
+
+ def test_policy_plan_cannot_count_dispatched_action_as_deny(self):
+ bad = plan()
+ bad['purpose'] = 'policy'
+ with self.assertRaises(AssertionError):
+ validate_plan(bad)
+
+
+class SmokeStageTests(unittest.TestCase):
+ def test_parallel_prebarrier_failure_preserves_root_cause_and_aborts_sibling(self):
+ steps = [{'agent': i, 'tool': 'press_key'} for i in range(2)]
+ entered = threading.Event()
+ calls = []
+ def action(step, barrier):
+ calls.append(step['agent'])
+ if step['agent'] == 1:
+ self.assertTrue(entered.wait(1))
+ raise RuntimeError('selection grounding unavailable')
+ entered.set()
+ barrier.wait(timeout=2)
+ self.fail('sibling must not dispatch')
+ results, errors = parallel_actions(steps, action)
+ self.assertEqual(results, [])
+ self.assertCountEqual(calls, [0, 1])
+ self.assertEqual(errors, [
+ {'agent': 0, 'tool': 'press_key', 'error_type': 'BrokenBarrierError', 'message': ''},
+ {'agent': 1, 'tool': 'press_key', 'error_type': 'RuntimeError',
+ 'message': 'selection grounding unavailable'}])
+
+ def test_parallel_postbarrier_failure_retains_successful_sibling_without_replay(self):
+ steps = [{'agent': i, 'tool': 'press_key'} for i in range(2)]
+ calls = []
+ def action(step, barrier):
+ barrier.wait(timeout=2)
+ calls.append(step['agent'])
+ if step['agent'] == 0:
+ raise RuntimeError('unconfirmed effect')
+ return {'agent': 1, 'expected': 'dispatched'}
+ results, errors = parallel_actions(steps, action)
+ self.assertEqual(results, [{'agent': 1, 'expected': 'dispatched'}])
+ self.assertCountEqual(calls, [0, 1])
+ self.assertEqual(errors, [{'agent': 0, 'tool': 'press_key', 'error_type': 'RuntimeError',
+ 'message': 'unconfirmed effect'}])
+
+ def test_runner_grounds_full_snapshots_and_never_recovers_or_replays(self):
+ for app, stage, elements in (
+ ('calc', 'insert', [{'role': 'table cell', 'label': 'A1', 'selected': True}]),
+ ('inkscape', 'select', INKSCAPE['elements']),
+ ('inkscape', 'move', INKSCAPE_SELECTED['elements'])):
+ for failure in (None, 'no_elements', 'dialog', 'extra_window', 'after_dialog', 'transport', 'unmarked'):
+ with self.subTest(app=app, stage=stage, failure=failure), \
+ tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ candidate = plan()
+ index = 0 if app == 'calc' else 1
+ tool_name, arguments = SMOKE_STEPS[app][stage]
+ candidate['phases'] = [{'agent': index, 'smoke_stage': stage,
+ 'tool': tool_name, 'arguments': arguments}]
+ if failure == 'unmarked':
+ del candidate['phases'][0]['smoke_stage']
+ bounds = {'x': 0, 'y': 0, 'width': 600, 'height': 600}
+ for i, spec in enumerate(candidate['agents']):
+ spec.update(bounds=bounds, name=f'agent-{i}', profile={'mode': 'standard'})
+ path = root / f'{i}.xml'
+ path.write_text('<synthetic/>')
+ candidate['outputs'][i]['path'] = str(path)
+ path = root / 'plan.json'
+ path.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=path, evidence=root / 'evidence', trace_socket=None,
+ driver=root / 'driver', primary_grab=root / 'primary-grab',
+ foreground_journal=root / 'journal', record_video=False)
+ calls, held = [], [True]
+ agents = [Mock(process=Mock(pid=101 + i, poll=Mock(return_value=None))) for i in range(2)]
+ observer = Mock()
+ targets = [candidate['foreground']] + [spec['target'] for spec in candidate['agents']]
+
+ def tool(name, parameters):
+ if name == 'list_windows':
+ windows = copy.deepcopy(targets)
+ if failure == 'extra_window':
+ windows.append({**candidate['agents'][index]['target'], 'window_id': 999})
+ return {'structuredContent': {'windows': windows}}
+ if name == 'get_window_state':
+ calls.append(('snapshot', parameters))
+ sent = any(row[0] == 'input' for row in calls)
+ rows = elements
+ if failure in ('no_elements', 'unmarked'):
+ rows = []
+ if failure == 'dialog' or (failure == 'after_dialog' and sent):
+ rows = [{'role': 'dialog'}]
+ return {'structuredContent': {'screenshot_width': 600, 'window_bounds': bounds,
+ 'tree_markdown': (INKSCAPE_SELECTED if stage == 'move'
+ else INKSCAPE)['tree_markdown'],
+ 'elements': rows}}
+ if name == 'get_desktop_state':
+ return {'structuredContent': {'screen_width': 800, 'screen_height': 800}}
+ if name != tool_name:
+ return {'structuredContent': {}}
+ calls.append(('input', parameters))
+ if failure == 'transport':
+ raise TimeoutError('unknown input outcome')
+ return {'structuredContent': {'route': 'synthetic_events', 'effect': 'unverifiable',
+ 'delivery': {'mode': 'background'}}}
+
+ for mcp in agents + [observer]:
+ mcp.tool.side_effect = tool
+ replacements = {'provenance': Mock(return_value={}),
+ 'DirectMCP': Mock(side_effect=agents + [observer]),
+ 'subprocess.Popen': Mock(return_value=Mock(poll=Mock(return_value=None))),
+ 'primary_acknowledgement': Mock(return_value='HELD\n'),
+ 'verify_output': Mock(return_value={'verified': True}),
+ 'wait_for': lambda predicate: self.assertTrue(predicate()),
+ 'state': lambda path: {'held': held[0], 'clicks': 0, 'keys': 0, 'scroll': 0},
+ 'wm': lambda: {'pid': 10, 'address': '0x10', 'workspace': 1,
+ 'cursor': {'x': 100, 'y': 200}},
+ 'stop_process': lambda process: held.__setitem__(0, False)}
+ for name, replacement in replacements.items():
+ stack.enter_context(patch('production_realapp_proof.' + name, replacement))
+ self.assertEqual(run(args), 0 if failure in (None, 'unmarked') else 1)
+ inputs = [i for i, row in enumerate(calls) if row[0] == 'input']
+ self.assertEqual(len(inputs), 0 if failure in ('no_elements', 'dialog', 'extra_window') else 1)
+ if inputs:
+ i = inputs[0]
+ self.assertEqual(calls[i - 1][0], 'snapshot')
+ self.assertEqual(calls[i + 1][0], 'snapshot')
+ self.assertEqual(calls[i][1]['delivery_mode'], 'background')
+ self.assertNotIn('smoke_stage', calls[i][1])
+ for _, parameters in (calls[i - 1], calls[i + 1]):
+ self.assertEqual('max_elements' in parameters, failure == 'unmarked')
+ self.assertEqual('max_depth' in parameters, failure == 'unmarked')
+ for mcp in agents + [observer]:
+ mcp.close.assert_called_once()
+ self.assertFalse(held[0])
+ report = json.loads((args.evidence / 'result.json').read_text())
+ if failure is None:
+ self.assertEqual(report['actions'][0]['smoke_stage'], stage)
+
+
+class PointerStageTests(unittest.TestCase):
+ def test_only_declared_intermediate_episodes_may_omit_saved_outputs(self):
+ for index, name in enumerate(POINTER_EPISODES):
+ candidate = plan()
+ candidate.update(pointer_episode={'name': name, 'index': index, 'count': 5},
+ require_overlap=name == 'drags')
+ if name != 'save':
+ candidate['outputs'] = []
+ validate_plan(candidate)
+ moving = copy.deepcopy(candidate)
+ moving['moving_primary'] = True
+ if name == 'drags':
+ validate_plan(moving)
+ else:
+ with self.assertRaises(AssertionError):
+ validate_plan(moving)
+ for mutation in (lambda p: p['pointer_episode'].update(count=4),
+ lambda p: p['pointer_episode'].update(index=True),
+ lambda p: p['pointer_episode'].update(name='unknown'),
+ lambda p: p['pointer_episode'].update(extra=True),
+ lambda p: p.update(purpose='policy'),
+ lambda p: p.update(require_overlap=name != 'drags')):
+ invalid = copy.deepcopy(candidate)
+ mutation(invalid)
+ with self.assertRaises(AssertionError):
+ validate_plan(invalid)
+ for metadata in ({}, {'pointer_episode': None},
+ {'pointer_episode': {'name': 'save', 'index': 4, 'count': 5}}):
+ with self.subTest(metadata=metadata), self.assertRaises(AssertionError):
+ validate_plan({**plan(), **metadata, 'outputs': []})
+
+ def test_primary_guard_fails_at_deadline_or_any_helper_exit(self):
+ helper = Mock(poll=Mock(return_value=None))
+ require_primary_active(helper, 100, now_ns=99)
+ for now in (100, 101):
+ with self.assertRaisesRegex(AssertionError, 'deadline expired'):
+ require_primary_active(helper, 100, now_ns=now)
+ for code in (0, 1, -15):
+ helper.poll.return_value = code
+ with self.assertRaisesRegex(AssertionError, 'helper exited'):
+ require_primary_active(helper, 100, now_ns=99)
+
+ def test_pointer_stages_reject_supplied_coordinates_or_wrong_tool(self):
+ candidate = plan()
+ candidate['phases'] = [{'agent': 0, 'pointer_stage': 'click_b2', 'tool': 'click', 'arguments': {}}]
+ validate_plan(candidate)
+ for change in ({'arguments': {'x': 1, 'y': 2}}, {'tool': 'press_key'},
+ {'pointer_stage': 'unknown'}, {'smoke_stage': 'insert'},
+ {'expect': {'kind': 'partial'}}):
+ changed = copy.deepcopy(candidate)
+ changed['phases'][0].update(change)
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ validate_plan(changed)
+
+ def test_pointer_actions_use_the_same_response_image_and_never_replay(self):
+ for failure in (None, 'before', 'after', 'after_recovers', 'missing_image', 'transport',
+ 'helper_before', 'deadline_before', 'helper_after', 'deadline_after'):
+ with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ candidate = plan()
+ candidate['phases'] = [{'agent': 0, 'pointer_stage': 'click_b2', 'tool': 'click', 'arguments': {}}]
+ bounds = {'x': 0, 'y': 0, 'width': 600, 'height': 600}
+ for index, spec in enumerate(candidate['agents']):
+ spec.update(bounds=bounds, name=f'agent-{index}', profile={'mode': 'standard'})
+ output = root / f'{index}.xml'
+ output.write_text('<synthetic/>')
+ candidate['outputs'][index]['path'] = str(output)
+ plan_path = root / 'plan.json'
+ plan_path.write_text(json.dumps(candidate))
+ args = SimpleNamespace(plan=plan_path, evidence=root / 'evidence', trace_socket=None,
+ driver=root / 'driver', primary_grab=root / 'primary-grab',
+ foreground_journal=root / 'journal', record_video=False)
+ targets = [candidate['foreground']] + [spec['target'] for spec in candidate['agents']]
+ clients, calls, held = [], [], [True]
+ clock_now = [1]
+ grab = Mock(poll=Mock(return_value=None))
+ def expire_primary(phase):
+ if failure == 'helper_' + phase:
+ grab.poll.return_value = 0
+ if failure == 'deadline_' + phase:
+ clock_now[0] = 1 + PRIMARY_LIFETIME_MS * 1_000_000
+ def client(driver, folder, profile):
+ mcp = Mock(directory=folder, counter=0,
+ process=Mock(pid=100 + len(clients), poll=Mock(return_value=None)))
+ clients.append(mcp)
+ def tool(name, parameters):
+ mcp.counter += 1
+ if name == 'list_windows':
+ return {'structuredContent': {'windows': targets}}
+ if name == 'get_window_state':
+ if any(row[0] == 'input' for row in calls):
+ expire_primary('after')
+ calls.append(('snapshot', parameters, folder.name, mcp.counter))
+ image = folder / f'{mcp.counter}.png'
+ image.write_bytes(b'synthetic image read by a stub')
+ return {'structuredContent': {'screenshot_width': 600, 'window_bounds': bounds},
+ 'content': [] if failure == 'missing_image' else
+ [{'type': 'image', 'image_file': image.name}]}
+ if name == 'get_desktop_state':
+ return {'structuredContent': {'screen_width': 800, 'screen_height': 800}}
+ if name == 'click':
+ calls.append(('input', parameters))
+ if failure == 'transport':
+ raise TimeoutError('unknown outcome')
+ return {'structuredContent': {'route': 'synthetic_events', 'effect': 'unverifiable'}}
+ return {'structuredContent': {}}
+ mcp.tool.side_effect = tool
+ return mcp
+ def ground_pointer(*_):
+ if failure == 'before':
+ raise RuntimeError('missing grounding')
+ expire_primary('before')
+ return {'x': 103, 'y': 205}, {'app': 'calc', 'stage': 'click_b2'}
+ grounding = Mock(side_effect=ground_pointer)
+ verification = Mock(return_value={'verified': True},
+ side_effect=AssertionError('unchanged app') if failure == 'after' else None)
+ if failure == 'after_recovers':
+ verification.side_effect = [AssertionError('not settled'), {'verified': True}, {'verified': True}]
+ replacements = {'provenance': Mock(return_value={}), 'DirectMCP': client,
+ 'subprocess.Popen': Mock(return_value=grab),
+ 'time.monotonic_ns': lambda: clock_now[0],
+ 'primary_acknowledgement': Mock(return_value='HELD\n'),
+ 'verify_output': Mock(return_value={'verified': True}),
+ 'wait_for': lambda predicate: self.assertTrue(predicate()),
+ 'state': lambda path: {'held': held[0], 'clicks': 0, 'keys': 0, 'scroll': 0},
+ 'wm': lambda: {'pid': 10, 'address': '0x10', 'workspace': 1, 'cursor': {'x': 100, 'y': 200}},
+ 'stop_process': lambda process: held.__setitem__(0, False),
+ 'pointer_grounding.read_pixels': lambda path: path,
+ 'pointer_grounding.action': grounding, 'pointer_grounding.verify': verification}
+ for name, replacement in replacements.items():
+ stack.enter_context(patch('production_realapp_proof.' + name, replacement))
+ self.assertEqual(run(args), 0 if failure is None else 1)
+ inputs = [index for index, row in enumerate(calls) if row[0] == 'input']
+ self.assertEqual(len(inputs), 0 if failure in
+ ('before', 'missing_image', 'helper_before', 'deadline_before') else 1)
+ for index in inputs:
+ self.assertEqual(calls[index - 1][0], 'snapshot')
+ self.assertEqual(calls[index + 1][0], 'snapshot')
+ self.assertEqual(calls[index][1], {**candidate['agents'][0]['target'],
+ 'session': 'agent-0', 'delivery_mode': 'background',
+ 'x': 103, 'y': 205})
+ before = calls[index - 1]
+ self.assertTrue(grounding.call_args.args[1].endswith(f'{before[2]}/{before[3]}.png'))
+ self.assertEqual(grounding.call_args.args[0]['proof_image'], grounding.call_args.args[1])
+ if failure is None:
+ after = calls[inputs[0] + 1]
+ self.assertTrue(verification.call_args.args[1].endswith(f'{after[2]}/{after[3]}.png'))
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertTrue(report['actions'][0]['app_effect_verified'])
+ self.assertEqual(report['actions'][0]['pointer_stage'], 'click_b2')
+ self.assertEqual(report['actions'][0]['pointer_evidence'],
+ {'before_request': before[3], 'after_request': after[3]})
+ if inputs:
+ self.assertEqual(len(list(args.evidence.glob('pointer-agent-*.json'))), 1)
+ if failure in ('after', 'after_recovers'):
+ diagnostic = json.loads((args.evidence / 'pointer-effect-failure-agent-0.json').read_text())
+ self.assertFalse(diagnostic['replayed'])
+ self.assertEqual(len(diagnostic['samples']), 2)
+ self.assertEqual(verification.call_count, 3)
+ if failure == 'after_recovers':
+ self.assertTrue(all(row['effect']['verified'] for row in diagnostic['samples']))
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['result'], 'failed')
+ self.assertEqual(report['actions'], [])
+ if failure and failure.startswith(('helper_', 'deadline_')):
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['result'], 'failed')
+ self.assertIn('primary grab', report['error'])
+ self.assertEqual(report['actions'], [])
+ for mcp in clients:
+ mcp.close.assert_called_once()
+ self.assertFalse(held[0])
+
+
+class ResponseTests(unittest.TestCase):
+ def test_common_policy_refusal_uses_existing_envelope_not_invented_action_fields(self):
+ result = {'isError': True, 'structuredContent': {'status': 'refused',
+ 'refusal': {'code': 'bounded_resource_outside_manifest', 'message': 'out of scope'}}}
+ check_response(result, {'kind': 'refused', 'reason': 'bounded_resource_outside_manifest'})
+ with self.assertRaises(AssertionError):
+ check_response(result, {'kind': 'refused', 'reason': 'permission_denied'})
+
+ def test_dispatched_does_not_mean_verified_app_effect(self):
+ response = {'structuredContent': {'route': 'synthetic_events', 'effect': 'unverifiable',
+ 'delivery': {'mode': 'background'}}}
+ checked = check_response(response, {'kind': 'dispatched'})
+ self.assertFalse(checked['app_effect_verified'])
+ for change in ({'effect': 'partial'}, {'effect': 'suspected_noop'},
+ {'delivery': {'mode': 'unknown'}}, {'route': 'global_input'}):
+ with self.assertRaises(AssertionError):
+ check_response({'structuredContent': {**response['structuredContent'], **change}},
+ {'kind': 'dispatched'})
+
+ def test_refusal_requires_exact_reason_and_absent_delivery(self):
+ content = {'effect': 'refused', 'reason': 'permission_denied'}
+ expected = {'kind': 'refused', 'reason': 'permission_denied'}
+ check_response({'isError': True, 'structuredContent': content}, expected)
+ for change in ({'reason': 'unsupported'}, {'effect': 'partial'},
+ {'delivery': {'mode': 'unknown', 'delivered_count': 0}}):
+ with self.assertRaises(AssertionError):
+ check_response({'isError': True, 'structuredContent': {**content, **change}}, expected)
+
+ def test_partial_and_unknown_are_explicit_not_success_relabels(self):
+ content = {'route': 'synthetic_events', 'effect': 'partial',
+ 'delivery': {'mode': 'unknown', 'delivered_count': 2}}
+ for kind in ('partial', 'unknown'):
+ self.assertEqual(check_response({'isError': True, 'structuredContent': content},
+ {'kind': kind})['expected'], kind)
+ with self.assertRaises(AssertionError):
+ check_response({'structuredContent': {**content, 'delivery': {'mode': 'background'}}},
+ {'kind': 'partial'})
+
+ def test_no_dispatch_rejects_press_without_completion(self):
+ before = {**trace(START), 'active': True}
+ assert_no_dispatch(before, copy.deepcopy(before))
+ for kind in ('pointer_button', 'agent_admitted', 'agent_approved', 'agent_drag_start'):
+ after = {**trace(START, (kind, 100, 200, 1, 1)), 'active': True}
+ with self.assertRaises(AssertionError):
+ assert_no_dispatch(before, after)
+
+ def test_no_dispatch_rejects_missing_or_changed_telemetry(self):
+ before = {**trace(START), 'active': True}
+ for change in ({'hook': False}, {'overflow': True}, {'timed_out': True},
+ {'count': 2}, {'active': False}, {'events': []}):
+ with self.assertRaises(AssertionError):
+ assert_no_dispatch(before, {**before, **change})
+
+
+class OutputTests(unittest.TestCase):
+ def test_svg_asserts_saved_translation_and_rejects_resize(self):
+ before = b'<svg><rect id="shape" x="1" y="2" width="3" height="4"/></svg>'
+ after = b'<svg><rect id="shape" x="11" y="32" width="3" height="4"/></svg>'
+ oracle = {'agent': 1, 'path': 'drawing.svg', 'xpath': './rect',
+ 'rect_translation': [[10, 10], [30, 30]]}
+ self.assertTrue(verify_output(before, after, oracle)['verified'])
+ for invalid in (before, after.replace(b'width="3"', b'width="5"')):
+ with self.assertRaises(AssertionError):
+ verify_output(before, invalid, oracle)
+
+ def test_calc_can_use_independently_read_ods_content(self):
+ def ods(value):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, 'w') as archive:
+ archive.writestr('content.xml', f'<sheet><cell value="{value}"/></sheet>')
+ return stream.getvalue()
+ oracle = {'agent': 0, 'path': 'sheet.ods', 'zip_member': 'content.xml',
+ 'xpath': './cell', 'attributes': {'value': '96'}}
+ self.assertTrue(verify_output(ods(1), ods(96), oracle)['verified'])
+ with self.assertRaises(AssertionError):
+ verify_output(ods(1), ods(75), oracle)
+
+
+def motion_command(sequence, point, command_ns=1, ack_ns=2):
+ x, y = point
+ return {'sequence': sequence, 'x': x, 'y': y, 'command_ns': command_ns,
+ 'ack_ns': ack_ns, 'acknowledgement': f'MOVED {x} {y}\n'}
+
+
+class MovingPrimaryTests(unittest.TestCase):
+ def test_entire_square_must_fit_inside_foreground_and_desktop(self):
+ bounds = {'x': 0, 'y': 0, 'width': 600, 'height': 600}
+ desktop = {'screen_width': 800, 'screen_height': 800}
+ route = primary_trajectory(bounds, [100, 200], desktop)
+ self.assertEqual(len(route), 32)
+ self.assertEqual(route[0], [120, 200])
+ self.assertEqual(route[-1], [100, 200])
+ for point in ([450, 200], [100, 450], [-1, 200]):
+ with self.assertRaises(AssertionError):
+ primary_trajectory(bounds, point, desktop)
+ with self.assertRaisesRegex(AssertionError, 'desktop'):
+ primary_trajectory({**bounds, 'x': 700}, [100, 200], desktop)
+
+ def test_moving_endpoints_allow_only_cursor_change(self):
+ before = {'pid': 10, 'address': '0x10', 'workspace': 1, 'cursor': {'x': 100, 'y': 200}}
+ after = {**before, 'cursor': {'x': 120, 'y': 200}}
+ assert_primary_state(before, after, True)
+ with self.assertRaises(AssertionError):
+ assert_primary_state(before, after, False)
+ for key in ('pid', 'address', 'workspace'):
+ with self.assertRaises(AssertionError):
+ assert_primary_state(before, {**after, key: 'changed'}, True)
+
+ def test_missing_malformed_incomplete_and_reordered_logs_fail(self):
+ route = [[120, 200], [140, 200]]
+ commands = [motion_command(1, route[0]), motion_command(2, route[1], 3, 4)]
+ self.assertEqual(expected_primary_motion(commands, route), route)
+ malformed = [None, [], {}, ['bad'], commands[1:], list(reversed(commands))]
+ for change in ({'sequence': True}, {'sequence': 3}, {'x': float('nan')},
+ {'y': 300}, {'command_ns': 0}, {'ack_ns': None}, {'ack_ns': -1},
+ {'acknowledgement': None}, {'acknowledgement': 'MOVED 140 200\n'}):
+ malformed.append([{**commands[0], **change}, commands[1]])
+ for log in malformed:
+ with self.subTest(log=log), self.assertRaises(AssertionError):
+ expected_primary_motion(log, route)
+
+ def test_trace_must_match_commands_without_extra_motion_focus_or_grab_changes(self):
+ route = [[120, 200], [100, 200]]
+ commands = [motion_command(1, route[0]), motion_command(2, route[1], 3, 4)]
+ expected = expected_primary_motion(commands, route)
+ events = [('cursor', *point, 0, 0) for point in route]
+ self.assertEqual(analyze(trace(START, *events, STOP), expected_motion=expected)['result'], 'passed')
+ bad_events = [events[:1], list(reversed(events)),
+ [events[0], ('cursor', 150, 200, 0, 0), *events[1:]]]
+ for kind in ('pointer_focus', 'keyboard_focus', 'pointer_button', 'pointer_axis', 'keyboard_key'):
+ bad_events.append([events[0], (kind, 120, 200, 0, 0), events[1]])
+ for rows in bad_events:
+ self.assertEqual(analyze(trace(START, *rows, STOP), expected_motion=expected)['result'], 'failed')
+ self.assertEqual(analyze({**trace(START, *events, STOP), 'overflow': True},
+ expected_motion=expected)['result'], 'inconclusive')
+
+ def test_acknowledgement_rejects_timeout_eof_partial_and_oversized_lines(self):
+ stream = Mock()
+ for chunks, readiness in (([b''], [[stream]]), ([b'MOVED 120'], [[stream], []]),
+ ([b'x' * 128, b'x\n'], [[stream], [stream]])):
+ with patch('production_realapp_proof.os.read', side_effect=chunks), \
+ patch('production_realapp_proof.select.select', side_effect=[(r, [], []) for r in readiness]), \
+ self.assertRaises(AssertionError):
+ primary_acknowledgement(stream)
+ with patch('production_realapp_proof.os.read', side_effect=[b'MOVED ', b'120 200\n']), \
+ patch('production_realapp_proof.select.select', return_value=([stream], [], [])):
+ self.assertEqual(primary_acknowledgement(stream), 'MOVED 120 200\n')
+
+ def test_independent_stream_retains_each_command_and_requires_exact_ack(self):
+ for acknowledgement in ('MOVED 120 200\n', 'MOVED 999 200\n', 'MOVED 120 200\nextra\n'):
+ commands, grab, ready = [], Mock(), Mock()
+ done = Mock(wait=Mock(side_effect=[False, True]))
+ with patch('production_realapp_proof.primary_acknowledgement', return_value=acknowledgement):
+ if acknowledgement == 'MOVED 120 200\n':
+ move_primary(grab, [[120, 200]], done, ready, commands, Mock())
+ self.assertEqual(expected_primary_motion(commands, [[120, 200]]), [[120, 200]])
+ ready.set.assert_called_once()
+ else:
+ with self.assertRaisesRegex(AssertionError, 'malformed'):
+ move_primary(grab, [[120, 200]], done, ready, commands, Mock())
+ ready.set.assert_not_called()
+ grab.stdin.write.assert_called_once_with('MOVE 120 200\n')
+ grab.stdin.flush.assert_called_once()
+ self.assertEqual(commands[0]['acknowledgement'], acknowledgement)
+
+ def test_no_trace_fails_before_provenance_or_process_launch(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source_plan = root / 'plan.json'
+ source_plan.write_text(json.dumps({**plan(), 'moving_primary': True}))
+ args = SimpleNamespace(plan=source_plan, evidence=root / 'evidence', trace_socket=None)
+ with patch('production_realapp_proof.provenance') as provenance, \
+ patch('production_realapp_proof.subprocess.Popen') as spawn:
+ self.assertEqual(run(args), 1)
+ provenance.assert_not_called()
+ spawn.assert_not_called()
+ result = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(result['result'], 'failed')
+ self.assertEqual(result['error'], 'moving primary requires continuous trace')
+ self.assertEqual(result['continuous_isolation'], 'unproven')
+
+ def test_runner_uses_acknowledged_motion_and_brackets_background_action(self):
+ # Exercise orchestration without a compositor, Driver process, or GUI.
+ for during_action, failure in ((True, None), (False, None), (True, 'ack'),
+ (True, 'join'), (True, 'action'), (True, 'startup'),
+ (True, 'late_ack'), (True, 'motion')):
+ with self.subTest(during_action=during_action, failure=failure), \
+ tempfile.TemporaryDirectory() as directory, ExitStack() as stack:
+ root = Path(directory)
+ bounds = {'x': 0, 'y': 0, 'width': 600, 'height': 600}
+ spec = {'target': {'pid': 20, 'window_id': 200}, 'bounds': bounds,
+ 'name': 'agent', 'profile': {'mode': 'standard'}}
+ source_plan = root / 'plan.json'
+ source_plan.write_text(json.dumps({
+ 'purpose': 'policy', 'moving_primary': True, 'primary_point': [100, 200],
+ 'foreground': {'pid': 10, 'window_id': 100}, 'agents': [spec],
+ 'phases': [{'agent': 0, 'tool': 'click', 'arguments': {'x': 10, 'y': 20},
+ 'expect': {'kind': 'refused', 'reason': 'permission_denied'}}]}))
+ args = SimpleNamespace(plan=source_plan, evidence=root / 'evidence',
+ trace_socket=root / 'cua-input-v3.sock', driver=root / 'driver',
+ primary_grab=root / 'primary-grab', foreground_journal=root / 'journal',
+ record_video=False)
+ log, action_calls, held = [], [], [True]
+
+ def append_motion(point):
+ now = time.monotonic_ns()
+ log.append(motion_command(len(log) + 1, point, now, now))
+
+ def movement(grab, trajectory, done, ready, commands, mark):
+ nonlocal log
+ log = commands
+ append_motion([120, 200])
+ if failure == 'motion':
+ raise RuntimeError('movement failed')
+ ready.set()
+
+ def tool(name, arguments):
+ if name == 'get_window_state':
+ action_calls.append('snapshot')
+ return {'structuredContent': {'screenshot_width': 600, 'window_bounds': bounds}}
+ if name == 'get_desktop_state':
+ return {'structuredContent': {'screen_width': 800, 'screen_height': 800}}
+ if name == 'click':
+ action_calls.append('click')
+ self.assertEqual(arguments['delivery_mode'], 'background')
+ if during_action:
+ append_motion([140, 200])
+ if failure == 'ack':
+ log[-1]['acknowledgement'] = None
+ if failure == 'late_ack':
+ log[-1]['ack_ns'] += 1_000_000_000_000
+ if failure == 'action':
+ raise RuntimeError('transport failed')
+ return {'isError': True, 'structuredContent': {
+ 'effect': 'refused', 'reason': 'permission_denied'}}
+ return {'structuredContent': {}}
+
+ agent = Mock(process=Mock(pid=11, poll=Mock(return_value=None)))
+ observer = Mock()
+ agent.tool.side_effect = observer.tool.side_effect = tool
+ grab = Mock(stdout=io.StringIO('HELD\n'), poll=Mock(return_value=None))
+ trace_client = Mock(hello={'protocol': 3})
+ initial = ('cursor', 120, 200, 0, 0)
+ final = ('cursor', 140, 200, 0, 0)
+ events = [initial, final] if during_action else [initial]
+ trace_client.collect.side_effect = [
+ {**trace(START, initial), 'active': True},
+ {**trace(START, *events), 'active': True},
+ trace(START, *events, ('stop', *events[-1][1:3], 0, 0))]
+
+ workers = []
+ def thread(target, daemon):
+ self.assertTrue(daemon)
+ worker = Mock(is_alive=Mock(side_effect=lambda: failure == 'join' and held[0]))
+ worker.start.side_effect = target
+ workers.append(worker)
+ return worker
+
+ replacements = {
+ 'provenance': Mock(return_value={}),
+ 'DirectMCP': Mock(side_effect=[agent, observer]),
+ 'subprocess.Popen': Mock(return_value=grab),
+ 'primary_acknowledgement': Mock(side_effect=AssertionError('incomplete HELD'))
+ if failure == 'startup' else Mock(return_value='HELD\n'),
+ 'select.select': Mock(return_value=([grab.stdout], [], [])),
+ 'wait_for': lambda predicate: self.assertTrue(predicate()),
+ 'state': lambda path: {'held': held[0], 'clicks': 0, 'keys': 0, 'scroll': 0},
+ 'wm': lambda: {'pid': 10, 'address': '0x10', 'workspace': 1,
+ 'cursor': {'x': log[-1]['x'] if log else 100, 'y': 200}},
+ 'Trace': Mock(return_value=trace_client), 'threading.Thread': thread,
+ 'move_primary': movement, 'stop_process': lambda process: held.__setitem__(0, False),
+ }
+ for name, replacement in replacements.items():
+ stack.enter_context(patch('production_realapp_proof.' + name, replacement))
+ self.assertEqual(run(args), 0 if during_action and failure is None else 1)
+ if failure not in ('startup', 'motion'):
+ click_index = action_calls.index('click')
+ self.assertEqual(action_calls[click_index - 1:click_index + 2], ['snapshot', 'click', 'snapshot'])
+ self.assertIn('controlled', replacements['subprocess.Popen'].call_args.args[0])
+ report = json.loads((args.evidence / 'result.json').read_text())
+ if during_action and failure is None:
+ self.assertEqual(report['continuous_isolation'], 'passed')
+ self.assertEqual(report['primary_commands_during_actions'], 1)
+ self.assertEqual(json.loads((args.evidence / 'expected-primary-motion.json').read_text()),
+ [[120, 200], [140, 200]])
+ self.assertEqual(report['actions'][0]['no_dispatch'], 'verified')
+ else:
+ self.assertEqual(report['continuous_isolation'], 'unproven')
+ self.assertEqual(json.loads((args.evidence / 'primary-motion-commands.json').read_text()), log)
+ self.assertFalse(held[0])
+ agent.close.assert_called_once()
+ observer.close.assert_called_once()
+ if failure != 'startup':
+ trace_client.close.assert_called_once()
+ workers[0].join.assert_called_with(timeout=3)
+ self.assertEqual(workers[0].join.call_count, 2)
+ if failure == 'join':
+ cleanup = json.loads((args.evidence / 'cleanup.json').read_text())
+ self.assertIn('stop_primary_motion', [row['operation'] for row in cleanup['errors']])
+ self.assertFalse(workers[0].is_alive())
+
+
+class RuntimeTests(unittest.TestCase):
+ def test_profiles_keep_managed_policy_and_remove_inherited_approval(self):
+ inherited = {'CUA_DRIVER_PERMISSION_MODE': 'unrestricted',
+ 'CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS': '1',
+ 'CUA_DRIVER_SESSION_POLICY_FILE': 'old-manifest',
+ 'CUA_DRIVER_CAPABILITY_MANIFEST_APPROVED': '1',
+ 'CUA_DRIVER_MANAGED_POLICY_FILE': 'managed.yaml'}
+ env = profile_environment({'mode': 'standard'}, inherited)
+ self.assertEqual(env, {'CUA_DRIVER_PERMISSION_MODE': 'standard',
+ 'CUA_DRIVER_MANAGED_POLICY_FILE': 'managed.yaml'})
+
+ def test_profile_matrix_uses_normal_environment_contract(self):
+ with tempfile.NamedTemporaryFile() as manifest:
+ for mode in ('standard', 'bounded', 'unrestricted'):
+ profile = {'mode': mode, 'manifest': manifest.name, 'approve_manifest': True,
+ 'acknowledge_unrestricted': True}
+ env = profile_environment(profile, {})
+ self.assertEqual(env['CUA_DRIVER_PERMISSION_MODE'], mode)
+ self.assertEqual(env['CUA_DRIVER_CAPABILITY_MANIFEST_APPROVED'], '1')
+ for mode in ('standard', 'unrestricted'):
+ profile_environment({'mode': mode, 'acknowledge_unrestricted': True}, {})
+ for profile in ({'mode': 'bounded'}, {'mode': 'unrestricted'},
+ {'mode': 'standard', 'manifest': 'unreviewed.yaml'}):
+ with self.assertRaises(AssertionError):
+ profile_environment(profile, {})
+
+ def test_distinct_labels_are_not_process_ownership(self):
+ def client(pid):
+ return SimpleNamespace(process=Mock(pid=pid, poll=Mock(return_value=None)))
+ self.assertEqual(assert_distinct_runtimes([client(1), client(2)]), [1, 2])
+ with self.assertRaises(AssertionError):
+ assert_distinct_runtimes([client(1), client(1)])
+
+ def test_owned_process_is_reaped_after_terminate_timeout(self):
+ process = Mock()
+ process.poll.return_value = None
+ process.wait.side_effect = [subprocess.TimeoutExpired('child', 5),
+ subprocess.TimeoutExpired('child', 5), 0]
+ stop_process(process)
+ process.stdin.close.assert_called_once()
+ process.terminate.assert_called_once()
+ process.kill.assert_called_once()
+ self.assertEqual(process.wait.call_count, 3)
+
+ def test_initialization_failure_closes_owned_process(self):
+ process = Mock()
+ process.poll.return_value = 0
+ with tempfile.TemporaryDirectory() as directory, \
+ patch('production_mcp.subprocess.Popen', return_value=process) as spawn, \
+ patch('driver_input_live.MCP.rpc', side_effect=TimeoutError('unknown')):
+ with self.assertRaises(TimeoutError):
+ DirectMCP(Path('/synthetic/driver'), Path(directory), {'mode': 'standard'})
+ self.assertEqual(spawn.call_args.args[0], ['/synthetic/driver', 'mcp', '--direct'])
+ process.wait.assert_called_once()
+
+ def test_timeout_poison_prevents_replay(self):
+ mcp = DirectMCP.__new__(DirectMCP)
+ mcp.failed = mcp.closed = False
+ with patch('driver_input_live.MCP.rpc', side_effect=TimeoutError('unknown')) as rpc:
+ with self.assertRaises(TimeoutError):
+ mcp.rpc('tools/call', {})
+ with self.assertRaisesRegex(RuntimeError, 'do not replay'):
+ mcp.rpc('tools/call', {})
+ rpc.assert_called_once()
+
+ def test_unrestricted_direct_launch_uses_environment_not_serve_only_flags(self):
+ process = Mock()
+ process.poll.return_value = 0
+ with tempfile.TemporaryDirectory() as directory, \
+ patch('production_mcp.subprocess.Popen', return_value=process) as spawn, \
+ patch('driver_input_live.MCP.rpc', return_value={}):
+ mcp = DirectMCP(Path('/synthetic/driver'), Path(directory),
+ {'mode': 'unrestricted', 'acknowledge_unrestricted': True})
+ mcp.close()
+ self.assertEqual(spawn.call_args.args[0], [
+ '/synthetic/driver', 'mcp', '--direct'])
+ self.assertEqual(spawn.call_args.kwargs['env']['CUA_DRIVER_PERMISSION_MODE'], 'unrestricted')
+ self.assertEqual(spawn.call_args.kwargs['env']['CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS'], '1')
+
+ def test_preflight_failure_is_retained_as_failure(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ import json
+ source_plan = root / 'plan.json'
+ source_plan.write_text(json.dumps(plan()))
+ args = SimpleNamespace(plan=source_plan, evidence=root / 'evidence')
+ with patch('production_realapp_proof.provenance', side_effect=AssertionError('SHA mismatch')):
+ self.assertEqual(run(args), 1)
+ result = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(result['result'], 'failed')
+ self.assertEqual(result['error'], 'SHA mismatch')
+ self.assertTrue((args.evidence / 'cleanup.json').is_file())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.py
new file mode 100644
index 0000000000..58198ed0ed
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.py
@@ -0,0 +1,589 @@
+"""TEST ONLY: production v3 DPMS fault proof in one explicitly selected guest.
+
+Use the geometry proof's CLI flags. Plan: purpose=session_fault,
+disposable=true, fault={kind:dpms}, vm={machine_id,boot_id}, compositor with
+pid,instance,uid,starttime,exe, foreground, primary_point, package_versions,
+one Calc pointer agent and recovery={pointer_stage:click_b2|click_a1} as in
+production_geometry_fault_proof. identities={foreground,target} contains exact
+/proc identities (pid,uid,starttime,exe). foreground_fixture={sha256,journal}
+binds the repository isolated-input/main.py hash and its journal's canonical
+path,device,inode,uid. monitors is the exact list returned by monitor_identity.
+The foreground process must run that source fixture with --actor Foreground.
+
+Every mutation is test-owned IPC; normal Driver alone supplies app input.
+The 20-second independent watchdog wakes only this disposable test desktop.
+Watchdog restoration is emergency cleanup, never successful proof. Success
+requires cancellation and own-seat release before explicit test restoration,
+a fresh Driver action refused with session_unavailable and zero dispatch while
+off, then a new runtime, fresh screenshot and successful new action after on.
+DPMS is expected to change only monitor power and desktop generations: no
+primary cursor, focus, held-button or input exceptions are suppressed.
+
+Lock is deliberately unsupported: its real primary focus/grab transitions
+need a separately qualified oracle. A lock request fails preflight, never
+becomes a skipped/passing row. Portable tests are not native certification.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+import fcntl
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import select
+import socket
+import stat
+import struct
+import subprocess
+import sys
+import time
+
+from desktop_faults import _identity, _same_compositor, _hypr, _dpms_dispatch
+from driver_input_live import state, wait_for, wm
+from primary_trace import Trace, analyze
+from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, active_drags, call_drag,
+ close_owned, grounded_snapshot, poll_active, prepare_drag, stopped_prefix, verify_recovery_cleanup)
+from production_desktop_fault_proof import guest_identity, idle_lanes, verify_status
+from production_geometry_fault_proof import recover, fault_outcome, validate_plan as geometry_plan
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity, check_response,
+ primary_acknowledgement, provenance, require_primary_active, trace_interval)
+from realapp_proof import cleanup_all, released_synthetic_input
+
+
+WATCHDOG_SECONDS = 20
+PROCESS_KEYS = {'pid', 'uid', 'starttime', 'exe'}
+MONITOR_KEYS = ('id', 'name', 'width', 'height', 'x', 'y', 'scale', 'transform')
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'session_fault' and plan['fault'] == {'kind': 'dpms'}, \
+ 'only DPMS is qualified; session-lock primary transition oracle is unsupported'
+ bounds = plan['agents'][0]['bounds']
+ geometry_plan({**plan, 'purpose': 'geometry_fault',
+ 'compositor': {key: plan['compositor'][key] for key in ('pid', 'instance')},
+ 'fault': {'kind': 'move', 'to': [bounds['x'] + 1, bounds['y']]}})
+ assert plan['agents'][0]['app'] == 'calc', 'only the qualified synthetic Calc episode is supported'
+ assert set(plan['vm']) == {'machine_id', 'boot_id'}
+ assert re.fullmatch(r'[0-9a-f]{32}', plan['vm']['machine_id'])
+ assert re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', plan['vm']['boot_id'])
+ assert set(plan['compositor']) == PROCESS_KEYS | {'instance'}
+ assert set(plan['identities']) == {'foreground', 'target'}
+ for identity in [*plan['identities'].values(),
+ {key: plan['compositor'][key] for key in PROCESS_KEYS}]:
+ assert set(identity) == PROCESS_KEYS
+ assert type(identity['pid']) is int and identity['pid'] > 1
+ assert type(identity['uid']) is int and identity['uid'] >= 0
+ assert re.fullmatch(r'[0-9]+', identity['starttime'])
+ assert Path(identity['exe']).is_absolute()
+ assert Path(plan['compositor']['exe']).name == 'Hyprland'
+ assert plan['identities']['target']['pid'] == plan['agents'][0]['target']['pid']
+ assert plan['identities']['foreground']['pid'] == plan['foreground']['pid']
+ fixture = plan['foreground_fixture']
+ assert set(fixture) == {'sha256', 'journal'} and re.fullmatch(r'[0-9a-f]{64}', fixture['sha256'])
+ journal = fixture['journal']
+ assert set(journal) == {'path', 'device', 'inode', 'uid'} and Path(journal['path']).is_absolute()
+ assert all(type(journal[key]) is int and journal[key] >= 0 for key in ('device', 'inode', 'uid'))
+ assert plan['monitors'] == monitor_identity([{**row, 'dpmsStatus': True} for row in plan['monitors']])
+
+
+def monitor_identity(rows):
+ """Bind all outputs; never wake a newly attached, unreviewed output."""
+ assert rows and len({r['name'] for r in rows}) == len(rows), 'missing or duplicate monitors'
+ result = []
+ for row in rows:
+ assert type(row.get('dpmsStatus')) is bool, 'compositor does not expose DPMS acknowledgement'
+ assert isinstance(row.get('name'), str) and row['name']
+ assert all(type(row.get(k)) is int for k in ('id', 'width', 'height', 'x', 'y', 'transform'))
+ assert row['width'] > 0 and row['height'] > 0 and row['id'] >= 0
+ assert type(row.get('scale')) in (int, float) and 0 < row['scale'] <= 8
+ result.append({key: row[key] for key in MONITOR_KEYS})
+ return sorted(result, key=lambda row: row['name'])
+
+
+def guard_guest(config):
+ assert platform.system() == 'Linux' and guest_identity() == config['vm'], 'wrong disposable VM or boot'
+ assert config['disposable'] is True
+ assert subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode == 0, 'VM required'
+ assert os.environ.get('HYPRLAND_INSTANCE_SIGNATURE') == config['instance'], 'wrong compositor session'
+ assert config['compositor']['uid'] == os.getuid()
+ assert Path(config['compositor']['exe']).name == 'Hyprland'
+ _same_compositor(config['compositor'], config['instance'])
+
+
+def power(config, expected=None):
+ rows = json.loads(_hypr(config['instance'], '-j', 'monitors', 'all'))
+ assert monitor_identity(rows) == config['monitors'], 'reviewed monitor identity or geometry changed'
+ if expected is not None:
+ assert all(row['dpmsStatus'] is expected for row in rows), 'DPMS state not acknowledged'
+ return rows
+
+
+def production_status(config):
+ return verify_status(json.loads(_hypr(config['instance'], '-j', 'cua:status')), True)
+
+
+def lanes(status, cleared=False, *, allow_passive=False):
+ verify_status(status, True)
+ result = {row['lane']: row for row in status['input']['lanes']}
+ for row in result.values():
+ assert isinstance(row.get('epoch'), str) and row['epoch']
+ assert all(type(row.get(key)) is int and row[key] >= 0 for key in ('desktop_generation', 'dispatches'))
+ if cleared:
+ assert all(type(row.get(key)) is int and row[key] == 0 for key in ('held_button', 'held_keys'))
+ assert all(row.get(key) is False for key in ('drag_active', 'lease_active', 'keyboard_focus'))
+ assert type(row.get('pointer_focus')) is bool
+ if not allow_passive:
+ assert row['pointer_focus'] is False
+ return result
+
+
+def transition(before, after):
+ old, new = lanes(before), lanes(after, cleared=True)
+ for lane in old:
+ assert old[lane]['epoch'] == new[lane]['epoch'], 'compositor lane replaced'
+ assert new[lane]['desktop_generation'] > old[lane]['desktop_generation'], 'DPMS did not revoke authority'
+ assert new[lane].get('reserved') is False, 'reservation survived DPMS transition'
+
+
+@contextmanager
+def control_lock(config):
+ # One private lock serializes watchdog and controller, including the off IPC.
+ with open(config['lock_path'], 'rb') as stream:
+ info = os.fstat(stream.fileno())
+ assert [info.st_dev, info.st_ino, info.st_uid] == config['lock_identity']
+ fcntl.flock(stream, fcntl.LOCK_EX)
+ yield
+
+
+def restore_power(config, emergency=False):
+ with control_lock(config):
+ guard_guest(config)
+ record = {'started_ns': time.monotonic_ns(), 'emergency': emergency, 'result': 'unproven'}
+ before = power(config)
+ # A marker prevents an expired watchdog from being followed by new off IPC.
+ Path(config['restored_path']).touch(exist_ok=True)
+ assert _hypr(config['instance'], 'dispatch', _dpms_dispatch('on')) == 'ok', 'DPMS restoration refused'
+ def restored():
+ rows = power(config)
+ return rows if all(row['dpmsStatus'] is True for row in rows) else None
+ record.update(before=before, after=wait_for(restored, timeout=2), status=production_status(config),
+ observed_ns=time.monotonic_ns(), result='restored')
+ return record
+
+
+def watchdog(config, reader):
+ """Independent child restores at deadline or controller EOF, never app input."""
+ print('ARMED', flush=True)
+ delay = max(0, (config['deadline_ns'] - time.monotonic_ns()) / 1_000_000_000)
+ ready = select.select([reader], [], [], delay)[0]
+ if ready and os.read(reader, 1) == b'C':
+ return
+ try:
+ record = restore_power(config, emergency=True)
+ except Exception as error:
+ record = {'result': 'failed', 'error': str(error), 'emergency': True}
+ Path(config['watchdog_path']).write_text(json.dumps(record))
+
+
+class SessionFault:
+ def __init__(self, plan, args):
+ self.plan, self.args = plan, args
+ self.config = {'disposable': plan['disposable'], 'vm': plan['vm'],
+ 'compositor': {key: plan['compositor'][key] for key in PROCESS_KEYS},
+ 'instance': plan['compositor']['instance'], 'monitors': plan['monitors']}
+ self.child = self.cancel_fd = None
+ self.mutated = False
+ self.record = {'result': 'unproven', 'kind': 'dpms'}
+ self.check_targets()
+ power(self.config, True)
+ self.record['before'] = production_status(self.config)
+ (args.evidence / 'pre-fault-status.json').write_text(json.dumps(self.record['before']))
+ idle_lanes(self.record['before'])
+
+ def check_targets(self):
+ guard_guest(self.config)
+ spec = self.plan['agents'][0]
+ for identity in self.plan['identities'].values():
+ assert identity['uid'] == os.getuid() and _identity(identity['pid']) == identity, 'process identity changed'
+ app_process_identity('calc', spec['target']['pid'])
+ fixture = self.args.source / 'libs/cua-driver/tests/fixtures/apps/linux/isolated-input/main.py'
+ assert fixture.resolve(strict=True) == fixture, 'canonical source fixture required'
+ assert hashlib.sha256(fixture.read_bytes()).hexdigest() == self.plan['foreground_fixture']['sha256']
+ argv = [x.decode() for x in Path(f'/proc/{self.plan["foreground"]["pid"]}/cmdline').read_bytes().split(b'\0') if x]
+ assert len(argv) == 6 and Path(argv[1]).resolve(strict=True) == fixture, 'wrong foreground fixture command'
+ assert argv[2:4] == ['--actor', 'Foreground'] and argv[4] == '--journal'
+ journal = self.plan['foreground_fixture']['journal']
+ path = self.args.foreground_journal
+ assert str(path) == journal['path'] == argv[5] and path.resolve(strict=True) == path
+ info = path.lstat()
+ assert stat.S_ISREG(info.st_mode) and [info.st_dev, info.st_ino, info.st_uid] == [journal[k] for k in ('device', 'inode', 'uid')]
+ windows = json.loads(_hypr(self.config['instance'], '-j', 'clients'))
+ for target in (spec['target'], self.plan['foreground']):
+ selected = [w for w in windows if w.get('pid') == target['pid']]
+ assert len(selected) == 1 and selected[0].get('xwayland') is False
+ assert int(selected[0]['address'], 16) == target['window_id'], 'target window changed'
+ if target == spec['target']:
+ assert 'cua-smoke-calc' in selected[0].get('title', ''), 'wrong synthetic Calc document'
+ assert dict(zip(('x', 'y', 'width', 'height'), [*selected[0]['at'], *selected[0]['size']])) == spec['bounds']
+
+ def arm(self):
+ assert self.child is None, 'watchdog already armed'
+ root = self.args.evidence.resolve(strict=True)
+ lock = root / 'dpms-control.lock'
+ with lock.open('xb'):
+ pass
+ info = lock.stat()
+ self.config.update(lock_path=str(lock), lock_identity=[info.st_dev, info.st_ino, info.st_uid],
+ restored_path=str(root / 'dpms-restored'), watchdog_path=str(root / 'watchdog.json'),
+ deadline_ns=time.monotonic_ns() + WATCHDOG_SECONDS * 1_000_000_000)
+ reader, self.cancel_fd = os.pipe()
+ try:
+ self.child = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), '--watchdog',
+ json.dumps(self.config), str(reader)], pass_fds=(reader,), stdout=subprocess.PIPE,
+ text=True, start_new_session=True)
+ assert select.select([self.child.stdout], [], [], 2)[0] and self.child.stdout.readline() == 'ARMED\n', 'watchdog did not arm'
+ finally:
+ os.close(reader)
+
+ def live_deadline(self):
+ assert self.child and self.child.poll() is None, 'watchdog exited early'
+ assert time.monotonic_ns() + 1_000_000_000 < self.config['deadline_ns'], 'watchdog deadline too near'
+ assert not Path(self.config['restored_path']).exists(), 'watchdog already restored'
+
+ def inject(self, trace, initial, pending, guard):
+ with control_lock(self.config):
+ self.check_targets()
+ self.record['monitors_before'] = power(self.config, True)
+ self.record['gate_status'] = production_status(self.config)
+ page, active = poll_active(trace, initial, None, [pending])
+ lane = next(iter(active))
+ assert set(active) == {lane}
+ guard()
+ self.live_deadline()
+ assert not pending.done(), 'drag finished before fault'
+ requested = time.monotonic_ns()
+ assert 0 <= requested - page['events'][-1][1] <= 250_000_000, 'stale active drag gate'
+ self.record.update(prefix=page, lane=lane, requested_ns=requested,
+ watchdog_deadline_ns=self.config['deadline_ns'])
+ self.mutated = True # Lost IPC reply may still mean power changed.
+ assert _hypr(self.config['instance'], 'dispatch', _dpms_dispatch('off')) == 'ok', 'DPMS-off dispatcher unsupported'
+ self.record['acknowledged_ns'] = time.monotonic_ns()
+ def off():
+ rows = power(self.config)
+ return rows if all(row['dpmsStatus'] is False for row in rows) else None
+ self.record['monitors_off'] = wait_for(off, timeout=2)
+ self.record.update(after=production_status(self.config), observed_ns=time.monotonic_ns(), result='observed')
+ transition(self.record['gate_status'], self.record['after'])
+ guard()
+ return lane
+
+ def unavailable(self):
+ self.check_targets()
+ self.live_deadline()
+ return power(self.config, False)
+
+ def restore(self):
+ if not self.mutated:
+ return {'result': 'not_needed'}
+ result = restore_power(self.config)
+ self.mutated = False
+ # Explicit restoration has ended the fault. Reap the watchdog before
+ # slow app observation/recovery can reach its former wake deadline.
+ self.close()
+ return result
+
+ def close(self):
+ # Cancel only after observed restoration. Otherwise EOF triggers recovery.
+ if self.cancel_fd is not None:
+ if not self.mutated:
+ try:
+ os.write(self.cancel_fd, b'C')
+ except BrokenPipeError:
+ pass
+ os.close(self.cancel_fd)
+ self.cancel_fd = None
+ if self.child:
+ self.child.wait(timeout=10)
+ assert self.child.returncode == 0, 'watchdog failed'
+ self.child.stdout.close()
+ self.child = None
+
+
+def verify_cancelled(boundary, record, action):
+ assert record['result'] == 'observed'
+ prefix, lane = record['prefix'], record['lane']
+ assert set(active_drags(prefix)) == {lane}
+ assert prefix['events'][-1][1] <= record['requested_ns'] <= record['acknowledged_ns'] <= record['observed_ns']
+ assert record['requested_ns'] - prefix['events'][-1][1] <= 250_000_000
+ assert record['observed_ns'] < record['watchdog_deadline_ns'], 'fault outlived watchdog deadline'
+ assert monitor_identity(record['monitors_before']) == monitor_identity(record['monitors_off'])
+ assert all(row['dpmsStatus'] is True for row in record['monitors_before'])
+ assert all(row['dpmsStatus'] is False for row in record['monitors_off']), 'DPMS-off not observed'
+ tail = [row for row in trace_interval(prefix, boundary) if row[5] in (1, 2)]
+ assert all(row[5] == lane for row in tail), 'cleanup crossed lanes'
+ cancelled = [row for row in tail if row[2] == 'agent_cancel']
+ assert len(cancelled) == 1 and cancelled[0][1] >= record['requested_ns'], 'missing post-fault cancellation'
+ assert all(row[2] in ('agent_cancel', 'pointer_button', 'pointer_leave', 'keyboard_leave',
+ 'pointer_motion', 'pointer_enter') for row in tail), 'unexpected action after fault'
+ assert not any(row[2] in ('pointer_motion', 'pointer_enter') and row[0] > cancelled[0][0]
+ for row in tail), 'input continued after cancellation'
+ releases = [row for row in tail if row[2] == 'pointer_button']
+ assert len(releases) == 1 and releases[0][6] == 0 and releases[0][0] > cancelled[0][0], 'missing own-seat release'
+ isolation = analyze(stopped_prefix(boundary))
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped_prefix(boundary)), isolation
+ transition(record['gate_status'], record['after'])
+ return {'result': 'verified', 'outcome': fault_outcome(action), 'continuous_isolation': isolation}
+
+
+def verify_refusal(record):
+ assert record['outcome'] == 'response' and record['replayed'] is False
+ check_response(record['response'], {'kind': 'refused', 'reason': 'session_unavailable'})
+ assert not [row for row in trace_interval(record['trace_before'], record['trace_after']) if row[5] in (1, 2)], 'refused action emitted synthetic events'
+ before, after = lanes(record['before'], cleared=True), lanes(record['after'], cleared=True)
+ for lane in before:
+ assert all(before[lane][key] == after[lane][key] for key in ('epoch', 'desktop_generation', 'dispatches')), 'refused action dispatched or desktop changed'
+ assert record['prepared_ns'] <= record['dispatch_ns'] <= record['observed_ns'] < record['deadline_ns']
+ assert record['dispatch_ns'] - record['prepared_ns'] <= MAX_GROUNDING_AGE_NS
+ assert all(row['dpmsStatus'] is False for row in record['monitors_before'] + record['monitors_after'])
+ assert monitor_identity(record['monitors_before']) == monitor_identity(record['monitors_after'])
+ assert analyze(stopped_prefix(record['trace_after']))['result'] == 'passed'
+ return {'result': 'verified', 'reason': 'session_unavailable', 'no_dispatch': 'verified'}
+
+
+def prepare_refusal(prepared, spec, stage):
+ """Derive the refused pixel probe from the same pre-fault target image.
+
+ Both actions address this exact window, and neither uses a session-bound
+ element token. A second simultaneous AT-SPI walk of the same app adds
+ contention, not newer evidence. The refusal remains bounded by the first
+ observation's original timestamp; powered-off capture is unavailable.
+ """
+ assert spec['app'] == 'calc' and stage in ('click_a1', 'click_b2')
+ snapshot = prepared['snapshot']
+ assert prepared['target'] == spec['target']
+ assert {key: snapshot[key] for key in ('pid', 'window_id')} == spec['target']
+ assert snapshot['window_bounds'] == spec['bounds']
+ assert prepared['prepared_ns'] == snapshot['proof_observation_started_ns']
+ arguments, _ = pointer_grounding.action(
+ snapshot, pointer_grounding.read_pixels(snapshot['proof_image']), 'calc', stage)
+ return {'snapshot': snapshot, 'arguments': arguments, 'session': spec['name'] + '-unavailable',
+ 'prepared_ns': prepared['prepared_ns']}
+
+
+def prepare_actions(clients, spec, stage, save):
+ """Ground two distinct runtimes' same-window pixel actions without input."""
+ assert len(clients) == 2
+ assert_distinct_runtimes(clients)
+ prepared = prepare_drag(clients[0], spec)
+ probe = prepare_refusal(prepared, spec, stage)
+ save('drag-grounding.json', prepared)
+ save('refusal-grounding.json', probe)
+ return prepared, probe
+
+
+def refuse(client, spec, prepared, fault, trace, guard, save):
+ record = {**prepared, 'outcome': 'unknown', 'replayed': False, 'runtime_pid': client.process.pid,
+ 'deadline_ns': fault.config['deadline_ns'], 'before': production_status(fault.config),
+ 'monitors_before': fault.unavailable(), 'trace_before': trace.collect()}
+ try:
+ guard()
+ fault.live_deadline()
+ record['dispatch_ns'] = time.monotonic_ns()
+ assert 0 <= record['dispatch_ns'] - record['prepared_ns'] <= MAX_GROUNDING_AGE_NS, 'refusal grounding expired'
+ record['response'] = client.tool('click', {**prepared['arguments'], **spec['target'],
+ 'session': prepared['session'], 'delivery_mode': 'background'})
+ record['outcome'] = 'response'
+ record.update(after=production_status(fault.config), monitors_after=fault.unavailable(),
+ trace_after=trace.collect(), observed_ns=time.monotonic_ns())
+ record['verification'] = verify_refusal(record)
+ return record
+ finally:
+ save('unavailable-action.json', record)
+
+
+def connect_trace(path, config):
+ expected = Path(os.environ['XDG_RUNTIME_DIR']) / 'hypr' / config['instance'] / path.name
+ assert path.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')
+ assert path.is_absolute() and path == expected and path.resolve(strict=True) == path
+ info = path.lstat()
+ assert stat.S_ISSOCK(info.st_mode) and info.st_uid == config['compositor']['uid']
+ trace = Trace(path)
+ try:
+ peer = struct.unpack('3i', trace.socket.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
+ assert peer[:2] == (config['compositor']['pid'], config['compositor']['uid'])
+ assert trace.hello['protocol'] == 3
+ return trace
+ except BaseException:
+ trace.close()
+ raise
+
+
+def preserve_interrupted_state(observer, spec, action, restoration, guard, save):
+ """Observe the partial app state after explicit wake, before recovery input."""
+ assert restoration['result'] == 'restored' and restoration['emergency'] is False
+ assert action['replayed'] is False
+ guard()
+ snapshot = grounded_snapshot(observer, spec['target'], spec, session=False)
+ observed_ns = time.monotonic_ns()
+ assert restoration['observed_ns'] <= snapshot['proof_observation_started_ns'] <= observed_ns
+ record = {'snapshot': snapshot, 'action': action, 'replayed': False,
+ 'restoration_observed_ns': restoration['observed_ns'], 'observed_ns': observed_ns}
+ save('interrupted-state.json', record)
+ guard()
+ return record
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2))
+ report = {'result': 'failed', 'scope': 'native-session-dpms-fault', 'recovery': {'result': 'unproven'},
+ 'lock': 'unsupported_primary_transition_oracle', 'full_desktop_matrix': False, 'physical_hardware': False}
+ clients, observer, grab, trace, fault, pool, future = [], None, None, None, None, None, None
+ baseline = primary_before = deadline = prefix = None
+ def guard():
+ require_primary_active(grab, deadline)
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ return DirectMCP(args.driver, directory, PROFILE)
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ fault = SessionFault(plan, args)
+ origin = provenance(args, plan)
+ for name in ('production_session_fault_proof.py', 'production_session_fault_proof_test.py',
+ 'production_desktop_fault_proof.py', 'production_geometry_fault_proof.py',
+ 'production_cancel_proof.py', 'desktop_faults.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ save('provenance.json', origin)
+ spec = plan['agents'][0]
+ clients.append(launch('agent'))
+ clients.append(launch('refusal'))
+ observer = launch('observer')
+ report['runtime_pids'] = assert_distinct_runtimes([*clients, observer])
+ for client, name in ((clients[0], spec['name']), (clients[1], spec['name'] + '-unavailable')):
+ assert not client.tool('start_session', {'session': name}).get('isError')
+ foreground = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError')
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < foreground['width'] and 0 < y < foreground['height']
+ x, y = foreground['x'] + x, foreground['y'] + y
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid'] and baseline['held']
+ trace = connect_trace(args.trace_socket, fault.config)
+ start_ns = time.monotonic_ns()
+ trace.exchange('TRACE_START')
+ initial = trace.collect()
+ assert start_ns <= initial['events'][0][1] <= time.monotonic_ns()
+ assert not any(row[5] in (1, 2) for row in initial['events'])
+ prepared, probe = prepare_actions(clients, spec, plan['recovery']['pointer_stage'], save)
+ fault.arm()
+ guard()
+ pool = ThreadPoolExecutor(max_workers=1)
+ future = pool.submit(call_drag, clients[0], spec, prepared, guard)
+ lane = fault.inject(trace, initial, future, guard)
+ report['action'] = future.result(timeout=3)
+ save('drag-action.json', report['action'])
+ boundary = trace.collect()
+ save('fault-prefix.json', boundary)
+ report['fault'] = verify_cancelled(boundary, fault.record, report['action'])
+ report['refusal'] = refuse(clients[1], spec, probe, fault, trace, guard, save)
+ fault.unavailable()
+ restoration = fault.restore()
+ save('restoration.json', restoration)
+ assert boundary['events'][-1][1] < restoration['started_ns']
+ assert report['refusal']['observed_ns'] <= restoration['started_ns']
+ assert restoration['observed_ns'] < fault.config['deadline_ns'] and not Path(fault.config['watchdog_path']).exists(), 'watchdog recovery is not proof'
+ transition(report['refusal']['after'], restoration['status'])
+ for client in clients:
+ close_owned(client)
+ boundary = trace.collect()
+ save('pre-recovery-prefix.json', boundary)
+ report['teardown'] = verify_recovery_cleanup(report['refusal']['trace_after'], stopped_prefix(boundary))
+ preserve_interrupted_state(observer, spec, report['action'], restoration, guard, save)
+ clients.append(launch('recovery'))
+ assert clients[-1].process.pid not in report['runtime_pids'], 'reused prior runtime'
+ prefix = recover(clients[-1], observer, clients[0], spec, plan['recovery']['pointer_stage'],
+ trace, boundary, lane, guard, save, report['recovery'])
+ save('recovery-prefix.json', prefix)
+ fault.check_targets()
+ power(fault.config, True)
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = []
+ # Restore first on failure; a blocking runtime close must not delay wake.
+ if fault:
+ operations += [('preserve_fault', lambda: save('fault.json', fault.record)),
+ ('restore_dpms', lambda: save('cleanup-restoration.json', fault.restore())),
+ ('close_watchdog', fault.close)]
+ operations += [(f'close_agent_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)]
+ if future:
+ def preserve_action():
+ report['action'] = future.result(timeout=3)
+ save('drag-action.json', report['action'])
+ operations.append(('preserve_action', preserve_action))
+ if pool:
+ operations.append(('shutdown_pool', lambda: pool.shutdown(wait=False, cancel_futures=True)))
+ if trace:
+ def finish_trace():
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('trace.json', stopped)
+ guard()
+ isolation = verify_recovery_cleanup(prefix, stopped) if prefix else analyze(stopped)
+ assert isolation['result'] == 'passed' and released_synthetic_input(stopped), isolation
+ report['continuous_isolation'] = isolation
+ assert wm() == primary_before, 'primary cursor/focus/workspace changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'scroll', 'held')), current
+ guard()
+ operations += [('finish_trace', finish_trace), ('close_trace', trace.close)]
+ def release_primary():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release_primary))
+ if observer:
+ operations.append(('close_observer', lambda: close_owned(observer)))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ if not __debug__:
+ raise SystemExit('assertions must be enabled')
+ if len(sys.argv) == 4 and sys.argv[1] == '--watchdog':
+ watchdog(json.loads(sys.argv[2]), int(sys.argv[3]))
+ else:
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.py
new file mode 100644
index 0000000000..ef7da16c52
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.py
@@ -0,0 +1,500 @@
+"""Portable synthetic orchestration checks, never native DPMS/lock certification."""
+from copy import deepcopy
+from contextlib import nullcontext
+import json
+import os
+from pathlib import Path
+import tempfile
+import time
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_session_fault_proof as proof
+
+
+MONITOR = {'id': 0, 'name': 'Virtual-1', 'width': 1280, 'height': 800,
+ 'x': 0, 'y': 0, 'scale': 1.0, 'transform': 0}
+BOUNDS = {'x': 10, 'y': 20, 'width': 800, 'height': 600}
+PARTIAL = {'structuredContent': {'effect': 'partial', 'route': 'synthetic_events',
+ 'delivery': {'mode': 'background', 'delivered_count': 1}}}
+REFUSED = {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'session_unavailable'}}
+
+
+def identity(pid, exe='/usr/bin/python3'):
+ return {'pid': pid, 'uid': 1000, 'starttime': '123', 'exe': exe}
+
+
+def plan():
+ return {'purpose': 'session_fault', 'disposable': True, 'fault': {'kind': 'dpms'},
+ 'vm': {'machine_id': '1' * 32, 'boot_id': '12345678-1234-1234-1234-123456789abc'},
+ 'compositor': {**identity(50, '/usr/bin/Hyprland'), 'instance': 'test_1'},
+ 'foreground': {'pid': 10, 'window_id': 100}, 'primary_point': [20, 20],
+ 'identities': {'foreground': identity(10), 'target': identity(20, '/usr/bin/soffice.bin')},
+ 'foreground_fixture': {'sha256': 'a' * 64, 'journal': {'path': '/test/foreground.jsonl',
+ 'device': 1, 'inode': 2, 'uid': 1000}}, 'monitors': [dict(MONITOR)],
+ 'agents': [{'app': 'calc', 'name': 'session', 'target': {'pid': 20, 'window_id': 200},
+ 'bounds': dict(BOUNDS), 'pointer_stage': 'select_range', 'drag': {}}],
+ 'recovery': {'pointer_stage': 'click_b2'}}
+
+
+def status(generation=1, held=False):
+ return {'configured': True, 'transport': {'ready': True}, 'input': {
+ 'protocol': 3, 'test_only': False, 'seat_lifetime': 'compositor',
+ 'upgrade': 'desktop_restart', 'transport_ready': True,
+ 'lanes': [{'lane': lane, 'epoch': str(lane + 1) * 32, 'desktop_generation': generation,
+ 'dispatches': 0, 'held_button': 272 if held and lane == 0 else 0,
+ 'held_keys': 0, 'drag_active': held and lane == 0, 'lease_active': held and lane == 0,
+ 'pointer_focus': held and lane == 0, 'keyboard_focus': False, 'reserved': held and lane == 0}
+ for lane in (0, 1)]}}
+
+
+ACTIVE = [(0, 'start', 0, 0), (1, 'agent_admitted', 1, 0), (2, 'agent_drag_start', 1, 0),
+ (3, 'pointer_button', 1, 1), (4, 'pointer_motion', 1, 0)]
+CANCEL = ACTIVE + [(8, 'agent_cancel', 1, 0), (9, 'pointer_button', 1, 0), (10, 'pointer_leave', 1, 0)]
+
+
+def trace(rows):
+ return {'hook': True, 'active': True, 'overflow': False, 'timed_out': False, 'count': len(rows),
+ 'events': [[i + 1, ms * 1_000_000, kind, 100, 100, lane, value]
+ for i, (ms, kind, lane, value) in enumerate(rows)]}
+
+
+def fault_record():
+ return {'result': 'observed', 'prefix': trace(ACTIVE), 'lane': 1, 'requested_ns': 6_000_000,
+ 'acknowledged_ns': 7_000_000, 'observed_ns': 12_000_000,
+ 'gate_status': status(1, held=True), 'after': status(2), 'watchdog_deadline_ns': 20_000_000,
+ 'monitors_before': [{**MONITOR, 'dpmsStatus': True}],
+ 'monitors_off': [{**MONITOR, 'dpmsStatus': False}]}
+
+
+def refusal_record():
+ return {'outcome': 'response', 'replayed': False, 'response': deepcopy(REFUSED),
+ 'before': status(2), 'after': status(2), 'trace_before': trace(CANCEL), 'trace_after': trace(CANCEL),
+ 'prepared_ns': 1_000_000, 'dispatch_ns': 13_000_000, 'observed_ns': 14_000_000,
+ 'deadline_ns': 20_000_000, 'monitors_before': [{**MONITOR, 'dpmsStatus': False}],
+ 'monitors_after': [{**MONITOR, 'dpmsStatus': False}]}
+
+
+class PlanTests(unittest.TestCase):
+ def test_exact_dpms_calc_plan_only(self):
+ proof.validate_plan(plan())
+ for change in ({'disposable': False}, {'purpose': 'apps'}, {'fault': {'kind': 'lock'}},
+ {'fault': {'kind': 'dpms', 'unlock': True}}, {'monitors': []},
+ {'recovery': {'pointer_stage': 'select_range'}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.validate_plan({**plan(), **change})
+ with self.assertRaisesRegex(AssertionError, 'session-lock'):
+ proof.validate_plan({**plan(), 'fault': {'kind': 'lock'}})
+
+ def test_foreground_and_target_process_bindings_are_required(self):
+ for field, value in [('pid', 99), ('uid', -1), ('starttime', 'unknown'), ('exe', 'relative')]:
+ candidate = plan()
+ candidate['identities']['target'][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_unsupported_lock_writes_failed_result_without_native_setup(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'plan.json'
+ path.write_text(json.dumps({**plan(), 'fault': {'kind': 'lock'}}))
+ args = SimpleNamespace(plan=path, evidence=Path(directory) / 'evidence')
+ with patch.object(proof, 'SessionFault') as controller, patch('builtins.print'):
+ self.assertEqual(proof.run(args), 1)
+ controller.assert_not_called()
+ report = json.loads((args.evidence / 'result.json').read_text())
+ self.assertEqual(report['result'], 'failed')
+ self.assertIn('session-lock', report['error'])
+
+ def test_monitors_must_have_acknowledgeable_dpms_and_exact_identity(self):
+ self.assertEqual(proof.monitor_identity([{**MONITOR, 'dpmsStatus': True}]), [MONITOR])
+ for row in (MONITOR, {**MONITOR, 'dpmsStatus': 1}, {**MONITOR, 'dpmsStatus': None},
+ {**MONITOR, 'dpmsStatus': True, 'scale': float('nan')}):
+ with self.subTest(row=row), self.assertRaises(AssertionError):
+ proof.monitor_identity([row])
+ config = {'instance': 'test_1', 'monitors': [MONITOR]}
+ for row in ({**MONITOR, 'name': 'New-output', 'dpmsStatus': False},
+ {**MONITOR, 'width': 1920, 'dpmsStatus': False}, {**MONITOR, 'dpmsStatus': True}):
+ with patch.object(proof, '_hypr', return_value=json.dumps([row])), self.assertRaises(AssertionError):
+ proof.power(config, False)
+
+ def test_host_wrong_boot_or_wrong_compositor_refused(self):
+ candidate = plan()
+ config = {'disposable': True, 'vm': candidate['vm'], 'instance': 'test_1',
+ 'compositor': identity(50, '/usr/bin/Hyprland')}
+ for failure in ('host', 'boot', 'not_vm', 'session', 'process', None):
+ with self.subTest(failure=failure), \
+ patch.object(proof.platform, 'system', return_value='Darwin' if failure == 'host' else 'Linux'), \
+ patch.object(proof, 'guest_identity', return_value={} if failure == 'boot' else candidate['vm']), \
+ patch.object(proof.subprocess, 'run', return_value=SimpleNamespace(returncode=1 if failure == 'not_vm' else 0)), \
+ patch.dict(os.environ, {'HYPRLAND_INSTANCE_SIGNATURE': 'wrong' if failure == 'session' else 'test_1'}), \
+ patch.object(proof.os, 'getuid', return_value=1000), \
+ patch.object(proof, '_same_compositor', side_effect=AssertionError('changed') if failure == 'process' else None):
+ if failure:
+ with self.assertRaises(AssertionError):
+ proof.guard_guest(config)
+ else:
+ proof.guard_guest(config)
+
+
+class OracleTests(unittest.TestCase):
+ def test_constructor_accepts_inert_baseline_but_not_reserved_input(self):
+ for reserved in (False, True):
+ with self.subTest(reserved=reserved), tempfile.TemporaryDirectory() as root:
+ before = status()
+ before['input']['lanes'][1].update(pointer_focus=True, reserved=reserved)
+ args = SimpleNamespace(evidence=Path(root))
+ with patch.object(proof.SessionFault, 'check_targets'), patch.object(proof, 'power'), \
+ patch.object(proof, 'production_status', return_value=before):
+ if reserved:
+ with self.assertRaisesRegex(AssertionError, 'authority'):
+ proof.SessionFault(plan(), args)
+ else:
+ fault = proof.SessionFault(plan(), args)
+ self.assertFalse(fault.mutated)
+ self.assertIsNone(fault.child)
+ self.assertEqual(json.loads((args.evidence / 'pre-fault-status.json').read_text()), before)
+
+ def test_passive_recovery_does_not_relax_transition_or_held_state_checks(self):
+ passive = status(1)
+ passive['input']['lanes'][0]['pointer_focus'] = True
+ with self.assertRaises(AssertionError):
+ proof.lanes(passive, cleared=True)
+ proof.lanes(passive, cleared=True, allow_passive=True)
+ for field, value in (('held_button', 272), ('held_keys', 1), ('drag_active', True),
+ ('lease_active', True), ('keyboard_focus', True), ('pointer_focus', 1)):
+ altered = deepcopy(passive)
+ altered['input']['lanes'][0][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.lanes(altered, cleared=True, allow_passive=True)
+
+ def test_cancel_requires_real_partial_or_unknown_and_owned_release(self):
+ action = {'outcome': 'response', 'response': PARTIAL, 'replayed': False}
+ self.assertEqual(proof.verify_cancelled(trace(CANCEL), fault_record(), action)['result'], 'verified')
+ self.assertEqual(proof.verify_cancelled(trace(CANCEL), fault_record(),
+ {'outcome': 'unknown', 'replayed': False})['outcome']['kind'], 'unknown')
+ for rows in (ACTIVE, ACTIVE + [(8, 'pointer_button', 1, 0)],
+ ACTIVE + [(8, 'agent_cancel', 2, 0), (9, 'pointer_button', 1, 0)],
+ ACTIVE + [(8, 'pointer_button', 1, 0), (9, 'agent_cancel', 1, 0)],
+ CANCEL + [(11, 'pointer_motion', 1, 0)], CANCEL + [(11, 'agent_drag_end', 1, 0)]):
+ with self.subTest(rows=rows), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(rows), fault_record(), action)
+ with self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), fault_record(), {**action, 'response': REFUSED})
+
+ def test_dpms_has_no_primary_focus_input_or_warp_suppression(self):
+ action = {'outcome': 'response', 'response': PARTIAL, 'replayed': False}
+ for kind in ('cursor', 'pointer_focus', 'keyboard_focus', 'pointer_leave', 'pointer_button', 'keyboard_key', 'pointer_axis'):
+ page = trace(CANCEL + [(11, kind, 0, 0), (12, 'cursor', 0, 0)])
+ if kind == 'cursor':
+ page['events'][-2][3] += 1 # Warp and return must still fail.
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ proof.verify_cancelled(page, fault_record(), action)
+ for key, value in [('hook', False), ('overflow', True), ('timed_out', True), ('count', 0), ('active', False)]:
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_cancelled({**trace(CANCEL), key: value}, fault_record(), action)
+
+ def test_status_is_production_v3_and_lifecycle_revokes_both_lanes(self):
+ proof.transition(status(1, held=True), status(2))
+ for key, value in [('epoch', 'new'), ('desktop_generation', 1), ('held_button', 272),
+ ('held_keys', 1), ('reserved', True), ('lease_active', True), ('pointer_focus', True)]:
+ changed = status(2)
+ changed['input']['lanes'][1][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.transition(status(1), changed)
+ for key, value in [('test_only', True), ('protocol', 0), ('transport_ready', False)]:
+ changed = status(2)
+ changed['input'][key] = value
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.lanes(changed)
+
+ def test_unobserved_power_or_watchdog_expiry_cannot_certify_cancellation(self):
+ action = {'outcome': 'response', 'response': PARTIAL, 'replayed': False}
+ for change in ({'monitors_off': []}, {'monitors_off': [{**MONITOR, 'dpmsStatus': True}]},
+ {'watchdog_deadline_ns': 11_000_000}, {'requested_ns': 300_000_000}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.verify_cancelled(trace(CANCEL), {**fault_record(), **change}, action)
+
+ def test_refusal_requires_exact_reason_zero_dispatch_and_unavailable_interval(self):
+ self.assertEqual(proof.verify_refusal(refusal_record())['no_dispatch'], 'verified')
+ for change in ({'outcome': 'unknown'}, {'replayed': True}, {'response': PARTIAL},
+ {'observed_ns': 21_000_000}, {'prepared_ns': -6_000_000_000},
+ {'monitors_after': [{**MONITOR, 'dpmsStatus': True}]}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ proof.verify_refusal({**refusal_record(), **change})
+ for key in ('dispatches', 'desktop_generation', 'held_button'):
+ changed = refusal_record()
+ changed['after']['input']['lanes'][0][key] += 1
+ with self.subTest(key=key), self.assertRaises(AssertionError):
+ proof.verify_refusal(changed)
+ for kind in ('pointer_enter', 'agent_admitted', 'agent_cancel', 'pointer_button'):
+ changed = refusal_record()
+ changed['trace_after'] = trace(CANCEL + [(11, kind, 1, 0)])
+ with self.subTest(kind=kind), self.assertRaises(AssertionError):
+ proof.verify_refusal(changed)
+
+
+class GroundingTests(unittest.TestCase):
+ def test_interrupted_state_is_observed_after_restoration_without_input(self):
+ observer, guard, save = Mock(), Mock(), Mock()
+ spec = plan()['agents'][0]
+ action = {'outcome': 'response', 'response': PARTIAL, 'replayed': False}
+ restoration = {'result': 'restored', 'emergency': False, 'observed_ns': 10}
+ snapshot = {'proof_observation_started_ns': 20, 'proof_image': 'interrupted.png'}
+ with patch.object(proof, 'grounded_snapshot', return_value=snapshot) as observed, \
+ patch.object(proof.time, 'monotonic_ns', return_value=30):
+ record = proof.preserve_interrupted_state(observer, spec, action, restoration, guard, save)
+ observed.assert_called_once_with(observer, spec['target'], spec, session=False)
+ save.assert_called_once_with('interrupted-state.json', record)
+ self.assertIs(record['action'], action)
+ self.assertIs(record['snapshot'], snapshot)
+ self.assertEqual(record['restoration_observed_ns'], 10)
+ self.assertEqual(record['observed_ns'], 30)
+ self.assertEqual(guard.call_count, 2)
+ observer.tool.assert_not_called()
+
+ def test_interrupted_state_refuses_emergency_wake_and_stale_capture(self):
+ for failure in ('emergency', 'not_restored', 'stale_capture', 'replayed'):
+ restoration = {'result': 'restored', 'emergency': False, 'observed_ns': 10}
+ action = {'replayed': failure == 'replayed'}
+ if failure == 'emergency':
+ restoration['emergency'] = True
+ if failure == 'not_restored':
+ restoration['result'] = 'unproven'
+ snapshot = {'proof_observation_started_ns': 5 if failure == 'stale_capture' else 20}
+ save = Mock()
+ with self.subTest(failure=failure), \
+ patch.object(proof, 'grounded_snapshot', return_value=snapshot), \
+ patch.object(proof.time, 'monotonic_ns', return_value=30), \
+ self.assertRaises(AssertionError):
+ proof.preserve_interrupted_state(Mock(), plan()['agents'][0], action, restoration, Mock(), save)
+ save.assert_not_called()
+
+ def test_one_observation_grounds_both_same_window_pixel_actions_without_input(self):
+ clients = [Mock(process=Mock(pid=pid, poll=Mock(return_value=None))) for pid in (100, 101)]
+ spec = plan()['agents'][0]
+ prepared, probe = {'prepared_ns': 100}, {'prepared_ns': 200}
+ def drag(client, received):
+ self.assertIs(client, clients[0])
+ self.assertIs(received, spec)
+ return prepared
+ def refusal(grounding, received, stage):
+ self.assertIs(grounding, prepared)
+ self.assertIs(received, spec)
+ self.assertEqual(stage, 'click_b2')
+ return probe
+ save = Mock()
+ with patch.object(proof, 'prepare_drag', side_effect=drag), \
+ patch.object(proof, 'prepare_refusal', side_effect=refusal):
+ self.assertEqual(proof.prepare_actions(clients, spec, 'click_b2', save), (prepared, probe))
+ self.assertEqual([call.args for call in save.call_args_list],
+ [('drag-grounding.json', prepared), ('refusal-grounding.json', probe)])
+ for client in clients:
+ client.tool.assert_not_called()
+
+ def test_failed_observation_never_dispatches_or_saves_a_complete_pair(self):
+ clients = [Mock(process=Mock(pid=pid, poll=Mock(return_value=None))) for pid in (100, 101)]
+ save = Mock()
+ with patch.object(proof, 'prepare_drag', side_effect=AssertionError('bad snapshot')), \
+ patch.object(proof, 'prepare_refusal', return_value={}):
+ with self.assertRaisesRegex(AssertionError, 'bad snapshot'):
+ proof.prepare_actions(clients, plan()['agents'][0], 'click_b2', save)
+ save.assert_not_called()
+ for client in clients:
+ client.tool.assert_not_called()
+
+ def test_shared_runtime_is_rejected_before_observation(self):
+ client = Mock(process=Mock(pid=100, poll=Mock(return_value=None)))
+ with patch.object(proof, 'prepare_drag') as drag, patch.object(proof, 'prepare_refusal') as refusal:
+ with self.assertRaises(AssertionError):
+ proof.prepare_actions([client, client], plan()['agents'][0], 'click_b2', Mock())
+ drag.assert_not_called()
+ refusal.assert_not_called()
+
+ def test_refusal_keeps_original_observation_time(self):
+ for observed_ns in (100, 120):
+ spec = plan()['agents'][0]
+ snapshot = {**spec['target'], 'window_bounds': spec['bounds'],
+ 'proof_image': '/synthetic/agent.png',
+ 'proof_observation_started_ns': observed_ns}
+ prepared = {'snapshot': snapshot, 'target': spec['target'], 'prepared_ns': observed_ns}
+ with patch.object(proof.time, 'monotonic_ns', side_effect=AssertionError('must not reset timestamp')), \
+ patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'), \
+ patch.object(proof.pointer_grounding, 'action', return_value=({'x': 1, 'y': 2}, {})):
+ result = proof.prepare_refusal(prepared, spec, 'click_b2')
+ self.assertEqual(result, {'snapshot': snapshot, 'arguments': {'x': 1, 'y': 2},
+ 'session': 'session-unavailable',
+ 'prepared_ns': observed_ns})
+
+ def test_shared_observation_requires_exact_identity_geometry_and_time(self):
+ spec = plan()['agents'][0]
+ original = {'snapshot': {**spec['target'], 'window_bounds': spec['bounds'],
+ 'proof_observation_started_ns': 100}, 'target': spec['target'], 'prepared_ns': 100}
+ for change in ('target', 'pid', 'window_id', 'bounds', 'timestamp', 'missing_timestamp'):
+ prepared = deepcopy(original)
+ if change == 'target': prepared['target']['pid'] += 1
+ elif change in ('pid', 'window_id'): prepared['snapshot'][change] += 1
+ elif change == 'bounds': prepared['snapshot']['window_bounds']['x'] += 1
+ elif change == 'timestamp': prepared['prepared_ns'] += 1
+ else: del prepared['snapshot']['proof_observation_started_ns']
+ with self.subTest(change=change), patch.object(proof.pointer_grounding, 'read_pixels') as pixels:
+ with self.assertRaises((AssertionError, KeyError)):
+ proof.prepare_refusal(prepared, spec, 'click_b2')
+ pixels.assert_not_called()
+
+ def test_stale_or_future_probe_is_retained_without_dispatch(self):
+ for prepared_ns in (-proof.MAX_GROUNDING_AGE_NS, 101):
+ client, save = Mock(process=Mock(pid=100)), Mock()
+ fault = Mock(config={'deadline_ns': 1_000_000_000},
+ unavailable=Mock(return_value=[{**MONITOR, 'dpmsStatus': False}]))
+ with patch.object(proof.time, 'monotonic_ns', return_value=100), \
+ patch.object(proof, 'production_status', return_value=status(2)):
+ with self.assertRaisesRegex(AssertionError, 'refusal grounding expired'):
+ proof.refuse(client, plan()['agents'][0], {'prepared_ns': prepared_ns},
+ fault, Mock(collect=Mock(return_value=trace(CANCEL))), Mock(), save)
+ client.tool.assert_not_called()
+ self.assertEqual(save.call_args.args[0], 'unavailable-action.json')
+ self.assertEqual(save.call_args.args[1]['outcome'], 'unknown')
+ self.assertFalse(save.call_args.args[1]['replayed'])
+
+
+class WatchdogTests(unittest.TestCase):
+ def test_injection_is_gated_by_fresh_pending_drag_and_acks_exact_power(self):
+ def wait_once(predicate, timeout):
+ result = predicate()
+ if not result:
+ raise TimeoutError('DPMS off unsupported')
+ return result
+ for failure in (None, 'stale', 'done', 'lost_reply', 'no_off'):
+ with self.subTest(failure=failure):
+ fault = object.__new__(proof.SessionFault)
+ fault.config = {'instance': 'test_1', 'deadline_ns': 20_000_000}
+ fault.record, fault.mutated = {}, False
+ fault.check_targets, fault.live_deadline = Mock(), Mock()
+ pending = Mock(done=Mock(return_value=failure == 'done'))
+ with patch.object(proof, 'control_lock', return_value=nullcontext()), \
+ patch.object(proof, 'power', side_effect=[[{**MONITOR, 'dpmsStatus': True}],
+ [{**MONITOR, 'dpmsStatus': failure == 'no_off'}]]), \
+ patch.object(proof, 'production_status', side_effect=[status(1, held=True), status(2)]), \
+ patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2_000_000})), \
+ patch.object(proof.time, 'monotonic_ns', return_value=300_000_000 if failure == 'stale' else 6_000_000), \
+ patch.object(proof, 'wait_for', side_effect=wait_once), \
+ patch.object(proof, '_hypr', return_value='ok',
+ side_effect=RuntimeError('IPC lost') if failure == 'lost_reply' else None) as dispatch:
+ if failure:
+ with self.assertRaises((AssertionError, RuntimeError, TimeoutError)):
+ fault.inject(Mock(), trace(ACTIVE), pending, Mock())
+ if failure in ('stale', 'done'):
+ dispatch.assert_not_called()
+ self.assertFalse(fault.mutated)
+ else:
+ self.assertTrue(fault.mutated, 'lost reply still requires restoration')
+ else:
+ self.assertEqual(fault.inject(Mock(), trace(ACTIVE), pending, Mock()), 1)
+ self.assertEqual(fault.record['result'], 'observed')
+ dispatch.assert_called_once_with('test_1', 'dispatch', 'hl.dsp.dpms({ action = "disable" })')
+
+ def test_controller_eof_and_timeout_restore_but_cancel_does_not(self):
+ for trigger in ('eof', 'timeout', 'cancel', 'failure'):
+ with self.subTest(trigger=trigger), tempfile.TemporaryDirectory() as directory:
+ reader, writer = os.pipe()
+ config = {'deadline_ns': time.monotonic_ns() + (0 if trigger == 'timeout' else 1_000_000_000),
+ 'watchdog_path': str(Path(directory) / 'watchdog.json')}
+ if trigger == 'cancel':
+ os.write(writer, b'C')
+ if trigger in ('eof', 'failure'):
+ os.close(writer)
+ writer = None
+ try:
+ with patch.object(proof, 'restore_power', return_value={'result': 'restored', 'emergency': True},
+ side_effect=RuntimeError('wrong boot') if trigger == 'failure' else None) as restore:
+ proof.watchdog(config, reader)
+ if trigger == 'cancel':
+ restore.assert_not_called()
+ self.assertFalse(Path(config['watchdog_path']).exists())
+ else:
+ restore.assert_called_once_with(config, emergency=True)
+ result = json.loads(Path(config['watchdog_path']).read_text())
+ self.assertEqual(result['result'], 'failed' if trigger == 'failure' else 'restored')
+ finally:
+ os.close(reader)
+ if writer is not None:
+ os.close(writer)
+
+ def test_expired_watchdog_marker_or_dead_child_blocks_new_fault(self):
+ for failure in (None, 'deadline', 'marker', 'exited'):
+ with tempfile.TemporaryDirectory() as directory:
+ fault = object.__new__(proof.SessionFault)
+ marker = Path(directory) / 'restored'
+ fault.config = {'deadline_ns': time.monotonic_ns() + (0 if failure == 'deadline' else 5_000_000_000),
+ 'restored_path': str(marker)}
+ fault.child = Mock(poll=Mock(return_value=0 if failure == 'exited' else None))
+ if failure == 'marker':
+ marker.touch()
+ if failure:
+ with self.subTest(failure=failure), self.assertRaises(AssertionError):
+ fault.live_deadline()
+ else:
+ fault.live_deadline()
+
+ def test_restore_verifies_monitor_set_before_any_wake_and_marks_terminal(self):
+ with tempfile.TemporaryDirectory() as directory:
+ lock = Path(directory) / 'lock'
+ lock.touch()
+ info = lock.stat()
+ config = {'lock_path': str(lock), 'lock_identity': [info.st_dev, info.st_ino, info.st_uid],
+ 'restored_path': str(Path(directory) / 'restored'), 'instance': 'test_1'}
+ with patch.object(proof, 'guard_guest'), patch.object(proof, 'power', side_effect=AssertionError('new output')), \
+ patch.object(proof, '_hypr') as dispatch, self.assertRaisesRegex(AssertionError, 'new output'):
+ proof.restore_power(config)
+ dispatch.assert_not_called()
+ self.assertFalse(Path(config['restored_path']).exists())
+ with patch.object(proof, 'guard_guest'), \
+ patch.object(proof, 'power', side_effect=[[{**MONITOR, 'dpmsStatus': False}], [{**MONITOR, 'dpmsStatus': True}]]), \
+ patch.object(proof, 'production_status', return_value=status(3)), \
+ patch.object(proof, '_hypr', return_value='ok') as dispatch:
+ self.assertEqual(proof.restore_power(config)['result'], 'restored')
+ dispatch.assert_called_once_with('test_1', 'dispatch', 'hl.dsp.dpms({ action = "enable" })')
+ self.assertTrue(Path(config['restored_path']).exists())
+
+ def test_failed_restore_leaves_eof_recovery_armed(self):
+ fault = object.__new__(proof.SessionFault)
+ fault.mutated, fault.config = True, {}
+ with patch.object(proof, 'restore_power', side_effect=RuntimeError('IPC lost')), self.assertRaises(RuntimeError):
+ fault.restore()
+ self.assertTrue(fault.mutated)
+ reader, fault.cancel_fd = os.pipe()
+ fault.child = None
+ try:
+ fault.close()
+ self.assertEqual(os.read(reader, 1), b'')
+ finally:
+ os.close(reader)
+
+ def test_successful_restore_disarms_and_reaps_before_app_recovery(self):
+ fault = object.__new__(proof.SessionFault)
+ fault.mutated, fault.config = True, {}
+ reader, fault.cancel_fd = os.pipe()
+ child = fault.child = Mock(returncode=0)
+ try:
+ def restored(config):
+ self.assertTrue(fault.mutated)
+ child.wait.assert_not_called()
+ return {'result': 'restored', 'emergency': False}
+ with patch.object(proof, 'restore_power', side_effect=restored):
+ self.assertEqual(fault.restore()['result'], 'restored')
+ self.assertFalse(fault.mutated)
+ self.assertEqual(os.read(reader, 2), b'C')
+ self.assertIsNone(fault.cancel_fd)
+ self.assertIsNone(fault.child)
+ child.wait.assert_called_once_with(timeout=10)
+ child.stdout.close.assert_called_once()
+ fault.close()
+ self.assertEqual(fault.restore(), {'result': 'not_needed'})
+ child.wait.assert_called_once()
+ finally:
+ os.close(reader)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.py
new file mode 100644
index 0000000000..ec3c02c87b
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.py
@@ -0,0 +1,499 @@
+"""TEST ONLY: destroy one exact disposable Calc target during a normal MCP drag.
+
+CLI flags match production_geometry_fault_proof. Plan uses the exact VM,
+compositor, processes, foreground, primary_point, package_versions and one
+Calc agent from production_primary_conflict_proof, with purpose=target_lifetime,
+case=active_drag and fault={kind:destroy,signal:SIGKILL}. recovery is
+{mode:prepared_distinct_process,agent:<Calc spec>,identity:<exact /proc identity>}
+where its pointer_stage is click_a1 or click_b2 and drag={}. Both Calc specs add
+owned={document:{path,device,inode,uid,sha256},profile:<canonical directory>}.
+Each document is an existing suite cua-smoke-calc.ods in a private directory;
+each profile is that document's sibling calc-profile. Both processes must have
+the suite's exact launch argv. The controller prepares both before this run.
+
+Only normal Driver MCP sends application input. This runner sends one SIGKILL
+through a revalidated pidfd, only after held-drag trace AND status gates. Saved
+bytes are archived before injection. A destroyed client cannot acknowledge a
+release: require cleared/pruned compositor state, never fabricate a wire release
+or filter the raw trace to balance it. Require partial stale_target, unchanged
+idle sibling input/authority (resource pruning is allowed), and continuous
+primary isolation. Recovery is one fresh
+click on the separately prepared process with a new runtime and screenshot.
+Same-client recovery, relaunch, PID/address reuse, active sibling cancellation,
+full desktop certification and physical hardware are explicitly unproven.
+No app launches, signer material, policy changes, production edits or replay.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import select
+import signal
+import stat
+import subprocess
+import time
+
+from desktop_faults import _hypr, _identity, _same_compositor
+from driver_input_live import state, wait_for, wm
+from primary_trace import analyze
+from production_active_lock_proof import drag_once, held_status
+from production_cancel_proof import (PROFILE, MAX_GROUNDING_AGE_NS, active_drags,
+ close_owned, grounded_snapshot, poll_active, prepare_drag, stopped_prefix, verify_fresh_observation)
+from production_desktop_fault_proof import guest_identity
+from production_geometry_fault_proof import window_bounds
+from production_mcp import DirectMCP, assert_distinct_runtimes, stop_process
+import production_pointer_grounding as pointer_grounding
+from production_primary_conflict_proof import ExactDesktop, validate_identity, validate_plan as primary_plan
+from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity,
+ capacity_lane, check_response, primary_acknowledgement, provenance,
+ require_primary_active, trace_interval)
+from production_session_fault_proof import lanes
+from realapp_proof import cleanup_all
+
+
+def validate_owned(spec):
+ assert spec['app'] == 'calc' and spec['drag'] == {}
+ owned = spec['owned']
+ assert set(owned) == {'document', 'profile'}
+ document = owned['document']
+ assert set(document) == {'path', 'device', 'inode', 'uid', 'sha256'}
+ path = Path(document['path'])
+ assert path.is_absolute() and path.name == 'cua-smoke-calc.ods'
+ assert all(type(document[k]) is int and document[k] >= 0 for k in ('device', 'inode', 'uid'))
+ assert len(document['sha256']) == 64 and all(c in '0123456789abcdef' for c in document['sha256'])
+ assert Path(owned['profile']) == path.parent / 'calc-profile'
+
+
+def validate_plan(plan):
+ assert plan['purpose'] == 'target_lifetime' and plan['case'] == 'active_drag'
+ assert plan['fault'] == {'kind': 'destroy', 'signal': 'SIGKILL'}
+ recovery = plan['recovery']
+ assert set(recovery) == {'mode', 'agent', 'identity'}
+ assert recovery['mode'] == 'prepared_distinct_process'
+ fresh = recovery['agent']
+ assert fresh['pointer_stage'] in ('click_a1', 'click_b2')
+ base = {k: v for k, v in plan.items() if k != 'fault'}
+ primary_plan({**base, 'purpose': 'primary_conflict', 'case': 'initial_refusal',
+ 'recovery': {'pointer_stage': 'click_b2'}})
+ primary_plan({**base, 'purpose': 'primary_conflict', 'case': 'initial_refusal',
+ 'agents': [{**fresh, 'pointer_stage': 'select_range'}],
+ 'processes': {**plan['processes'], 'target': recovery['identity']},
+ 'recovery': {'pointer_stage': 'click_b2'}})
+ old = plan['agents'][0]
+ for spec in (old, fresh):
+ validate_owned(spec)
+ validate_identity(recovery['identity'])
+ identities = [*plan['processes'].values(), recovery['identity'], plan['compositor']]
+ assert len({p['pid'] for p in identities}) == 4, 'recovery must be a distinct process'
+ assert len({s['window_id'] for s in (old['target'], fresh['target'], plan['foreground'])}) == 3
+ assert old['name'] != fresh['name'] and old['owned']['profile'] != fresh['owned']['profile']
+ assert old['owned']['document']['path'] != fresh['owned']['document']['path']
+
+
+def saved_document(spec):
+ """Read only the identity-bound saved output; selection never saves it."""
+ expected = spec['owned']['document']
+ path = Path(expected['path'])
+ assert path.resolve(strict=True) == path, 'document alias refused'
+ parent = path.parent.stat()
+ assert parent.st_uid == os.getuid() and not parent.st_mode & 0o077, 'private test directory required'
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ try:
+ info = os.fstat(fd)
+ assert stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and 0 < info.st_size <= 16 * 1024 * 1024
+ assert [info.st_dev, info.st_ino, info.st_uid] == [expected[k] for k in ('device', 'inode', 'uid')]
+ assert info.st_uid == os.getuid() and not info.st_mode & 0o022
+ with os.fdopen(os.dup(fd), 'rb') as stream:
+ data = stream.read(16 * 1024 * 1024 + 1)
+ assert len(data) == info.st_size and hashlib.sha256(data).hexdigest() == expected['sha256']
+ fields = ('st_dev', 'st_ino', 'st_size', 'st_mtime_ns', 'st_ctime_ns')
+ assert all(getattr(now, k) == getattr(info, k) for now in (os.fstat(fd), path.lstat()) for k in fields)
+ return data
+ finally:
+ os.close(fd)
+
+
+def check_calc(spec, identity):
+ assert _identity(identity['pid']) == identity, 'Calc process identity changed'
+ assert identity['uid'] == os.getuid()
+ profile = Path(spec['owned']['profile'])
+ assert profile.resolve(strict=True) == profile and profile.is_dir()
+ assert profile.stat().st_uid == os.getuid() and not profile.stat().st_mode & 0o077
+ argv = Path(f'/proc/{identity["pid"]}/cmdline').read_bytes().rstrip(b'\0').split(b'\0')
+ expected = [identity['exe'], f'-env:UserInstallation={profile.as_uri()}', '--norestore',
+ '--nologo', '--calc', spec['owned']['document']['path']]
+ assert [x.decode() for x in argv] == expected, 'not the exact dedicated suite Calc launch'
+
+
+class TargetLifetime(ExactDesktop):
+ """No PID-name matching, shell signals, fallback kills, relaunch or retries."""
+ def __init__(self, plan):
+ self.plan, self.instance = plan, plan['compositor']['instance']
+ self.compositor = {k: v for k, v in plan['compositor'].items() if k != 'instance'}
+ self.spec, self.fresh = plan['agents'][0], plan['recovery']['agent']
+ self.fd, self.sent, self.destroyed = None, False, False
+ self.record = {'result': 'unproven', 'target': self.spec['target']}
+ assert subprocess.run(['systemd-detect-virt', '--vm', '--quiet'], timeout=2).returncode == 0
+ self.guard()
+ for spec, identity in ((self.spec, plan['processes']['target']), (self.fresh, plan['recovery']['identity'])):
+ app_process_identity('calc', identity['pid'])
+ check_calc(spec, identity)
+ saved_document(spec)
+ self.fd = os.pidfd_open(self.spec['target']['pid'])
+ try:
+ self.guard() # Revalidate AFTER binding, closing PID reuse race.
+ except BaseException:
+ self.close()
+ raise
+
+ def guard(self):
+ assert self.plan['disposable'] is True and platform.system() == 'Linux'
+ assert guest_identity() == self.plan['vm'], 'wrong VM boot'
+ assert os.environ.get('HYPRLAND_INSTANCE_SIGNATURE') == self.instance
+ assert self.compositor['uid'] == os.getuid()
+ _same_compositor(self.compositor, self.instance)
+ checks = [('foreground', self.plan['foreground'], self.plan['processes']['foreground'], None),
+ ('replacement', self.fresh['target'], self.plan['recovery']['identity'], self.fresh)]
+ if not self.sent:
+ checks.append(('target', self.spec['target'], self.plan['processes']['target'], self.spec))
+ if self.fd is not None:
+ assert not select.select([self.fd], [], [], 0)[0], 'target already exited'
+ windows = json.loads(_hypr(self.instance, '-j', 'clients'))
+ for name, target, identity, spec in checks:
+ assert _identity(identity['pid']) == identity, name + ' identity changed'
+ selected = [w for w in windows if w.get('pid') == target['pid']]
+ assert len(selected) == 1, 'ambiguous ' + name + ' windows'
+ window = selected[0]
+ assert int(window['address'], 16) == target['window_id'] and window.get('xwayland') is False
+ if spec:
+ check_calc(spec, identity)
+ assert 'cua-smoke-calc.ods' in window.get('title', '')
+ assert window_bounds(window) == spec['bounds'], 'reviewed bounds changed'
+ return windows
+
+ def status(self):
+ self.guard()
+ status = json.loads(_hypr(self.instance, '-j', 'cua:status'))
+ lanes(status)
+ return status
+
+ def gone(self):
+ windows = self.guard()
+ target = self.spec['target']
+ exited = bool(select.select([self.fd], [], [], 0)[0])
+ absent = not any(w.get('pid') == target['pid'] or int(w['address'], 16) == target['window_id'] for w in windows)
+ if exited and absent:
+ self.destroyed = True
+ return {'pidfd_exited': True, 'window_absent': True, 'observed_ns': time.monotonic_ns()}
+ return None
+
+ def inject(self, trace, initial, pending, guard):
+ assert not self.sent and self.fd is not None, 'one termination attempt only'
+ self.guard()
+ saved_document(self.spec)
+ page, active = poll_active(trace, initial, None, [pending])
+ lane = next(iter(active))
+ status_started = time.monotonic_ns()
+ before = self.status()
+ held_status(before, lane)
+ self.guard()
+ guard()
+ assert not pending.done(), 'drag already returned'
+ requested = time.monotonic_ns()
+ assert 0 <= requested - page['events'][-1][1] <= 250_000_000
+ assert 0 <= requested - status_started <= 250_000_000, 'stale held-state gate'
+ self.record.update(prefix=page, lane=lane, gate_status=before,
+ status_started_ns=status_started, requested_ns=requested)
+ self.sent = True # A lost acknowledgement never authorizes a retry.
+ signal.pidfd_send_signal(self.fd, signal.SIGKILL)
+ self.record['gone'] = wait_for(self.gone, timeout=3)
+ def cleared():
+ observed = self.status()
+ self.record['last_status'] = observed
+ try:
+ verify_cleared(before, observed, lane)
+ except AssertionError:
+ return None
+ return observed
+ self.record['after'] = wait_for(cleared, timeout=3)
+ self.record['observed_ns'] = time.monotonic_ns()
+ self.record['result'] = 'observed'
+ guard()
+ return lane
+
+ def close(self):
+ if self.fd is not None:
+ os.close(self.fd)
+ self.fd = None
+
+
+def verify_cleared(before, after, lane):
+ held_status(before, lane)
+ old, new = lanes(before), lanes(after, cleared=True)
+ resources = {'seat_resources', 'pointer_resources', 'keyboard_resources'}
+ for key in old:
+ assert all(old[key][k] == new[key][k] for k in ('epoch', 'desktop_generation', 'dispatches'))
+ assert all(type(new[key][k]) is int and 0 <= new[key][k] <= old[key][k] for k in resources)
+ if key != lane - 1:
+ # A toolkit can bind both globals. Its death may prune resources
+ # from the idle lane too, but must not change its input/authority.
+ assert {k: v for k, v in old[key].items() if k not in resources} == {
+ k: v for k, v in new[key].items() if k not in resources}, 'idle sibling lane changed'
+ else:
+ assert new[key]['reserved'] is True, 'target loss unexpectedly lost runtime reservation'
+ assert all(type(new[key][k]) is int and new[key][k] < old[key][k]
+ for k in resources), 'destroyed resources not pruned'
+
+
+def isolation(page, *, stopped=False):
+ result = analyze(page if stopped else stopped_prefix(page))
+ assert result['result'] == 'passed', result
+ return result
+
+
+def verify_fault(boundary, record, action):
+ assert record['result'] == 'observed'
+ assert record['gone']['pidfd_exited'] is True and record['gone']['window_absent'] is True
+ prefix, lane = record['prefix'], record['lane']
+ assert set(active_drags(prefix)) == {lane}
+ assert all(r[5] in (0, lane) for r in prefix['events'])
+ assert all(r[2] in ('agent_approved', 'agent_admitted', 'agent_drag_start', 'pointer_enter',
+ 'pointer_motion', 'pointer_button') for r in prefix['events'] if r[5] == lane)
+ requested = record['requested_ns']
+ assert 0 <= requested - prefix['events'][-1][1] <= 250_000_000
+ assert 0 <= requested - record['status_started_ns'] <= 250_000_000
+ assert requested <= record['gone']['observed_ns'] <= record['observed_ns']
+ tail = trace_interval(prefix, boundary)
+ synthetic = [r for r in tail if r[5] in (1, 2)]
+ assert all(r[5] == lane for r in synthetic), 'cleanup crossed lanes'
+ cancels = [r for r in synthetic if r[2] == 'agent_cancel']
+ assert len(cancels) == 1 and requested <= cancels[0][1] <= record['observed_ns']
+ allowed = {'agent_cancel', 'pointer_motion', 'pointer_enter', 'pointer_leave', 'keyboard_leave', 'pointer_button'}
+ assert all(r[2] in allowed for r in synthetic), 'replay or false completion'
+ assert not any(r[2] in ('pointer_motion', 'pointer_enter') and r[0] > cancels[0][0] for r in synthetic)
+ releases = [r for r in synthetic if r[2] == 'pointer_button']
+ assert len(releases) <= 1 and all(r[6] == 0 and r[0] > cancels[0][0] for r in releases)
+ verify_cleared(record['gate_status'], record['after'], lane)
+ assert action['replayed'] is False and action['outcome'] == 'response', 'unknown delivery; never replay'
+ check_response(action['response'], {'kind': 'partial'})
+ content = action['response']['structuredContent']
+ assert content.get('reason') == 'stale_target' and content['delivery']['mode'] == 'background'
+ assert content['delivery']['delivered_count'] > 0
+ assert action['dispatch_ns'] <= prefix['events'][-1][1] <= action['observed_ns']
+ return {'result': 'verified', 'reason': 'stale_target', 'lane': lane,
+ 'continuous_isolation': isolation(boundary), 'own_state': 'cleared_and_pruned',
+ 'wire_release_events': len(releases), 'destroyed_client_release_ack': 'unprovable',
+ 'unsaved_drag_effect': 'unproven'}
+
+
+def cleanup_trace(before, after, *, stopped=False):
+ if stopped:
+ assert after['events'][:before['count']] == before['events'], 'trace history changed'
+ rows = after['events'][before['count']:]
+ else:
+ rows = trace_interval(before, after)
+ assert all(r[2] in ('agent_cancel', 'pointer_leave', 'keyboard_leave')
+ for r in rows if r[5] in (1, 2)), 'unexpected input after action'
+ return isolation(after, stopped=stopped)
+
+
+def recover(client, observer, victim, fault, trace, boundary, lane, guard, save, result):
+ assert fault.destroyed and victim.process.poll() is not None
+ assert victim.process.pid not in assert_distinct_runtimes([client, observer])
+ spec = fault.fresh
+ fault.guard()
+ assert not client.tool('start_session', {'session': spec['name']}).get('isError')
+ prepared = prepare_drag(client, spec)
+ assert prepared['target'] != fault.spec['target']
+ result.update(grounding=prepared, runtime_pid=client.process.pid, replayed=False)
+ save('recovery-grounding.json', result)
+ guard()
+ fault.guard()
+ dispatch = time.monotonic_ns()
+ assert 0 <= dispatch - prepared['prepared_ns'] <= MAX_GROUNDING_AGE_NS
+ result['action'] = {'outcome': 'unknown', 'replayed': False, 'dispatch_ns': dispatch}
+ save('recovery-action.json', result['action'])
+ try:
+ response = client.tool('click', {**prepared['arguments'], **spec['target'],
+ 'session': spec['name'], 'delivery_mode': 'background'})
+ result['action'].update(outcome='response', response=response)
+ except Exception as error:
+ result['action']['error'] = str(error)
+ finally:
+ result['action']['observed_ns'] = time.monotonic_ns()
+ save('recovery-action.json', result['action'])
+ after = grounded_snapshot(observer, spec['target'], spec, session=False)
+ save('recovery-after.json', after)
+ assert result['action']['outcome'] == 'response', 'recovery unknown; never replay'
+ check_response(response, {'kind': 'dispatched'})
+ assert_distinct_runtimes([client, observer])
+ assert dispatch <= result['action']['observed_ns'], 'action returned before dispatch'
+ verify_fresh_observation(prepared['snapshot'], after, observer, after_ns=result['action']['observed_ns'])
+ result['app_effect'] = pointer_grounding.verify(after, pointer_grounding.read_pixels(after['proof_image']), prepared['oracle'])
+ page = trace.collect()
+ save('recovery-prefix.json', page)
+ rows = trace_interval(boundary, page)
+ assert capacity_lane(boundary, page, 'click') == lane
+ synthetic = [r for r in rows if r[5] in (1, 2)]
+ assert all(r[5] == lane for r in synthetic)
+ assert sum(r[2] == 'agent_admitted' for r in synthetic) == 1
+ assert sum(r[2] == 'agent_action_end' for r in synthetic) == 1
+ assert all(r[2] in ('agent_admitted', 'agent_approved', 'agent_action_end', 'pointer_enter',
+ 'pointer_motion', 'pointer_button', 'pointer_leave', 'keyboard_leave') for r in synthetic)
+ assert [r[6] for r in synthetic if r[2] == 'pointer_button'] == [1, 0]
+ recovered = lanes(fault.status())
+ for key, row in recovered.items():
+ assert row['held_button'] == row['held_keys'] == 0
+ assert all(row[k] is False for k in ('drag_active', 'lease_active', 'keyboard_focus'))
+ assert row['reserved'] is (key == lane - 1)
+ if key != lane - 1:
+ assert row['pointer_focus'] is False
+ result['continuous_isolation'] = isolation(page)
+ guard()
+ result['result'] = 'verified'
+ return page
+
+
+def run(args):
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ def save(name, value):
+ (args.evidence / name).write_text(json.dumps(value, indent=2) + '\n')
+ report = {'result': 'failed', 'scope': 'exact-target-destruction-and-prepared-distinct-recovery',
+ 'recovery': {'result': 'unproven'}, 'same_client_recovery': 'unproven',
+ 'pid_or_address_reuse': 'unproven', 'active_sibling': 'unproven',
+ 'full_desktop_matrix': False, 'physical_hardware': False}
+ clients, observer, fault, trace, grab, pool, future = [], None, None, None, None, None, None
+ prefix = baseline = primary_before = deadline = None
+ action = {'outcome': 'unknown', 'replayed': False}
+ def guard():
+ require_primary_active(grab, deadline)
+ try:
+ plan = json.loads(args.plan.read_text())
+ save('plan.json', plan)
+ validate_plan(plan)
+ fault = TargetLifetime(plan)
+ origin = provenance(args, plan)
+ origin['ownership'] = {key: plan[key] for key in ('vm', 'compositor', 'processes', 'recovery')}
+ for name in ('production_target_lifetime_proof.py', 'production_target_lifetime_proof_test.py'):
+ path = Path(__file__).with_name(name)
+ origin['files'][name] = {'path': str(path.resolve()), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
+ save('provenance.json', origin)
+ for name, spec in (('target', fault.spec), ('replacement', fault.fresh)):
+ (args.evidence / (name + '-saved-before.ods')).write_bytes(saved_document(spec))
+ save('prepared-app-identities.json', {
+ name: app_process_identity('calc', spec['target']['pid'])
+ for name, spec in (('target', fault.spec), ('replacement', fault.fresh))})
+ def launch(name):
+ directory = args.evidence / name
+ directory.mkdir()
+ return DirectMCP(args.driver, directory, PROFILE)
+ clients.append(launch('agent'))
+ observer = launch('observer')
+ report['driver_processes'] = assert_distinct_runtimes([clients[0], observer])
+ assert not clients[0].tool('start_session', {'session': fault.spec['name']}).get('isError')
+ bounds = grounded_snapshot(observer, plan['foreground'])['window_bounds']
+ desktop = observer.tool('get_desktop_state', {})
+ assert not desktop.get('isError')
+ desktop = desktop['structuredContent']
+ x, y = plan['primary_point']
+ assert 0 < x < bounds['width'] and 0 < y < bounds['height']
+ x, y = x + bounds['x'], y + bounds['y']
+ assert 0 <= x < desktop['screen_width'] and 0 <= y < desktop['screen_height']
+ deadline = time.monotonic_ns() + PRIMARY_LIFETIME_MS * 1_000_000
+ grab = subprocess.Popen([str(args.primary_grab), str(x), str(y), str(desktop['screen_width']),
+ str(desktop['screen_height']), str(PRIMARY_LIFETIME_MS)], stdout=subprocess.PIPE, text=True)
+ assert primary_acknowledgement(grab.stdout) == 'HELD\n'
+ wait_for(lambda: state(args.foreground_journal)['held'], timeout=3)
+ primary_before, baseline = wm(), state(args.foreground_journal)
+ assert primary_before['pid'] == plan['foreground']['pid'] and baseline['held']
+ save('initial-primary.json', {'primary': primary_before, 'foreground': baseline})
+ status = fault.status()
+ lanes(status, cleared=True)
+ save('initial-status.json', status)
+ trace = fault.trace(args.trace_socket)
+ start = time.monotonic_ns()
+ trace.exchange('TRACE_START')
+ initial = trace.collect()
+ save('initial-trace.json', initial)
+ assert start <= initial['events'][0][1] <= time.monotonic_ns()
+ assert not any(r[5] in (1, 2) for r in initial['events'])
+ prepared = prepare_drag(clients[0], fault.spec)
+ save('drag-grounding.json', prepared)
+ guard()
+ pool = ThreadPoolExecutor(max_workers=1)
+ future = pool.submit(drag_once, clients[0], fault.spec, prepared, action, save)
+ lane = fault.inject(trace, initial, future, guard)
+ save('fault.json', fault.record)
+ future.result(timeout=5)
+ report['action'] = action
+ boundary = trace.collect()
+ save('fault-prefix.json', boundary)
+ report['fault'] = verify_fault(boundary, fault.record, action)
+ for name, spec in (('target', fault.spec), ('replacement', fault.fresh)):
+ (args.evidence / (name + '-saved-after.ods')).write_bytes(saved_document(spec))
+ report['saved_output'] = 'identity_and_bytes_unchanged; archived_before_and_after'
+ close_owned(clients[0])
+ teardown = trace.collect()
+ cleanup_trace(boundary, teardown)
+ save('pre-recovery-prefix.json', teardown)
+ clients.append(launch('recovery'))
+ prefix = recover(clients[-1], observer, clients[0], fault, trace, teardown, lane, guard, save, report['recovery'])
+ report['result'] = 'passed'
+ except Exception as error:
+ report['error'] = str(error)
+ finally:
+ operations = [(f'close_agent_{i}', lambda c=c: close_owned(c)) for i, c in enumerate(clients)]
+ if future:
+ operations.append(('wait_action', lambda: future.result(timeout=5)))
+ operations.append(('preserve_action', lambda: save('drag-action.json', action)))
+ if pool:
+ operations.append(('shutdown_pool', lambda: pool.shutdown(wait=False, cancel_futures=True)))
+ if fault:
+ operations.append(('preserve_fault', lambda: save('fault.json', fault.record)))
+ if trace:
+ def finish():
+ trace.exchange('TRACE_STOP')
+ stopped = trace.collect()
+ save('trace.json', stopped)
+ report['continuous_isolation'] = cleanup_trace(prefix, stopped, stopped=True) if prefix else isolation(stopped, stopped=True)
+ guard()
+ primary_after = wm()
+ assert primary_after == primary_before
+ current = state(args.foreground_journal)
+ assert all(current[k] == baseline[k] for k in ('clicks', 'keys', 'scroll', 'held'))
+ save('final-primary.json', {'primary': primary_after, 'foreground': current})
+ final = fault.status()
+ save('final-status.json', final)
+ assert all(r['reserved'] is False for r in lanes(final, cleared=True).values())
+ operations.extend([('finish_trace', finish), ('close_trace', trace.close)])
+ if fault:
+ operations.append(('close_pidfd', fault.close))
+ def release():
+ if grab:
+ if grab.poll() is None:
+ grab.terminate()
+ stop_process(grab)
+ wait_for(lambda: not state(args.foreground_journal)['held'], timeout=3)
+ operations.append(('release_primary', release))
+ if observer:
+ operations.append(('close_observer', lambda: close_owned(observer)))
+ errors = cleanup_all(operations)
+ save('cleanup.json', {'errors': errors})
+ if errors:
+ report['result'] = 'failed'
+ save('result.json', report)
+ print(json.dumps(report), flush=True)
+ return 0 if report['result'] == 'passed' else 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'plugin', 'source', 'primary-grab', 'plan', 'evidence', 'foreground-journal', 'trace-socket'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--source-sha', required=True)
+ raise SystemExit(run(parser.parse_args()))
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.py
new file mode 100644
index 0000000000..a711e5b4e3
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.py
@@ -0,0 +1,292 @@
+"""Portable adversarial preparation tests; never native lifetime certification."""
+from contextlib import ExitStack
+from copy import deepcopy
+import hashlib
+import json
+import os
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+import production_target_lifetime_proof as proof
+from production_primary_conflict_proof_test import plan as base_plan, identity, DELIVERED
+from production_session_fault_proof_test import ACTIVE, PARTIAL, status, trace
+
+
+DESTROYED = ACTIVE + [(8, 'agent_cancel', 1, 0)]
+
+
+def owned(directory):
+ return {'document': {'path': directory + '/cua-smoke-calc.ods', 'device': 1,
+ 'inode': 2, 'uid': 1000, 'sha256': 'a' * 64}, 'profile': directory + '/calc-profile'}
+
+
+def plan():
+ result = base_plan()
+ result.update(purpose='target_lifetime', case='active_drag', fault={'kind': 'destroy', 'signal': 'SIGKILL'})
+ result['agents'][0]['owned'] = owned('/test/original')
+ fresh = {**deepcopy(result['agents'][0]), 'name': 'fresh', 'target': {'pid': 30, 'window_id': 300},
+ 'pointer_stage': 'click_b2', 'owned': owned('/test/replacement')}
+ result['recovery'] = {'mode': 'prepared_distinct_process', 'agent': fresh, 'identity': identity(30)}
+ return result
+
+
+def statuses():
+ before, after = status(held=True), status()
+ after['input']['lanes'][0]['reserved'] = True
+ for old, new in zip(before['input']['lanes'], after['input']['lanes']):
+ for key in ('seat_resources', 'pointer_resources', 'keyboard_resources'):
+ old[key], new[key] = 3, 2
+ return before, after
+
+
+def record():
+ before, after = statuses()
+ return {'result': 'observed', 'target': plan()['agents'][0]['target'], 'lane': 1,
+ 'prefix': trace(ACTIVE), 'gate_status': before, 'after': after,
+ 'requested_ns': 6_000_000, 'status_started_ns': 5_000_000,
+ 'gone': {'pidfd_exited': True, 'window_absent': True, 'observed_ns': 9_000_000},
+ 'observed_ns': 10_000_000}
+
+
+def action():
+ response = deepcopy(PARTIAL)
+ response['structuredContent']['reason'] = 'stale_target'
+ return {'outcome': 'response', 'replayed': False, 'response': response,
+ 'dispatch_ns': 500_000, 'observed_ns': 11_000_000}
+
+
+class PlanTests(unittest.TestCase):
+ def test_exact_disposable_distinct_replacement_only(self):
+ proof.validate_plan(plan())
+ mutations = [lambda p: p.update(disposable=False),
+ lambda p: p['fault'].update(signal='SIGTERM'),
+ lambda p: p['recovery'].update(mode='relaunch'),
+ lambda p: p['recovery']['agent'].update(pointer_stage='select_range'),
+ lambda p: p['recovery']['agent'].update(target=p['agents'][0]['target']),
+ lambda p: p['recovery']['identity'].update(pid=20),
+ lambda p: p['agents'][0]['owned'].update(profile='/real/profile'),
+ lambda p: p['agents'][0]['owned']['document'].update(path='/real/work.ods'),
+ lambda p: p['agents'][0].update(drag={'pid': 99}),
+ lambda p: p['recovery']['agent'].update(owned=p['agents'][0]['owned'])]
+ for mutate in mutations:
+ candidate = plan()
+ mutate(candidate)
+ with self.subTest(candidate=candidate), self.assertRaises(AssertionError):
+ proof.validate_plan(candidate)
+
+ def test_saved_output_exact_bytes_identity_and_alias_refusal(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary).resolve()
+ path = root / 'cua-smoke-calc.ods'
+ path.write_bytes(b'existing saved bytes')
+ info = path.stat()
+ spec = {'owned': {'document': {'path': str(path), 'device': info.st_dev,
+ 'inode': info.st_ino, 'uid': info.st_uid, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}}}
+ self.assertEqual(proof.saved_document(spec), b'existing saved bytes')
+ for key, value in (('inode', info.st_ino + 1), ('sha256', '0' * 64)):
+ changed = deepcopy(spec)
+ changed['owned']['document'][key] = value
+ with self.assertRaises(AssertionError):
+ proof.saved_document(changed)
+ alias = root / 'alias.ods'
+ alias.symlink_to(path)
+ spec['owned']['document']['path'] = str(alias)
+ with self.assertRaises(AssertionError):
+ proof.saved_document(spec)
+
+ def test_calc_requires_identity_and_exact_launch_argv(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary).resolve()
+ profile = root / 'calc-profile'
+ profile.mkdir(mode=0o700)
+ spec = {'owned': owned(str(root))}
+ expected_identity = {**identity(20), 'uid': os.getuid()}
+ argv = [expected_identity['exe'], f'-env:UserInstallation={profile.as_uri()}',
+ '--norestore', '--nologo', '--calc', str(root / 'cua-smoke-calc.ods')]
+ for words in (argv, argv + ['/private.ods'], argv[:-1], [*argv[:1], '-env:UserInstallation=file:///real', *argv[2:]]):
+ with patch.object(proof, '_identity', return_value=expected_identity), \
+ patch.object(Path, 'read_bytes', return_value=b'\0'.join(x.encode() for x in words) + b'\0'):
+ if words == argv:
+ proof.check_calc(spec, expected_identity)
+ else:
+ with self.assertRaises(AssertionError):
+ proof.check_calc(spec, expected_identity)
+ with patch.object(proof, '_identity', return_value={}), self.assertRaises(AssertionError):
+ proof.check_calc(spec, expected_identity)
+
+
+class OracleTests(unittest.TestCase):
+ def test_destroyed_surface_requires_no_invented_release(self):
+ result = proof.verify_fault(trace(DESTROYED), record(), action())
+ self.assertEqual(result['wire_release_events'], 0)
+ self.assertEqual(result['destroyed_client_release_ack'], 'unprovable')
+ observed_release = DESTROYED + [(9, 'pointer_button', 1, 0)]
+ self.assertEqual(proof.verify_fault(trace(observed_release), record(), action())['wire_release_events'], 1)
+
+ def test_unknown_refusal_success_wrong_reason_or_replay_cannot_pass(self):
+ mutations = [lambda a: a.update(outcome='unknown'), lambda a: a.update(replayed=True),
+ lambda a: a.update(response=DELIVERED),
+ lambda a: a['response']['structuredContent'].update(reason='cancelled'),
+ lambda a: a['response']['structuredContent']['delivery'].update(delivered_count=0),
+ lambda a: a['response']['structuredContent']['delivery'].update(mode='unknown')]
+ for mutate in mutations:
+ observed = action()
+ mutate(observed)
+ with self.subTest(action=observed), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(DESTROYED), record(), observed)
+
+ def test_raw_trace_rejects_corruption_primary_leaks_other_lane_and_replay(self):
+ for field, value in (('hook', False), ('active', False), ('overflow', True), ('timed_out', True), ('count', 0)):
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ proof.verify_fault({**trace(DESTROYED), field: value}, record(), action())
+ for kind, lane, value in [('pointer_button', 0, 0), ('keyboard_key', 0, 1), ('pointer_focus', 0, 0),
+ ('pointer_axis', 0, 0), ('agent_cancel', 2, 0), ('agent_admitted', 1, 0),
+ ('agent_drag_end', 1, 0), ('agent_drag_start', 1, 0), ('agent_action_end', 1, 0),
+ ('pointer_motion', 1, 0), ('pointer_button', 1, 1), ('keyboard_key', 1, 1)]:
+ with self.subTest(kind=kind, lane=lane), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(DESTROYED + [(9, kind, lane, value)]), record(), action())
+ for corrupt in ('history', 'warp_return', 'missing_cancel', 'early_cancel'):
+ page = trace(DESTROYED)
+ if corrupt == 'history':
+ page['events'][1][1] += 1
+ elif corrupt == 'warp_return':
+ page = trace(DESTROYED + [(9, 'cursor', 0, 0), (10, 'cursor', 0, 0)])
+ page['events'][-2][3] += 2
+ elif corrupt == 'missing_cancel':
+ page = trace(ACTIVE)
+ else:
+ page['events'][-1][1] = 5_000_000
+ with self.subTest(corrupt=corrupt), self.assertRaises(AssertionError):
+ proof.verify_fault(page, record(), action())
+
+ def test_exit_absence_fresh_gate_and_pruned_state_required(self):
+ for mutate in [lambda r: r['gone'].update(pidfd_exited=False),
+ lambda r: r['gone'].update(window_absent=False),
+ lambda r: r.update(requested_ns=300_000_000),
+ lambda r: r.update(status_started_ns=7_000_000),
+ lambda r: r['after']['input']['lanes'][0].update(held_button=272),
+ lambda r: r['after']['input']['lanes'][0].update(pointer_resources=3),
+ lambda r: r['after']['input']['lanes'][1].update(dispatches=1),
+ lambda r: r['after']['input']['lanes'][1].update(pointer_resources=4),
+ lambda r: r['after']['input']['lanes'][1].update(reserved=True)]:
+ observed = record()
+ mutate(observed)
+ with self.subTest(record=observed), self.assertRaises(AssertionError):
+ proof.verify_fault(trace(DESTROYED), observed, action())
+
+
+class InjectionTests(unittest.TestCase):
+ def test_pidfd_binding_revalidates_identity_and_closes_on_failure(self):
+ with ExitStack() as stack:
+ guard = stack.enter_context(patch.object(proof.TargetLifetime, 'guard',
+ side_effect=[None, AssertionError('recycled PID')]))
+ stack.enter_context(patch.object(proof.subprocess, 'run', return_value=SimpleNamespace(returncode=0)))
+ for name in ('app_process_identity', 'check_calc', 'saved_document'):
+ stack.enter_context(patch.object(proof, name))
+ opened = stack.enter_context(patch.object(proof.os, 'pidfd_open', create=True, return_value=77))
+ closed = stack.enter_context(patch.object(proof.os, 'close'))
+ with self.assertRaisesRegex(AssertionError, 'recycled PID'):
+ proof.TargetLifetime(plan())
+ self.assertEqual(guard.call_count, 2)
+ opened.assert_called_once_with(20)
+ closed.assert_called_once_with(77)
+
+ def test_pidfd_only_once_and_no_signal_before_all_gates(self):
+ for failure in (None, 'identity', 'pending', 'held', 'stale', 'signal_lost', 'exit_timeout'):
+ with self.subTest(failure=failure), ExitStack() as stack:
+ fault = object.__new__(proof.TargetLifetime)
+ fault.fd, fault.sent, fault.record = 77, False, {}
+ fault.guard = Mock(side_effect=AssertionError('identity') if failure == 'identity' else None)
+ before, after = statuses()
+ fault.status = Mock(side_effect=[status() if failure == 'held' else before, after])
+ fault.gone = Mock(return_value={'pidfd_exited': True, 'window_absent': True, 'observed_ns': 9_000_000})
+ pending = Mock(done=Mock(return_value=failure == 'pending'))
+ stack.enter_context(patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2})))
+ stack.enter_context(patch.object(proof, 'saved_document'))
+ fault.spec = plan()['agents'][0]
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[5_000_000,
+ 300_000_000 if failure == 'stale' else 6_000_000, 10_000_000]))
+ send = stack.enter_context(patch.object(proof.signal, 'pidfd_send_signal', create=True,
+ side_effect=OSError('lost signal result') if failure == 'signal_lost' else None))
+ stack.enter_context(patch.object(proof, 'wait_for', side_effect=TimeoutError('exit')
+ if failure == 'exit_timeout' else lambda check, timeout: check()))
+ if failure:
+ with self.assertRaises((AssertionError, OSError, TimeoutError)):
+ fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock())
+ else:
+ self.assertEqual(fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock()), 1)
+ self.assertEqual(fault.record['result'], 'observed')
+ if failure in ('identity', 'pending', 'held', 'stale'):
+ send.assert_not_called()
+ else:
+ send.assert_called_once_with(77, proof.signal.SIGKILL)
+ with self.assertRaisesRegex(AssertionError, 'one termination'):
+ fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock())
+
+ def test_gone_requires_pidfd_exit_and_old_address_absence(self):
+ for exited, windows in ((False, []), (True, [{'pid': 21, 'address': '0xc8'}]),
+ (True, [{'pid': 20, 'address': '0xff'}]), (True, [])):
+ fault = object.__new__(proof.TargetLifetime)
+ fault.fd, fault.spec, fault.destroyed = 77, plan()['agents'][0], False
+ fault.guard = Mock(return_value=windows)
+ with patch.object(proof.select, 'select', return_value=([77] if exited else [], [], [])):
+ self.assertEqual(bool(fault.gone()), exited and not windows)
+
+
+class RecoveryTests(unittest.TestCase):
+ def test_one_fresh_distinct_action_unknown_never_replayed(self):
+ for failure in (None, 'alive', 'reused_runtime', 'stale', 'unknown', 'bad_effect', 'same_snapshot',
+ 'same_artifact', 'cached', 'before_return', 'same_runtime', 'dead_after'):
+ with self.subTest(failure=failure), ExitStack() as stack:
+ candidate = plan()
+ recovered_status = status()
+ recovered_status['input']['lanes'][0]['reserved'] = True
+ fault = SimpleNamespace(destroyed=True, spec=candidate['agents'][0], fresh=candidate['recovery']['agent'],
+ guard=Mock(), status=Mock(return_value=recovered_status))
+ client = Mock(process=Mock(pid=100 if failure == 'reused_runtime' else 101, poll=Mock(return_value=None)))
+ observer = Mock(directory=Path.cwd(), process=Mock(pid=101 if failure == 'same_runtime' else 102,
+ poll=Mock(side_effect=[None, 0] if failure == 'dead_after' else None, return_value=None)))
+ victim = Mock(process=Mock(pid=100, poll=Mock(return_value=None if failure == 'alive' else 0)))
+ client.tool.side_effect = [{}, TimeoutError('lost reply') if failure == 'unknown' else DELIVERED]
+ before = {'snapshot_id': 's00000001', 'proof_image': 'before.png',
+ 'proof_runtime': {'pid': 101, 'directory': str(Path.cwd())},
+ 'proof_observation_started_ns': 100, 'proof_observation_finished_ns': 101}
+ after = {**before, 'proof_runtime': {'pid': 102, 'directory': str(Path.cwd())},
+ 'proof_image': 'after.png', 'proof_observation_started_ns': 104, 'proof_observation_finished_ns': 105}
+ if failure == 'same_snapshot':
+ after = dict(before)
+ elif failure == 'same_artifact':
+ after['proof_image'] = before['proof_image']
+ elif failure == 'cached':
+ after.update(proof_observation_started_ns=100, proof_observation_finished_ns=101)
+ elif failure == 'before_return':
+ after['proof_observation_started_ns'] = 102
+ prepared = {'target': fault.fresh['target'], 'snapshot': before, 'prepared_ns': 100,
+ 'arguments': {'x': 20, 'y': 30}, 'oracle': {'stage': 'click_b2'}}
+ stack.enter_context(patch.object(proof, 'prepare_drag', return_value=prepared))
+ stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value=after))
+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=
+ [proof.MAX_GROUNDING_AGE_NS + 101] if failure == 'stale' else [102, 103, 106]))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value=[]))
+ stack.enter_context(patch.object(proof.pointer_grounding, 'verify',
+ side_effect=AssertionError('bad effect') if failure == 'bad_effect' else None))
+ page = trace(DESTROYED + [(12, 'agent_admitted', 1, 0), (13, 'pointer_button', 1, 1),
+ (14, 'pointer_button', 1, 0), (15, 'agent_action_end', 1, 0)])
+ collector, result = Mock(collect=Mock(return_value=page)), {}
+ if failure:
+ with self.assertRaises(AssertionError):
+ proof.recover(client, observer, victim, fault, collector, trace(DESTROYED), 1, Mock(), Mock(), result)
+ else:
+ proof.recover(client, observer, victim, fault, collector, trace(DESTROYED), 1, Mock(), Mock(), result)
+ self.assertEqual(result['result'], 'verified')
+ clicks = [call for call in client.tool.call_args_list if call.args[0] == 'click']
+ self.assertEqual(len(clicks), 0 if failure in ('alive', 'reused_runtime', 'stale', 'same_runtime') else 1)
+ if clicks:
+ self.assertEqual(clicks[0].args[1]['pid'], 30)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/realapp-validation.md b/libs/cua-driver/hyprland-plugin/tests/realapp-validation.md
new file mode 100644
index 0000000000..f5dad23340
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/realapp-validation.md
@@ -0,0 +1,186 @@
+# Concurrent real-app input validation
+
+On 2026-09-05, two independent Cua Driver MCP connections edited LibreOffice
+Calc and Inkscape in an Omarchy Fleet VM while a foreground fixture retained
+the primary pointer grab. Concurrent drags overlapped for 1.49–1.77 seconds.
+The parked and moving-pointer cases recorded no uncommanded primary motion,
+focus changes, foreground input leakage, or unexpected button releases.
+
+This is a nonshipping compatibility experiment in [draft
+#3572](https://github.com/trycua/cua/pull/3572), not production or bare-metal
+certification. The normal plugin build remains discovery-only. This record
+extends the earlier [single-seat GTK3 fixture result](input-validation.md);
+it does not change that result's tested revision or historical limitations.
+
+## Exact artifacts
+
+Native binaries came from committed source. The later proof-helper commit
+changes test orchestration and assertions, not either native binary.
+
+| Component | Tested identity |
+| --- | --- |
+| Native source | `571bbe356e41d531e13182363575d566b68b5e16` |
+| Proof helper source | `354c934ec6705a3fe039f4c2ae1da49e8fd22ec9` |
+| Omarchy | `4.0.1-1` |
+| Hyprland | `0.56.2-1`, commit `efb50993780079460b0cbed1363e2166a2de1d9f` |
+| Portal | `xdg-desktop-portal-hyprland 1.4.1-1` |
+| Driver source and installed version | `0.23.2`, task-local source build |
+| Plugin | `0.1.0`, explicitly enabled input experiment |
+| Compiler | GCC `16.1.1`, matching the compositor; shared C++ runtime |
+| LibreOffice | Arch package `26.2.5-3`, native Wayland |
+| Inkscape | Arch package `1.4.4-6`, native Wayland |
+| Recorder | `wf-recorder 0.6.0-2`, invoked through Driver recording |
+| Display | One 1920 × 1080 output, scale 1 |
+
+The artifact SHA-256 values are:
+
+- Native source archive: `b3abafc90a02a38c75c074191e493687f5845c1847c6119076adf26ca04a8b47`.
+- Plugin: `f4828207ac3af02425a901180bed922bd16ac5cec32f78aa28eb06ff69e53269`.
+- Driver: `2c924c7bd63bc167d4ac9c805932ff20a0d4ceeb06cc8f6e7a858788ce945dc9`.
+- `realapp_proof.py`: `b1545cf159ec9e97e1cd2f9e831db71259e07470804aab4474ba16d7be71b236`.
+
+The loaded plugin's ABI fingerprint matched
+`efb50993780079460b0cbed1363e2166a2de1d9f_aq_0.14_hu_0.14_hg_0.5_hc_0.1_hlg_0.6`.
+The installed executable and the running service's `/proc/PID/exe` had the
+same Driver digest. Installation used the repository's `install-local.sh`
+with task-local guest paths. Existing Driver installations were preserved;
+no host installation, Fleet image publication, merge, or release occurred.
+
+## What the tests measure
+
+[`realapp_proof.py`](realapp_proof.py) runs reviewed, deterministic plans through
+two separate MCP processes. Each owns a private lifecycle, an independently
+leased synthetic seat, and a visible agent cursor. Public session labels are
+not credentials. An external operator signs short-lived grants bound to the
+connection, target, and epoch; the private signing key never enters the VM.
+
+The desktop uses Omarchy's tiled layout: a foreground raw-event fixture beside
+Calc and Inkscape. Every background input call is bracketed by fresh Driver
+window snapshots. Plans pin the observed window identities and geometry and
+refuse a stale layout. The canvas and spreadsheet gestures deliberately
+exercise the raw plugin route. Every delivered action must report
+`route: synthetic_events`; the test cannot substitute an AT-SPI or foreground
+action and still pass.
+
+The independent app oracles read the files saved by Ctrl+S. They assert the
+numeric value of Calc cell B3 and a predeclared translation range for Inkscape's
+`agent-shape` rectangle, with unchanged width and height. Before/after files are
+retained. A successful transport response or cursor animation is not task proof.
+
+[`primary_grab.c`](primary_grab.c) supplies an independent virtual primary
+pointer, holding the foreground button throughout the measurement. The moving
+case commands a loop inside that window. This is not a physical mouse or a
+human gameplay test.
+
+[`primary_trace.py`](primary_trace.py) analyzes event-level compositor
+instrumentation, not periodic screenshots alone. It requires a complete,
+ordered trace with working hooks, start/stop markers, and no overflow or
+timeout. Incomplete telemetry is inconclusive. The checks cover:
+
+- Every observed primary cursor position, including transient warp-and-return.
+- Exact ordered correspondence with commanded motion in the moving case.
+- Primary pointer/keyboard focus and enter/leave events.
+- Foreground button, key, and scroll leakage, including unexpected releases.
+- Actual overlapping synthetic drag intervals, not overlapping animations.
+- Balanced synthetic button/key press and release counts in each lane.
+
+The foreground fixture's independent raw-event journal and compositor
+identity/workspace readback supplement the trace. HUD counters are cumulative;
+the harness compares baseline deltas for each run.
+
+## Results
+
+Each positive row has complete telemetry, no primary focus/leak/release
+violations, balanced synthetic input, and an empty cleanup-error list.
+
+| Case | Trace events | Primary motion | Drag overlap | App or control result | Video duration |
+| --- | ---: | --- | ---: | --- | ---: |
+| Parked primary | 168 | None | 1491.820 ms | Eight actions; B3 = 96; shape moved and saved | 37.083 s |
+| Moving primary | 731 | All 276 commands matched; no extra motion | 1537.106 ms | Eight actions; B3 = 75; shape moved and saved | 37.231 s |
+| Warp-and-return control | 7 | One uncommanded 50 px excursion detected | Not applicable | Detector correctly failed isolation despite identical endpoints | 17.441 s |
+| Cancel one lane | 91 | None | 337.783 ms | Calc drag cancelled; Inkscape finished and saved | 22.222 s |
+| Global Stop | 50 | None | 316.710 ms | Both in-flight drags returned `stopped` | 22.154 s |
+| Parked repeat after Stop | 181 | None | 1771.956 ms | Eight actions; B3 = 96; shape moved and saved | 37.097 s |
+
+Cancel and Stop were issued only after the trace showed both drags had started.
+After Cancel, further input on that lane required new operator approval while
+the other lane remained usable. After Stop, both lanes required new approval.
+Neither left a synthetic button or key held. These are test-operator protocol
+controls, not a claim of finished user-facing cancellation UX.
+
+Stop is not undo: partial app changes made before cancellation remain. The
+repeat plan accounted for the observed unsaved partial shape movement and
+declared its saved-file translation range before execution.
+
+The negative-control test passes only when isolation detection fails for the
+intended excursion. It issues no background app actions and must not be counted
+as a successful isolation run.
+
+## Recordings and retained evidence
+
+Every case has an uninterrupted original `recording.mp4`, MCP before/after
+snapshots, a guest-monotonic action timeline, the complete compositor trace,
+analysis JSON, and cleanup results. Successful app-edit cases also retain the
+saved documents. The recordings contain synthetic test content. Raw operational
+logs and authorization packets are not committed to the public repository.
+
+Video start-call and start-response timestamps bracket recorder startup; they
+do not provide frame-exact synchronization with the compositor trace. The live
+HUD provides visual correlation. All six original H.264 files decoded fully,
+and representative interaction and result frames were inspected. These are
+variable-frame-rate recordings. To check them without introducing null-muxer
+timestamp-rounding warnings, preserve the source timebase:
+
+```bash
+ffmpeg -v error -i recording.mp4 -fps_mode passthrough -enc_time_base demux -f null -
+```
+
+## Supporting checks
+
+- Six native plugin CTests passed: protocol, status, Linux transport, both
+ mocked API variants, and the CMake API probe.
+- Native Rust tests passed: 43 common runtime-isolation, four window-target,
+ seven `hyprland_input`, three `experimental_`, and two `primary_seat` tests.
+- All 36 Python helper tests passed with the cryptography dependency available.
+- The final module passed [`nested_lifecycle.py`](nested_lifecycle.py): two
+ owned nested compositors, six discovery mutation refusals per start, clean
+ restart, old socket/connection closure, fresh socket/epoch, sibling liveness,
+ and clean shutdown. The parent module was not reloaded by this test.
+- Final inspection found the original parent and app identities intact, both
+ leases inactive, the primary button released, and the intended Driver still
+ running. Fresh Driver desktop capture verified the scene after lifecycle
+ cleanup.
+
+These checks supplement the real-app evidence. They do not replace the
+repository's complete canonical desktop E2E matrix, which has not run for this
+candidate.
+
+## Setup failures and remaining limits
+
+Two failed attempts were retained rather than counted as passes:
+
+1. Approval before establishing the foreground hold allowed primary focus to
+ revoke the app lease. Input refused with `pending_operator_approval`. The
+ committed helper establishes the foreground hold before applying approval.
+2. Apps that survived an earlier plugin reload did not bind the replacement
+ synthetic input resources. Input refused with `client_not_bound`. Saving
+ the test document and restarting both apps fixed the test setup. App
+ survival after reload is not proof that input can resume without a restart.
+
+Exact-window foreground hotkeys also refused with `foreground_unavailable`
+because Hyprland exact-address activation is not implemented. Explicit Driver
+desktop input was used only for authorized setup, outside the background proof.
+
+This candidate supports two bounded experimental lanes, not arbitrary numbers
+of synthetic seats. It conservatively rejects primary/agent conflicts within
+the same Wayland client. Its resident `NODELETE` handlers remain a test-only
+unload workaround with a bounded reload count, not a production lifetime design.
+
+Unproven areas include Chromium/Ozone, Electron, GTK4, Qt6, XWayland,
+subsurfaces/popups, Unicode/IME/raw text, modified pointer gestures, fractional
+scaling, multiple monitors, target loss, mid-action geometry changes,
+lock/DPMS transitions, and held-state expiry/disconnect/unload. The earlier
+single-seat grant/replay tests are historical evidence, not fresh coverage of
+every two-lane interaction. Broader protocol tests, permission UX, resource
+lifetime review, [RFC #3550](https://github.com/trycua/cua/issues/3550), and the
+physical Omarchy acceptance gate remain open. Keep the implementation draft.
diff --git a/libs/cua-driver/hyprland-plugin/tests/realapp_proof.py b/libs/cua-driver/hyprland-plugin/tests/realapp_proof.py
new file mode 100644
index 0000000000..5f7c181d2c
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/realapp_proof.py
@@ -0,0 +1,378 @@
+"""Run reviewed, snapshot-grounded app tasks through independent Driver MCPs.
+
+The plan records exact observed window identities/bounds and actions. It is a
+deterministic regression runner, not an autonomous model benchmark. No signing
+key enters this process. Each input call has a fresh before/after snapshot;
+app output assertions live in the reviewed plan and are independently read.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import re
+import select
+import subprocess
+import threading
+import time
+from types import SimpleNamespace
+import xml.etree.ElementTree as ET
+
+from driver_input_live import MCP, wait_for, state, wm
+from primary_trace import Trace, analyze
+
+
+def cleanup_all(operations):
+ """Attempt every independent cleanup even after transport/recorder failure."""
+ errors = []
+ for name, operation in operations:
+ try:
+ operation()
+ except Exception as error:
+ errors.append({'operation': name, 'error': str(error)})
+ return errors
+
+
+def released_synthetic_input(data):
+ """Balance wire-level press/release events independently for both seats."""
+ balances = {(actor, kind): 0 for actor in (1, 2) for kind in ('pointer_button', 'keyboard_key')}
+ for row in data['events']:
+ key = (row[5], row[2])
+ if key in balances:
+ balances[key] += 1 if row[6] else -1
+ assert balances[key] >= 0, 'release without a captured synthetic press'
+ assert not any(balances.values()), 'synthetic input remains held at trace end'
+ return True
+
+
+def rect_position(node):
+ """Small independent oracle for the reviewed SVG rectangle fixture only."""
+ x, y = float(node.get('x', '0')), float(node.get('y', '0'))
+ transform = node.get('transform', '')
+ if transform:
+ match = re.fullmatch(r'translate\(\s*([-+\d.eE]+)[,\s]+([-+\d.eE]+)\s*\)', transform)
+ assert match, 'unsupported SVG transform; cannot establish saved geometry'
+ x += float(match[1]); y += float(match[2])
+ assert math.isfinite(x) and math.isfinite(y)
+ return [x, y]
+
+
+def validate_plan(plan):
+ assert len(plan['agents']) <= 2, 'only two independent lanes exist'
+ for phase in plan['phases']:
+ steps = phase.get('parallel', [] if phase.get('negative_control') else [phase])
+ agents = [step['agent'] for step in steps]
+ assert len(agents) == len(set(agents)), 'one MCP connection cannot serve concurrent steps'
+ assert all(type(index) is int and 0 <= index < len(plan['agents']) for index in agents)
+ if 'control' in phase:
+ assert 'parallel' in phase and len(agents) == 2
+ assert phase['control']['command'] in ('CANCEL', 'STOP')
+ assert phase['control']['agent'] in agents
+ for oracle in plan.get('outputs', []):
+ if 'rect_translation' in oracle:
+ assert len(oracle['rect_translation']) == 2
+ assert all(len(bounds) == 2 and bounds[0] <= bounds[1] for bounds in oracle['rect_translation'])
+
+
+def run(args):
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ plan = json.loads(args.plan.read_text())
+ validate_plan(plan)
+ (args.evidence / 'plan.json').write_text(json.dumps(plan, indent=2))
+ # A public label cannot be adopted by a new transport after a prior run.
+ # Evidence directories are exclusive, making these names run-specific.
+ for spec in plan['agents']:
+ spec['name'] += '-' + args.evidence.name
+ clients, operators = [], []
+ foreground = plan['foreground']
+ recorder = None
+ grab = None
+ watcher = None
+ mover = None
+ result = None
+ motion_done = threading.Event()
+ expected_motion = [] if plan.get('moving_primary') else None
+ motion_errors = []
+ done = threading.Event()
+ trace = Trace(args.input_directory / 'cua-input-test.sock')
+ before_app_files = {}
+ timeline_lock = threading.Lock()
+
+ def mark(event, **fields):
+ with timeline_lock, (args.evidence / 'timeline.jsonl').open('a') as stream:
+ stream.write(json.dumps({'monotonic_ns': time.monotonic_ns(), 'event': event, **fields}) + '\n')
+ for oracle in plan.get('outputs', []):
+ before_app_files[oracle['path']] = Path(oracle['path']).read_bytes()
+
+ def client(directory):
+ directory.mkdir()
+ return MCP(SimpleNamespace(evidence=directory, driver=args.driver, driver_socket=args.driver_socket))
+
+ def snapshot(mcp, target, label=None):
+ result = mcp.tool('get_window_state', {**target, 'max_elements': 100, 'max_depth': 6,
+ **({'session': label} if label else {})})
+ assert not result.get('isError'), result
+ assert result['structuredContent'].get('screenshot_width', 0) > 0, 'missing grounding image'
+ return result['structuredContent']
+
+ def action(index, step, ready=None):
+ mcp, spec = clients[index], plan['agents'][index]
+ before = snapshot(mcp, spec['target'], spec['name'])
+ assert before['window_bounds'] == spec['bounds'], 'target geometry changed since grounding'
+ if ready:
+ ready.wait(timeout=20)
+ mark('action_start', agent=index, tool=step['tool'])
+ result = mcp.tool(step['tool'], {**spec['target'], **step['arguments'],
+ 'session': spec['name'], 'delivery_mode': 'background'})
+ mark('action_response', agent=index, tool=step['tool'], error=bool(result.get('isError')))
+ after = snapshot(mcp, spec['target'], spec['name'])
+ if 'expect_refusal' in step:
+ assert result.get('isError') and result.get('structuredContent', {}).get('reason') == step['expect_refusal'], result
+ else:
+ assert not result.get('isError'), result
+ assert result['structuredContent']['route'] == 'synthetic_events', 'not plugin input evidence'
+ assert after['window_bounds'] == before['window_bounds']
+ primary_now = wm()
+ keys = ('pid', 'address', 'workspace') if expected_motion is not None else primary_before.keys()
+ assert all(primary_now[key] == primary_before[key] for key in keys), 'primary state changed'
+ current = state(args.foreground_journal)
+ assert all(current[key] == baseline[key] for key in ('clicks', 'keys', 'held')), current
+ return result['structuredContent']
+
+ def watch():
+ observer = Trace(args.input_directory / 'cua-input-test.sock')
+ rows = []
+ try:
+ while not done.wait(0.05):
+ page = observer.exchange('TRACE_READ ' + str(len(rows)))
+ rows.extend(page['events'])
+ if not rows:
+ continue
+ primary = [r for r in rows if r[5] == 0]
+ motions = [r[3:5] for r in primary if r[2] == 'cursor']
+ violations = (sum(math.dist(point, rows[0][3:5]) > .01 for point in motions)
+ if expected_motion is None else sum(i >= len(expected_motion) or math.dist(point, expected_motion[i]) > .01
+ for i, point in enumerate(motions)))
+ metrics = {'status': 'recording' if page['active'] else 'stopped',
+ 'cursor_violations': violations,
+ 'focus_events': sum(r[2] in ('pointer_focus', 'keyboard_focus', 'pointer_enter', 'pointer_leave', 'keyboard_enter', 'keyboard_leave') for r in primary),
+ 'releases': sum(r[2] == 'pointer_button' and r[6] == 0 for r in primary),
+ 'actions': sum(r[2] in ('agent_action_end', 'agent_drag_end') for r in rows)}
+ if page['overflow'] or page['timed_out'] or not page['hook']:
+ metrics['status'] = 'inconclusive'
+ if args.metrics:
+ temporary = args.metrics.with_suffix('.pending')
+ temporary.write_text(json.dumps(metrics))
+ temporary.replace(args.metrics)
+ finally:
+ observer.close()
+
+ def move_primary():
+ # Known commands from an independent primary-seat test source, not an
+ # agent overlay or a background input call. Every command is read back.
+ offsets = ([(x, 0) for x in range(20, 161, 20)] + [(160, y) for y in range(20, 161, 20)]
+ + [(x, 160) for x in range(140, -1, -20)] + [(0, y) for y in range(140, -1, -20)])
+ try:
+ index = 0
+ while not motion_done.wait(0.1):
+ dx, dy = offsets[index % len(offsets)]; index += 1
+ x, y = int(fg['x'] + point[0] + dx), int(fg['y'] + point[1] + dy)
+ assert fg['x'] < x < fg['x'] + fg['width'] and fg['y'] < y < fg['y'] + fg['height']
+ expected_motion.append([x, y])
+ mark('primary_motion_command', x=x, y=y)
+ grab.stdin.write(f'MOVE {x} {y}\n'); grab.stdin.flush()
+ assert select.select([grab.stdout], [], [], 2)[0], 'primary command acknowledgement missing'
+ assert grab.stdout.readline().strip() == f'MOVED {x} {y}'
+ except Exception as error:
+ motion_errors.append(str(error))
+
+ try:
+ for index, spec in enumerate(plan['agents']):
+ mcp = client(args.evidence / ('agent-' + str(index)))
+ clients.append(mcp)
+ started_session = mcp.tool('start_session', {'session': spec['name']})
+ assert not started_session.get('isError'), started_session
+ first = snapshot(mcp, spec['target'], spec['name'])
+ assert first['window_bounds'] == spec['bounds'], 'plan geometry is stale'
+ pending = mcp.tool('press_key', {**spec['target'], 'key': 'Escape', 'session': spec['name']})
+ snapshot(mcp, spec['target'], spec['name'])
+ request = pending.get('structuredContent', {})
+ assert pending.get('isError') and request.get('reason') == 'pending_operator_approval', pending
+ (args.evidence / f'grant-request-{index}.json').write_text(json.dumps(request))
+ print('GRANTS_REQUIRED', flush=True)
+ wait_for(lambda: all((args.evidence / f'grant-{i}.json').exists() for i in range(len(clients))), 180)
+ recorder = client(args.evidence / 'observer')
+ snapshot(recorder, foreground)
+ desktop = recorder.tool('get_desktop_state', {})['structuredContent']
+ fg = snapshot(recorder, foreground)['window_bounds']
+ point = plan.get('primary_point', [300, 300])
+ grab = subprocess.Popen([str(args.primary_grab), str(fg['x'] + point[0]), str(fg['y'] + point[1]),
+ str(desktop['screen_width']), str(desktop['screen_height']), '60000']
+ + (['controlled'] if expected_motion is not None else []),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ assert wait_for(lambda: select.select([grab.stdout], [], [], 0)[0])
+ assert grab.stdout.readline().strip() == 'HELD'
+ wait_for(lambda: state(args.foreground_journal)['held'])
+ snapshot(recorder, foreground)
+ primary_before = wm()
+ assert primary_before['pid'] == foreground['pid']
+ baseline = state(args.foreground_journal)
+ # Establish the independent primary hold before approval. A grant for a
+ # currently foreground client is correctly revoked by the compositor.
+ for index in range(len(clients)):
+ request = json.loads((args.evidence / f'grant-request-{index}.json').read_text())
+ grant = json.loads((args.evidence / f'grant-{index}.json').read_text())
+ assert all(grant[key] == request[key] for key in ('epoch', 'challenge', 'target'))
+ endpoint = 'cua-input-test.sock' if request['lane'] == 0 else 'cua-input-test-2.sock'
+ operator = Trace(args.input_directory / endpoint)
+ operators.append(operator)
+ operator.exchange(grant['packet'])
+ trace.exchange('TRACE_START')
+ watcher = threading.Thread(target=watch)
+ watcher.start()
+ mark('video_start_call')
+ recording = recorder.tool('start_recording', {'output_dir': str(args.evidence / 'video'), 'record_video': True})
+ mark('video_start_response')
+ assert not recording.get('isError'), recording
+ assert recording['structuredContent']['video_active'], recording
+ if expected_motion is not None:
+ mover = threading.Thread(target=move_primary)
+ mover.start()
+ started = time.monotonic()
+ results = []
+ for phase in plan['phases']:
+ time.sleep(phase.get('pause_before', 0))
+ if phase.get('negative_control'):
+ assert expected_motion is None, 'negative control requires a parked baseline'
+ snapshot(recorder, foreground)
+ mark('negative_control_start')
+ subprocess.run([str(args.primary_grab), str(fg['x'] + point[0]), str(fg['y'] + point[1]),
+ str(desktop['screen_width']), str(desktop['screen_height']), '100', 'canary'], check=True)
+ mark('negative_control_end')
+ snapshot(recorder, foreground)
+ assert wm() == primary_before, 'negative control must return to identical endpoints'
+ elif 'parallel' in phase:
+ ready = threading.Barrier(len(phase['parallel']))
+ control_offset = trace.exchange('TRACE_READ 0')['count']
+ with ThreadPoolExecutor(max_workers=len(clients)) as pool:
+ futures = [pool.submit(action, step['agent'], step, ready) for step in phase['parallel']]
+ if 'control' in phase:
+ started_actors = set()
+ def both_drags_started():
+ nonlocal control_offset
+ page = trace.exchange('TRACE_READ ' + str(control_offset))
+ control_offset += len(page['events'])
+ started_actors.update(row[5] for row in page['events'] if row[2] == 'agent_drag_start')
+ return started_actors == {1, 2}
+ wait_for(both_drags_started, 12)
+ time.sleep(0.25)
+ control = phase['control']
+ mark('operator_control', command=control['command'], agent=control['agent'])
+ operators[control['agent']].exchange(control['command'])
+ results.extend(future.result() for future in futures)
+ else:
+ results.append(action(phase['agent'], phase))
+ time.sleep(max(0, plan.get('minimum_video_seconds', 30) - (time.monotonic() - started)))
+ motion_done.set()
+ if mover: mover.join(timeout=5)
+ assert not motion_errors, motion_errors
+ snapshot(recorder, foreground)
+ mark('video_stop_call')
+ stopped = recorder.tool('stop_recording', {})
+ mark('video_stop_response')
+ assert not stopped.get('isError') and not stopped['structuredContent'].get('last_error'), stopped
+ trace.exchange('TRACE_STOP')
+ done.set(); watcher.join(timeout=5)
+ data = trace.collect()
+ report = analyze(data, expected_motion=expected_motion)
+ (args.evidence / 'expected-primary-motion.json').write_text(json.dumps(expected_motion))
+ if args.metrics:
+ args.metrics.write_text(json.dumps({'status': report['result'],
+ 'cursor_violations': report.get('uncommanded_motion_events'),
+ 'focus_events': report.get('focus_events'),
+ 'releases': report.get('unexpected_button_releases'),
+ 'actions': report.get('agent_action_completions')}))
+ (args.evidence / 'trace.json').write_text(json.dumps(data, indent=2))
+ (args.evidence / 'isolation.json').write_text(json.dumps(report, indent=2))
+ if plan.get('expect_detected_theft'):
+ assert report['result'] == 'failed' and report['uncommanded_motion_events'] > 0, report
+ assert 49 < report['max_primary_displacement_px'] <= 50, report
+ assert data['events'][0][3:5] == data['events'][-1][3:5], 'negative control endpoints differ'
+ else:
+ assert report['result'] == 'passed', report
+ if plan.get('require_overlap'):
+ assert report['agent_drag_overlap_ms'] >= 100, report
+ assert released_synthetic_input(data)
+ outputs = []
+ for output_index, oracle in enumerate(plan.get('outputs', [])):
+ content = Path(oracle['path']).read_bytes()
+ saved = args.evidence / 'saved-outputs'
+ saved.mkdir(exist_ok=True)
+ (saved / f'{output_index}-before{Path(oracle["path"]).suffix}').write_bytes(before_app_files[oracle['path']])
+ (saved / f'{output_index}-after{Path(oracle["path"]).suffix}').write_bytes(content)
+ assert content != before_app_files[oracle['path']], 'application did not save a changed file'
+ tree = ET.fromstring(content)
+ node = tree.find(oracle['xpath'], oracle.get('namespaces', {}))
+ assert node is not None, oracle
+ for key, expected in oracle.get('attributes', {}).items():
+ assert node.get(key) == expected, (key, node.attrib)
+ if 'rect_translation' in oracle:
+ original = ET.fromstring(before_app_files[oracle['path']]).find(oracle['xpath'], oracle.get('namespaces', {}))
+ assert original is not None
+ before_xy, after_xy = rect_position(original), rect_position(node)
+ delta = [b - a for a, b in zip(before_xy, after_xy)]
+ assert all(low <= value <= high for value, (low, high) in zip(delta, oracle['rect_translation'])), delta
+ assert all(node.get(key) == original.get(key) for key in ('width', 'height')), 'shape was resized'
+ outputs.append({'path': Path(oracle['path']).name, 'verified': True, 'attributes': node.attrib})
+ result = {'result': 'passed', 'isolation': report, 'outputs': outputs,
+ 'driver_actions': len(results), 'autonomous_model_benchmark': False,
+ 'synthetic_input_released': True,
+ 'harness_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
+ 'negative_control': bool(plan.get('expect_detected_theft')),
+ 'video': str(args.evidence / 'video' / 'recording.mp4')}
+ finally:
+ motion_done.set()
+ if mover: mover.join(timeout=5)
+ done.set()
+ if watcher: watcher.join(timeout=6)
+ try:
+ trace.exchange('TRACE_STOP')
+ data = trace.collect()
+ if not (args.evidence / 'trace.json').exists():
+ (args.evidence / 'trace.json').write_text(json.dumps(data, indent=2))
+ (args.evidence / 'isolation.json').write_text(json.dumps(analyze(data, expected_motion=expected_motion), indent=2))
+ except (OSError, RuntimeError): pass
+ operations = []
+ if recorder:
+ operations += [('stop_video', lambda: recorder.tool('stop_recording', {})), ('close_recorder', recorder.close)]
+ for index, operator in enumerate(operators):
+ operations += [(f'cancel_{index}', lambda op=operator: op.exchange('CANCEL')),
+ (f'close_operator_{index}', operator.close)]
+ def release_primary():
+ if grab and grab.poll() is None:
+ grab.terminate(); grab.wait(timeout=5)
+ if grab:
+ wait_for(lambda: not state(args.foreground_journal)['held'])
+ operations.append(('release_primary', release_primary))
+ operations.extend((f'close_agent_{i}', mcp.close) for i, mcp in enumerate(clients))
+ operations.append(('close_trace', trace.close))
+ cleanup_errors = cleanup_all(operations)
+ (args.evidence / 'cleanup.json').write_text(json.dumps({'errors': cleanup_errors}, indent=2))
+ if args.metrics and (result is None or cleanup_errors):
+ args.metrics.write_text(json.dumps({'status': 'failed', 'cursor_violations': None,
+ 'focus_events': None, 'releases': None, 'actions': None}))
+ assert not cleanup_errors, cleanup_errors
+ (args.evidence / 'result.json').write_text(json.dumps(result, indent=2))
+ print(json.dumps(result), flush=True)
+
+
+if __name__ == '__main__':
+ if not __debug__:
+ raise RuntimeError('assertions must be enabled')
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('driver', 'driver-socket', 'input-directory', 'primary-grab', 'plan', 'evidence', 'foreground-journal'):
+ parser.add_argument('--' + name, required=True, type=Path)
+ parser.add_argument('--metrics', type=Path)
+ run(parser.parse_args())
diff --git a/libs/cua-driver/hyprland-plugin/tests/realapp_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/realapp_proof_test.py
new file mode 100644
index 0000000000..cd52e6e193
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/realapp_proof_test.py
@@ -0,0 +1,55 @@
+import unittest
+import xml.etree.ElementTree as ET
+
+from realapp_proof import cleanup_all, rect_position, released_synthetic_input, validate_plan
+from primary_trace_test import START, STOP, trace
+
+
+class ProofOracles(unittest.TestCase):
+ def test_cleanup_failure_does_not_skip_primary_release(self):
+ completed = []
+ def broken():
+ raise OSError('closed test transport')
+ errors = cleanup_all([('video', broken), ('primary', lambda: completed.append(True))])
+ self.assertEqual(completed, [True])
+ self.assertEqual(errors[0]['operation'], 'video')
+
+ def test_synthetic_release_must_balance_within_each_lane(self):
+ press = ('pointer_button', 100, 200, 1, 1)
+ release = ('pointer_button', 100, 200, 1, 0)
+ self.assertTrue(released_synthetic_input(trace(START, press, release, STOP)))
+ for events in ((press,), (release,), (press, ('pointer_button', 100, 200, 2, 0))):
+ with self.assertRaises(AssertionError):
+ released_synthetic_input(trace(START, *events, STOP))
+
+ def test_control_requires_two_distinct_agents_and_known_command(self):
+ plan = {'agents': [{}, {}], 'phases': [{'parallel': [{'agent': 0}, {'agent': 1}],
+ 'control': {'command': 'CANCEL', 'agent': 0}}]}
+ validate_plan(plan)
+ plan['phases'][0]['control']['command'] = 'APPROVE'
+ with self.assertRaises(AssertionError):
+ validate_plan(plan)
+
+ def test_saved_rectangle_position_is_independent_of_ui(self):
+ self.assertEqual(rect_position(ET.fromstring('<rect x="120" y="170"/>')), [120, 170])
+ self.assertEqual(rect_position(ET.fromstring('<rect x="120" y="170" transform="translate(100,50)"/>')), [220, 220])
+ for transform in ('rotate(90)', 'matrix(1,0,0,1,0,0)', 'translate(nan,0)'):
+ with self.assertRaises(AssertionError):
+ rect_position(ET.Element('rect', {'transform': transform}))
+
+ def test_parallel_steps_cannot_share_a_transport(self):
+ plan = {'agents': [{}, {}], 'phases': [{'parallel': [{'agent': 0}, {'agent': 1}]}]}
+ validate_plan(plan)
+ plan['phases'][0]['parallel'][1]['agent'] = 0
+ with self.assertRaises(AssertionError):
+ validate_plan(plan)
+
+ def test_missing_delta_or_out_of_range_agent_cannot_pass(self):
+ with self.assertRaises(AssertionError):
+ validate_plan({'agents': [{}], 'phases': [{'agent': 1}]})
+ with self.assertRaises(AssertionError):
+ validate_plan({'agents': [], 'phases': [], 'outputs': [{'rect_translation': []}]})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/retirement_evidence.py b/libs/cua-driver/hyprland-plugin/tests/retirement_evidence.py
new file mode 100644
index 0000000000..15fd9d42a6
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/retirement_evidence.py
@@ -0,0 +1,110 @@
+"""Fail-closed, pure evidence oracles for native input-seat retirement.
+
+Passing these helpers on synthetic data is not native compositor evidence.
+"""
+import re
+
+
+NAMES = {"Cua-Test-Agent", "Cua-Test-Agent-2"}
+
+
+def active_experiment(status):
+ experiment = status.get("experiment", {})
+ if (status.get("name") != "cua-hyprland-plugin"
+ or status.get("state") != "input_experiment"
+ or status.get("configured") is not True
+ or status.get("abi", {}).get("match") is not True
+ or status.get("transport", {}).get("ready") is not True
+ or experiment.get("transport_ready") is not True
+ or experiment.get("test_only") is not True
+ or experiment.get("protocol") != 0
+ or experiment.get("seat_lifetime") != "compositor"
+ or experiment.get("upgrade") != "desktop_restart"):
+ raise AssertionError("require the active, ABI-matched restart-required experiment")
+ lanes = experiment.get("lanes", [])
+ if len(lanes) != 2 or {lane.get("lane") for lane in lanes} != {0, 1}:
+ raise AssertionError("require both input lanes")
+ for lane in lanes:
+ if any(lane.get(field) != 0 for field in ("held_button", "held_keys")) or any(
+ lane.get(field) is not False for field in ("lease_active", "drag_active", "reserved")):
+ raise AssertionError("input lanes must be idle and unclaimed before the test")
+
+
+def replacement_refusal(status):
+ """A missing plugin/disabled config/ABI error cannot pass retirement refusal.
+
+PLUGIN_INIT registers status successfully; the enabled config reload then
+refuses seat creation and records its runtime error. A load exit code alone
+does not prove this path was reached.
+"""
+ transport = status.get("transport", {})
+ errors = {
+ "input seat lifetime unavailable; restart the desktop before loading a replacement plugin",
+ "restart desktop before replacing input seats",
+ }
+ if (status.get("name") != "cua-hyprland-plugin"
+ or status.get("configured") is not True
+ or status.get("abi", {}).get("match") is not True
+ or status.get("state") != "discovery_only"
+ or status.get("compositor_epoch") != 0
+ or transport.get("ready") is not False
+ or transport.get("last_error") not in errors
+ or status.get("capabilities", {}).get("enabled") != []
+ or "experiment" in status):
+ raise AssertionError("missing explicit configured runtime retirement refusal")
+ return {"runtime_restart_refusal": True, "transport_ready": False}
+
+
+def bound_seats(wire):
+ """Resolve both named synthetic seats to registry globals and client IDs."""
+ bindings = {}
+ for match in re.finditer(
+ r'wl_registry[#@]\d+\.bind\((\d+), "wl_seat", \d+, new id [^#@\n]+[#@](\d+)\)', wire):
+ global_id, resource = map(int, match.groups())
+ bindings[resource] = global_id
+ named = {}
+ for match in re.finditer(r'wl_seat[#@](\d+)\.name\("([^"]+)"\)', wire):
+ resource, name = match.groups()
+ if name in NAMES:
+ resource = int(resource)
+ if name in named or resource not in bindings:
+ raise AssertionError("ambiguous or missing synthetic seat binding")
+ if not re.search(rf'wl_seat[#@]{resource}\.capabilities\([1-7]\)', wire):
+ raise AssertionError("synthetic seat has no enabled capabilities evidence")
+ named[name] = (resource, bindings[resource])
+ if set(named) != NAMES or len(set(named.values())) != 2:
+ raise AssertionError("both distinct synthetic seats must be bound before unload")
+ return named
+
+
+def retired_seats(seats, wire):
+ if set(seats) != NAMES or len(set(seats.values())) != 2:
+ raise AssertionError("require both distinct preflight seat bindings")
+ for resource, global_id in seats.values():
+ if not re.search(rf'wl_seat[#@]{resource}\.capabilities\(0\)', wire):
+ raise AssertionError("missing zero-capability notification for retired seat")
+ if not re.search(rf'wl_registry[#@]\d+\.global_remove\({global_id}\)', wire):
+ raise AssertionError("missing retired seat global removal")
+ if re.search(rf'wl_seat[#@]{resource}\.capabilities\([1-7]\)', wire):
+ raise AssertionError("retired seat capabilities re-enabled")
+ if re.search(r'wl_registry[#@]\d+\.global\(\d+, "wl_seat",', wire):
+ raise AssertionError("unexpected new seat global after retirement")
+ return {"retired_seats": len(seats), "capabilities_zero": True, "globals_removed": True}
+
+
+def socket_closed(client):
+ """Require EOF/reset; timeouts and arbitrary I/O errors are failures."""
+ try:
+ if client.recv(2048) != b"":
+ raise AssertionError("old connection still returned data")
+ except ConnectionResetError:
+ pass
+ return True
+
+
+def service_owns_socket(unix_table, fd_links, path):
+ """Bind the requested MCP socket to the selected live service, not a label."""
+ rows = [line.split(maxsplit=7) for line in unix_table.splitlines()]
+ matches = [row for row in rows if len(row) == 8 and row[7] == str(path)]
+ if len(matches) != 1 or "socket:[" + matches[0][6] + "]" not in fd_links:
+ raise AssertionError("Driver socket is not uniquely owned by the selected service")
diff --git a/libs/cua-driver/hyprland-plugin/tests/retirement_evidence_test.py b/libs/cua-driver/hyprland-plugin/tests/retirement_evidence_test.py
new file mode 100644
index 0000000000..b1c3bc6939
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/retirement_evidence_test.py
@@ -0,0 +1,179 @@
+"""Synthetic oracle tests only; no plugin load, desktop, or input execution."""
+import socket
+import unittest
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from input_retirement_live import preflight
+from retirement_evidence import active_experiment, bound_seats, replacement_refusal, retired_seats, service_owns_socket, socket_closed
+
+
+def active():
+ return {"name": "cua-hyprland-plugin", "state": "input_experiment", "configured": True, "abi": {"match": True},
+ "transport": {"ready": True}, "experiment": {"transport_ready": True,
+ "test_only": True, "protocol": 0,
+ "seat_lifetime": "compositor", "upgrade": "desktop_restart", "lanes": [
+ {"lane": lane, "held_button": 0, "held_keys": 0, "lease_active": False,
+ "drag_active": False, "reserved": False} for lane in (0, 1)]}}
+
+
+def refusal():
+ return {"name": "cua-hyprland-plugin", "configured": True, "state": "discovery_only",
+ "compositor_epoch": 0, "abi": {"match": True}, "capabilities": {"enabled": []},
+ "transport": {"ready": False, "last_error":
+ "input seat lifetime unavailable; restart the desktop before loading a replacement plugin"}}
+
+
+BOUND = '''[100] -> wl_registry#2.bind(41, "wl_seat", 7, new id [unknown]#10)
+[101] wl_seat#10.capabilities(3)
+[102] wl_seat#10.name("Cua-Test-Agent")
+[103] -> wl_registry#2.bind(42, "wl_seat", 7, new id wl_seat#11)
+[104] wl_seat#11.capabilities(3)
+[105] wl_seat#11.name("Cua-Test-Agent-2")
+'''
+RETIRED = '''[200] wl_seat#10.capabilities(0)
+[201] wl_registry#2.global_remove(41)
+[202] wl_seat#11.capabilities(0)
+[203] wl_registry#2.global_remove(42)
+'''
+
+
+class RetirementEvidenceTest(unittest.TestCase):
+ def test_active_requires_two_idle_restart_required_lanes(self):
+ active_experiment(active())
+ for field, value in (("held_button", 272), ("held_keys", 1), ("lease_active", True),
+ ("drag_active", True), ("reserved", True)):
+ candidate = active()
+ candidate["experiment"]["lanes"][1][field] = value
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ active_experiment(candidate)
+
+ def test_missing_duplicate_and_wrong_contract_lanes_fail(self):
+ for change in ({"lanes": []}, {"lanes": [active()["experiment"]["lanes"][0]] * 2},
+ {"upgrade": "hot_reload"}, {"seat_lifetime": "plugin"}, {"transport_ready": False}):
+ candidate = active()
+ candidate["experiment"].update(change)
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ active_experiment(candidate)
+
+ def test_structured_runtime_refusal(self):
+ self.assertEqual(replacement_refusal(refusal()),
+ {"runtime_restart_refusal": True, "transport_ready": False})
+ candidate = refusal()
+ candidate["transport"]["last_error"] = "restart desktop before replacing input seats"
+ replacement_refusal(candidate)
+
+ def test_plugin_absence_disabled_configuration_and_abi_refusal_are_not_retirement(self):
+ for change in ({"name": "other"}, {"configured": False}, {"abi": {"match": False}},
+ {"state": "input_experiment"}, {"compositor_epoch": 1},
+ {"experiment": {}}, {"capabilities": {"enabled": ["discovery"]}},
+ {"transport": {"ready": False, "last_error": "ABI mismatch"}},
+ {"transport": {"ready": False, "last_error": ""}}):
+ with self.subTest(change=change), self.assertRaises(AssertionError):
+ replacement_refusal({**refusal(), **change})
+ for absent in ({}, {"error": "unknown request"}, {"ok": False}):
+ with self.subTest(absent=absent), self.assertRaises(AssertionError):
+ replacement_refusal(absent)
+
+ def test_partial_status_never_passes(self):
+ for field in refusal():
+ candidate = refusal()
+ del candidate[field]
+ with self.subTest(field=field), self.assertRaises(AssertionError):
+ replacement_refusal(candidate)
+
+ def test_ready_transport_with_restart_error_still_fails(self):
+ candidate = refusal()
+ candidate["transport"]["ready"] = True
+ with self.assertRaises(AssertionError):
+ replacement_refusal(candidate)
+
+ def test_both_wayland_log_resource_delimiters(self):
+ for delimiter in ("#", "@"):
+ with self.subTest(delimiter=delimiter):
+ seats = bound_seats(BOUND.replace("#", delimiter))
+ self.assertEqual(seats, {"Cua-Test-Agent": (10, 41), "Cua-Test-Agent-2": (11, 42)})
+ self.assertEqual(retired_seats(seats, RETIRED.replace("#", delimiter)),
+ {"retired_seats": 2, "capabilities_zero": True, "globals_removed": True})
+
+ def test_absent_unbound_ambiguous_or_disabled_initial_seats_fail(self):
+ for wire in ("", BOUND.replace('"Cua-Test-Agent-2"', '"primary"'),
+ BOUND.replace('new id wl_seat#11', 'new id wl_seat#12'),
+ BOUND.replace("capabilities(3)", "capabilities(0)"),
+ BOUND + 'wl_seat#13.name("Cua-Test-Agent")\n'):
+ with self.subTest(wire=wire), self.assertRaises(AssertionError):
+ bound_seats(wire)
+
+ def test_each_resource_requires_both_retirement_events(self):
+ lines = RETIRED.splitlines(keepends=True)
+ for index in range(len(lines)):
+ with self.subTest(index=index), self.assertRaises(AssertionError):
+ retired_seats(bound_seats(BOUND), "".join(lines[:index] + lines[index + 1:]))
+
+ def test_empty_or_duplicate_bindings_cannot_pass_retirement(self):
+ for seats in ({}, {"Cua-Test-Agent": (10, 41)},
+ {"Cua-Test-Agent": (10, 41), "Cua-Test-Agent-2": (10, 41)}):
+ with self.subTest(seats=seats), self.assertRaises(AssertionError):
+ retired_seats(seats, RETIRED)
+
+ def test_wrong_resource_ids_do_not_prove_cleanup(self):
+ for wire in (RETIRED.replace("#10.", "#110."), RETIRED.replace("(41)", "(141)")):
+ with self.subTest(wire=wire), self.assertRaises(AssertionError):
+ retired_seats(bound_seats(BOUND), wire)
+
+ def test_republished_global_or_reenabled_capabilities_fail(self):
+ for suffix in ('wl_seat#10.capabilities(3)', 'wl_registry#2.global(43, "wl_seat", 7)'):
+ with self.subTest(suffix=suffix), self.assertRaises(AssertionError):
+ retired_seats(bound_seats(BOUND), RETIRED + suffix)
+
+ def test_closure_requires_eof_or_reset(self):
+ client = Mock()
+ client.recv.return_value = b""
+ self.assertTrue(socket_closed(client))
+ client.recv.side_effect = ConnectionResetError()
+ self.assertTrue(socket_closed(client))
+ for error in (socket.timeout(), PermissionError(), OSError()):
+ client.recv.side_effect = error
+ with self.subTest(error=type(error)), self.assertRaises(type(error)):
+ socket_closed(client)
+
+ def test_open_connection_or_buffered_response_is_not_closure(self):
+ client = Mock()
+ client.recv.return_value = b'{"ok":true}'
+ with self.assertRaises(AssertionError):
+ socket_closed(client)
+
+ def test_opt_in_refuses_before_any_hyprctl_query(self):
+ with patch("input_retirement_live.ctl") as command, patch("input_retirement_live.sys.platform", "linux"):
+ with self.assertRaisesRegex(ValueError, "opt-in"):
+ preflight(SimpleNamespace(disposable_session_restart_required=False))
+ command.assert_not_called()
+
+ def test_non_linux_refuses_even_with_opt_in(self):
+ with patch("input_retirement_live.ctl") as command, patch("input_retirement_live.sys.platform", "darwin"):
+ with self.assertRaises(ValueError):
+ preflight(SimpleNamespace(disposable_session_restart_required=True))
+ command.assert_not_called()
+
+ def test_wrong_selected_instance_refuses_before_status_or_mutation(self):
+ args = SimpleNamespace(disposable_session_restart_required=True, compositor_pid=123)
+ with patch("input_retirement_live.sys.platform", "linux"), patch.dict(
+ "input_retirement_live.os.environ", {"HYPRLAND_INSTANCE_SIGNATURE": "synthetic-instance"}), patch(
+ "input_retirement_live.ctl", return_value='[{"instance":"synthetic-instance","pid":456}]') as command:
+ with self.assertRaisesRegex(ValueError, "selected disposable compositor"):
+ preflight(args)
+ command.assert_called_once_with("-j", "instances")
+
+ def test_service_socket_requires_matching_inode_and_exact_path(self):
+ table = "000: 00000002 00000000 00010000 0001 01 456 /run/synthetic/driver.sock\n"
+ service_owns_socket(table, ["socket:[456]"], "/run/synthetic/driver.sock")
+ for records, links, path in ((table, ["socket:[789]"], "/run/synthetic/driver.sock"),
+ (table, ["socket:[456]"], "/run/other/driver.sock"),
+ (table + table, ["socket:[456]"], "/run/synthetic/driver.sock"),
+ ("", ["socket:[456]"], "/run/synthetic/driver.sock")):
+ with self.subTest(records=records, links=links, path=path), self.assertRaises(AssertionError):
+ service_owns_socket(records, links, path)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/seat_lifetime_test.cpp b/libs/cua-driver/hyprland-plugin/tests/seat_lifetime_test.cpp
new file mode 100644
index 0000000000..e9f5b33e31
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/seat_lifetime_test.cpp
@@ -0,0 +1,50 @@
+#include "seat_lifetime.hpp"
+
+#include <array>
+#include <cstdlib>
+#include <iostream>
+
+namespace {
+void check(bool condition, const char* message) {
+ if (!condition) {
+ std::cerr << "FAIL: " << message << '\n';
+ std::exit(1);
+ }
+}
+bool refused(const std::string& directory) {
+ try {
+ cua::hyprland::SeatLifetime second(directory);
+ return false;
+ } catch (const std::runtime_error&) {
+ return true;
+ }
+}
+}
+
+int main() {
+ std::array<char, 64> pattern{};
+ const std::string seed = "/tmp/cua-seat-lifetime-XXXXXX";
+ seed.copy(pattern.data(), seed.size());
+ const auto* created = mkdtemp(pattern.data());
+ check(created != nullptr, "create isolated instance directory");
+ const std::string directory(created);
+ const auto marker = directory + "/cua-input-seat-lifetime";
+ {
+ cua::hyprland::SeatLifetime failed_initialization(directory);
+ check(refused(directory), "parallel initialization refuses");
+ }
+ check(access(marker.c_str(), F_OK) != 0, "failed initialization releases reservation");
+ {
+ cua::hyprland::SeatLifetime initialized(directory);
+ initialized.publish();
+ }
+ check(refused(directory), "replacement after publication requires desktop restart");
+ struct stat metadata{};
+ check(lstat(marker.c_str(), &metadata) == 0 && S_ISDIR(metadata.st_mode) &&
+ (metadata.st_mode & 0777) == 0700,
+ "lifetime marker stays private");
+ // This is the test-owned desktop teardown, never plugin hot unload.
+ check(rmdir(marker.c_str()) == 0, "remove test instance marker");
+ check(rmdir(directory.c_str()) == 0, "remove test instance directory");
+ std::cout << "seat lifetime tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/session_lock_fixture.c b/libs/cua-driver/hyprland-plugin/tests/session_lock_fixture.c
new file mode 100644
index 0000000000..b5eecb5294
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/session_lock_fixture.c
@@ -0,0 +1,205 @@
+/* Disposable-guest adversary, not an authentication/production lock screen.
+ * Generate ext-session-lock-v1-client-protocol.h and protocol C with
+ * wayland-scanner from wayland-protocols/staging/ext-session-lock/
+ * ext-session-lock-v1.xml, then link this file and generated C with
+ * pkg-config --cflags --libs wayland-client. Output binary: session_lock_fixture.
+ *
+ * Supply an opaque lock surface on each advertised output. Waiting for the
+ * compositor's missing-surface fallback would measure its grace period rather
+ * than a normally configured lock. Recovery sends unlock_and_destroy and waits
+ * for a wl_display.sync acknowledgment. Never kill this client to unlock.
+ */
+#define _GNU_SOURCE
+#include <wayland-client.h>
+#include "ext-session-lock-v1-client-protocol.h"
+#include <errno.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/mman.h>
+#include <time.h>
+#include <unistd.h>
+
+static struct ext_session_lock_manager_v1 *manager;
+static struct ext_session_lock_v1 *lock;
+static struct wl_compositor *compositor;
+static struct wl_shm *shm;
+static struct output {
+ struct wl_output *output;
+ struct wl_surface *surface;
+ struct ext_session_lock_surface_v1 *lock_surface;
+} outputs[16];
+static unsigned output_count;
+static int locked, finished, synced;
+static volatile sig_atomic_t release_requested;
+
+static uint64_t now_ns(void) {
+ struct timespec value;
+ clock_gettime(CLOCK_MONOTONIC, &value);
+ return (uint64_t)value.tv_sec * 1000000000ULL + value.tv_nsec;
+}
+static void event(const char *name) {
+ printf("{\"event\":\"%s\",\"observed_ns\":%llu}\n", name,
+ (unsigned long long)now_ns());
+ fflush(stdout);
+}
+static void release(int sig) { (void)sig; release_requested = 1; }
+static void buffer_released(void *data, struct wl_buffer *buffer) {
+ (void)data; wl_buffer_destroy(buffer);
+}
+static const struct wl_buffer_listener buffer_listener = {buffer_released};
+static void configure(void *data, struct ext_session_lock_surface_v1 *surface,
+ uint32_t serial, uint32_t width, uint32_t height) {
+ struct output *output = data;
+ if (!width || !height || width > 8192 || height > 8192) exit(1);
+ size_t bytes = (size_t)width * height * 4;
+ int fd = memfd_create("test-lock-black", MFD_CLOEXEC);
+ if (fd < 0 || ftruncate(fd, (off_t)bytes)) exit(1);
+ /* A fresh memfd is zero-filled. XRGB ignores alpha, so it is opaque black. */
+ struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, (int32_t)bytes);
+ struct wl_buffer *buffer = wl_shm_pool_create_buffer(pool, 0, (int32_t)width,
+ (int32_t)height, (int32_t)width * 4, WL_SHM_FORMAT_XRGB8888);
+ wl_shm_pool_destroy(pool); close(fd);
+ wl_buffer_add_listener(buffer, &buffer_listener, NULL);
+ ext_session_lock_surface_v1_ack_configure(surface, serial);
+ wl_surface_attach(output->surface, buffer, 0, 0);
+ wl_surface_damage(output->surface, 0, 0, (int32_t)width, (int32_t)height);
+ wl_surface_commit(output->surface);
+}
+static const struct ext_session_lock_surface_v1_listener surface_listener = {configure};
+static void global(void *data, struct wl_registry *registry, uint32_t name,
+ const char *interface, uint32_t version) {
+ (void)data; (void)version;
+ if (!strcmp(interface, "ext_session_lock_manager_v1"))
+ manager = wl_registry_bind(registry, name, &ext_session_lock_manager_v1_interface, 1);
+ else if (!strcmp(interface, "wl_compositor"))
+ compositor = wl_registry_bind(registry, name, &wl_compositor_interface, 1);
+ else if (!strcmp(interface, "wl_shm"))
+ shm = wl_registry_bind(registry, name, &wl_shm_interface, 1);
+ else if (!strcmp(interface, "wl_output")) {
+ if (output_count == 16) exit(1);
+ outputs[output_count++].output = wl_registry_bind(registry, name, &wl_output_interface, 1);
+ }
+}
+static void removed(void *data, struct wl_registry *registry, uint32_t name) {
+ (void)data; (void)registry; (void)name;
+}
+static const struct wl_registry_listener registry_listener = {global, removed};
+static void on_locked(void *data, struct ext_session_lock_v1 *object) {
+ (void)data; (void)object; locked = 1; event("locked");
+}
+static void on_finished(void *data, struct ext_session_lock_v1 *object) {
+ (void)data; (void)object; finished = 1; event("finished");
+}
+static const struct ext_session_lock_v1_listener lock_listener = {on_locked, on_finished};
+static void on_sync(void *data, struct wl_callback *callback, uint32_t serial) {
+ (void)data; (void)serial; synced = 1; wl_callback_destroy(callback);
+}
+static const struct wl_callback_listener sync_listener = {on_sync};
+
+/* All display waits are bounded. A hung compositor cannot wedge this helper
+ * indefinitely; a missing unlocked acknowledgment is failure, never success. */
+static int pump(struct wl_display *display, int watch_stdin) {
+ if (wl_display_dispatch_pending(display) < 0) return -1;
+ if (wl_display_flush(display) < 0 && errno != EAGAIN) return -1;
+ struct pollfd fds[2] = {{wl_display_get_fd(display), POLLIN, 0},
+ {watch_stdin ? STDIN_FILENO : -1, POLLIN, 0}};
+ int ready = poll(fds, 2, 20);
+ if (ready < 0) return errno == EINTR ? 0 : -1;
+ if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) return -1;
+ if ((fds[0].revents & POLLIN) && wl_display_dispatch(display) < 0) return -1;
+ if (fds[1].revents & (POLLIN | POLLHUP | POLLERR)) {
+ char byte;
+ /* Once LOCK has been read, any additional byte or EOF requests unlock. */
+ (void)read(STDIN_FILENO, &byte, 1);
+ release_requested = 1;
+ }
+ return 0;
+}
+static long number(const char *text, long min, long max) {
+ char *end; errno = 0;
+ long result = strtol(text, &end, 10);
+ if (errno || !*text || *end || result < min || result > max) exit(2);
+ return result;
+}
+
+int main(int argc, char **argv) {
+ if (argc != 3) return 2;
+ long duration = number(argv[1], 2000, 20000);
+ pid_t expected = (pid_t)number(argv[2], 2, 2147483647);
+ struct sigaction action = {.sa_handler = release};
+ sigemptyset(&action.sa_mask);
+ sigaction(SIGUSR1, &action, NULL);
+ sigaction(SIGTERM, &action, NULL);
+ sigaction(SIGINT, &action, NULL);
+ signal(SIGPIPE, SIG_IGN);
+ struct wl_display *display = wl_display_connect(NULL);
+ if (!display) return 1;
+ struct ucred peer;
+ socklen_t size = sizeof(peer);
+ if (getsockopt(wl_display_get_fd(display), SOL_SOCKET, SO_PEERCRED, &peer, &size) ||
+ peer.pid != expected || peer.uid != getuid()) return 1;
+ struct wl_registry *registry = wl_display_get_registry(display);
+ wl_registry_add_listener(registry, &registry_listener, NULL);
+ struct wl_callback *callback = wl_display_sync(display);
+ wl_callback_add_listener(callback, &sync_listener, NULL);
+ uint64_t deadline = now_ns() + 2000000000ULL;
+ while (!synced && now_ns() < deadline && !release_requested)
+ if (pump(display, 0) < 0) return 1;
+ if (!synced || !manager || !compositor || !shm || !output_count || release_requested) return 1;
+ event("ready");
+ /* Byte-wise bounded input prevents an incomplete command from blocking the
+ * independent deadline. No arbitrary commands or real credentials exist. */
+ char command[5]; unsigned used = 0;
+ deadline = now_ns() + 3000000000ULL;
+ while (used < sizeof(command) && now_ns() < deadline && !release_requested) {
+ struct pollfd input = {STDIN_FILENO, POLLIN, 0};
+ if (poll(&input, 1, 20) < 0 && errno != EINTR) return 1;
+ if (input.revents & (POLLIN | POLLHUP)) {
+ if (read(STDIN_FILENO, command + used, 1) != 1) return 1;
+ ++used;
+ }
+ }
+ if (used != sizeof(command) || memcmp(command, "LOCK\n", sizeof(command)) || release_requested) return 1;
+ lock = ext_session_lock_manager_v1_lock(manager);
+ ext_session_lock_v1_add_listener(lock, &lock_listener, NULL);
+ for (unsigned i = 0; i < output_count; ++i) {
+ outputs[i].surface = wl_compositor_create_surface(compositor);
+ outputs[i].lock_surface = ext_session_lock_v1_get_lock_surface(lock,
+ outputs[i].surface, outputs[i].output);
+ ext_session_lock_surface_v1_add_listener(outputs[i].lock_surface,
+ &surface_listener, &outputs[i]);
+ }
+ deadline = now_ns() + (uint64_t)duration * 1000000ULL;
+ while (!finished && !locked && now_ns() < deadline)
+ if (pump(display, 1) < 0) return 1;
+ if (finished) { ext_session_lock_v1_destroy(lock); wl_display_flush(display); return 1; }
+ if (!locked) return 1; /* No protocol unlock is legal before locked. */
+ while (!release_requested && now_ns() < deadline)
+ if (pump(display, 1) < 0) return 1;
+ ext_session_lock_v1_unlock_and_destroy(lock);
+ synced = 0;
+ callback = wl_display_sync(display);
+ wl_callback_add_listener(callback, &sync_listener, NULL);
+ deadline = now_ns() + 2000000000ULL;
+ while (!synced && now_ns() < deadline)
+ if (pump(display, 0) < 0) return 1;
+ if (!synced) return 1;
+ event("unlocked");
+ for (unsigned i = 0; i < output_count; ++i) {
+ ext_session_lock_surface_v1_destroy(outputs[i].lock_surface);
+ wl_surface_destroy(outputs[i].surface);
+ wl_output_destroy(outputs[i].output);
+ }
+ ext_session_lock_manager_v1_destroy(manager);
+ wl_shm_destroy(shm);
+ wl_compositor_destroy(compositor);
+ wl_registry_destroy(registry);
+ wl_display_flush(display);
+ wl_display_disconnect(display);
+ return 0;
+}
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 56a6016a6a..9287389a89 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -1257,6 +1257,7 @@ name = "cua-driver-testkit"
version = "0.23.2"
dependencies = [
"core-foundation",
+ "image",
"libc",
"objc2-app-kit 0.2.2",
"serde",
@@ -3223,6 +3224,7 @@ dependencies = [
"dirs",
"enumflags2",
"evdev",
+ "futures-util",
"getrandom 0.4.2",
"image",
"keyring",
diff --git a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
index c6d0cb65bc..5a84eb0024 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
@@ -66,9 +66,9 @@ focus, workspace, or compositor cursor.
### Persistent focus-proxy exception
-`bring_to_front` is not part of the normal input ladder. For an ordinary
-`background_unavailable` response, retry only the refused action with
-`delivery_mode:"foreground"`; cua-driver activates the target, performs the
+`bring_to_front` is not part of the normal input ladder. After an ordinary
+`background_unavailable` response, and only with foreground authorization,
+retry the refused action with `delivery_mode:"foreground"`; cua-driver activates the target, performs the
action, and restores the prior active window. Use `bring_to_front` only when a
focus-proxy surface must remain foreground across multiple calls, such as a
remote desktop session, or when repeated action-scoped activation prevents the
@@ -85,8 +85,9 @@ those through `verify_state` or multimodal reading.
**Escalation** — action responses use the cross-platform closed
`escalation:{target, reason}` shape. See `SKILL.md` → behavior matrix. On a
standard Wayland compositor the Linux-specific target is **`foreground`**
-(raw background pixels cannot target an unfocused window); the opt-in nested
-compositor is a separate environment. Use **`pixel` on X11** (an element px
+(raw background pixels cannot target an unfocused window without a dedicated
+adapter); the opt-in nested compositor and Hyprland input v3 candidate below
+have separate limits. Use **`pixel` on X11** (an element px
action — background pixel click — lands via
AT-SPI `do_action`-at-point off the screenshot already in the snapshot — the
matrix below).
@@ -120,9 +121,10 @@ Modality is chosen at **action time**, by how you address the target:
`get_window_state` returning `degraded:true` (empty AT-SPI walk) is the cue to
do an **element px action** off that same screenshot (X11) or escalate to
-`delivery_mode:"foreground"` (standard Wayland: raw background pixels cannot
-target an unfocused window there). The nested compositor has its own
-experimental per-surface routes.
+`delivery_mode:"foreground"` when authorized (standard Wayland has no general
+raw background route). The nested compositor and Hyprland input v3 candidate
+have their own experimental per-surface routes; an empty tree does not establish
+eligibility for either route.
## Cross-platform schema residuals (Linux)
@@ -216,6 +218,9 @@ driver selects a backend from compositor capabilities:
- Sway and other wlroots compositors use foreign-toplevel discovery,
wlr-screencopy, virtual pointer, and virtual keyboard protocols.
+- Hyprland has separate discovery and capture adapters. Its optional plugin
+ defaults to discovery-only; the opt-in input v3 source candidate has the
+ qualification and validation limits below. Do not inherit Sway coverage.
- GNOME/Mutter uses the bundled WinRects Shell helper for target geometry and
activation, plus portal/libei for foreground raw input.
- KDE/KWin uses AT-SPI and portal facilities where available. Target-specific
@@ -235,13 +240,82 @@ control. Other focus-bound background pointer and keyboard shapes return an
exact `background_unavailable` result. They do not report success after a
silent drop.
-Raw Wayland input requires explicitly authorized `delivery_mode:"foreground"`.
+Outside an explicitly enabled, qualified compositor-owned background route,
+raw Wayland input requires explicitly authorized `delivery_mode:"foreground"`.
The driver activates the selected target through a verified compositor adapter
before dispatch. If
the compositor has no target-addressable activation or input backend, the call
refuses before sending input. Reconstructing coordinates alone does not make
raw background PX possible on a standard compositor.
+### Hyprland input v3 source candidate
+
+[PR #3572](https://github.com/trycua/cua/pull/3572) records dated, exact-source
+validation results for the experimental opt-in input v3 candidate. Acceptance
+requires the unchanged complete Linux canonical runner on native Hyprland and
+separate bounded qualified-app proof. The default plugin build remains
+discovery-only.
+The candidate source reports Driver `0.23.2`; published Driver `0.23.2` does not
+include these branch changes. Switching Driver channels does not install or
+enable the plugin. Build and loading require the exact Hyprland ABI and compiler
+toolchain; v3 uses `CUA_HYPRLAND_INPUT=ON`, separate from the historical
+`CUA_HYPRLAND_TEST_INPUT` experiment.
+
+Driver admits each action through its normal shared permission, resource, and
+lifecycle policy. There is no additional Omarchy approval panel or external
+signer. The plugin accepts the trusted desktop account over same-user local
+sockets; this does not sandbox native code running as that user. Application
+qualification is a compatibility check, not authorization.
+
+The initial native qualification scope is Calc from `libreoffice-fresh 26.2.5-3`
+and Inkscape `1.4.4-6`, subject to per-operation native evidence. Before each
+action, Driver matches `/proc/<pid>/exe` to the canonical executable path
+(`/usr/lib/libreoffice/program/soffice.bin` or `/usr/bin/inkscape`), checks the
+exact package name and version in the local pacman database and its executable
+file listing, and rechecks process identity. Unknown or unavailable package
+identity refuses. Package eligibility does not certify every LibreOffice
+application or operation.
+
+The plugin separately binds the exact live native surface and checks geometry,
+desktop availability, primary-client and other-lane conflicts, and the compiled
+default `evdev`/`pc105`/`us` keymap. The candidate excludes variants, options,
+remaps, multiple layout groups, missing keyboards, Unicode, IME input,
+arbitrary held-key streams, and modified pointer gestures. Chromium, Electron,
+and XWayland raw background input are outside this scope. AT-SPI routes retain
+their separate behavior.
+
+Two compositor seats, `Cua-Agent` and `Cua-Agent-2`, persist across configuration
+disable/re-enable. Each connection claims one lane, and each admitted action
+requires a fresh target binding. Plugin replacement requires a desktop restart;
+do not treat historical experiment reload workarounds as a supported lifecycle.
+Refusals never authorize a hidden foreground fallback, display wake, or session
+unlock. A dispatch acknowledgement is `effect:"unverifiable"`; verify the
+application effect from fresh state. Do not replay canceled, partial, or unknown
+actions.
+
+The candidate also adds an explicitly requested foreground route, advertised
+by the plugin as `foreground_target:true`. It binds the exact native top-level
+surface on the compositor thread and intentionally changes primary focus and,
+for pointer actions, cursor position. It does not restore the previous focus or
+cursor. This route has no Calc/Inkscape background package gate. The canonical
+native harness covers defined GTK3, Electron, and Tauri foreground cases. It refuses
+held physical input, grabs, constraints, drag-and-drop, ambiguous primary seat
+bindings, and non-neutral keyboard modifiers. Background refusal never selects
+this route automatically. Driver expands bounded ASCII text under the exact
+US keymap; Unicode and IME remain outside its raw-input scope.
+
+The retained bounded app evidence at source
+`f180e8828b8f31cc153e3c44eaa89a9c13c5bc68` includes instrumented Calc/Inkscape
+proof on both seats and an uninstrumented smoke. The plugin tree and
+uninstrumented module hash are unchanged at
+`1133a06e4f205cf80188a7ac9e41102f37611fea`. The proof covers recorded actions
+and observation intervals, not every application operation or release package.
+Portable tests and historical experiments do not replace complete native
+harness acceptance. Compatible release artifacts and final Fleet image
+packaging and lifecycle validation require separate evidence. Physical Omarchy
+parity requires separate acceptance; it is not a gate for publishing a validated
+Fleet image.
+
## Quick triage
If a tool call surprises you on Linux:
@@ -280,6 +354,7 @@ ask the user.
|---|---|---|
| X11/Openbox | AT-SPI trees and actions, foreground pointer and keyboard input, window and desktop capture, and video | Raw background delivery remains toolkit-specific; unsupported shapes refuse |
| 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 plain US keymap; 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 |
| 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 |
diff --git a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md
index e141f7460c..c3bbea99a6 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md
@@ -81,15 +81,32 @@ Each action writes to `turn-NNNNN/` (five-digit zero-padded counter):
summary, result-error flag, pid, click point (when applicable), ISO-8601
timestamp.
- `click.png` — for click-family actions (`click`, `double_click`,
- `right_click`): a copy of `before.png` with a red marker drawn at
- the click point. **Both addressing modes are covered:** explicit
- `x, y` clicks use the supplied coordinates directly, and
+ `right_click`): a copy of the pre-input image with a red marker drawn at
+ the click point. Usually that source is `before.png`. When Windows scrolls
+ an element into view during an action, it retains an additional
+ `click_source.png` immediately before coordinate input. In that case,
+ `action.json` names `click_point_image: "click_source.png"`, and
+ `evidence.json` records `click.source_image` and the `click_source` capture
+ status. The original before/after images and state remain intact.
+ **Both addressing modes are covered:** explicit
+ `x, y` clicks use the platform's recording-coordinate mapping, and
`element_index`-addressed clicks resolve to the element's center
- via the live AX/UIA cache, then convert to window-local screenshot
- pixels. Absent for non-click tools. It is also absent, and explicitly
+ via the live AX/UIA cache, then convert to the retained image's coordinate
+ space. Native Hyprland recording retains the output image, so both kinds of
+ marker use output coordinates. Pixel markers also account for the target
+ window's origin and any snapshot resize or zoom. Absent for non-click tools.
+ It is also absent, and explicitly
classified as not applicable, when the driver refuses a click before target
- resolution; no input was aimed in that case. A dispatched click whose marker
- cannot be resolved or rendered remains an evidence failure.
+ resolution; no input was aimed in that case. A successful plain Linux AT-SPI
+ or Windows UIA element click (Invoke, Toggle, SelectionItem, or ExpandCollapse)
+ can activate a control without a visible point, such as an offscreen button.
+ In that case, `semantic_action_without_point` records why
+ there is no marker. The action must carry explicit accessibility transport
+ and known delivery metadata; its before/after state, images, and requested
+ video remain required. This exception does not apply to pixel clicks,
+ Windows SendInput clicks, uncertain delivery, or failed marker rendering.
+ Out-of-image points are rejected, never moved to an image edge. Other dispatched clicks whose markers
+ cannot be resolved or rendered remain evidence failures.
## When to use it
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs
index 4b21971a6a..18004509d9 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs
@@ -86,6 +86,8 @@ pub enum ActionTransport {
LinuxLibei,
LinuxWaylandVirtualPointer,
LinuxCuaCompositorInject,
+ LinuxHyprlandIsolatedInput,
+ LinuxHyprlandForegroundInput,
LinuxX11ConfigureWindow,
BrowserCdpInputMouse,
BrowserCdpInputKey,
@@ -122,6 +124,8 @@ impl ActionTransport {
Self::LinuxLibei,
Self::LinuxWaylandVirtualPointer,
Self::LinuxCuaCompositorInject,
+ Self::LinuxHyprlandIsolatedInput,
+ Self::LinuxHyprlandForegroundInput,
Self::LinuxX11ConfigureWindow,
Self::BrowserCdpInputMouse,
Self::BrowserCdpInputKey,
@@ -147,7 +151,8 @@ impl ActionTransport {
Self::MacosCgEventPid
| Self::WindowsPostMessage
| Self::LinuxPty
- | Self::LinuxXSendEvent => ActionRoute::SyntheticEvents,
+ | Self::LinuxXSendEvent
+ | Self::LinuxHyprlandIsolatedInput => ActionRoute::SyntheticEvents,
Self::MacosCgEventHid
| Self::WindowsTargetedInjection
| Self::WindowsSendInput
@@ -156,6 +161,7 @@ impl ActionTransport {
| Self::LinuxXTest
| Self::LinuxLibei
| Self::LinuxWaylandVirtualPointer
+ | Self::LinuxHyprlandForegroundInput
| Self::LinuxCuaCompositorInject => ActionRoute::GlobalInput,
Self::WindowsSetWindowPos | Self::LinuxX11ConfigureWindow => ActionRoute::SystemApi,
Self::BrowserCdpRuntimeFunction => ActionRoute::Dom,
@@ -1026,6 +1032,8 @@ fn transport_name(transport: ActionTransport) -> &'static str {
ActionTransport::LinuxLibei => "linux_libei",
ActionTransport::LinuxWaylandVirtualPointer => "linux_wayland_virtual_pointer",
ActionTransport::LinuxCuaCompositorInject => "linux_cua_compositor_inject",
+ ActionTransport::LinuxHyprlandIsolatedInput => "linux_hyprland_isolated_input",
+ ActionTransport::LinuxHyprlandForegroundInput => "linux_hyprland_foreground_input",
ActionTransport::LinuxX11ConfigureWindow => "linux_x11_configure_window",
ActionTransport::BrowserCdpInputMouse => "browser_cdp_input_mouse",
ActionTransport::BrowserCdpInputKey => "browser_cdp_input_key",
@@ -1190,6 +1198,30 @@ mod tests {
assert!(routes.contains(&ActionRoute::TrustedInput));
}
+ #[test]
+ fn hyprland_foreground_does_not_claim_isolated_background_delivery() {
+ let record = ActionExecutionRecord::builder(
+ ActionEffect::Unverifiable,
+ ActionTransport::LinuxHyprlandForegroundInput,
+ RequestedDelivery::Foreground,
+ )
+ .actual_delivery(ActualDelivery::Foreground)
+ .build()
+ .unwrap();
+ assert_eq!(
+ record.stable_projection().unwrap().route,
+ ActionRoute::GlobalInput
+ );
+ assert_eq!(
+ ActionTransport::LinuxHyprlandIsolatedInput.route(),
+ ActionRoute::SyntheticEvents
+ );
+ assert_eq!(
+ transport_name(ActionTransport::LinuxHyprlandForegroundInput),
+ "linux_hyprland_foreground_input"
+ );
+ }
+
#[test]
fn confirmed_requires_evidence() {
assert_eq!(
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs
index d50ce437a5..3792d4bdf0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs
@@ -101,6 +101,7 @@ pub fn resize_png_if_needed(png_bytes: &[u8], max_dim: u32) -> Result<Vec<u8>> {
/// env-var name on Windows).
pub fn write_crosshair_png(png_bytes: &[u8], cx: f64, cy: f64, path: &str) -> Result<()> {
let mut img = decode_png_to_rgba8(png_bytes)?;
+ validate_crosshair_point(&img, cx, cy)?;
draw_crosshair(&mut img, cx, cy);
let path = if let Some(rest) = path.strip_prefix('~') {
@@ -127,6 +128,7 @@ pub fn write_crosshair_png(png_bytes: &[u8], cx: f64, cy: f64, path: &str) -> Re
/// `click.png` without a temp file.
pub fn crosshair_png_bytes(png_bytes: &[u8], cx: f64, cy: f64) -> Result<Vec<u8>> {
let mut img = decode_png_to_rgba8(png_bytes)?;
+ validate_crosshair_point(&img, cx, cy)?;
draw_crosshair(&mut img, cx, cy);
let mut out = Vec::new();
@@ -135,6 +137,23 @@ pub fn crosshair_png_bytes(png_bytes: &[u8], cx: f64, cy: f64) -> Result<Vec<u8>
Ok(out)
}
+fn validate_crosshair_point(
+ img: &ImageBuffer<image::Rgba<u8>, Vec<u8>>,
+ cx: f64,
+ cy: f64,
+) -> Result<()> {
+ if !cx.is_finite()
+ || !cy.is_finite()
+ || cx < 0.0
+ || cy < 0.0
+ || cx >= f64::from(img.width())
+ || cy >= f64::from(img.height())
+ {
+ bail!("click point is outside the retained image");
+ }
+ Ok(())
+}
+
/// Internal: decode PNG to a mutable RGBA8 image buffer.
fn decode_png_to_rgba8(png_bytes: &[u8]) -> Result<ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
let cursor = std::io::Cursor::new(png_bytes);
@@ -337,6 +356,23 @@ mod tests {
assert_eq!((w, h), (40, 40));
}
+ #[test]
+ fn crosshair_rejects_invalid_centers_instead_of_clamping_to_an_edge() {
+ let png = encode_rgba_to_png(&vec![0u8; 40 * 40 * 4], 40, 40).unwrap();
+ for point in [
+ (-1.0, 20.0),
+ (20.0, -1.0),
+ (40.0, 20.0),
+ (20.0, 40.0),
+ (f64::NAN, 20.0),
+ (20.0, f64::INFINITY),
+ ] {
+ assert!(crosshair_png_bytes(&png, point.0, point.1).is_err());
+ }
+ assert!(crosshair_png_bytes(&png, 0.0, 0.0).is_ok());
+ assert!(crosshair_png_bytes(&png, 39.0, 39.0).is_ok());
+ }
+
#[test]
fn bgra_to_png_swaps_channels() {
// 1x1 BGRA pixel: B=10, G=20, R=30, A=40.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
index acd86dc4ec..c24ca3c47d 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
@@ -10,7 +10,7 @@
//! t_ms_from_session_start, t_start_ms_from_session_start }
use std::path::{Path, PathBuf};
-use std::sync::{Mutex, OnceLock};
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
use std::time::Instant;
@@ -119,6 +119,9 @@ pub fn set_ax_snapshot_fn(
type ElementBoundsFnBox = Box<dyn Fn(u64, i64, u32) -> Option<(f64, f64)> + Send + Sync>;
static ELEMENT_BOUNDS_FN: OnceLock<ElementBoundsFnBox> = OnceLock::new();
+type PixelPointFnBox =
+ Box<dyn Fn(&Value, Option<u64>, Option<i64>, f64, f64) -> Option<(f64, f64)> + Send + Sync>;
+
/// Register the platform-specific element-bounds resolver. Args: (window_id, pid, element_index).
pub fn set_element_bounds_fn(
f: impl Fn(u64, i64, u32) -> Option<(f64, f64)> + Send + Sync + 'static,
@@ -133,6 +136,75 @@ struct TurnCapture {
screenshot_classification: Option<&'static str>,
}
+#[derive(Default)]
+struct DispatchClickCapture {
+ image: Option<(Vec<u8>, f64, f64)>,
+ failure: Option<&'static str>,
+}
+
+struct DispatchClickScope {
+ window_id: u64,
+ pid: i64,
+ capture: Mutex<DispatchClickCapture>,
+}
+
+tokio::task_local! {
+ static DISPATCH_CLICK_SCOPE: Option<Arc<DispatchClickScope>>;
+}
+
+/// Capture the exact target after scrolling/focus preparation and before input.
+/// The closure is lazy: unrelated, private, and unrecorded calls never capture.
+/// Only the first matching capture is attempted, including capture failures.
+pub fn capture_dispatch_click_target(
+ window_id: u64,
+ pid: i64,
+ capture: impl FnOnce() -> Option<(Vec<u8>, f64, f64)>,
+) {
+ let _ = DISPATCH_CLICK_SCOPE.try_with(|scope| {
+ let Some(scope) = scope else { return };
+ if (scope.window_id, scope.pid) != (window_id, pid) {
+ return;
+ }
+ let mut retained = scope.capture.lock().unwrap();
+ if retained.image.is_some() || retained.failure.is_some() {
+ return;
+ }
+ match capture() {
+ Some((png, x, y)) if point_in_image(&png, x, y) => {
+ retained.image = Some((png, x, y));
+ }
+ Some(_) => retained.failure = Some("invalid_capture"),
+ None => retained.failure = Some("capture_failed"),
+ }
+ });
+}
+
+fn point_in_image(png: &[u8], x: f64, y: f64) -> bool {
+ image::load_from_memory_with_format(png, image::ImageFormat::Png).is_ok_and(|image| {
+ let (width, height) = (image.width(), image.height());
+ x.is_finite()
+ && y.is_finite()
+ && x >= 0.0
+ && y >= 0.0
+ && x < f64::from(width)
+ && y < f64::from(height)
+ })
+}
+
+/// Task-local state follows the invocation future and disappears on cancellation.
+/// An empty scope also masks any outer recording during a nested dispatch.
+pub(crate) async fn scope_dispatch_click_capture<F: std::future::Future>(
+ pending: Option<&PendingTurn>,
+ dispatch: F,
+) -> F::Output {
+ DISPATCH_CLICK_SCOPE
+ .scope(
+ pending.and_then(|turn| turn.dispatch_click.clone()),
+ dispatch,
+ )
+ .await
+}
+
/// A reserved recording turn captured immediately before tool dispatch.
/// `ToolRegistry` passes this token back after dispatch so both phases share
/// one stable `turn-NNNNN` directory even when calls complete out of order.
@@ -148,11 +220,13 @@ pub struct PendingTurn {
click_point: Option<(f64, f64)>,
capture_visual_state: bool,
before: TurnCapture,
+ dispatch_click: Option<Arc<DispatchClickScope>>,
}
-/// Persistent recording session state (singleton per process).
+/// Persistent recording session state owned by one tool registry.
pub struct RecordingSession {
inner: Mutex<RecordingInner>,
+ pixel_point_fn: OnceLock<PixelPointFnBox>,
}
struct RecordingInner {
@@ -219,6 +293,7 @@ pub struct RecordingState {
impl RecordingSession {
pub fn new() -> Self {
Self {
+ pixel_point_fn: OnceLock::new(),
inner: Mutex::new(RecordingInner {
enabled: false,
generation: 0,
@@ -236,6 +311,18 @@ impl RecordingSession {
}
}
+ /// Install this registry's mapper from tool pixels to recording pixels.
+ /// Register once during runtime assembly; absent mappers preserve coordinates.
+ pub fn set_pixel_point_fn(
+ &self,
+ f: impl Fn(&Value, Option<u64>, Option<i64>, f64, f64) -> Option<(f64, f64)>
+ + Send
+ + Sync
+ + 'static,
+ ) {
+ let _ = self.pixel_point_fn.set(Box::new(f));
+ }
+
/// Enable recording at `output_dir`, optionally with video capture.
/// Counterpart to `stop()`. Returns the resulting state.
///
@@ -536,7 +623,14 @@ impl RecordingSession {
element_index = u64::try_from(resolved_index).ok();
}
}
- let click_point = resolve_click_point(tool_name, &args, window_id, pid, element_index);
+ let click_point = resolve_click_point(
+ tool_name,
+ &args,
+ window_id,
+ pid,
+ element_index,
+ self.pixel_point_fn.get(),
+ );
let before = if capture_visual_state {
capture_turn(window_id, pid)
} else {
@@ -568,6 +662,19 @@ impl RecordingSession {
click_point,
capture_visual_state,
before,
+ dispatch_click: if capture_visual_state
+ && matches!(tool_name, "click" | "double_click" | "right_click")
+ {
+ window_id.zip(pid).map(|(window_id, pid)| {
+ Arc::new(DispatchClickScope {
+ window_id,
+ pid,
+ capture: Mutex::new(DispatchClickCapture::default()),
+ })
+ })
+ } else {
+ None
+ },
})
}
@@ -652,13 +759,17 @@ fn resolve_click_point(
window_id: Option<u64>,
pid: Option<i64>,
element_index: Option<u64>,
+ pixel_point_fn: Option<&PixelPointFnBox>,
) -> Option<(f64, f64)> {
use crate::tool_args::ArgsExt;
if !matches!(tool_name, "click" | "double_click" | "right_click") {
return None;
}
match (args.opt_f64("x"), args.opt_f64("y")) {
- (Some(x), Some(y)) => Some((x, y)),
+ (Some(x), Some(y)) => match pixel_point_fn {
+ Some(resolve) => resolve(args, window_id, pid, x, y),
+ None => Some((x, y)),
+ },
_ => match (window_id, pid, element_index, ELEMENT_BOUNDS_FN.get()) {
(Some(wid), Some(pid), Some(index), Some(resolve)) => u32::try_from(index)
.ok()
@@ -706,9 +817,10 @@ fn write_evidence_manifest(
state_expected: bool,
click_expected: bool,
click_captured: bool,
+ supplemental: &DispatchClickCapture,
click_not_applicable_classification: &'static str,
) -> anyhow::Result<()> {
- let manifest = serde_json::json!({
+ let mut manifest = serde_json::json!({
"schema": "cua-turn-evidence/v1",
"before": {
"state": capture_status(before.state.is_some(), state_expected, None),
@@ -735,6 +847,20 @@ fn write_evidence_manifest(
})
},
});
+ manifest["click"]["source_image"] = serde_json::json!(if supplemental.image.is_some()
+ || supplemental.failure.is_some()
+ {
+ "click_source.png"
+ } else {
+ "before.png"
+ });
+ if supplemental.image.is_some() || supplemental.failure.is_some() {
+ manifest["click_source"] =
+ capture_status(supplemental.image.is_some(), true, supplemental.failure);
+ if supplemental.image.is_some() {
+ manifest["click_source"]["source_image"] = serde_json::json!("click_source.png");
+ }
+ }
write_json_atomic(&turn_dir.join("evidence.json"), &manifest)
}
@@ -756,6 +882,66 @@ fn strip_internal_keys(args: &Value) -> std::borrow::Cow<'_, Value> {
}
}
+// Semantic activation has no spatial marker only when the retained execution
+// record proves a single accessibility dispatch without escalation or replay.
+fn semantic_action_without_point(action: &Value) -> bool {
+ let args = &action["arguments"];
+ let truth = &action["action_truth"];
+ action["tool"] == "click"
+ && action["result_error"] == false
+ && action.get("click_point").is_none()
+ && action.get("click_point_image").is_none()
+ && (args["element_index"].as_u64().is_some()
+ || args["element_token"]
+ .as_str()
+ .is_some_and(|token| !token.is_empty()))
+ && args.get("x").is_none()
+ && args.get("y").is_none()
+ && args.get("raw").is_none_or(|value| value == false)
+ && args.get("button").is_none_or(|value| value == "left")
+ && args
+ .get("count")
+ .is_none_or(|value| value.as_u64() == Some(1))
+ && args
+ .get("click_count")
+ .is_none_or(|value| value.as_u64() == Some(1))
+ && ["modifier", "modifiers"].iter().all(|key| {
+ args.get(*key)
+ .is_none_or(|value| value.as_array().is_some_and(Vec::is_empty))
+ })
+ && matches!(
+ truth["transport"].as_str(),
+ Some(
+ "linux_at_spi_action"
+ | "windows_uia_invoke"
+ | "windows_uia_toggle"
+ | "windows_uia_selection"
+ | "windows_uia_expand_collapse"
+ )
+ )
+ && truth["route"] == "accessibility"
+ && matches!(truth["effect"].as_str(), Some("confirmed" | "unverifiable"))
+ && matches!(
+ truth["actual_delivery"].as_str(),
+ Some("background" | "foreground")
+ )
+ && truth["requested_delivery"] == truth["actual_delivery"]
+ && truth.get("escalation").is_some_and(Value::is_null)
+ && truth["fallbacks"].as_array().is_some_and(Vec::is_empty)
+ && truth
+ .get("delivered_count")
+ .is_some_and(|value| value.is_null() || value.as_u64() == Some(1))
+ && truth["attempts"].as_array().is_some_and(|attempts| {
+ // Legacy single-dispatch results carry transport/delivery above
+ // without a per-attempt journal. Any supplied attempt must match.
+ attempts.len() <= 1
+ && attempts.iter().all(|attempt| {
+ attempt["transport"] == truth["transport"]
+ && attempt["delivery"] == truth["actual_delivery"]
+ })
+ })
+}
+
fn write_turn(
pending: PendingTurn,
result_text: &str,
@@ -774,7 +960,41 @@ fn write_turn(
click_point,
capture_visual_state,
before,
+ dispatch_click,
} = pending;
+ let supplemental = dispatch_click
+ .map(|scope| std::mem::take(&mut *scope.capture.lock().unwrap()))
+ .unwrap_or_default();
+ let click_source = supplemental
+ .image
+ .as_ref()
+ .map(|(png, _, _)| png.as_slice());
+ let click_point = supplemental
+ .image
+ .as_ref()
+ .map(|(_, x, y)| (*x, *y))
+ .or_else(|| {
+ supplemental
+ .failure
+ .is_none()
+ .then_some(click_point)
+ .flatten()
+ });
+ let marker_source = click_source.or(before.screenshot.as_deref());
+ // Offscreen accessibility bounds can be sentinel coordinates. Only a
+ // point inside a readable pre-action image can ground a spatial marker.
+ let click_point =
+ match marker_source.and_then(|png| crate::image_utils::png_dimensions(png).ok()) {
+ Some((width, height)) => click_point.filter(|(x, y)| {
+ x.is_finite()
+ && y.is_finite()
+ && *x >= 0.0
+ && *y >= 0.0
+ && *x < f64::from(width)
+ && *y < f64::from(height)
+ }),
+ None => click_point,
+ };
std::fs::create_dir_all(&turn_dir)?;
let now = now_ms();
let after = if capture_visual_state {
@@ -789,15 +1009,15 @@ fn write_turn(
let click_family = matches!(tool_name.as_str(), "click" | "double_click" | "right_click");
let action_refused = action_record
.is_some_and(|record| record.effect == crate::action_record::ActionEffect::Refused);
- let refused_before_target_resolution = click_family && result_is_error && click_point.is_none();
+ let refused_before_target_resolution = click_family
+ && result_is_error
+ && click_point.is_none()
+ && (action_record.is_none() || action_refused);
// A target may resolve successfully and still be refused before input
// dispatch (for example, a minimized Windows element). Retaining the
// resolved point in action.json is useful diagnostic context, but a
// crosshair would falsely imply that a click was delivered.
let refused_before_dispatch = click_family && result_is_error && action_refused;
- let click_expected =
- click_family && !refused_before_target_resolution && !refused_before_dispatch;
-
let mut payload = serde_json::json!({
"tool": tool_name,
"arguments": args,
@@ -810,11 +1030,23 @@ fn write_turn(
if let Some((cx, cy)) = click_point {
payload["click_point"] = serde_json::json!({"x": cx, "y": cy});
}
+ if click_source.is_some() || supplemental.failure.is_some() {
+ payload["click_point_image"] = serde_json::json!("click_source.png");
+ }
if let Some(action_record) = action_record {
payload["action_truth"] = action_record.debug_json();
}
+ let semantic_without_point =
+ supplemental.failure.is_none() && semantic_action_without_point(&payload);
+ let click_expected = click_family
+ && !refused_before_target_resolution
+ && !refused_before_dispatch
+ && !semantic_without_point;
write_json_atomic(&turn_dir.join("action.json"), &payload)?;
write_phase_artifacts(&turn_dir, "after", &after)?;
+ if let Some(source) = click_source {
+ std::fs::write(turn_dir.join("click_source.png"), source)?;
+ }
// Preserve the original post-action names for existing trajectory readers.
if let Some(state) = &after.state {
@@ -829,11 +1061,9 @@ fn write_turn(
// after the modal HWND has closed.
let mut click_captured = false;
if click_expected {
- if let (Some((cx, cy)), Some(screenshot), Some(marker)) = (
- click_point,
- before.screenshot.as_deref(),
- CLICK_MARKER_FN.get(),
- ) {
+ if let (Some((cx, cy)), Some(screenshot), Some(marker)) =
+ (click_point, marker_source, CLICK_MARKER_FN.get())
+ {
if let Some(click_png) = marker(screenshot, cx, cy) {
std::fs::write(turn_dir.join("click.png"), click_png)?;
click_captured = true;
@@ -847,10 +1077,13 @@ fn write_turn(
pid.is_some() && capture_visual_state,
click_expected,
click_captured,
+ &supplemental,
if refused_before_target_resolution {
"action_refused_before_target_resolution"
} else if refused_before_dispatch {
"action_refused_before_dispatch"
+ } else if semantic_without_point {
+ "semantic_action_without_point"
} else {
"not_a_click_action"
},
@@ -941,10 +1174,589 @@ fn validate_video_metadata(meta: VideoMetadata) -> anyhow::Result<VideoMetadata>
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn pixel_mappers_follow_registry_lifetimes_and_concurrent_runtime_state() {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ use std::sync::Arc;
+
+ fn registry(ratio: &Arc<AtomicU32>) -> (crate::tool::ToolRegistry, tempfile::TempDir) {
+ let registry = crate::tool::ToolRegistry::new();
+ let output = tempfile::tempdir().unwrap();
+ {
+ let mut inner = registry.recording.inner.lock().unwrap();
+ inner.enabled = true;
+ inner.output_dir = Some(output.path().to_owned());
+ }
+ let ratio = Arc::downgrade(ratio);
+ registry.recording.set_pixel_point_fn(move |_, _, _, x, y| {
+ let ratio = f64::from(ratio.upgrade()?.load(Ordering::SeqCst));
+ Some((x * ratio, y * ratio))
+ });
+ (registry, output)
+ }
+
+ fn point(registry: &crate::tool::ToolRegistry) -> Option<(f64, f64)> {
+ // Suppress platform capture so this tests runtime mapping without
+ // depending on the process-wide screenshot and accessibility hooks.
+ registry
+ .recording
+ .begin_private_turn(
+ "click",
+ &serde_json::json!({"pid": 1, "window_id": 2, "x": 3, "y": 4}),
+ now_ms(),
+ )
+ .unwrap()
+ .click_point
+ }
+
+ let first_state = Arc::new(AtomicU32::new(2));
+ let (first, first_output) = registry(&first_state);
+ assert_eq!(point(&first), Some((6.0, 8.0)));
+ drop(first);
+ drop(first_state);
+ drop(first_output);
+
+ let replacement_state = Arc::new(AtomicU32::new(3));
+ let other_state = Arc::new(AtomicU32::new(5));
+ let (replacement, _replacement_output) = registry(&replacement_state);
+ let (other, _other_output) = registry(&other_state);
+ std::thread::scope(|scope| {
+ scope.spawn(|| {
+ assert_eq!(point(&replacement), Some((9.0, 12.0)));
+ replacement_state.store(7, Ordering::SeqCst);
+ assert_eq!(point(&replacement), Some((21.0, 28.0)));
+ });
+ scope.spawn(|| {
+ assert_eq!(point(&other), Some((15.0, 20.0)));
+ other_state.store(11, Ordering::SeqCst);
+ assert_eq!(point(&other), Some((33.0, 44.0)));
+ });
+ });
+ drop(other);
+ drop(other_state);
+ assert_eq!(point(&replacement), Some((21.0, 28.0)));
+ }
+
+ fn semantic_click_fixture() -> Value {
+ serde_json::json!({
+ "tool": "click", "result_error": false,
+ "arguments": {"pid": 1, "window_id": 2, "element_index": 3},
+ "action_truth": {
+ "effect": "unverifiable", "transport": "linux_at_spi_action",
+ "route": "accessibility", "requested_delivery": "background",
+ "actual_delivery": "background", "delivered_count": null,
+ "attempts": [], "fallbacks": [], "escalation": null
+ }
+ })
+ }
+
+ fn dispatch_pending(root: &Path) -> PendingTurn {
+ PendingTurn {
+ generation: 0,
+ turn_dir: root.to_path_buf(),
+ tool_name: "click".into(),
+ args: serde_json::json!({"pid": 901, "window_id": 902, "element_index": 3}),
+ start_ms: 0,
+ session_start_ms: 0,
+ window_id: Some(902),
+ pid: Some(901),
+ click_point: Some((500.0, 500.0)),
+ capture_visual_state: true,
+ before: TurnCapture {
+ screenshot: Some(crate::image_utils::encode_rgba_to_png(&[0; 24], 3, 2).unwrap()),
+ state: Some(b"original state".to_vec()),
+ screenshot_classification: None,
+ },
+ dispatch_click: Some(Arc::new(DispatchClickScope {
+ window_id: 902,
+ pid: 901,
+ capture: Mutex::new(DispatchClickCapture::default()),
+ })),
+ }
+ }
+
+ #[tokio::test]
+ async fn dispatch_capture_is_lazy_exact_private_and_cancel_safe() {
+ let root = tempfile::tempdir().unwrap();
+ let pending = dispatch_pending(root.path());
+ let forbidden = || -> Option<(Vec<u8>, f64, f64)> { panic!("unexpected capture") };
+ capture_dispatch_click_target(902, 901, forbidden);
+ scope_dispatch_click_capture(None, async {
+ capture_dispatch_click_target(902, 901, forbidden);
+ })
+ .await;
+ scope_dispatch_click_capture(Some(&pending), async {
+ capture_dispatch_click_target(903, 901, forbidden);
+ capture_dispatch_click_target(902, 903, forbidden);
+ scope_dispatch_click_capture(None, async {
+ capture_dispatch_click_target(902, 901, forbidden);
+ })
+ .await;
+ })
+ .await;
+
+ let session = RecordingSession::new();
+ assert!(session.begin_turn("click", &pending.args, 0).is_none());
+ {
+ let mut inner = session.inner.lock().unwrap();
+ inner.enabled = true;
+ inner.output_dir = Some(root.path().to_path_buf());
+ }
+ let private = session
+ .begin_private_turn("click", &pending.args, 0)
+ .unwrap();
+ scope_dispatch_click_capture(Some(&private), async {
+ capture_dispatch_click_target(902, 901, forbidden);
+ })
+ .await;
+ assert!(private.dispatch_click.is_none());
+
+ let mut cancelled = Box::pin(scope_dispatch_click_capture(Some(&pending), async {
+ capture_dispatch_click_target(902, 901, || None);
+ std::future::pending::<()>().await;
+ }));
+ assert!(matches!(
+ std::future::poll_fn(|cx| {
+ std::task::Poll::Ready(std::future::Future::poll(cancelled.as_mut(), cx))
+ })
+ .await,
+ std::task::Poll::Pending
+ ));
+ drop(cancelled);
+ capture_dispatch_click_target(902, 901, forbidden);
+ assert_eq!(
+ pending
+ .dispatch_click
+ .as_ref()
+ .unwrap()
+ .capture
+ .lock()
+ .unwrap()
+ .failure,
+ Some("capture_failed")
+ );
+ }
+
+ #[tokio::test]
+ async fn concurrent_dispatch_scopes_keep_their_own_images() {
+ let root = tempfile::tempdir().unwrap();
+ let first = dispatch_pending(root.path());
+ let second = dispatch_pending(root.path());
+ let capture = |pending: PendingTurn, byte: u8| async move {
+ scope_dispatch_click_capture(Some(&pending), async {
+ tokio::task::yield_now().await;
+ capture_dispatch_click_target(902, 901, || {
+ Some((
+ crate::image_utils::encode_rgba_to_png(&[byte; 16], 2, 2).unwrap(),
+ f64::from(byte % 2),
+ 1.0,
+ ))
+ });
+ tokio::task::yield_now().await;
+ })
+ .await;
+ let scope = pending.dispatch_click.unwrap();
+ let retained = scope.capture.lock().unwrap();
+ let (png, x, y) = retained.image.as_ref().unwrap();
+ assert_eq!(
+ *png,
+ crate::image_utils::encode_rgba_to_png(&[byte; 16], 2, 2).unwrap()
+ );
+ assert_eq!((*x, *y), (f64::from(byte % 2), 1.0));
+ };
+ let (first, second) = tokio::join!(
+ tokio::spawn(capture(first, 1)),
+ tokio::spawn(capture(second, 2))
+ );
+ first.unwrap();
+ second.unwrap();
+ }
+
+ #[tokio::test]
+ async fn stale_generation_discards_supplemental_capture() {
+ let root = tempfile::tempdir().unwrap();
+ let session = RecordingSession::new();
+ {
+ let mut inner = session.inner.lock().unwrap();
+ inner.enabled = true;
+ inner.output_dir = Some(root.path().to_path_buf());
+ }
+ let pending = session
+ .begin_turn(
+ "click",
+ &serde_json::json!({
+ "pid":901, "window_id":902, "element_index":3,
+ }),
+ 0,
+ )
+ .unwrap();
+ scope_dispatch_click_capture(Some(&pending), async {
+ capture_dispatch_click_target(902, 901, || {
+ Some((
+ crate::image_utils::encode_rgba_to_png(&[255; 16], 2, 2).unwrap(),
+ 1.0,
+ 1.0,
+ ))
+ });
+ })
+ .await;
+ session.inner.lock().unwrap().generation += 1;
+ session.finish_turn(pending, "discard old generation");
+ assert!(!root.path().join("turn-00001/action.json").exists());
+ assert!(!root.path().join("turn-00001/click_source.png").exists());
+ }
+
+ #[tokio::test]
+ async fn supplemental_click_preserves_before_and_rejects_invalid_capture() {
+ setup_test_marker();
+ for point in [
+ Some((1.0, 0.5)),
+ None,
+ Some((-1.0, 0.0)),
+ Some((2.0, 0.0)),
+ Some((0.0, 2.0)),
+ Some((f64::NAN, 0.0)),
+ Some((0.0, f64::INFINITY)),
+ ] {
+ let root = tempfile::tempdir().unwrap();
+ let pending = dispatch_pending(root.path());
+ let original = pending.before.screenshot.clone().unwrap();
+ let source = crate::image_utils::encode_rgba_to_png(&[255; 16], 2, 2).unwrap();
+ write_phase_artifacts(root.path(), "before", &pending.before).unwrap();
+ scope_dispatch_click_capture(Some(&pending), async {
+ capture_dispatch_click_target(902, 901, || {
+ point.map(|(x, y)| (source.clone(), x, y))
+ });
+ capture_dispatch_click_target(902, 901, || {
+ panic!("second attempt must be ignored")
+ });
+ })
+ .await;
+ write_turn(pending, "clicked", None, false).unwrap();
+ let action: Value =
+ serde_json::from_slice(&std::fs::read(root.path().join("action.json")).unwrap())
+ .unwrap();
+ let evidence: Value =
+ serde_json::from_slice(&std::fs::read(root.path().join("evidence.json")).unwrap())
+ .unwrap();
+ assert_eq!(
+ std::fs::read(root.path().join("before.png")).unwrap(),
+ original
+ );
+ assert_eq!(
+ std::fs::read(root.path().join("before_state.json")).unwrap(),
+ b"original state"
+ );
+ assert_eq!(action["click_point_image"], "click_source.png");
+ assert_eq!(evidence["click"]["source_image"], "click_source.png");
+ if point == Some((1.0, 0.5)) {
+ assert_eq!(action["click_point"], serde_json::json!({"x":1.0,"y":0.5}));
+ assert_eq!(evidence["click_source"]["status"], "captured");
+ assert_eq!(
+ std::fs::read(root.path().join("click_source.png")).unwrap(),
+ source
+ );
+ assert_eq!(
+ std::fs::read(root.path().join("click.png")).unwrap(),
+ crate::image_utils::crosshair_png_bytes(&source, 1.0, 0.5).unwrap(),
+ );
+ } else {
+ assert!(action.get("click_point").is_none());
+ assert_eq!(evidence["click_source"]["status"], "unavailable");
+ assert_eq!(evidence["click"]["status"], "unavailable");
+ assert!(!root.path().join("click_source.png").exists());
+ assert!(!root.path().join("click.png").exists());
+ }
+ }
+ assert!(!point_in_image(b"invalid PNG", 0.0, 0.0));
+ }
+
+ #[test]
+ fn windows_semantic_exception_requires_matching_uia_attempt() {
+ let mut action = semantic_click_fixture();
+ action["action_truth"]["transport"] = serde_json::json!("windows_uia_invoke");
+ action["action_truth"]["attempts"] =
+ serde_json::json!([{"transport":"windows_uia_invoke","delivery":"background"}]);
+ assert!(semantic_action_without_point(&action));
+ for transport in ["windows_send_input", "linux_at_spi_action", "unknown"] {
+ let mut rejected = action.clone();
+ rejected["action_truth"]["attempts"][0]["transport"] = serde_json::json!(transport);
+ assert!(!semantic_action_without_point(&rejected));
+ }
+ action["click_point_image"] = serde_json::json!("click_source.png");
+ assert!(!semantic_action_without_point(&action));
+ action.as_object_mut().unwrap().remove("click_point_image");
+ action["action_truth"]["transport"] = serde_json::json!("windows_send_input");
+ action["action_truth"]["attempts"][0]["transport"] =
+ serde_json::json!("windows_send_input");
+ assert!(!semantic_action_without_point(&action));
+ }
+
+ #[test]
+ fn semantic_click_without_point_requires_exact_action_truth() {
+ for transport in [
+ "linux_at_spi_action",
+ "windows_uia_invoke",
+ "windows_uia_toggle",
+ "windows_uia_selection",
+ "windows_uia_expand_collapse",
+ ] {
+ let mut original = semantic_click_fixture();
+ original["action_truth"]["transport"] = serde_json::json!(transport);
+ assert!(semantic_action_without_point(&original));
+ let mut token = original.clone();
+ token["arguments"]
+ .as_object_mut()
+ .unwrap()
+ .remove("element_index");
+ token["arguments"]["element_token"] = serde_json::json!("e:fixture");
+ token["action_truth"]["requested_delivery"] = serde_json::json!("foreground");
+ token["action_truth"]["actual_delivery"] = serde_json::json!("foreground");
+ token["action_truth"]["effect"] = serde_json::json!("confirmed");
+ assert!(semantic_action_without_point(&token));
+ for (pointer, replacements) in [
+ ("/result_error", serde_json::json!([true, null])),
+ ("/tool", serde_json::json!(["double_click", "right_click"])),
+ ("/action_truth", serde_json::json!([null])),
+ (
+ "/action_truth/effect",
+ serde_json::json!(["unknown", "partial", "suspected_noop", "refused"]),
+ ),
+ (
+ "/action_truth/transport",
+ serde_json::json!(["linux_x11_event", "unknown"]),
+ ),
+ (
+ "/action_truth/route",
+ serde_json::json!(["unknown", "synthetic_events"]),
+ ),
+ (
+ "/action_truth/actual_delivery",
+ serde_json::json!(["unknown", null]),
+ ),
+ (
+ "/action_truth/requested_delivery",
+ serde_json::json!(["foreground"]),
+ ),
+ ("/action_truth/delivered_count", serde_json::json!([0, 2])),
+ (
+ "/action_truth/escalation",
+ serde_json::json!([{"kind":"retry_with_pixel_target"}]),
+ ),
+ ("/action_truth/fallbacks", serde_json::json!([[{}]])),
+ (
+ "/action_truth/attempts",
+ serde_json::json!([[{}], [{}, {}]]),
+ ),
+ ("/arguments/element_index", serde_json::json!([null, -1])),
+ ] {
+ for replacement in replacements.as_array().unwrap() {
+ let mut action = original.clone();
+ *action.pointer_mut(pointer).unwrap() = replacement.clone();
+ assert!(
+ !semantic_action_without_point(&action),
+ "{pointer}: {action}"
+ );
+ }
+ }
+ for (key, value) in [
+ ("x", serde_json::json!(10)),
+ ("y", serde_json::json!(20)),
+ ("raw", serde_json::json!(true)),
+ ("button", serde_json::json!("right")),
+ ("count", serde_json::json!(2)),
+ ("click_count", serde_json::json!(2)),
+ ("modifier", serde_json::json!(["shift"])),
+ ("modifiers", serde_json::json!(["ctrl"])),
+ ] {
+ let mut action = original.clone();
+ action["arguments"][key] = value;
+ assert!(!semantic_action_without_point(&action), "{key}");
+ }
+ let mut point = original.clone();
+ point["click_point"] = serde_json::json!({"x":10,"y":20});
+ assert!(!semantic_action_without_point(&point));
+ for key in [
+ "actual_delivery",
+ "requested_delivery",
+ "attempts",
+ "fallbacks",
+ "escalation",
+ "delivered_count",
+ "transport",
+ "route",
+ "effect",
+ ] {
+ let mut action = original.clone();
+ action["action_truth"].as_object_mut().unwrap().remove(key);
+ assert!(!semantic_action_without_point(&action), "missing {key}");
+ }
+ }
+ }
+
use std::sync::atomic::{AtomicUsize, Ordering};
+ #[test]
+ fn semantic_turn_records_truth_without_inventing_a_marker() {
+ use crate::action_record::{
+ ActionEffect, ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
+ };
+ for (actual, is_error, point, expected) in [
+ (
+ ActualDelivery::Background,
+ false,
+ None,
+ "semantic_action_without_point",
+ ),
+ (
+ ActualDelivery::Foreground,
+ false,
+ None,
+ "semantic_action_without_point",
+ ),
+ (ActualDelivery::Unknown, true, None, "capture_failed"),
+ (
+ ActualDelivery::Background,
+ false,
+ Some((10.0, 20.0)),
+ "capture_failed",
+ ),
+ ] {
+ let root = tempfile::tempdir().unwrap();
+ let requested = if actual == ActualDelivery::Foreground {
+ RequestedDelivery::Foreground
+ } else {
+ RequestedDelivery::Background
+ };
+ let record = ActionExecutionRecord::builder(
+ ActionEffect::Unverifiable,
+ ActionTransport::LinuxAtSpiAction,
+ requested,
+ )
+ .actual_delivery(actual)
+ .build()
+ .unwrap();
+ let pending = PendingTurn {
+ generation: 0,
+ turn_dir: root.path().to_path_buf(),
+ tool_name: "click".into(),
+ args: serde_json::json!({"pid":1,"element_index":3}),
+ start_ms: 0,
+ session_start_ms: 0,
+ window_id: None,
+ pid: Some(1),
+ click_point: point,
+ capture_visual_state: false,
+ before: TurnCapture::default(),
+ dispatch_click: None,
+ };
+ write_turn(pending, "AT-SPI outcome", Some(&record), is_error).unwrap();
+ let action: Value =
+ serde_json::from_slice(&std::fs::read(root.path().join("action.json")).unwrap())
+ .unwrap();
+ let manifest: Value =
+ serde_json::from_slice(&std::fs::read(root.path().join("evidence.json")).unwrap())
+ .unwrap();
+ assert_eq!(action["action_truth"], record.debug_json());
+ assert_eq!(manifest["click"]["classification"], expected);
+ assert_eq!(
+ manifest["click"]["status"],
+ if expected == "capture_failed" {
+ "unavailable"
+ } else {
+ "not_applicable"
+ }
+ );
+ assert!(!root.path().join("click.png").exists());
+ }
+ }
+
+ #[test]
+ fn offscreen_semantic_points_are_absent_but_pixel_clicks_still_need_markers() {
+ use crate::action_record::{
+ ActionEffect, ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
+ };
+ let png = crate::image_utils::encode_rgba_to_png(&[0; 16], 2, 2).unwrap();
+ for point in [
+ (f64::NAN, 0.0),
+ (f64::INFINITY, 0.0),
+ (-1.0, 0.0),
+ (2.0, 0.0),
+ (0.0, 2.0),
+ (i32::MIN as f64, i32::MAX as f64),
+ ] {
+ for pixel in [false, true] {
+ let root = tempfile::tempdir().unwrap();
+ let record = ActionExecutionRecord::builder(
+ ActionEffect::Unverifiable,
+ ActionTransport::LinuxAtSpiAction,
+ RequestedDelivery::Background,
+ )
+ .actual_delivery(ActualDelivery::Background)
+ .build()
+ .unwrap();
+ let args = if pixel {
+ serde_json::json!({"pid":1,"x":point.0,"y":point.1})
+ } else {
+ serde_json::json!({"pid":1,"element_index":3})
+ };
+ write_turn(
+ PendingTurn {
+ generation: 0,
+ turn_dir: root.path().to_path_buf(),
+ tool_name: "click".into(),
+ args,
+ start_ms: 0,
+ session_start_ms: 0,
+ window_id: None,
+ pid: Some(1),
+ click_point: Some(point),
+ capture_visual_state: false,
+ before: TurnCapture {
+ screenshot: Some(png.clone()),
+ ..Default::default()
+ },
+ dispatch_click: None,
+ },
+ "AT-SPI outcome",
+ Some(&record),
+ false,
+ )
+ .unwrap();
+ let action: Value = serde_json::from_slice(
+ &std::fs::read(root.path().join("action.json")).unwrap(),
+ )
+ .unwrap();
+ let manifest: Value = serde_json::from_slice(
+ &std::fs::read(root.path().join("evidence.json")).unwrap(),
+ )
+ .unwrap();
+ assert!(action.get("click_point").is_none());
+ assert_eq!(
+ manifest["click"]["classification"],
+ if pixel {
+ "capture_failed"
+ } else {
+ "semantic_action_without_point"
+ }
+ );
+ assert!(!root.path().join("click.png").exists());
+ }
+ }
+ }
+
struct FailingVideo;
+ fn setup_test_marker() {
+ set_click_marker_fn(|png, x, y| {
+ Some(
+ crate::image_utils::crosshair_png_bytes(png, x, y)
+ .unwrap_or_else(|_| b"click".to_vec()),
+ )
+ });
+ }
+
impl VideoBackend for FailingVideo {
fn stop(self: Box<Self>) -> anyhow::Result<VideoMetadata> {
anyhow::bail!("recorder did not finalize")
@@ -973,7 +1785,7 @@ mod tests {
let phase = STATES.fetch_add(1, Ordering::SeqCst);
Some(format!(r#"{{"phase":{phase}}}"#).into_bytes())
});
- set_click_marker_fn(|_, _, _| Some(b"click".to_vec()));
+ setup_test_marker();
set_element_bounds_fn(|window_id, pid, element_index| {
Some((window_id as f64 + element_index as f64, pid as f64))
});
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
index ddbd73f329..727d30574f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -1379,6 +1379,24 @@ pub fn is_session_ended(session_id: &str) -> bool {
ended_sessions().lock().unwrap().contains_key(session_id)
}
+/// Whether termination has been requested for a runtime-private lifecycle.
+///
+/// Long-running adapters may use this to relinquish held input before their
+/// dispatch guard drops. Cleanup hooks still run only after admitted work has
+/// unwound. This read-only cancellation signal neither grants authority nor
+/// revives a session; callers must use the registry's private id, not a label.
+pub fn is_session_ending(session_id: &str) -> bool {
+ // Match admission/termination lock order and observe pending termination
+ // and completed termination in one read-side critical section.
+ let ended = ended_sessions().lock().unwrap();
+ ended.contains_key(session_id)
+ || lifecycle_records()
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .is_some_and(|record| record.pending_end.is_some())
+}
+
/// Revive a previously-ended session id by clearing its tombstone, so a fresh
/// `start_session` with a recycled id works as a caller would expect: the id
/// becomes live again and its actions stop being rejected by the resurrection
@@ -1997,7 +2015,12 @@ mod tests {
)
.expect("idempotent start must preserve the live dispatch record");
+ assert!(!is_session_ending(sid));
+ assert!(!end_session_for_owner(sid, "unrelated-owner"));
+ assert!(!is_session_ending(sid));
assert!(end_session_for_owner(sid, owner));
+ assert!(is_session_ending(sid));
+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 0);
let snapshot = session_snapshot(sid, owner, DEFAULT_SESSION_IDLE_TTL).unwrap();
assert!(snapshot.ending);
assert!(!is_session_ended(sid));
@@ -2007,6 +2030,7 @@ mod tests {
drop(guard);
assert!(is_session_ended(sid));
+ assert!(is_session_ending(sid));
assert_eq!(cleanup_calls.load(Ordering::SeqCst), 1);
assert!(end_session_for_owner(sid, owner));
assert_eq!(cleanup_calls.load(Ordering::SeqCst), 1);
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 76fd8b26bf..0cb5548da1 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -507,6 +507,15 @@ pub enum ProtectedResourceOwnership {
pub trait Tool: Send + Sync {
fn def(&self) -> &ToolDef;
+ /// Implementation-attested routing that cannot touch the primary input
+ /// lane. The adapter must serialize its own lifecycle and fail closed if
+ /// that independent route is unavailable; it must never fall back to
+ /// global input. Caller fields alone cannot establish this guarantee.
+ /// Existing platform routes conservatively retain global coordination.
+ fn has_independent_input_lane(&self, _args: &Value) -> bool {
+ false
+ }
+
/// Trusted implementation-side provenance for prompt-light disposable
/// resources. The default is deliberately conservative: caller arguments
/// never establish ownership, and an adapter may skip protected consent
@@ -1496,7 +1505,11 @@ impl ToolRegistry {
"start_recording" | "stop_recording" | "get_recording_state" | "replay_trajectory"
);
let private_consent_turn = is_existing_profile_prepare(resolved_name, &args);
- let _desktop_action = if is_physical_desktop_action(resolved_name) {
+ let _desktop_action = if requires_desktop_coordination(
+ resolved_name,
+ &args,
+ tool.has_independent_input_lane(&args),
+ ) {
let coordinator = desktop_action_coordinator();
// Avoid yielding the dispatch task when the process-wide input
// lane is uncontended. On Windows, that yield creates a window in
@@ -1522,7 +1535,11 @@ impl ToolRegistry {
})
.flatten();
- let mut result = tool.invoke(args.clone()).await;
+ let mut result = crate::recording::scope_dispatch_click_capture(
+ pending_turn.as_ref(),
+ tool.invoke(args.clone()),
+ )
+ .await;
drop(lifecycle_dispatch);
// The platform worker has exited, so another text operation for this
// pid may now start even while result projection and evidence capture
@@ -2561,6 +2578,21 @@ fn is_physical_desktop_action(tool: &str) -> bool {
)
}
+fn requires_desktop_coordination(tool: &str, args: &Value, independent_lane: bool) -> bool {
+ if !is_physical_desktop_action(tool) {
+ return false;
+ }
+ // Only an implementation-attested, exact-window background route can
+ // leave the shared lane. Explicit desktop and foreground calls never do.
+ let exact_background_window = args["pid"].as_u64().is_some_and(|pid| pid > 0)
+ && args["window_id"].as_u64().is_some_and(|id| id > 0)
+ && args["scope"] != "desktop"
+ && args.pointer("/target/kind").and_then(Value::as_str) != Some("desktop")
+ && args["delivery_mode"] != "foreground"
+ && args["dispatch"] != "foreground";
+ !(independent_lane && exact_background_window)
+}
+
/// Bucket that owns the processes a call is allowed to terminate.
///
/// A call that declares a session keys its launches to that session, so
@@ -3639,6 +3671,74 @@ resources:
assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
+ #[tokio::test]
+ async fn background_input_rechecks_manifest_before_every_adapter_dispatch() {
+ // The adapter may retain a native connection after a successful call.
+ // Reusing its public session label must not reuse resource authority.
+ for mode in [
+ PermissionMode::Standard,
+ PermissionMode::Bounded,
+ PermissionMode::Unrestricted,
+ ] {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let registry = input_registry(None, hits.clone());
+ let context = manifest_context(
+ mode,
+ r#"
+version: 3
+expires_after: 1h
+idle_timeout: 30m
+allow:
+ tools: [click]
+resources:
+ desktop:
+ windows:
+ - pid: 42
+ window_id: 7
+"#,
+ );
+ for (window, expected_calls) in [(7, 1), (8, 1), (7, 2), (9, 2)] {
+ let result = registry.invoke_with_context("click", serde_json::json!({
+ "pid": 42, "window_id": window, "x": 10, "y": 20,
+ "delivery_mode": "background", "session": "persistent-native-connection",
+ "_session_id": "forged-authority", "_lane": 0,
+ }), context.clone()).await;
+ assert_eq!(
+ result.is_error == Some(true),
+ window != 7,
+ "{mode:?}: window {window}"
+ );
+ assert_eq!(
+ hits.load(Ordering::SeqCst),
+ expected_calls,
+ "denied input must never enter the adapter"
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn background_input_without_manifest_uses_existing_promptless_modes() {
+ for context in [standard_context(), unrestricted_context()] {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let registry = input_registry(None, hits.clone());
+ for window in [7, 8] {
+ let result = registry
+ .invoke_with_context(
+ "click",
+ serde_json::json!({
+ "pid": 42, "window_id": window, "x": 10, "y": 20,
+ "delivery_mode": "background", "session": "ordinary-desktop-input",
+ }),
+ context.clone(),
+ )
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ }
+ assert_eq!(hits.load(Ordering::SeqCst), 2);
+ }
+ }
+
#[tokio::test]
async fn canonical_dispatch_normalizes_legacy_delivery_mode_before_execution() {
let hits = Arc::new(AtomicUsize::new(0));
@@ -4517,6 +4617,33 @@ resources:
assert_eq!(max_active.load(Ordering::SeqCst), 1);
}
+ #[test]
+ fn independent_input_requires_adapter_attestation_and_an_exact_background_window() {
+ use super::requires_desktop_coordination;
+ let exact = serde_json::json!({"pid": 10, "window_id": 20, "delivery_mode": "background"});
+ assert!(requires_desktop_coordination("drag", &exact, false));
+ assert!(!requires_desktop_coordination("drag", &exact, true));
+ for fields in [
+ serde_json::json!({"scope": "desktop"}),
+ serde_json::json!({"target": {"kind": "desktop"}}),
+ serde_json::json!({"delivery_mode": "foreground"}),
+ serde_json::json!({"dispatch": "foreground"}),
+ serde_json::json!({"pid": 0}),
+ serde_json::json!({"window_id": null}),
+ ] {
+ let mut args = exact.clone();
+ args.as_object_mut()
+ .unwrap()
+ .extend(fields.as_object().unwrap().clone());
+ assert!(requires_desktop_coordination("drag", &args, true), "{args}");
+ }
+ assert!(requires_desktop_coordination(
+ "drag",
+ &serde_json::json!({"independent_input_lane": true}),
+ false
+ ));
+ }
+
#[test]
fn overlapping_text_input_for_one_pid_fails_fast_and_releases_after_completion() {
let pid = 8_675_410;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs
index 6203bb4b4b..823bfcfdcf 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs
@@ -68,6 +68,10 @@ impl Tool for PidOnlyWindowTargetGuard {
self.inner.def()
}
+ fn has_independent_input_lane(&self, args: &Value) -> bool {
+ self.inner.has_independent_input_lane(args)
+ }
+
async fn protected_resource_ownership(
&self,
adapter_id: &str,
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml
index 6a20b23b05..eb36a7f29c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml
@@ -11,6 +11,7 @@ publish = false
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
+image = { workspace = true }
tempfile = "3"
[target.'cfg(unix)'.dependencies]
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
index eb07f5c804..e25bc9fef2 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
@@ -1578,6 +1578,15 @@ fn validate_one_turn(turn: &Path, cell_id: &str, errors: &mut Vec<String>) {
}
}
+ if manifest
+ .as_ref()
+ .is_some_and(|value| value["click"]["classification"] == "semantic_action_without_point")
+ && !action.as_ref().is_some_and(semantic_action_without_point)
+ {
+ errors.push(format!(
+ "invalid semantic-click classification for {cell_id}/{turn_name}: action does not prove a single semantic dispatch without a point"
+ ));
+ }
if action.as_ref().is_some_and(|value| {
matches!(
value["tool"].as_str(),
@@ -1585,7 +1594,10 @@ fn validate_one_turn(turn: &Path, cell_id: &str, errors: &mut Vec<String>) {
)
}) {
let refused_before_target_resolution = action.as_ref().is_some_and(|value| {
- value["result_error"].as_bool() == Some(true) && value.get("click_point").is_none()
+ value["result_error"].as_bool() == Some(true)
+ && value.get("click_point").is_none()
+ && (value.get("action_truth").is_none()
+ || value["action_truth"]["effect"] == "refused")
});
let refused_before_dispatch = action.as_ref().is_some_and(|value| {
value["result_error"].as_bool() == Some(true)
@@ -1608,6 +1620,21 @@ fn validate_one_turn(turn: &Path, cell_id: &str, errors: &mut Vec<String>) {
}
return;
}
+ if action.as_ref().is_some_and(semantic_action_without_point) {
+ if !manifest.as_ref().is_some_and(|value| {
+ value["click"]["status"] == "not_applicable"
+ && value["click"]["classification"] == "semantic_action_without_point"
+ }) || turn.join("click.png").exists()
+ {
+ errors.push(format!(
+ "invalid semantic-click evidence for {cell_id}/{turn_name}: expected not_applicable/semantic_action_without_point without click.png"
+ ));
+ }
+ return;
+ }
+ if let (Some(action), Some(manifest)) = (&action, &manifest) {
+ validate_click_source(turn, cell_id, action, manifest, errors);
+ }
validate_capture_status(
manifest.as_ref(),
&["click"],
@@ -1627,6 +1654,131 @@ fn validate_one_turn(turn: &Path, cell_id: &str, errors: &mut Vec<String>) {
}
}
+// A tool may scroll an element into view after the original before image.
+// Its actual input point must be grounded in the supplemental pre-input frame.
+fn validate_click_source(
+ turn: &Path,
+ cell_id: &str,
+ action: &Value,
+ manifest: &Value,
+ errors: &mut Vec<String>,
+) {
+ let declared = action.get("click_point_image");
+ if declared.is_none() {
+ if manifest.get("click_source").is_some()
+ || manifest["click"]
+ .get("source_image")
+ .is_some_and(|source| source != "before.png")
+ || turn.join("click_source.png").exists()
+ {
+ errors.push(format!(
+ "undeclared supplemental click source for {cell_id}"
+ ));
+ }
+ return;
+ }
+ if declared.and_then(Value::as_str) != Some("click_source.png")
+ || manifest["click"]["source_image"] != "click_source.png"
+ {
+ errors.push(format!("invalid supplemental click source for {cell_id}"));
+ return;
+ }
+ validate_capture_status(
+ Some(manifest),
+ &["click_source"],
+ cell_id,
+ "click_source.png",
+ errors,
+ );
+ let decode = |name: &str| -> Option<image::DynamicImage> {
+ let mut reader = image::ImageReader::open(turn.join(name)).ok()?;
+ reader.set_format(image::ImageFormat::Png);
+ reader.decode().ok()
+ };
+ let (Some(source), Some(marker)) = (decode("click_source.png"), decode("click.png")) else {
+ errors.push(format!("invalid supplemental click PNG for {cell_id}"));
+ return;
+ };
+ let point = action["click_point"]["x"]
+ .as_f64()
+ .zip(action["click_point"]["y"].as_f64());
+ if source.width() == 0
+ || source.height() == 0
+ || source.width() != marker.width()
+ || source.height() != marker.height()
+ || !point.is_some_and(|(x, y)| {
+ x.is_finite()
+ && y.is_finite()
+ && x >= 0.0
+ && y >= 0.0
+ && x < f64::from(source.width())
+ && y < f64::from(source.height())
+ })
+ {
+ errors.push(format!("invalid supplemental click geometry for {cell_id}"));
+ }
+}
+
+// Semantic activation has no spatial marker only when the retained execution
+// record proves a single accessibility dispatch without escalation or replay.
+fn semantic_action_without_point(action: &Value) -> bool {
+ let args = &action["arguments"];
+ let truth = &action["action_truth"];
+ action["tool"] == "click"
+ && action["result_error"] == false
+ && action.get("click_point").is_none()
+ && action.get("click_point_image").is_none()
+ && (args["element_index"].as_u64().is_some()
+ || args["element_token"]
+ .as_str()
+ .is_some_and(|token| !token.is_empty()))
+ && args.get("x").is_none()
+ && args.get("y").is_none()
+ && args.get("raw").is_none_or(|value| value == false)
+ && args.get("button").is_none_or(|value| value == "left")
+ && args
+ .get("count")
+ .is_none_or(|value| value.as_u64() == Some(1))
+ && args
+ .get("click_count")
+ .is_none_or(|value| value.as_u64() == Some(1))
+ && ["modifier", "modifiers"].iter().all(|key| {
+ args.get(*key)
+ .is_none_or(|value| value.as_array().is_some_and(Vec::is_empty))
+ })
+ && matches!(
+ truth["transport"].as_str(),
+ Some(
+ "linux_at_spi_action"
+ | "windows_uia_invoke"
+ | "windows_uia_toggle"
+ | "windows_uia_selection"
+ | "windows_uia_expand_collapse"
+ )
+ )
+ && truth["route"] == "accessibility"
+ && matches!(truth["effect"].as_str(), Some("confirmed" | "unverifiable"))
+ && matches!(
+ truth["actual_delivery"].as_str(),
+ Some("background" | "foreground")
+ )
+ && truth["requested_delivery"] == truth["actual_delivery"]
+ && truth.get("escalation").is_some_and(Value::is_null)
+ && truth["fallbacks"].as_array().is_some_and(Vec::is_empty)
+ && truth
+ .get("delivered_count")
+ .is_some_and(|value| value.is_null() || value.as_u64() == Some(1))
+ && truth["attempts"].as_array().is_some_and(|attempts| {
+ // Legacy single-dispatch results carry transport/delivery above
+ // without a per-attempt journal. Any supplied attempt must match.
+ attempts.len() <= 1
+ && attempts.iter().all(|attempt| {
+ attempt["transport"] == truth["transport"]
+ && attempt["delivery"] == truth["actual_delivery"]
+ })
+ })
+}
+
fn validate_capture_status(
manifest: Option<&Value>,
path: &[&str],
@@ -1696,8 +1848,212 @@ fn read_json_value(path: &Path) -> Result<Value, String> {
#[cfg(test)]
mod tests {
use super::*;
+
+ fn semantic_click_fixture() -> Value {
+ serde_json::json!({
+ "tool": "click", "result_error": false,
+ "arguments": {"pid": 1, "window_id": 2, "element_index": 3},
+ "action_truth": {
+ "effect": "unverifiable", "transport": "linux_at_spi_action",
+ "route": "accessibility", "requested_delivery": "background",
+ "actual_delivery": "background", "delivered_count": null,
+ "attempts": [], "fallbacks": [], "escalation": null
+ }
+ })
+ }
+
+ #[test]
+ fn semantic_click_without_point_requires_exact_action_truth() {
+ let original = semantic_click_fixture();
+ assert!(semantic_action_without_point(&original));
+ let mut token = original.clone();
+ token["arguments"]
+ .as_object_mut()
+ .unwrap()
+ .remove("element_index");
+ token["arguments"]["element_token"] = serde_json::json!("e:fixture");
+ token["action_truth"]["requested_delivery"] = serde_json::json!("foreground");
+ token["action_truth"]["actual_delivery"] = serde_json::json!("foreground");
+ token["action_truth"]["effect"] = serde_json::json!("confirmed");
+ assert!(semantic_action_without_point(&token));
+ for transport in [
+ "windows_uia_invoke",
+ "windows_uia_toggle",
+ "windows_uia_selection",
+ "windows_uia_expand_collapse",
+ ] {
+ let mut windows = original.clone();
+ windows["action_truth"]["transport"] = serde_json::json!(transport);
+ assert!(semantic_action_without_point(&windows));
+ windows["action_truth"]["attempts"] = serde_json::json!([{
+ "transport":transport, "delivery":"background"
+ }]);
+ assert!(semantic_action_without_point(&windows));
+ windows["action_truth"]["attempts"][0]["transport"] =
+ serde_json::json!("linux_at_spi_action");
+ assert!(!semantic_action_without_point(&windows));
+ }
+ for (pointer, replacements) in [
+ ("/result_error", serde_json::json!([true, null])),
+ ("/tool", serde_json::json!(["double_click", "right_click"])),
+ ("/action_truth", serde_json::json!([null])),
+ (
+ "/action_truth/effect",
+ serde_json::json!(["unknown", "partial", "suspected_noop", "refused"]),
+ ),
+ (
+ "/action_truth/transport",
+ serde_json::json!(["linux_x11_event", "windows_send_input", "unknown"]),
+ ),
+ (
+ "/action_truth/route",
+ serde_json::json!(["unknown", "synthetic_events"]),
+ ),
+ (
+ "/action_truth/actual_delivery",
+ serde_json::json!(["unknown", null]),
+ ),
+ (
+ "/action_truth/requested_delivery",
+ serde_json::json!(["foreground"]),
+ ),
+ ("/action_truth/delivered_count", serde_json::json!([0, 2])),
+ (
+ "/action_truth/escalation",
+ serde_json::json!([{"kind":"retry_with_pixel_target"}]),
+ ),
+ ("/action_truth/fallbacks", serde_json::json!([[{}]])),
+ (
+ "/action_truth/attempts",
+ serde_json::json!([[{}], [{}, {}]]),
+ ),
+ ("/arguments/element_index", serde_json::json!([null, -1])),
+ ] {
+ for replacement in replacements.as_array().unwrap() {
+ let mut action = original.clone();
+ *action.pointer_mut(pointer).unwrap() = replacement.clone();
+ assert!(
+ !semantic_action_without_point(&action),
+ "{pointer}: {action}"
+ );
+ }
+ }
+ for (key, value) in [
+ ("x", serde_json::json!(10)),
+ ("y", serde_json::json!(20)),
+ ("raw", serde_json::json!(true)),
+ ("button", serde_json::json!("right")),
+ ("count", serde_json::json!(2)),
+ ("click_count", serde_json::json!(2)),
+ ("modifier", serde_json::json!(["shift"])),
+ ("modifiers", serde_json::json!(["ctrl"])),
+ ] {
+ let mut action = original.clone();
+ action["arguments"][key] = value;
+ assert!(!semantic_action_without_point(&action), "{key}");
+ }
+ let mut point = original.clone();
+ point["click_point"] = serde_json::json!({"x":10,"y":20});
+ assert!(!semantic_action_without_point(&point));
+ let mut supplemental = original.clone();
+ supplemental["click_point_image"] = serde_json::json!("click_source.png");
+ assert!(!semantic_action_without_point(&supplemental));
+ for key in [
+ "actual_delivery",
+ "requested_delivery",
+ "attempts",
+ "fallbacks",
+ "escalation",
+ "delivered_count",
+ "transport",
+ "route",
+ "effect",
+ ] {
+ let mut action = original.clone();
+ action["action_truth"].as_object_mut().unwrap().remove(key);
+ assert!(!semantic_action_without_point(&action), "missing {key}");
+ }
+ }
+
use tempfile::TempDir;
+ fn supplemental_click_fixture() -> (TempDir, Value, Value) {
+ let root = tempfile::tempdir().unwrap();
+ for name in ["click_source.png", "click.png"] {
+ image::RgbImage::new(20, 30)
+ .save(root.path().join(name))
+ .unwrap();
+ }
+ let action = serde_json::json!({
+ "click_point_image":"click_source.png", "click_point":{"x":10,"y":15}
+ });
+ let manifest = serde_json::json!({
+ "click":{"status":"captured","source_image":"click_source.png"},
+ "click_source":{"status":"captured"}
+ });
+ (root, action, manifest)
+ }
+
+ #[test]
+ fn supplemental_click_source_requires_decodable_matching_geometry() {
+ let (root, action, manifest) = supplemental_click_fixture();
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &action, &manifest, &mut errors);
+ assert!(errors.is_empty(), "{errors:?}");
+ for point in [
+ serde_json::json!({"x":20,"y":15}),
+ serde_json::json!({"x":10,"y":30}),
+ serde_json::json!({"x":-1,"y":15}),
+ serde_json::json!({"x":10,"y":null}),
+ ] {
+ let mut invalid = action.clone();
+ invalid["click_point"] = point;
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &invalid, &manifest, &mut errors);
+ assert!(!errors.is_empty());
+ }
+ image::RgbImage::new(10, 10)
+ .save(root.path().join("click.png"))
+ .unwrap();
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &action, &manifest, &mut errors);
+ assert!(errors.iter().any(|error| error.contains("geometry")));
+ std::fs::write(root.path().join("click.png"), b"not a png").unwrap();
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &action, &manifest, &mut errors);
+ assert!(errors.iter().any(|error| error.contains("PNG")));
+ }
+
+ #[test]
+ fn supplemental_click_source_rejects_inconsistent_or_failed_metadata() {
+ let (root, action, manifest) = supplemental_click_fixture();
+ for source in [
+ serde_json::json!("../outside.png"),
+ serde_json::json!("before.png"),
+ serde_json::Value::Null,
+ ] {
+ let mut invalid = action.clone();
+ invalid["click_point_image"] = source;
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &invalid, &manifest, &mut errors);
+ assert!(!errors.is_empty());
+ }
+ let mut undeclared = action.clone();
+ undeclared
+ .as_object_mut()
+ .unwrap()
+ .remove("click_point_image");
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &undeclared, &manifest, &mut errors);
+ assert!(!errors.is_empty());
+ let mut failed = manifest.clone();
+ failed["click_source"] =
+ serde_json::json!({"status":"unavailable","classification":"capture_failed"});
+ let mut errors = Vec::new();
+ validate_click_source(root.path(), "fixture", &action, &failed, &mut errors);
+ assert!(!errors.is_empty());
+ }
+
fn delivered_case(id: &str) -> CaseSpec {
CaseSpec::delivered(
id,
@@ -1732,6 +2088,83 @@ mod tests {
)
}
+ #[test]
+ fn validator_semantic_click_requires_classification_and_retained_evidence() {
+ for token_target in [false, true] {
+ let (root, case, result, turn) = complete_turn_fixture();
+ let mut action = semantic_click_fixture();
+ if token_target {
+ action["arguments"]
+ .as_object_mut()
+ .unwrap()
+ .remove("element_index");
+ action["arguments"]["element_token"] = serde_json::json!("e:fixture");
+ }
+ std::fs::write(turn.join("action.json"), action.to_string()).unwrap();
+ let manifest_path = turn.join("evidence.json");
+ let mut manifest: Value =
+ serde_json::from_slice(&std::fs::read(&manifest_path).unwrap()).unwrap();
+ manifest["click"] = serde_json::json!({"status":"not_applicable","classification":"semantic_action_without_point"});
+ std::fs::write(&manifest_path, manifest.to_string()).unwrap();
+ assert!(
+ validate_catalog(&[case.clone()], &[result.clone()], Some(root.path()), true)
+ .is_err(),
+ "a semantic action cannot retain a spatial marker"
+ );
+ std::fs::remove_file(turn.join("click.png")).unwrap();
+ validate_catalog(&[case.clone()], &[result.clone()], Some(root.path()), true).unwrap();
+ action["click_point"] = serde_json::json!({"x":10,"y":20});
+ std::fs::write(turn.join("action.json"), action.to_string()).unwrap();
+ assert!(
+ validate_catalog(&[case.clone()], &[result.clone()], Some(root.path()), true)
+ .is_err(),
+ "resolved points still require markers"
+ );
+ manifest["click"]["status"] = serde_json::json!("captured");
+ std::fs::write(&manifest_path, manifest.to_string()).unwrap();
+ std::fs::write(turn.join("click.png"), b"png").unwrap();
+ assert!(
+ validate_catalog(&[case.clone()], &[result.clone()], Some(root.path()), true)
+ .is_err(),
+ "a captured marker cannot legitimize a false semantic classification"
+ );
+ std::fs::remove_file(turn.join("click.png")).unwrap();
+ manifest["click"]["status"] = serde_json::json!("not_applicable");
+ action.as_object_mut().unwrap().remove("click_point");
+ std::fs::write(turn.join("action.json"), action.to_string()).unwrap();
+ manifest["click"]["classification"] = serde_json::json!("capture_failed");
+ std::fs::write(&manifest_path, manifest.to_string()).unwrap();
+ assert!(
+ validate_catalog(&[case.clone()], &[result.clone()], Some(root.path()), true)
+ .is_err()
+ );
+ manifest["click"]["classification"] =
+ serde_json::json!("semantic_action_without_point");
+ std::fs::write(&manifest_path, manifest.to_string()).unwrap();
+ std::fs::remove_file(turn.join("after.png")).unwrap();
+ assert!(
+ validate_catalog(&[case], &[result], Some(root.path()), true).is_err(),
+ "semantic actions still need before/after evidence"
+ );
+ }
+ }
+
+ #[test]
+ fn validator_unknown_dispatched_error_is_not_a_pretarget_refusal() {
+ let (root, case, result, turn) = complete_turn_fixture();
+ let mut action = semantic_click_fixture();
+ action["result_error"] = serde_json::json!(true);
+ action["action_truth"]["actual_delivery"] = serde_json::json!("unknown");
+ std::fs::write(turn.join("action.json"), action.to_string()).unwrap();
+ let manifest_path = turn.join("evidence.json");
+ let mut manifest: Value =
+ serde_json::from_slice(&std::fs::read(&manifest_path).unwrap()).unwrap();
+ manifest["click"] = serde_json::json!({"status":"not_applicable","classification":"action_refused_before_target_resolution"});
+ std::fs::write(manifest_path, manifest.to_string()).unwrap();
+ std::fs::remove_file(turn.join("click.png")).unwrap();
+ assert!(validate_catalog(&[case], &[result], Some(root.path()), true).is_err());
+ }
+
fn complete_turn_fixture() -> (TempDir, CaseSpec, CaseResult, PathBuf) {
let root = tempfile::tempdir().expect("create artifact root");
let recording = root.path().join("recordings/cell-pid1-001");
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs
index 6a08db3a04..1707c590c6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs
@@ -151,7 +151,7 @@ mod tests {
#[test]
fn receives_fixture_state_over_loopback() {
let journal = FixtureJournal::start();
- let body = r#"{"status":{"text":"last_action=left_click"}}"#;
+ let body = r#"{"status":{"text":"last_action=left_click"},"scroll-tall":{"scrollTop":208.5,"clientHeight":128},"lbl-scroll-offset":{"text":"scroll_offset=104"}}"#;
let address = journal
.url()
.strip_prefix("http://")
@@ -172,5 +172,9 @@ mod tests {
std::thread::sleep(Duration::from_millis(10));
}
assert!(journal.contains("last_action=left_click"));
+ let state = journal.snapshot();
+ assert_eq!(state["scroll-tall"]["scrollTop"].as_f64(), Some(208.5));
+ assert_eq!(state["scroll-tall"]["clientHeight"].as_u64(), Some(128));
+ assert_eq!(state["lbl-scroll-offset"]["text"], "scroll_offset=104");
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
index 69b94ab6ef..058179624e 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
@@ -1095,6 +1095,10 @@ pub mod linux {
super::hyprland::client_address(target)
}
+ pub(crate) fn hyprland_focus_identity() -> Result<Option<u64>, ObserverError> {
+ super::hyprland::focus_identity()
+ }
+
pub(crate) fn hyprland_cursor_position() -> Result<(f64, f64), ObserverError> {
super::hyprland::cursor_position()
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs
index 2c68248ae0..784c9e611c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer_hyprland.rs
@@ -200,6 +200,173 @@ pub(super) fn client_address(target: TargetWindow) -> Result<String, ObserverErr
.ok_or_else(|| ObserverError::new("Hyprland target client not found"))
}
+fn sentinel_clients_without_animation(
+ target: TargetWindow,
+ mut query_clients: impl FnMut() -> Result<Vec<Client>, ObserverError>,
+ query_property: impl FnOnce() -> Result<serde_json::Value, ObserverError>,
+) -> Result<Vec<Client>, ObserverError> {
+ let check_identity = |clients: &[Client]| {
+ if target.pid == 0 || target.native_id == 0 {
+ return Err(ObserverError::new(
+ "Hyprland sentinel requires exact pid and native_id",
+ ));
+ }
+ select(clients, target)?.ok_or_else(|| {
+ ObserverError::new(format!(
+ "Hyprland sentinel missing during no_anim query: pid={} native_id={:#x}",
+ target.pid, target.native_id
+ ))
+ })?;
+ Ok(())
+ };
+ check_identity(&query_clients()?)?;
+ let property = query_property();
+ let clients = query_clients()?;
+ check_identity(&clients)?;
+ let property = property.map_err(|error| {
+ ObserverError::new(format!(
+ "Hyprland sentinel no_anim property unavailable: {error}; configure an exact-title sentinel-only no_anim rule before mapping"
+ ))
+ })?;
+ if property.get("no_anim").and_then(serde_json::Value::as_bool) != Some(true) {
+ return Err(ObserverError::new(format!(
+ "Hyprland sentinel requires no_anim=true, received {property}; configure an exact-title sentinel-only no_anim rule before mapping; client: {:?}",
+ select(&clients, target)?
+ )));
+ }
+ Ok(clients)
+}
+
+fn sentinel_no_anim_property(target: TargetWindow) -> Result<serde_json::Value, ObserverError> {
+ let output = bounded_output(
+ Command::new("hyprctl").args([
+ "-j",
+ "getprop",
+ &format!("address:{:#x}", target.native_id),
+ "no_anim",
+ ]),
+ QUERY_TIMEOUT,
+ OUTPUT_LIMIT,
+ )?;
+ serde_json::from_slice(&output)
+ .map_err(|error| ObserverError::new(format!("invalid getprop no_anim JSON: {error}")))
+}
+
+#[derive(Debug, PartialEq)]
+struct SentinelGeometryGoal {
+ at: [i64; 2],
+ size: [i64; 2],
+ monitor: i64,
+ workspace: i64,
+ monitor_region: (f64, f64, f64, f64),
+}
+
+fn sentinel_geometry(
+ clients: &[Client],
+ monitors: &[Monitor],
+ target: TargetWindow,
+) -> Result<Option<SentinelGeometryGoal>, ObserverError> {
+ if target.pid == 0 || target.native_id == 0 {
+ return Err(ObserverError::new(
+ "Hyprland sentinel requires exact pid and native_id",
+ ));
+ }
+ let Some(client) = select(clients, target)? else {
+ return Ok(None);
+ };
+ let Some(monitor) = monitors.iter().find(|monitor| monitor.id == client.monitor) else {
+ return Ok(None);
+ };
+ let region = monitor_region(monitor)?;
+ // hyprctl reports geometry goals, not animated surface bounds. These
+ // samples prove fullscreen/map readiness only; the separate no_anim gate
+ // excludes the known animation race. Driver's surface guard stays decisive.
+ if !client.mapped
+ || client.hidden
+ || client.fullscreen != 2
+ || client.size.iter().any(|size| *size <= 0)
+ || client.workspace.id != monitor.active_workspace.id
+ || monitor.special_workspace.id != 0
+ || ![
+ (client.at[0] as f64, region.0),
+ (client.at[1] as f64, region.1),
+ (client.size[0] as f64, region.2),
+ (client.size[1] as f64, region.3),
+ ]
+ .iter()
+ .all(|(actual, expected)| (actual - expected).abs() <= 1.0)
+ {
+ return Ok(None);
+ }
+ Ok(Some(SentinelGeometryGoal {
+ at: client.at,
+ size: client.size,
+ monitor: client.monitor,
+ workspace: client.workspace.id,
+ monitor_region: region,
+ }))
+}
+
+fn wait_for_sentinel_geometry(
+ target: TargetWindow,
+ timeout: Duration,
+ unchanged_for: Duration,
+ mut query: impl FnMut() -> Result<(Vec<Client>, Vec<Monitor>), ObserverError>,
+ mut elapsed: impl FnMut() -> Duration,
+ mut pause: impl FnMut(Duration),
+) -> Result<(), ObserverError> {
+ let mut candidate = None;
+ let mut since = Duration::ZERO;
+ loop {
+ let (clients, monitors) = query().map_err(|error| {
+ ObserverError::new(format!(
+ "Hyprland sentinel geometry query failed for pid={} native_id={:#x}; last candidate: {candidate:?}: {error}",
+ target.pid, target.native_id
+ ))
+ })?;
+ let now = elapsed();
+ let geometry = sentinel_geometry(&clients, &monitors, target).map_err(|error| {
+ ObserverError::new(format!(
+ "Hyprland sentinel geometry invalid for pid={} native_id={:#x}; last candidate: {candidate:?}: {error}",
+ target.pid, target.native_id
+ ))
+ })?;
+ if geometry != candidate || geometry.is_none() {
+ since = now;
+ candidate = geometry;
+ }
+ if now < timeout && candidate.is_some() && now.saturating_sub(since) >= unchanged_for {
+ return Ok(());
+ }
+ if now >= timeout {
+ return Err(ObserverError::new(format!(
+ "Hyprland sentinel fullscreen geometry goal did not become ready for pid={} native_id={:#x}; last client: {:?}; monitors: {monitors:?}",
+ target.pid, target.native_id, select(&clients, target)?
+ )));
+ }
+ pause((timeout - now).min(Duration::from_millis(25)));
+ }
+}
+
+impl TargetWindow {
+ pub(crate) fn wait_for_hyprland_sentinel_geometry(self) -> Result<(), ObserverError> {
+ let started = Instant::now();
+ wait_for_sentinel_geometry(
+ self,
+ Duration::from_secs(5),
+ Duration::from_millis(150),
+ || {
+ let clients = sentinel_clients_without_animation(self, clients, || {
+ sentinel_no_anim_property(self)
+ })?;
+ Ok((clients, query("monitors")?))
+ },
+ || started.elapsed(),
+ std::thread::sleep,
+ )
+ }
+}
+
fn parse_focus(value: serde_json::Value) -> Result<Option<u64>, ObserverError> {
if value.as_object().is_some_and(|object| object.is_empty()) {
return Ok(None);
@@ -489,6 +656,295 @@ mod tests {
}
}
+ fn fullscreen_client() -> Client {
+ let mut client = client(0x10, 100);
+ client.fullscreen = 2;
+ client.at = [-100, 0];
+ client.size = [720, 1280];
+ client
+ }
+
+ #[test]
+ fn sentinel_stable_goal_never_admits_enabled_or_unknown_animations() {
+ for property in [
+ json!({"no_anim": false}),
+ json!({}),
+ json!({"no_anim": "true"}),
+ json!({"no_anim": 1}),
+ json!(null),
+ ] {
+ let mut calls = 0;
+ let error = wait_for_sentinel_geometry(
+ target(),
+ Duration::from_millis(250),
+ Duration::ZERO,
+ || {
+ calls += 1;
+ let clients = sentinel_clients_without_animation(
+ target(),
+ || Ok(vec![fullscreen_client()]),
+ || Ok(property.clone()),
+ )?;
+ Ok((clients, vec![monitor()]))
+ },
+ || Duration::ZERO,
+ |_| panic!("invalid no_anim must fail before another observation"),
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("requires no_anim=true"), "{error}");
+ assert!(
+ error.contains("sentinel-only no_anim rule before mapping"),
+ "{error}"
+ );
+ assert!(error.contains("native_id=0x10"), "{error}");
+ assert_eq!(calls, 1);
+ }
+ }
+
+ #[test]
+ fn sentinel_no_anim_requires_exact_identity_on_both_sides_of_query() {
+ for bad_sample in [0, 1] {
+ for missing in [false, true] {
+ let mut samples = 0;
+ let mut property_calls = 0;
+ let result = sentinel_clients_without_animation(
+ target(),
+ || {
+ let mut client = fullscreen_client();
+ let bad = samples == bad_sample;
+ samples += 1;
+ if bad {
+ client.pid += 1;
+ }
+ Ok(if bad && missing { vec![] } else { vec![client] })
+ },
+ || {
+ property_calls += 1;
+ Ok(json!({"no_anim": true}))
+ },
+ );
+ assert!(result.is_err());
+ assert_eq!(property_calls, bad_sample);
+ assert_eq!(samples, bad_sample + 1);
+ }
+ }
+ }
+
+ #[test]
+ fn sentinel_no_anim_accepts_only_true_and_preserves_query_errors() {
+ let mut samples = 0;
+ let clients = sentinel_clients_without_animation(
+ target(),
+ || {
+ samples += 1;
+ Ok(vec![fullscreen_client()])
+ },
+ || Ok(json!({"no_anim": true})),
+ )
+ .unwrap();
+ assert_eq!(samples, 2);
+ assert!(sentinel_geometry(&clients, &[monitor()], target())
+ .unwrap()
+ .is_some());
+ for message in ["invalid getprop no_anim JSON", "hyprctl query timed out"] {
+ let error = sentinel_clients_without_animation(
+ target(),
+ || Ok(vec![fullscreen_client()]),
+ || Err(ObserverError::new(message)),
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains(message), "{error}");
+ assert!(error.contains("no_anim property unavailable"), "{error}");
+ }
+ }
+
+ fn wait_geometry_samples(
+ mut sample: impl FnMut(usize) -> (Vec<Client>, Vec<Monitor>),
+ ) -> (Result<(), ObserverError>, usize) {
+ let elapsed = std::cell::Cell::new(Duration::ZERO);
+ let mut calls = 0;
+ let result = wait_for_sentinel_geometry(
+ target(),
+ Duration::from_millis(250),
+ Duration::from_millis(75),
+ || {
+ let value = sample(calls);
+ calls += 1;
+ Ok(value)
+ },
+ || elapsed.get(),
+ |duration| elapsed.set(elapsed.get() + duration),
+ );
+ (result, calls)
+ }
+
+ #[test]
+ fn sentinel_geometry_waits_for_fullscreen_and_unchanged_goals() {
+ let (result, calls) = wait_geometry_samples(|index| {
+ let mut client = fullscreen_client();
+ match index {
+ 0 => client.size = [0, 0],
+ 1..=4 => {
+ // Equal nonempty startup samples must never suffice.
+ client.fullscreen = 0;
+ client.size = [100, 80];
+ }
+ 5 => client.at[0] += 1,
+ _ => {}
+ }
+ (vec![client], vec![monitor()])
+ });
+ assert!(result.is_ok(), "{result:?}");
+ assert_eq!(calls, 10);
+ }
+
+ #[test]
+ fn sentinel_geometry_accepts_stable_native_fullscreen() {
+ let (result, calls) =
+ wait_geometry_samples(|_| (vec![fullscreen_client()], vec![monitor()]));
+ assert!(result.is_ok(), "{result:?}");
+ assert_eq!(calls, 4);
+ }
+
+ #[test]
+ fn sentinel_geometry_query_time_counts_toward_fixed_deadline() {
+ let elapsed = std::cell::Cell::new(Duration::ZERO);
+ let mut calls = 0;
+ let result = wait_for_sentinel_geometry(
+ target(),
+ Duration::from_millis(250),
+ Duration::from_millis(75),
+ || {
+ calls += 1;
+ elapsed.set(elapsed.get() + Duration::from_millis(150));
+ Ok((vec![fullscreen_client()], vec![monitor()]))
+ },
+ || elapsed.get(),
+ |duration| elapsed.set(elapsed.get() + duration),
+ );
+ assert!(result.is_err());
+ assert_eq!(calls, 2);
+ }
+
+ #[test]
+ fn sentinel_geometry_query_failure_preserves_identity_and_geometry() {
+ let mut calls = 0;
+ let error = wait_for_sentinel_geometry(
+ target(),
+ Duration::from_millis(250),
+ Duration::from_millis(75),
+ || {
+ calls += 1;
+ if calls == 1 {
+ Ok((vec![fullscreen_client()], vec![monitor()]))
+ } else {
+ Err(ObserverError::new("query unavailable"))
+ }
+ },
+ || Duration::ZERO,
+ |_| {},
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("native_id=0x10"), "{error}");
+ assert!(error.contains("size: [720, 1280]"), "{error}");
+ assert!(error.contains("query unavailable"), "{error}");
+ assert_eq!(calls, 2);
+ }
+
+ #[test]
+ fn sentinel_geometry_deadline_bounds_unready_and_flapping_samples() {
+ for flapping in [false, true] {
+ let (result, calls) = wait_geometry_samples(|index| {
+ let mut client = fullscreen_client();
+ if flapping {
+ client.at[0] += (index % 2) as i64;
+ } else {
+ client.size = [0, 0];
+ }
+ (vec![client], vec![monitor()])
+ });
+ let error = result.unwrap_err().to_string();
+ assert!(error.contains("native_id=0x10"), "{error}");
+ assert!(error.contains("size:"), "{error}");
+ assert!(error.contains("monitors:"), "{error}");
+ assert_eq!(calls, 11);
+ }
+ }
+
+ #[test]
+ fn sentinel_geometry_rejects_wrong_or_lost_identity() {
+ let mut wrong_pid = fullscreen_client();
+ wrong_pid.pid += 1;
+ assert!(sentinel_geometry(&[wrong_pid], &[monitor()], target()).is_err());
+ assert!(sentinel_geometry(
+ &[fullscreen_client()],
+ &[monitor()],
+ TargetWindow {
+ native_id: 0,
+ ..target()
+ }
+ )
+ .is_err());
+ for missing in [false, true] {
+ let (result, calls) = wait_geometry_samples(|index| {
+ let mut client = fullscreen_client();
+ if index > 1 {
+ client.address = "0x11".into();
+ }
+ let clients = if missing && index > 1 {
+ vec![]
+ } else {
+ vec![client]
+ };
+ (clients, vec![monitor()])
+ });
+ assert!(result.is_err());
+ assert_eq!(calls, 11);
+ }
+ }
+
+ #[test]
+ fn sentinel_geometry_rejects_missing_wrong_or_changed_monitor() {
+ for missing in [false, true] {
+ let (result, calls) = wait_geometry_samples(|_| {
+ let mut wrong = monitor();
+ wrong.id += 1;
+ (
+ vec![fullscreen_client()],
+ if missing { vec![] } else { vec![wrong] },
+ )
+ });
+ assert!(result.is_err());
+ assert_eq!(calls, 11);
+ }
+ let mut wrong = monitor();
+ wrong.width += 100.0;
+ assert!(
+ sentinel_geometry(&[fullscreen_client()], &[wrong], target())
+ .unwrap()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn sentinel_geometry_rejects_unmapped_hidden_and_off_workspace_clients() {
+ for mode in 0..4 {
+ let mut client = fullscreen_client();
+ match mode {
+ 0 => client.mapped = false,
+ 1 => client.hidden = true,
+ 2 => client.workspace.id += 1,
+ _ => client.fullscreen = 1,
+ }
+ assert!(sentinel_geometry(&[client], &[monitor()], target())
+ .unwrap()
+ .is_none());
+ }
+ }
+
#[test]
fn explicit_identity_never_selects_larger_sibling_or_missing_id_fallback() {
let small = client(0x10, 100);
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
index faf2e546ff..900c561349 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
@@ -113,6 +113,12 @@ impl ForegroundSentinel {
let focus_deadline = Instant::now() + Duration::from_secs(10);
if is_wayland_session() {
wait_for_journal(&journal_path, focus_deadline, r#""kind":"ready""#, "ready");
+ #[cfg(target_os = "linux")]
+ if hyprland::is_session() {
+ target
+ .wait_for_hyprland_sentinel_geometry()
+ .map_err(|error| error.to_string())?;
+ }
try_activate_native_foreground(driver, target)?;
// Electron may already be focused before its preload listener is ready.
// The compositor observation is the authoritative Wayland focus gate.
@@ -268,7 +274,7 @@ impl ForegroundSentinel {
#[cfg(target_os = "linux")]
focus_sway_target(driver, background_target)?;
if is_wayland_session() {
- wait_for_native_focus_lost(self.target)?;
+ wait_for_native_focus_lost(self.target, background_target)?;
} else {
wait_for_event(&self.journal_path, "blur", Duration::from_secs(3))?;
let (_, focus_violations) = self.observe();
@@ -1012,9 +1018,16 @@ fn wait_for_native_focus_stable(target: TargetWindow) {
}
#[cfg(target_os = "linux")]
-fn wait_for_native_focus_lost(target: TargetWindow) -> Result<(), String> {
+fn wait_for_native_focus_lost(
+ target: TargetWindow,
+ background_target: TargetWindow,
+) -> Result<(), String> {
use crate::observer::{ObserverBackend, TargetZ};
+ if hyprland::is_session() {
+ return hyprland::wait_for_focus_transfer(target, background_target);
+ }
+
let backend = NativeObserver::new();
let deadline = Instant::now() + Duration::from_secs(3);
loop {
@@ -1035,7 +1048,10 @@ fn wait_for_native_focus_lost(target: TargetWindow) -> Result<(), String> {
}
#[cfg(not(target_os = "linux"))]
-fn wait_for_native_focus_lost(_target: TargetWindow) -> Result<(), String> {
+fn wait_for_native_focus_lost(
+ _target: TargetWindow,
+ _background_target: TargetWindow,
+) -> Result<(), String> {
Err("native Wayland focus observation is only available on Linux".to_owned())
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs
index 3f7a978f04..c8ab621734 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel_hyprland.rs
@@ -135,6 +135,56 @@ pub(super) fn is_session() -> bool {
|| std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some())
}
+#[cfg(target_os = "linux")]
+pub(super) fn wait_for_focus_transfer(
+ sentinel: crate::observer::TargetWindow,
+ background: crate::observer::TargetWindow,
+) -> Result<(), String> {
+ use crate::observer::linux::{hyprland_focus_identity, hyprland_target_address};
+
+ let identity = |target| {
+ let address = hyprland_target_address(target).map_err(|error| error.to_string())?;
+ address
+ .strip_prefix("0x")
+ .and_then(|value| u64::from_str_radix(value, 16).ok())
+ .filter(|value| *value != 0)
+ .ok_or_else(|| format!("invalid Hyprland target address: {address}"))
+ };
+ let sentinel = identity(sentinel)?;
+ let background = identity(background)?;
+ if sentinel == background {
+ return Err(
+ "Hyprland focus canary requires distinct sentinel and background clients".into(),
+ );
+ }
+ // A raised floating target may only partially overlap the sentinel, so
+ // focus transfer must not depend on full-occlusion z-order classification.
+ wait_for_focus_identity(background, std::time::Duration::from_secs(3), || {
+ hyprland_focus_identity().map_err(|error| error.to_string())
+ })
+}
+
+fn wait_for_focus_identity(
+ expected: u64,
+ timeout: std::time::Duration,
+ mut query: impl FnMut() -> Result<Option<u64>, String>,
+) -> Result<(), String> {
+ let deadline = std::time::Instant::now() + timeout;
+ loop {
+ let current = query()?;
+ if current == Some(expected) {
+ return Ok(());
+ }
+ let remaining = deadline.saturating_duration_since(std::time::Instant::now());
+ if remaining.is_zero() {
+ return Err(format!(
+ "Hyprland focus-transfer canary did not focus expected client {expected:#x}; last focus: {current:?}"
+ ));
+ }
+ std::thread::sleep(remaining.min(std::time::Duration::from_millis(25)));
+ }
+}
+
#[cfg(target_os = "linux")]
pub(super) fn activate(
driver: &mut impl crate::Driver,
@@ -145,7 +195,7 @@ pub(super) fn activate(
// native id or ambiguous pid must not focus another client.
crate::observer::linux::hyprland_target_address(target).map_err(|error| error.to_string())?;
let observer = DesktopObserver::new(NativeObserver::new(), target);
- observer.snapshot().map_err(|error| error.to_string())?;
+ crate::observer::linux::hyprland_focus_identity().map_err(|error| error.to_string())?;
let response = driver.call(
"bring_to_front",
serde_json::json!({
@@ -239,6 +289,55 @@ mod tests {
use super::*;
use std::collections::VecDeque;
+ #[test]
+ fn focus_canary_accepts_only_expected_transfer() {
+ let mut samples = VecDeque::from([Some(7), None, Some(9), Some(11)]);
+ wait_for_focus_identity(11, std::time::Duration::from_secs(1), || {
+ Ok(samples.pop_front().expect("bounded focus samples"))
+ })
+ .unwrap();
+ assert!(samples.is_empty());
+ }
+
+ #[test]
+ fn focus_canary_rejects_unchanged_missing_and_wrong_focus() {
+ for current in [Some(7), None, Some(9)] {
+ let error =
+ wait_for_focus_identity(11, std::time::Duration::ZERO, || Ok(current)).unwrap_err();
+ assert!(error.contains("expected client 0xb"), "{error}");
+ assert!(
+ error.contains(&format!("last focus: {current:?}")),
+ "{error}"
+ );
+ }
+ }
+
+ #[test]
+ fn focus_canary_preserves_query_errors() {
+ let mut samples = VecDeque::from([
+ Ok(Some(7)),
+ Err("activewindow query failed".to_owned()),
+ Ok(Some(11)),
+ ]);
+ let error = wait_for_focus_identity(11, std::time::Duration::from_secs(1), || {
+ samples.pop_front().expect("bounded focus samples")
+ })
+ .unwrap_err();
+ assert_eq!(error, "activewindow query failed");
+ assert_eq!(samples.len(), 1);
+ }
+
+ #[test]
+ fn focus_canary_timeout_bounds_polling() {
+ let mut calls = 0;
+ let result = wait_for_focus_identity(11, std::time::Duration::ZERO, || {
+ calls += 1;
+ Ok(Some(7))
+ });
+ assert!(result.is_err());
+ assert_eq!(calls, 1);
+ }
+
fn state(cursor: Point) -> DesktopSnapshot {
DesktopSnapshot {
foreground: Some(7),
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/computer_history_cross_platform_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/computer_history_cross_platform_test.rs
index 7b73b822cc..3ed8250e12 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/computer_history_cross_platform_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/computer_history_cross_platform_test.rs
@@ -584,6 +584,14 @@ fn encrypted_history_survives_restart_and_cryptographically_purges() {
"Wayland click did not produce a delivered effect: {}",
clicked.raw
);
+ let route = clicked
+ .action_route()
+ .expect("Wayland click emitted no action route");
+ assert_eq!(
+ route, "accessibility",
+ "Wayland foreground click used an unexpected route: {}",
+ clicked.raw
+ );
let _settled_state = wait_for_window_text(&mut driver, pid, window_id, "counter=1");
let capability = cua_driver_core::tool::default_capabilities_for("click")
.into_iter()
@@ -593,7 +601,7 @@ fn encrypted_history_survives_restart_and_cryptographically_purges() {
capability, "input.pointer.click",
"history must use click's primary closed-contract capability"
);
- (capability, effect.to_owned(), "accessibility")
+ (capability, effect.to_owned(), route.to_owned())
} else {
let requested_x = bounds["x"].as_f64().expect("fixture x") + 18.0;
let requested_y = bounds["y"].as_f64().expect("fixture y") + 12.0;
@@ -620,7 +628,7 @@ fn encrypted_history_survives_restart_and_cryptographically_purges() {
(
"window.frame.set".to_owned(),
"confirmed".to_owned(),
- "system_api",
+ "system_api".to_owned(),
)
};
let ended = driver.call("end_session", json!({"session": RAW_SESSION}));
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
index c2b8465ab2..6390c7ec8f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
@@ -622,12 +622,59 @@ fn assert_fixture_text(fixture: &Fixture, id: &str, expected: &str) {
}
}
-fn fixture_marker_number(fixture: &Fixture, id: &str, prefix: &str) -> Option<u64> {
- fixture
- .journal
- .text(id)
- .and_then(|text| text.strip_prefix(prefix).map(str::to_owned))
- .and_then(|value| value.parse().ok())
+fn fixture_scroll_reached_viewport(state: &serde_json::Value) -> bool {
+ let scroll = &state["scroll-tall"];
+ let (Some(offset), Some(page)) = (
+ scroll["scrollTop"].as_f64(),
+ scroll["clientHeight"].as_f64(),
+ ) else {
+ return false;
+ };
+ offset.is_finite() && page.is_finite() && page > 0.0 && offset >= page
+}
+
+#[test]
+fn scroll_oracle_reads_live_geometry_not_event_mirrors() {
+ use serde_json::json;
+ let mut state = json!({
+ "scroll-tall": {"scrollTop": 208, "clientHeight": 128},
+ "lbl-scroll-offset": {"text": "scroll_offset=104"},
+ "lbl-scroll-client-height": {"text": "scroll_client_height=128"}
+ });
+ assert!(fixture_scroll_reached_viewport(&state));
+ state["scroll-tall"]["scrollTop"] = json!(128.25);
+ assert!(fixture_scroll_reached_viewport(&state));
+ state["lbl-scroll-offset"]["text"] = json!("scroll_offset=256");
+ for offset in [0.0, 104.0, 127.99] {
+ state["scroll-tall"]["scrollTop"] = json!(offset);
+ assert!(!fixture_scroll_reached_viewport(&state));
+ }
+}
+
+#[test]
+fn scroll_oracle_rejects_missing_or_invalid_geometry() {
+ use serde_json::{json, Value};
+ for invalid in [Value::Null, json!("128"), json!(true), json!({}), json!([])] {
+ assert!(!fixture_scroll_reached_viewport(&json!({
+ "scroll-tall": {"scrollTop": invalid.clone(), "clientHeight": 128}
+ })));
+ assert!(!fixture_scroll_reached_viewport(&json!({
+ "scroll-tall": {"scrollTop": 256, "clientHeight": invalid}
+ })));
+ }
+ for height in [0, -1] {
+ assert!(!fixture_scroll_reached_viewport(&json!({
+ "scroll-tall": {"scrollTop": 256, "clientHeight": height}
+ })));
+ }
+ for absent in [
+ json!({}),
+ json!({"scroll-tall": {}}),
+ json!({"scroll-tall": {"scrollTop": 256}}),
+ json!({"scroll-tall": {"clientHeight": 128}}),
+ ] {
+ assert!(!fixture_scroll_reached_viewport(&absent));
+ }
}
fn action_target_args(
@@ -711,6 +758,15 @@ fn run_pointer_action(
response.text()
);
assert_fixture_contains(fixture, expected_marker);
+ if tool == "click" {
+ assert_native_hyprland_semantic_route(
+ fixture,
+ "left_click",
+ addressing,
+ delivery,
+ &response,
+ );
+ }
delivered_observation()
}
@@ -1035,14 +1091,10 @@ fn run_scroll_action(fixture: &mut Fixture, addressing: &str, delivery: &str) ->
response.text(),
response.raw
);
+ assert_native_hyprland_semantic_route(fixture, "scroll", addressing, delivery, &response);
let deadline = Instant::now() + Duration::from_secs(2);
loop {
- let offset =
- fixture_marker_number(fixture, "lbl-scroll-offset", "scroll_offset=").unwrap_or(0);
- let page =
- fixture_marker_number(fixture, "lbl-scroll-client-height", "scroll_client_height=")
- .unwrap_or(0);
- if page > 0 && offset >= page {
+ if fixture_scroll_reached_viewport(&fixture.journal.snapshot()) {
break;
}
assert!(
@@ -1114,6 +1166,7 @@ fn run_child_window_action(fixture: &mut Fixture, addressing: &str, delivery: &s
response.text()
);
assert_fixture_contains(fixture, "child_windows=1");
+ assert_native_hyprland_semantic_route(fixture, "child_window", addressing, delivery, &response);
delivered_observation()
}
@@ -1178,7 +1231,92 @@ fn linux_real_pointer_input_available() -> bool {
false
}
+fn native_hyprland_semantic_input_available() -> bool {
+ #[cfg(target_os = "linux")]
+ {
+ // AT-SPI does not need an input-plugin socket. DISPLAY can coexist
+ // with native Wayland for XWayland clients in the same desktop.
+ platform_linux::wayland::wayland_input_enabled()
+ && platform_linux::wayland::hyprland::is_session()
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ false
+ }
+}
+
+fn native_hyprland_semantic_case(
+ available: bool,
+ host: &str,
+ action: &str,
+ targeting: Targeting,
+ delivery: Delivery,
+) -> bool {
+ // These fixture controls have proven focus-free AT-SPI actions. Do not
+ // extend this to other PX targets merely because they accept a click.
+ available
+ && delivery == Delivery::Background
+ && matches!(
+ (host, action, targeting),
+ ("electron" | "tauri", "left_click", Targeting::Px)
+ | ("electron" | "tauri", "child_window", Targeting::Px)
+ | ("electron", "scroll", Targeting::Ax)
+ )
+}
+
+fn assert_native_hyprland_semantic_route(
+ fixture: &Fixture,
+ action: &str,
+ addressing: &str,
+ delivery: &str,
+ response: &ToolResponse,
+) {
+ let targeting = match addressing {
+ "ax" => Targeting::Ax,
+ "px" => Targeting::Px,
+ _ => Targeting::NotApplicable,
+ };
+ if delivery == "background"
+ && native_hyprland_semantic_case(
+ native_hyprland_semantic_input_available(),
+ fixture.name,
+ action,
+ targeting,
+ Delivery::Background,
+ )
+ {
+ assert_eq!(
+ response.action_route(),
+ Some("accessibility"),
+ "{}",
+ response.raw
+ );
+ assert_eq!(
+ response.action_delivery_mode(),
+ Some("background"),
+ "{}",
+ response.raw
+ );
+ }
+}
+
fn shared_case(spec: &HostSpec, action: &str, addressing: &str, delivery: &str) -> CaseSpec {
+ shared_case_with_native_hyprland(
+ spec,
+ action,
+ addressing,
+ delivery,
+ native_hyprland_semantic_input_available(),
+ )
+}
+
+fn shared_case_with_native_hyprland(
+ spec: &HostSpec,
+ action: &str,
+ addressing: &str,
+ delivery: &str,
+ native_hyprland: bool,
+) -> CaseSpec {
let targeting = match addressing {
"ax" => Targeting::Ax,
"px" => Targeting::Px,
@@ -1191,8 +1329,11 @@ fn shared_case(spec: &HostSpec, action: &str, addressing: &str, delivery: &str)
};
let scenario = format!("{action}_{addressing}_{delivery}");
let cell_id = format!("{}-{}-{scenario}", std::env::consts::OS, spec.name).replace('_', "-");
- let expected_refusals = if cfg!(target_os = "windows") && delivery_kind == Delivery::Background
- {
+ let native_semantic =
+ native_hyprland_semantic_case(native_hyprland, spec.name, action, targeting, delivery_kind);
+ let expected_refusals = if native_semantic {
+ Vec::new()
+ } else if cfg!(target_os = "windows") && delivery_kind == Delivery::Background {
match (spec.name, action, targeting) {
("electron", "right_click" | "double_click" | "drag", _) => {
vec![RefusalCode::BackgroundOccluded]
@@ -1293,7 +1434,9 @@ fn shared_case(spec: &HostSpec, action: &str, addressing: &str, delivery: &str)
delivery_kind,
)
.unwrap_or_else(|error| panic!("{error}"));
- if cfg!(target_os = "windows")
+ if native_semantic {
+ route = cua_driver_testkit::e2e::DriverRoute::LinuxAtSpiAction;
+ } else if cfg!(target_os = "windows")
&& spec.name == "electron"
&& action == "left_click"
&& delivery_kind == Delivery::Background
@@ -1328,6 +1471,90 @@ fn shared_case(spec: &HostSpec, action: &str, addressing: &str, delivery: &str)
}
}
+#[test]
+fn native_hyprland_semantic_expectations_are_limited_to_proven_cells() {
+ for host in ["electron", "tauri", "wkwebview", "webview2"] {
+ for action in [
+ "left_click",
+ "child_window",
+ "right_click",
+ "double_click",
+ "scroll",
+ "drag",
+ "type_text",
+ "type_submit",
+ "press_key",
+ "hotkey",
+ "editor_save",
+ ] {
+ for targeting in [Targeting::Ax, Targeting::Px] {
+ let expected = matches!(
+ (host, action, targeting),
+ ("electron" | "tauri", "left_click", Targeting::Px)
+ | ("electron" | "tauri", "child_window", Targeting::Px)
+ | ("electron", "scroll", Targeting::Ax)
+ );
+ assert_eq!(
+ native_hyprland_semantic_case(
+ true,
+ host,
+ action,
+ targeting,
+ Delivery::Background
+ ),
+ expected,
+ "{host}/{action}/{targeting:?}",
+ );
+ assert!(!native_hyprland_semantic_case(
+ false,
+ host,
+ action,
+ targeting,
+ Delivery::Background
+ ));
+ assert!(!native_hyprland_semantic_case(
+ true,
+ host,
+ action,
+ targeting,
+ Delivery::Foreground
+ ));
+ }
+ }
+ }
+}
+
+#[test]
+fn native_hyprland_semantic_declarations_require_delivery_and_all_background_oracles() {
+ use cua_driver_testkit::e2e::{ContractExpectation, DriverRoute};
+
+ for (host, action, addressing) in [
+ ("electron", "left_click", "px"),
+ ("tauri", "left_click", "px"),
+ ("electron", "child_window", "px"),
+ ("tauri", "child_window", "px"),
+ ("electron", "scroll", "ax"),
+ ] {
+ let spec = HostSpec {
+ name: host,
+ path: PathBuf::new(),
+ args: Vec::new(),
+ title: "test",
+ };
+ let case = shared_case_with_native_hyprland(&spec, action, addressing, "background", true);
+ assert_eq!(case.expected_behavior, ContractExpectation::Deliver);
+ assert_eq!(case.driver_route, DriverRoute::LinuxAtSpiAction);
+ for oracle in [
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ] {
+ assert!(case.oracles.contains(&oracle), "missing {oracle:?}");
+ }
+ }
+}
+
fn cell_selected(case: &CaseSpec) -> bool {
let Ok(filter) = std::env::var("CUA_E2E_CELL_FILTER") else {
return true;
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs
index ad92e3c32b..08dd63a093 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs
@@ -150,6 +150,61 @@ fn preflight_state_ready(response: &cua_driver_testkit::ToolResponse, ax_marker:
)
}
+fn extract_last_video_frame(
+ video: &std::path::Path,
+ frame: &std::path::Path,
+) -> Result<(), String> {
+ // Preserve evidence and prevent stale output from hiding a frameless decode.
+ if frame
+ .try_exists()
+ .map_err(|error| format!("could not check preflight frame: {error}"))?
+ {
+ return Err("preflight frame already exists".to_owned());
+ }
+ // A VFR recording's final frame can precede its duration by more than a seek
+ // offset. Decode in order and overwrite one image to retain the last frame.
+ let extracted = Command::new("ffmpeg")
+ .args([
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostdin",
+ "-xerror",
+ "-y",
+ "-i",
+ ])
+ .arg(video)
+ .args([
+ "-map",
+ "0:v:0",
+ "-fps_mode",
+ "passthrough",
+ "-enc_time_base",
+ "demux",
+ "-f",
+ "image2",
+ "-update",
+ "1",
+ ])
+ .arg(frame)
+ .stdout(Stdio::null())
+ .output()
+ .map_err(|error| format!("ffmpeg is required for canonical E2E: {error}"))?;
+ let has_output = std::fs::metadata(frame)
+ .map(|metadata| metadata.is_file() && metadata.len() > 0)
+ .unwrap_or(false);
+ if !extracted.status.success() || !has_output {
+ let stderr = String::from_utf8_lossy(&extracted.stderr);
+ let diagnostic: String = stderr.chars().take(4096).collect();
+ return Err(format!(
+ "could not extract preflight video frame (status {}; output missing/empty: {}): {diagnostic}",
+ extracted.status,
+ !has_output,
+ ));
+ }
+ Ok(())
+}
+
fn run_preflight() {
let expected_sha = std::env::var("CUA_E2E_SOURCE_SHA").ok();
if let Some(expected_sha) = expected_sha.as_deref() {
@@ -372,19 +427,7 @@ fn run_preflight() {
assert!(probe.success(), "ffprobe rejected the preflight video");
let frame = recording_dir.join("preflight-frame.png");
- let extracted = Command::new("ffmpeg")
- .args(["-y", "-sseof", "-0.2", "-i"])
- .arg(&video)
- .args(["-frames:v", "1"])
- .arg(&frame)
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .status()
- .expect("ffmpeg is required for canonical E2E");
- assert!(
- extracted.success(),
- "could not extract preflight video frame"
- );
+ extract_last_video_frame(&video, &frame).unwrap_or_else(|error| panic!("{error}"));
let frame = image::open(&frame)
.expect("preflight video frame is not a readable image")
.to_rgb8();
@@ -420,6 +463,102 @@ fn readiness_requires_nonempty_ax_marker_and_screenshot_together() {
assert!(!readiness_contract(true, 1, true, true));
}
+#[test]
+fn last_frame_extraction_rejects_existing_output() {
+ let directory = tempfile::tempdir().unwrap();
+ let frame = directory.path().join("frame.png");
+ std::fs::write(&frame, b"existing evidence").unwrap();
+ let error =
+ extract_last_video_frame(&directory.path().join("missing.mp4"), &frame).unwrap_err();
+ assert!(error.contains("already exists"), "{error}");
+ assert_eq!(std::fs::read(frame).unwrap(), b"existing evidence");
+}
+
+#[test]
+#[ignore = "requires ffmpeg with lavfi and the mpeg4 encoder; no GUI required"]
+fn last_frame_extraction_handles_long_final_duration_and_invalid_input() {
+ let directory = tempfile::tempdir().unwrap();
+ let video = directory.path().join("two-colors.mp4");
+ let generated = Command::new("ffmpeg")
+ .args([
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostdin",
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=red:s=32x32:r=2:d=1.5",
+ "-vf",
+ "drawbox=color=blue:t=fill:enable='gte(t,1)',setpts='if(eq(N,2),4,N)'",
+ "-fps_mode",
+ "passthrough",
+ "-c:v",
+ "mpeg4",
+ ])
+ .arg(&video)
+ .output()
+ .expect("ffmpeg is required for this regression test");
+ assert!(
+ generated.status.success(),
+ "{}",
+ String::from_utf8_lossy(&generated.stderr)
+ );
+
+ // VFR timestamps are 0s, 0.5s, and 2s; the last (blue) frame lasts to 2.5s.
+ // Seeking to 2.3s reproduces a successful exit without emitting a frame.
+ let old_frame = directory.path().join("old-frame.png");
+ let old = Command::new("ffmpeg")
+ .args([
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostdin",
+ "-y",
+ "-sseof",
+ "-0.2",
+ "-i",
+ ])
+ .arg(&video)
+ .args(["-frames:v", "1"])
+ .arg(&old_frame)
+ .output()
+ .unwrap();
+ assert!(
+ old.status.success(),
+ "{}",
+ String::from_utf8_lossy(&old.stderr)
+ );
+ assert!(
+ !old_frame.exists(),
+ "fixture must reproduce the frameless seek"
+ );
+
+ let frame = directory.path().join("last-frame.png");
+ extract_last_video_frame(&video, &frame).unwrap();
+ let decoded = image::open(&frame).unwrap().to_rgb8();
+ assert_eq!(decoded.dimensions(), (32, 32));
+ assert!(
+ decoded
+ .pixels()
+ .all(|pixel| pixel[2] > 200 && pixel[0] < 30 && pixel[1] < 30),
+ "must retain the last blue frame, not the first red frame"
+ );
+
+ let invalid = directory.path().join("invalid.mp4");
+ std::fs::write(&invalid, b"not an MP4").unwrap();
+ for input in [invalid, directory.path().join("missing.mp4")] {
+ let output = directory.path().join("failed-frame.png");
+ let error = extract_last_video_frame(&input, &output).unwrap_err();
+ assert!(
+ error.contains("could not extract preflight video frame"),
+ "{error}"
+ );
+ assert!(!output.exists());
+ }
+}
+
#[test]
#[ignore]
fn canonical_e2e_environment_is_ready() {
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
index cc9b4f8c5f..e1955852c1 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
@@ -859,6 +859,17 @@ fn invoke_operation(
"GTK3 popover click failed: {}",
response.text()
);
+ if mode == "foreground"
+ && platform_linux::wayland::wayland_input_enabled()
+ && platform_linux::wayland::hyprland::is_session()
+ {
+ assert_eq!(
+ response.action_route(),
+ Some("accessibility"),
+ "GTK3 popover must use its semantic action: {}",
+ response.raw
+ );
+ }
wait_for_state(driver, pid, window_id, expected);
assert_popover_marker(driver, pid, window_id);
return false;
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/hyprland_foreground_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/hyprland_foreground_test.rs
new file mode 100644
index 0000000000..9e51c6de75
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/hyprland_foreground_test.rs
@@ -0,0 +1,603 @@
+//! Supplemental native Hyprland foreground safety regression.
+//!
+//! Requires the exact-candidate Driver/plugin, GTK3/PyGObject, hyprctl, and a
+//! disposable Hyprland desktop. Set CUA_DRIVER_RS_ENABLE_WAYLAND=1 and
+//! CUA_E2E_UNRESTRICTED_GUI=1; optionally set CUA_TEST_DRIVER_BIN and
+//! CUA_TEST_WORKSPACE_ROOT using the normal testkit overrides. Run with
+//! --ignored --nocapture --test-threads=1. This does not replace the desktop matrix.
+//! The grab case additionally requires cc, pkg-config, wayland-scanner,
+//! libwayland-client development files, and CUA_TEST_VIRTUAL_POINTER_XML pointing
+//! to the source wlr-virtual-pointer-unstable-v1.xml protocol.
+
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+
+use cua_driver_testkit::{spawn_in_job, workspace_root, Driver, McpDriver, ToolResponse};
+use serde_json::{json, Value};
+
+struct Fixture {
+ pid: u32,
+ window_id: u64,
+ address: String,
+ journal: PathBuf,
+}
+
+fn hyprctl(args: &[&str]) -> String {
+ let output = Command::new("hyprctl")
+ .args(args)
+ .output()
+ .expect("hyprctl must be installed in the native desktop");
+ assert!(output.status.success(), "hyprctl {args:?}: {output:?}");
+ String::from_utf8(output.stdout).expect("hyprctl UTF-8 output")
+}
+
+fn active_address() -> String {
+ let active: Value = serde_json::from_str(&hyprctl(&["-j", "activewindow"]))
+ .expect("Hyprland activewindow JSON");
+ active["address"].as_str().unwrap_or("").to_owned()
+}
+
+fn focus_window(address: &str) {
+ let selector = serde_json::to_string(&format!("address:{address}")).unwrap();
+ let action = format!("hl.dsp.focus({{ window = {selector} }})");
+ assert_eq!(hyprctl(&["dispatch", &action]).trim(), "ok");
+ assert_eq!(active_address(), address);
+}
+
+fn events(path: &Path) -> Vec<Value> {
+ let text = std::fs::read_to_string(path).expect("fixture journal must exist");
+ // A concurrently written final line is not an event until its newline lands.
+ text.split_inclusive('\n')
+ .filter(|line| line.ends_with('\n'))
+ .map(|line| serde_json::from_str(line).expect("valid fixture journal event"))
+ .collect()
+}
+
+fn launch(driver: &mut McpDriver, dir: &Path, actor: &str) -> Fixture {
+ let journal = dir.join(format!("{actor}.jsonl"));
+ let fixture = workspace_root().join("../tests/fixtures/apps/linux/isolated-input/main.py");
+ assert!(fixture.is_file(), "missing native fixture: {fixture:?}");
+ let child = spawn_in_job(
+ Command::new("python3")
+ .arg(fixture)
+ .args(["--actor", actor, "--journal"])
+ .arg(&journal)
+ .env("GDK_BACKEND", "wayland")
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit()),
+ )
+ .expect("launch repository raw-event GTK3 fixture");
+ let pid = child.id();
+ driver.reaper().push(child);
+ wait_fixture(driver, pid, journal, &format!("Cua Isolated Input {actor}"))
+}
+
+fn wait_fixture(driver: &mut McpDriver, pid: u32, journal: PathBuf, title: &str) -> Fixture {
+ let deadline = Instant::now() + Duration::from_secs(15);
+ loop {
+ let windows = driver.call("list_windows", json!({"pid": pid}));
+ if let Some(window_id) = windows.structured()["windows"]
+ .as_array()
+ .and_then(|windows| {
+ windows.iter().find(|window| {
+ window["pid"].as_u64() == Some(u64::from(pid))
+ && window["title"].as_str() == Some(title)
+ })
+ })
+ .and_then(|window| window["window_id"].as_u64())
+ {
+ let clients: Value =
+ serde_json::from_str(&hyprctl(&["-j", "clients"])).expect("Hyprland clients JSON");
+ let client = clients
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|client| {
+ client["pid"].as_u64() == Some(u64::from(pid))
+ && client["title"].as_str() == Some(title)
+ })
+ .expect("fixture must be independently visible in Hyprland IPC");
+ assert_eq!(client["xwayland"], false, "fixture must be native Wayland");
+ let address = client["address"].as_str().unwrap();
+ assert_eq!(
+ u64::from_str_radix(address.trim_start_matches("0x"), 16).unwrap(),
+ window_id,
+ "Driver window identity must match the independent compositor address"
+ );
+ return Fixture {
+ pid,
+ window_id,
+ address: address.to_owned(),
+ journal,
+ };
+ }
+ assert!(
+ Instant::now() < deadline,
+ "fixture failed to map: {}",
+ windows.text()
+ );
+ std::thread::sleep(Duration::from_millis(50));
+ }
+}
+
+fn launch_siblings(driver: &mut McpDriver, dir: &Path) -> (Fixture, Fixture) {
+ let script = workspace_root().join("../hyprland-plugin/tests/foreground_siblings.py");
+ assert!(script.is_file(), "missing sibling fixture: {script:?}");
+ let child = spawn_in_job(
+ Command::new("python3")
+ .arg(script)
+ .arg("--journal-dir")
+ .arg(dir)
+ .env("GDK_BACKEND", "wayland")
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit()),
+ )
+ .expect("launch same-client native GTK3 siblings");
+ let pid = child.id();
+ driver.reaper().push(child);
+ let target = wait_fixture(
+ driver,
+ pid,
+ dir.join("Target.jsonl"),
+ "Cua Foreground Target",
+ );
+ let sibling = wait_fixture(
+ driver,
+ pid,
+ dir.join("Sibling.jsonl"),
+ "Cua Foreground Sibling",
+ );
+ assert_ne!(target.window_id, sibling.window_id);
+ assert_ne!(target.address, sibling.address);
+ for fixture in [&target, &sibling] {
+ let deadline = Instant::now() + Duration::from_secs(3);
+ while !events(&fixture.journal).iter().any(|event| {
+ event["kind"] == "ready"
+ && event["pid"] == pid
+ && event["same_display"] == true
+ && event["native_wayland"] == true
+ }) {
+ assert!(
+ Instant::now() < deadline,
+ "same-client native fixture readiness must be proven"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ }
+ focus_window(&sibling.address);
+ (target, sibling)
+}
+
+fn snapshot(driver: &mut McpDriver, fixture: &Fixture) -> ToolResponse {
+ static SEQUENCE: AtomicUsize = AtomicUsize::new(0);
+ let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
+ let screenshot = fixture
+ .journal
+ .with_file_name(format!("snapshot-{sequence}-{}.png", fixture.pid));
+ let state = driver.call(
+ "get_window_state",
+ json!({"pid": fixture.pid, "window_id": fixture.window_id,
+ "screenshot_out_file": screenshot}),
+ );
+ assert!(!state.is_error(), "snapshot failed: {}", state.text());
+ assert!(
+ state.structured().get("screenshot_error").is_none(),
+ "{}",
+ state.structured()
+ );
+ for dimension in ["screenshot_width", "screenshot_height"] {
+ assert!(state.structured()[dimension].as_u64().unwrap_or(0) > 0);
+ }
+ state
+}
+
+#[test]
+#[ignore = "requires disposable native Hyprland, candidate plugin/Driver, GTK3 and unrestricted GUI"]
+fn foreground_drag_focus_loss_does_not_release_into_successor() {
+ drag_focus_loss(false);
+}
+
+#[test]
+#[ignore = "requires disposable native Hyprland, candidate plugin/Driver, GTK3 and unrestricted GUI"]
+fn foreground_drag_focus_loss_does_not_release_into_same_client_sibling() {
+ drag_focus_loss(true);
+}
+
+fn native_preflight() {
+ assert!(cfg!(target_os = "linux"), "native Linux test only");
+ assert!(std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some());
+ assert_eq!(
+ std::env::var("CUA_DRIVER_RS_ENABLE_WAYLAND").as_deref(),
+ Ok("1")
+ );
+ assert_eq!(
+ std::env::var("CUA_E2E_UNRESTRICTED_GUI").as_deref(),
+ Ok("1")
+ );
+}
+
+fn drag_focus_loss(same_client: bool) {
+ native_preflight();
+ let evidence_root = std::env::var_os("CUA_E2E_RECORDINGS_ROOT");
+ let journals = if let Some(root) = &evidence_root {
+ tempfile::Builder::new()
+ .prefix("hyprland-foreground-focus-loss-")
+ .tempdir_in(root)
+ } else {
+ tempfile::tempdir()
+ }
+ .expect("isolated fixture journals");
+ let journals_path = journals.path().to_path_buf();
+ // Retain raw journals and snapshots in the harness archive, including panics.
+ let _cleanup = if evidence_root.is_some() {
+ let _ = journals.keep();
+ None
+ } else {
+ Some(journals)
+ };
+ let mut driver = McpDriver::spawn_named("hyprland-foreground-focus-loss")
+ .expect("candidate Driver must be available");
+ let (target, successor) = if same_client {
+ launch_siblings(&mut driver, &journals_path)
+ } else {
+ (
+ launch(&mut driver, &journals_path, "Background"),
+ launch(&mut driver, &journals_path, "Foreground"),
+ )
+ };
+ snapshot(&mut driver, &successor);
+ let before = snapshot(&mut driver, &target);
+ assert_eq!(active_address(), successor.address);
+ let target_start = events(&target.journal).len();
+ let successor_start = events(&successor.journal).len();
+ let width = before.structured()["screenshot_width"].as_f64().unwrap();
+ let height = before.structured()["screenshot_height"].as_f64().unwrap();
+ driver.start_behavior_recording();
+
+ // Interrupt only after the application independently confirms the press.
+ // The MCP call remains in flight while this thread changes primary focus.
+ let interrupt = std::thread::spawn({
+ let journal = target.journal.clone();
+ let target_address = target.address.clone();
+ let successor_address = successor.address.clone();
+ move || {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ if events(&journal)[target_start..]
+ .iter()
+ .any(|event| event["kind"] == "button-press" && event["button"] == 1)
+ {
+ assert_eq!(active_address(), target_address);
+ focus_window(&successor_address);
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "drag never reached the target journal"
+ );
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+ });
+ let result = driver.call(
+ "drag",
+ json!({
+ "pid": target.pid, "window_id": target.window_id,
+ "from_x": width * 0.25, "from_y": height * 0.5,
+ "to_x": width * 0.75, "to_y": height * 0.5,
+ "duration_ms": 2000, "steps": 100, "delivery_mode": "foreground"
+ }),
+ );
+ std::fs::write(
+ journals_path.join("drag-result.json"),
+ serde_json::to_vec_pretty(result.structured()).unwrap(),
+ )
+ .expect("retain drag result");
+ interrupt.join().expect("independent focus intervention");
+ snapshot(&mut driver, &target);
+ snapshot(&mut driver, &successor);
+ assert_eq!(
+ result.action_effect(),
+ Some("partial"),
+ "{}",
+ result.structured()
+ );
+ assert!(
+ matches!(
+ result.action_delivery_mode(),
+ Some("foreground" | "unknown")
+ ),
+ "{}",
+ result.structured()
+ );
+ assert_eq!(result.structured()["delivery"]["delivered_count"], 1);
+ assert_eq!(active_address(), successor.address);
+
+ // Observe through the original drag deadline, including late queued release.
+ // The independent focus dispatcher may warp the cursor, so motion alone
+ // cannot be attributed to Driver. Raw press/release counters also do not
+ // establish GTK's internal cancellation state after pointer focus leaves.
+ let observation_deadline = Instant::now() + Duration::from_millis(2300);
+ while Instant::now() < observation_deadline {
+ let successor_events = events(&successor.journal);
+ assert!(
+ successor_events[successor_start..].iter().all(|event| {
+ !matches!(
+ event["kind"].as_str(),
+ Some("button-press" | "button-release" | "key-press" | "key-release")
+ )
+ }),
+ "successor received drag input: {:?}",
+ &successor_events[successor_start..]
+ );
+ std::thread::sleep(Duration::from_millis(25));
+ }
+ let target_events = events(&target.journal);
+ assert!(
+ target_events[target_start..]
+ .iter()
+ .any(|event| event["kind"] == "state"),
+ "target journal must remain live"
+ );
+ assert_eq!(
+ target_events[target_start..]
+ .iter()
+ .filter(|event| { event["kind"] == "button-press" && event["button"] == 1 })
+ .count(),
+ 1,
+ "drag must not be replayed"
+ );
+ let successor_events = events(&successor.journal);
+ assert!(
+ successor_events[successor_start..]
+ .iter()
+ .any(|event| event["kind"] == "state"),
+ "successor journal must remain live through observation"
+ );
+ snapshot(&mut driver, &successor);
+ assert_eq!(active_address(), successor.address);
+}
+
+fn build_primary_grab(dir: &Path) -> PathBuf {
+ let xml = PathBuf::from(
+ std::env::var_os("CUA_TEST_VIRTUAL_POINTER_XML")
+ .expect("set CUA_TEST_VIRTUAL_POINTER_XML to the source wlr virtual-pointer XML"),
+ );
+ assert!(xml.is_file(), "missing protocol source: {xml:?}");
+ let header = dir.join("wlr-virtual-pointer-unstable-v1-client-protocol.h");
+ let protocol = dir.join("virtual-pointer-protocol.c");
+ for (mode, output) in [("client-header", &header), ("private-code", &protocol)] {
+ let result = Command::new("wayland-scanner")
+ .arg(mode)
+ .arg(&xml)
+ .arg(output)
+ .output()
+ .expect("wayland-scanner required");
+ assert!(result.status.success(), "protocol generation: {result:?}");
+ }
+ let flags = Command::new("pkg-config")
+ .args(["--cflags", "--libs", "wayland-client"])
+ .output()
+ .expect("pkg-config required");
+ assert!(
+ flags.status.success(),
+ "libwayland-client development files required: {flags:?}"
+ );
+ let binary = dir.join("primary-grab");
+ let result = Command::new("cc")
+ .args(["-std=c11", "-Wall", "-Wextra", "-Werror"])
+ .arg("-I")
+ .arg(dir)
+ .arg(workspace_root().join("../hyprland-plugin/tests/primary_grab.c"))
+ .arg(protocol)
+ .args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
+ .arg("-o")
+ .arg(&binary)
+ .output()
+ .expect("C compiler required");
+ assert!(
+ result.status.success(),
+ "compile independent virtual pointer: {result:?}"
+ );
+ binary
+}
+
+fn last_state(journal: &[Value]) -> &Value {
+ journal
+ .iter()
+ .rev()
+ .find(|event| event["kind"] == "state")
+ .expect("fixture must have a live state heartbeat")
+}
+
+#[test]
+#[ignore = "requires disposable native Hyprland, GTK3, Wayland development tools and protocol XML"]
+fn foreground_action_refused_while_independent_virtual_pointer_holds_primary_grab() {
+ native_preflight();
+ let root = std::env::var_os("CUA_E2E_RECORDINGS_ROOT");
+ let dir = if let Some(root) = &root {
+ tempfile::Builder::new()
+ .prefix("hyprland-foreground-grab-")
+ .tempdir_in(root)
+ } else {
+ tempfile::tempdir()
+ }
+ .expect("test-owned helper build and evidence directory");
+ let path = dir.path().to_path_buf();
+ let _cleanup = if root.is_some() {
+ let _ = dir.keep();
+ None
+ } else {
+ Some(dir)
+ };
+ let binary = build_primary_grab(&path);
+ let mut driver = McpDriver::spawn_named("hyprland-foreground-primary-grab")
+ .expect("candidate Driver must be available");
+ let (target, foreground) = launch_siblings(&mut driver, &path);
+ snapshot(&mut driver, &target);
+ let before = snapshot(&mut driver, &foreground);
+ let desktop = driver.call("get_desktop_state", json!({}));
+ assert!(!desktop.is_error(), "{}", desktop.text());
+ let monitors: Value = serde_json::from_str(&hyprctl(&["-j", "monitors"])).unwrap();
+ let monitors = monitors.as_array().unwrap();
+ assert_eq!(
+ monitors.len(),
+ 1,
+ "virtual-pointer coordinate proof requires one output"
+ );
+ assert_eq!(monitors[0]["x"], 0);
+ assert_eq!(monitors[0]["y"], 0);
+ assert_eq!(monitors[0]["scale"].as_f64(), Some(1.0));
+ assert_eq!(monitors[0]["transform"], 0);
+ let bounds = &before.structured()["window_bounds"];
+ let window_width = bounds["width"].as_f64().unwrap();
+ let window_height = bounds["height"].as_f64().unwrap();
+ assert!(window_width >= 200.0 && window_height >= 200.0);
+ let x = (bounds["x"].as_f64().unwrap() + window_width / 2.0).round() as i64;
+ let y = (bounds["y"].as_f64().unwrap() + window_height / 2.0).round() as i64;
+ let width = desktop.structured()["screen_width"].as_u64().unwrap();
+ let height = desktop.structured()["screen_height"].as_u64().unwrap();
+ assert!(x >= 0 && y >= 0 && (x as u64) < width && (y as u64) < height);
+ driver.start_behavior_recording();
+ // Independent virtual pointer on the primary seat, not physical hardware.
+ // Closing controlled stdin releases immediately; the helper also has a timeout.
+ let mut grab = spawn_in_job(
+ Command::new(binary)
+ .args([
+ x.to_string(),
+ y.to_string(),
+ width.to_string(),
+ height.to_string(),
+ "10000".into(),
+ "controlled".into(),
+ ])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit()),
+ )
+ .expect("launch bounded independent primary-seat adversary");
+ let control = grab.stdin.take().unwrap();
+ driver.reaper().push(grab);
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let journal = events(&foreground.journal);
+ if journal
+ .iter()
+ .any(|event| event["kind"] == "state" && event["held"] == true)
+ {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "primary press must reach foreground journal"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert_eq!(active_address(), foreground.address);
+ let target_before = events(&target.journal);
+ let foreground_before = events(&foreground.journal);
+ assert_eq!(last_state(&foreground_before)["held"], true);
+ snapshot(&mut driver, &target);
+ let result = driver.call(
+ "click",
+ json!({"pid": target.pid, "window_id": target.window_id,
+ "x": 100, "y": 100, "delivery_mode": "foreground"}),
+ );
+ std::fs::write(
+ path.join("grab-refusal.json"),
+ serde_json::to_vec_pretty(result.structured()).unwrap(),
+ )
+ .expect("retain foreground refusal");
+ snapshot(&mut driver, &target);
+ snapshot(&mut driver, &foreground);
+ assert!(
+ result.is_error(),
+ "held primary grab must refuse: {}",
+ result.structured()
+ );
+ assert_eq!(
+ result.action_effect(),
+ Some("refused"),
+ "{}",
+ result.structured()
+ );
+ assert_eq!(result.structured()["code"], "foreground_unavailable");
+ assert_eq!(result.structured()["reason"], "primary_target_busy");
+ assert_eq!(result.structured()["detail"], "foreground_physical_buttons");
+ assert!(result.structured().get("delivery").is_none());
+ assert_eq!(active_address(), foreground.address);
+ std::thread::sleep(Duration::from_millis(300));
+ let target_after = events(&target.journal);
+ let foreground_after = events(&foreground.journal);
+ for (before, after) in [
+ (&target_before, &target_after),
+ (&foreground_before, &foreground_after),
+ ] {
+ assert!(
+ after[before.len()..]
+ .iter()
+ .any(|event| event["kind"] == "state"),
+ "both journals must remain live during refusal"
+ );
+ assert!(
+ after[before.len()..].iter().all(|event| !matches!(
+ event["kind"].as_str(),
+ Some("button-press" | "button-release" | "key-press" | "key-release")
+ )),
+ "refused action must emit no input: {:?}",
+ &after[before.len()..]
+ );
+ for field in ["clicks", "keys", "held", "motion"] {
+ assert_eq!(
+ last_state(before)[field],
+ last_state(after)[field],
+ "changed {field}"
+ );
+ }
+ }
+ assert_eq!(last_state(&foreground_after)["held"], true);
+ assert_eq!(active_address(), foreground.address);
+ drop(control);
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let journal = events(&foreground.journal);
+ if last_state(&journal)["held"] == false {
+ assert_eq!(
+ journal[foreground_after.len()..]
+ .iter()
+ .filter(|event| event["kind"] == "button-release" && event["button"] == 1)
+ .count(),
+ 1
+ );
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "independent helper must release its grab"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ // Observe after the adversary releases too: a refusal must not queue a retry.
+ std::thread::sleep(Duration::from_millis(300));
+ let target_final = events(&target.journal);
+ assert!(
+ target_final[target_before.len()..]
+ .iter()
+ .all(|event| !matches!(
+ event["kind"].as_str(),
+ Some("button-press" | "button-release" | "key-press" | "key-release")
+ )),
+ "refused click must not replay after primary release"
+ );
+ for field in ["clicks", "keys", "held", "motion"] {
+ assert_eq!(
+ last_state(&target_before)[field],
+ last_state(&target_final)[field]
+ );
+ }
+ snapshot(&mut driver, &target);
+ snapshot(&mut driver, &foreground);
+ assert_eq!(active_address(), foreground.address);
+}
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
index be79e5b15d..493656b5b9 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
@@ -390,10 +390,53 @@ pub fn track_pointer_command(x: f64, y: f64) -> OverlayCommand {
}
}
+/// Balance one cursor's visual press even if its action future is dropped.
+///
+/// The adapter binds `send` to its own cursor. This only resets artwork; it
+/// does not release native input, cancel a worker, or prove gesture cleanup.
+#[must_use = "keep the guard alive for the visual press interval"]
+pub struct PressedVisualGuard<F: Fn(OverlayCommand)> {
+ send: F,
+}
+
+impl<F: Fn(OverlayCommand)> PressedVisualGuard<F> {
+ pub fn new(send: F) -> Self {
+ send(OverlayCommand::SetPressed(true));
+ Self { send }
+ }
+}
+
+impl<F: Fn(OverlayCommand)> Drop for PressedVisualGuard<F> {
+ fn drop(&mut self) {
+ (self.send)(OverlayCommand::SetPressed(false));
+ }
+}
+
#[cfg(test)]
mod pointer_tracking_tests {
use super::*;
+ #[test]
+ fn visual_press_guard_releases_only_its_bound_cursor() {
+ use std::cell::Cell;
+ let first = Cell::new(false);
+ let sibling = Cell::new(false);
+ let send = |state: &Cell<bool>, command| {
+ let OverlayCommand::SetPressed(pressed) = command else {
+ panic!("visual press guard must only change pressed artwork");
+ };
+ state.set(pressed);
+ };
+ let first_guard = PressedVisualGuard::new(|command| send(&first, command));
+ let sibling_guard = PressedVisualGuard::new(|command| send(&sibling, command));
+ assert!(first.get() && sibling.get());
+ drop(first_guard);
+ assert!(!first.get());
+ assert!(sibling.get());
+ drop(sibling_guard);
+ assert!(!sibling.get());
+ }
+
#[test]
fn tracked_artwork_keeps_its_tip_on_the_native_pointer() {
let OverlayCommand::SnapTo {
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index 4546945d67..176bf349c7 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -11,6 +11,7 @@ anyhow = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
async-trait = "0.1"
+futures-util = "0.3"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
index 51ff02fd10..2d534d1025 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
@@ -168,8 +168,16 @@ pub fn focus_element(pid: u32, idx: usize) -> Result<bool> {
native::focus_element(pid, idx)
}
-pub fn scroll_element(pid: u32, idx: usize, direction: &str, amount: usize) -> Result<()> {
- native::scroll_element(pid, idx, direction, amount)
+pub use native::ScrollProgress;
+
+pub fn scroll_element(
+ pid: u32,
+ idx: usize,
+ direction: &str,
+ amount: usize,
+ by: cua_driver_contract::ScrollBy,
+) -> Result<ScrollProgress> {
+ native::scroll_element(pid, idx, direction, amount, by)
}
/// Enumerate top-level windows from the AT-SPI registry. The window-listing
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
index fce3a49f2c..1e48de540b 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
@@ -1185,6 +1185,7 @@ pub(super) fn walk_tree_bounded_with_timeout(
// deadline for both phases so a dead AT-SPI peer cannot outlive the
// operation timeout while resolving geometry.
let deadline = tokio::time::Instant::now() + timeout;
+ let walk_started = std::time::Instant::now();
let walk = async {
let conn = shared_connection().await?;
collect_visited_bounded(conn, pid, xid, max_elements, max_depth).await
@@ -1199,7 +1200,9 @@ pub(super) fn walk_tree_bounded_with_timeout(
let Some((visited, scoped_frame)) = walked else {
return Ok(None);
};
+ let walk_elapsed = walk_started.elapsed();
let (markdown, nodes) = render(&visited, scoped_frame);
+ let bounds_started = std::time::Instant::now();
let bounds = match before_snapshot_deadline(
deadline,
element_bounds_for_visited(&visited, pid, xid, scoped_frame),
@@ -1212,6 +1215,13 @@ pub(super) fn walk_tree_bounded_with_timeout(
Vec::new()
}
};
+ dlog!(
+ "snapshot phases pid {pid}: walk_ms={} bounds_ms={} visited={} bounds={}",
+ walk_elapsed.as_millis(),
+ bounds_started.elapsed().as_millis(),
+ visited.len(),
+ bounds.len()
+ );
// Bounds are keyed by the application-wide element index, so drop the
// entries for windows this snapshot no longer shows.
let bounds = if scoped_frame.is_some() {
@@ -1939,13 +1949,353 @@ pub fn perform_action(pid: u32, idx: usize) -> Result<(String, bool)> {
)
}
-/// Invoke an indexed scroll target's directional AT-SPI action.
-///
-/// Chromium exposes scrollable web regions as named actions such as
-/// `scrollDown`/`scrollForward`; using that accessibility route avoids the
-/// X11 `Button5` event path that Chromium silently drops in background mode.
-pub fn scroll_element(pid: u32, idx: usize, direction: &str, amount: usize) -> Result<()> {
- bounded(
+/// A mutation was attempted; callers must not replay through another route.
+#[derive(Debug)]
+pub struct ScrollProgress {
+ pub acknowledged: u32,
+ pub complete: bool,
+ pub detail: Option<String>,
+}
+
+fn finish_scroll(result: Result<()>, attempted: bool, acknowledged: u32) -> Result<ScrollProgress> {
+ match result {
+ Ok(()) => Ok(ScrollProgress {
+ acknowledged,
+ complete: true,
+ detail: None,
+ }),
+ Err(error) if attempted => Ok(ScrollProgress {
+ acknowledged,
+ complete: false,
+ detail: Some(error.to_string()),
+ }),
+ Err(error) => Err(error),
+ }
+}
+
+async fn scroll_sequence<D, DF, S, SF>(
+ amount: usize,
+ mut baseline: Option<Vec<(i64, i64)>>,
+ attempted: &std::cell::Cell<bool>,
+ acknowledged: &std::cell::Cell<u32>,
+ mut dispatch: D,
+ mut settle: S,
+) -> Result<()>
+where
+ D: FnMut() -> DF,
+ DF: std::future::Future<Output = Result<bool>>,
+ S: FnMut(Vec<(i64, i64)>) -> SF,
+ SF: std::future::Future<Output = Result<Vec<(i64, i64)>>>,
+{
+ for step in 0..amount.max(1) {
+ dlog!(
+ "scroll sequence dispatch step={} baseline={baseline:?}",
+ step + 1
+ );
+ let deadline = tokio::time::Instant::now() + CALL_TIMEOUT;
+ attempted.set(true);
+ if !tokio::time::timeout_at(deadline, dispatch())
+ .await
+ .map_err(|_| anyhow!("scroll action timed out"))??
+ {
+ return Err(anyhow!("scroll action returned false"));
+ }
+ acknowledged.set(acknowledged.get() + 1);
+ dlog!("scroll sequence acknowledged step={}", step + 1);
+ if step + 1 < amount {
+ if let Some(previous) = baseline.take() {
+ baseline = Some(
+ tokio::time::timeout_at(deadline, settle(previous))
+ .await
+ .map_err(|_| anyhow!("scroll movement did not settle before deadline"))??,
+ );
+ }
+ }
+ }
+ Ok(())
+}
+
+fn descendant_indices(depths: impl Iterator<Item = usize>, target: usize) -> Vec<usize> {
+ let depths: Vec<_> = depths.collect();
+ ((target + 1)..depths.len())
+ .take_while(|&index| depths[index] > depths[target])
+ .take(64)
+ .collect()
+}
+
+fn relative_position(
+ target: (i32, i32, i32, i32),
+ probe: (i32, i32, i32, i32),
+) -> Option<(i64, i64)> {
+ let valid =
+ |(x, y, w, h): (i32, i32, i32, i32)| x != i32::MIN && y != i32::MIN && w > 0 && h > 0;
+ (valid(target) && valid(probe)).then(|| {
+ (
+ i64::from(probe.0) - i64::from(target.0),
+ i64::from(probe.1) - i64::from(target.1),
+ )
+ })
+}
+
+struct PageMotion {
+ baseline: Vec<(i64, i64)>,
+ previous: Vec<(i64, i64)>,
+ stable: usize,
+}
+
+impl PageMotion {
+ fn new(baseline: Vec<(i64, i64)>) -> Self {
+ Self {
+ previous: baseline.clone(),
+ baseline,
+ stable: 0,
+ }
+ }
+
+ fn observe(&mut self, sample: &[(i64, i64)], direction: &str) -> bool {
+ if sample.len() != self.baseline.len() || sample.is_empty() {
+ return false;
+ }
+ let axis = |point: (i64, i64)| {
+ if matches!(direction, "left" | "right") {
+ point.0
+ } else {
+ point.1
+ }
+ };
+ let moved = sample.iter().zip(&self.baseline).any(|(&now, &before)| {
+ if matches!(direction, "up" | "left") {
+ axis(now) > axis(before)
+ } else {
+ axis(now) < axis(before)
+ }
+ });
+ self.stable = if moved && sample == self.previous {
+ self.stable + 1
+ } else {
+ 0
+ };
+ self.previous = sample.to_vec();
+ self.stable >= 2
+ }
+}
+
+#[cfg(test)]
+mod page_scroll_tests {
+ use super::*;
+ use std::cell::{Cell, RefCell};
+
+ #[test]
+ fn probes_are_bounded_descendants_in_preorder() {
+ assert_eq!(
+ descendant_indices([0, 1, 2, 3, 2, 1, 2].into_iter(), 1),
+ vec![2, 3, 4]
+ );
+ assert!(descendant_indices([0, 1, 1].into_iter(), 1).is_empty());
+ assert_eq!(
+ descendant_indices(std::iter::once(0).chain(std::iter::repeat(1).take(100)), 0).len(),
+ 64
+ );
+ }
+
+ #[test]
+ fn relative_geometry_rejects_unrealized_and_window_motion() {
+ assert_eq!(
+ relative_position((10, 20, 200, 100), (30, 60, 10, 10)),
+ Some((20, 40))
+ );
+ assert_eq!(
+ relative_position((110, 220, 200, 100), (130, 260, 10, 10)),
+ Some((20, 40))
+ );
+ assert!(relative_position((0, 0, 200, 100), (i32::MIN, 0, 10, 10)).is_none());
+ assert!(relative_position((0, 0, 0, 100), (0, 0, 10, 10)).is_none());
+ let mut motion = PageMotion::new(vec![(20, 40)]);
+ for _ in 0..10 {
+ assert!(!motion.observe(&[(20, 40)], "down"));
+ }
+ }
+
+ #[test]
+ fn directional_motion_requires_consecutive_stable_samples() {
+ for (direction, moved) in [
+ ("down", (20, 10)),
+ ("up", (20, 70)),
+ ("left", (50, 40)),
+ ("right", (-10, 40)),
+ ] {
+ let mut motion = PageMotion::new(vec![(20, 40)]);
+ assert!(!motion.observe(&[moved], direction));
+ assert!(!motion.observe(&[moved], direction));
+ assert!(motion.observe(&[moved], direction));
+ }
+ let mut motion = PageMotion::new(vec![(20, 40)]);
+ for _ in 0..4 {
+ assert!(!motion.observe(&[(20, 70)], "down"));
+ }
+ assert!(!motion.observe(&[], "down"));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn asynchronous_page_ack_waits_for_movement_and_stability() {
+ let events = RefCell::new(Vec::new());
+ let attempted = Cell::new(false);
+ let acknowledged = Cell::new(0);
+ scroll_sequence(
+ 2,
+ Some(vec![(0, 100)]),
+ &attempted,
+ &acknowledged,
+ || async {
+ events.borrow_mut().push("ack");
+ Ok(true)
+ },
+ |baseline| async {
+ let mut motion = PageMotion::new(baseline);
+ for (event, y) in [
+ ("unchanged", 100),
+ ("move", 0),
+ ("stable", 0),
+ ("stable", 0),
+ ] {
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ events.borrow_mut().push(event);
+ if motion.observe(&[(0, y)], "down") {
+ return Ok(vec![(0, y)]);
+ }
+ }
+ unreachable!()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ *events.borrow(),
+ vec!["ack", "unchanged", "move", "stable", "stable", "ack"]
+ );
+ assert_eq!(acknowledged.get(), 2);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn failed_or_timed_out_attempts_never_become_fallback() {
+ for successful_before in [0, 1] {
+ for timeout in [false, true] {
+ let attempted = Cell::new(false);
+ let acknowledged = Cell::new(0);
+ let result = scroll_sequence(
+ 2,
+ None,
+ &attempted,
+ &acknowledged,
+ || async {
+ if acknowledged.get() < successful_before {
+ return Ok(true);
+ }
+ if timeout {
+ std::future::pending::<()>().await;
+ }
+ Ok(false)
+ },
+ |baseline| async { Ok(baseline) },
+ )
+ .await;
+ let outcome = finish_scroll(result, attempted.get(), acknowledged.get()).unwrap();
+ assert!(!outcome.complete);
+ assert_eq!(outcome.acknowledged, successful_before);
+ }
+ }
+ assert!(finish_scroll(Err(anyhow!("unsupported before dispatch")), false, 0).is_err());
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn missing_or_stalled_probe_stops_after_first_ack() {
+ for timeout in [false, true] {
+ let attempted = Cell::new(false);
+ let acknowledged = Cell::new(0);
+ let result = scroll_sequence(
+ 2,
+ Some(vec![(0, 100)]),
+ &attempted,
+ &acknowledged,
+ || async { Ok(true) },
+ |_| async {
+ if timeout {
+ std::future::pending::<()>().await;
+ }
+ Err(anyhow!("probe disappeared"))
+ },
+ )
+ .await;
+ let outcome = finish_scroll(result, attempted.get(), acknowledged.get()).unwrap();
+ assert!(!outcome.complete);
+ assert_eq!(outcome.acknowledged, 1);
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn overall_timeout_retains_progress() {
+ let attempted = Cell::new(false);
+ let acknowledged = Cell::new(0);
+ let result = tokio::time::timeout(
+ Duration::from_millis(1),
+ scroll_sequence(
+ 2,
+ Some(vec![(0, 100)]),
+ &attempted,
+ &acknowledged,
+ || async { Ok(true) },
+ |_| std::future::pending::<Result<Vec<(i64, i64)>>>(),
+ ),
+ )
+ .await
+ .map_err(|_| anyhow!("overall timeout"))
+ .and_then(|r| r);
+ let outcome = finish_scroll(result, attempted.get(), acknowledged.get()).unwrap();
+ assert_eq!(outcome.acknowledged, 1);
+ assert!(!outcome.complete);
+ }
+}
+
+async fn sample_page_probes(
+ target: &atspi::proxy::component::ComponentProxy<'_>,
+ probes: &[atspi::proxy::component::ComponentProxy<'_>],
+ coord: CoordType,
+) -> Result<Vec<(i64, i64)>> {
+ let before = call(target.get_extents(coord))
+ .await
+ .and_then(|r| r.ok())
+ .ok_or_else(|| anyhow!("scroll target geometry unavailable"))?;
+ let mut sample = Vec::new();
+ for probe in probes {
+ let bounds = call(probe.get_extents(coord))
+ .await
+ .and_then(|r| r.ok())
+ .ok_or_else(|| anyhow!("scroll probe disappeared"))?;
+ sample.push(
+ relative_position(before, bounds)
+ .ok_or_else(|| anyhow!("scroll probe geometry invalid"))?,
+ );
+ }
+ let after = call(target.get_extents(coord)).await.and_then(|r| r.ok());
+ if after != Some(before) {
+ return Err(anyhow!("scroll target geometry changed during observation"));
+ }
+ Ok(sample)
+}
+
+/// Invoke the original target's semantic actions, pacing multi-page requests
+/// with descendant motion. `Err` means no mutation was attempted; an incomplete
+/// `ScrollProgress` preserves uncertainty after an attempted mutation.
+pub fn scroll_element(
+ pid: u32,
+ idx: usize,
+ direction: &str,
+ amount: usize,
+ by: cua_driver_contract::ScrollBy,
+) -> Result<ScrollProgress> {
+ let attempted = std::cell::Cell::new(false);
+ let acknowledged = std::cell::Cell::new(0);
+ let result = bounded(
async {
let conn = shared_connection().await?;
let visited = collect_visited(conn, pid)
@@ -1991,14 +2341,77 @@ pub fn scroll_element(pid: u32, idx: usize, direction: &str, amount: usize) -> R
}
if let (Some(action), Some(action_index)) = (action_proxy, selected) {
- for _ in 0..amount.max(1) {
- match call(action.do_action(action_index)).await {
- Some(Ok(true)) => {}
- Some(Ok(false)) => return Err(anyhow!("scroll action returned false")),
- Some(Err(e)) => return Err(anyhow!("scroll action failed: {e}")),
- None => return Err(anyhow!("scroll action timed out")),
+ let mut observation = None;
+ if by == cua_driver_contract::ScrollBy::Page && amount > 1 {
+ let component = proxies.component().await?;
+ let target_index = visited
+ .iter()
+ .position(|node| std::ptr::eq(node, target))
+ .unwrap();
+ let mut probes = Vec::new();
+ // Fix probe identities before dispatch; never replace vanished descendants.
+ for index in
+ descendant_indices(visited.iter().map(|node| node.depth), target_index)
+ {
+ if !visited[index].has_component {
+ continue;
+ }
+ if let Some(Ok(proxies)) = call(visited[index].acc.proxies()).await {
+ if let Some(Ok(probe)) = call(proxies.component()).await {
+ probes.push(probe);
+ }
+ }
+ }
+ for coord in [CoordType::Window, CoordType::Screen] {
+ let mut usable = Vec::new();
+ for probe in &probes {
+ if sample_page_probes(&component, std::slice::from_ref(probe), coord)
+ .await
+ .is_ok()
+ {
+ usable.push(probe.clone());
+ if usable.len() == 8 {
+ break;
+ }
+ }
+ }
+ if !usable.is_empty() {
+ let baseline = sample_page_probes(&component, &usable, coord).await?;
+ observation = Some((component.clone(), usable, coord, baseline));
+ break;
+ }
+ }
+ if observation.is_none() {
+ return Err(anyhow!("no usable descendant scroll probes"));
}
}
+ scroll_sequence(
+ amount,
+ observation.as_ref().map(|o| o.3.clone()),
+ &attempted,
+ &acknowledged,
+ || async { action.do_action(action_index).await.map_err(Into::into) },
+ |baseline| async {
+ let (component, probes, coord, _) = observation
+ .as_ref()
+ .expect("page probes selected before dispatch");
+ let mut motion = PageMotion::new(baseline);
+ let started = tokio::time::Instant::now();
+ loop {
+ let sample = sample_page_probes(component, probes, *coord).await?;
+ let settled = motion.observe(&sample, direction);
+ dlog!(
+ "scroll sequence sample elapsed_ms={} positions={sample:?} settled={settled}",
+ started.elapsed().as_millis()
+ );
+ if settled {
+ return Ok(sample);
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ },
+ )
+ .await?;
return Ok(());
}
@@ -2031,10 +2444,12 @@ pub fn scroll_element(pid: u32, idx: usize, direction: &str, amount: usize) -> R
};
let next =
(current + sign * increment * amount.max(1) as f64).clamp(minimum, maximum);
+ attempted.set(true);
call(value.set_current_value(next))
.await
.and_then(|result| result.ok())
.ok_or_else(|| anyhow!("scroll value update timed out"))?;
+ acknowledged.set(1);
return Ok(());
}
@@ -2043,7 +2458,8 @@ pub fn scroll_element(pid: u32, idx: usize, direction: &str, amount: usize) -> R
))
},
|| Err(anyhow!("scroll_element timed out for pid {pid}")),
- )
+ );
+ finish_scroll(result, attempted.get(), acknowledged.get())
}
/// Give an indexed element keyboard focus through AT-SPI Component.GrabFocus
@@ -2132,7 +2548,7 @@ pub fn perform_action_at_point(pid: u32, win_x: i32, win_y: i32) -> Result<Optio
Some(v) => v,
None => return Ok(None),
};
- let web_document_origin = web_document_origin_for_visited(&visited, pid, None)
+ let web_document_origin = web_document_origin_for_visited(&visited, pid, 0, None)
.await
.unwrap_or((0, 0));
@@ -2229,62 +2645,23 @@ pub fn perform_action_at_screen_point(
bounded(
async {
let conn = shared_connection().await?;
- let visited = match collect_visited(conn, pid).await? {
- Some(v) => v,
- None => return Ok(None),
- };
- let web_document_origin = web_document_origin_for_visited(&visited, pid, None)
- .await
- .unwrap_or((0, 0));
-
- // Reconstruct each indexable element's SCREEN frame the same way
- // get_window_state does: WINDOW-relative extents (GTK4 reports these
- // correctly; Screen is (0,0)) plus the window's screen origin (the
- // GNOME Shell helper on Wayland, _GTK_FRAME_EXTENTS on X11). When no
- // offset resolves, fall back to CoordType::Screen (correct on Qt/GTK3).
- let offset = window_to_screen_offset(pid, xid, None);
- let coord = if offset.is_some() {
- CoordType::Window
- } else {
- CoordType::Screen
- };
- let (ox, oy) = offset.unwrap_or((0, 0));
+ let (visited, scoped_frame) =
+ match collect_visited_bounded(conn, pid, xid, None, None).await? {
+ Some(walked) => walked,
+ None => return Ok(None),
+ };
- // (element_index, x, y, w, h, is_passive_label) over the SAME indexable
- // list `perform_action`/`get_window_state` use, so the chosen index
- // maps straight back to a verified `element_index` actuation.
+ // Share snapshot correlation and geometry, including renderer-frame
+ // rebasing and embedded WebProcess insets. Bounds retain application-
+ // wide indices even when only the target window's nodes are emitted.
let action_nodes: Vec<&Visited> = visited.iter().filter(|v| is_indexable(v)).collect();
- let mut frames: Vec<(usize, i32, i32, u32, u32, bool)> = Vec::new();
- for (idx, node) in action_nodes.iter().enumerate() {
- if !node.has_component {
- continue;
- }
- let Some(Ok(proxies)) = call(node.acc.proxies()).await else {
- continue;
- };
- let Some(Ok(comp)) = call(proxies.component()).await else {
- continue;
- };
- let Some(Ok((x, y, w, h))) = call(comp.get_extents(coord)).await else {
- continue;
- };
- if x == i32::MIN || y == i32::MIN || w <= 1 || h <= 1 {
- continue;
- }
- let (document_x, document_y) = if node.in_web_doc {
- web_document_origin
- } else {
- (0, 0)
- };
- frames.push((
- idx,
- x + ox + document_x,
- y + oy + document_y,
- w as u32,
- h as u32,
- is_passive_role(&node.role),
- ));
- }
+ let frames: Vec<_> = element_bounds_for_visited(&visited, pid, xid, scoped_frame)
+ .await
+ .into_iter()
+ .map(|(idx, x, y, w, h)| {
+ (idx, x, y, w, h, is_passive_role(&action_nodes[idx].role))
+ })
+ .collect();
let Some(idx) = select_click_target(&frames, screen_x, screen_y) else {
return Ok(None);
@@ -2429,7 +2806,7 @@ pub fn get_element_bounds(pid: u32, idx: usize) -> Result<(i32, i32, u32, u32)>
let visited = collect_visited(conn, pid)
.await?
.ok_or_else(|| anyhow!("no AT-SPI application for pid {pid}"))?;
- let web_document_origin = web_document_origin_for_visited(&visited, pid, None)
+ let web_document_origin = web_document_origin_for_visited(&visited, pid, 0, None)
.await
.unwrap_or((0, 0));
let action_nodes: Vec<&Visited> = visited.iter().filter(|v| is_indexable(v)).collect();
@@ -2704,6 +3081,35 @@ fn combine_wayland_content_offsets(
}
}
+fn hyprland_document_top_inset(
+ target: (u64, u32),
+ window: Option<(u64, u32, u32, u32)>,
+ document: (i32, i32, i32, i32),
+) -> Option<i32> {
+ let (address, pid, window_width, window_height) = window?;
+ let (x, y, width, height) = document;
+ if target.0 == 0 || target != (address, pid) || x != 0 || y < 0 || width <= 0 || height <= 0 {
+ return None;
+ }
+ let top = i64::from(window_height) - i64::from(height);
+ // A full-width embedded document can omit GTK's CSD header from its
+ // WINDOW origin. Reject partial panes and gaps larger than a title bar.
+ if (i64::from(window_width) - i64::from(width)).abs() > 4 || !(1..=128).contains(&top) {
+ return None;
+ }
+ Some(y.max(top as i32))
+}
+
+fn select_web_document<T>(
+ candidates: impl Iterator<Item = (T, usize, bool)>,
+ require_web_process_bus: bool,
+) -> Option<T> {
+ candidates
+ .filter(|(_, _, on_web_process_bus)| !require_web_process_bus || *on_web_process_bus)
+ .min_by_key(|(_, depth, _)| *depth)
+ .map(|(document, _, _)| document)
+}
+
/// Offset of embedded web content inside a captured Wayland toplevel.
/// Compositor decorations and toolkit document offsets are independent and
/// therefore additive: choosing one or the other leaves WebKit controls one
@@ -2711,6 +3117,7 @@ fn combine_wayland_content_offsets(
async fn web_document_origin_for_visited(
visited: &[Visited<'_>],
pid: u32,
+ xid: u64,
scoped_frame: Option<usize>,
) -> Option<(i32, i32)> {
if !crate::wayland::is_wayland() {
@@ -2720,17 +3127,40 @@ async fn web_document_origin_for_visited(
let compositor = sway_window
.as_ref()
.map(|window| (window.content_x, window.content_y));
- let document = visited
- .iter()
- .filter(|node| scoped_frame.is_none_or(|scope| node.frame_ordinal == scope))
- .filter(|node| node.has_component)
- .filter(|node| is_document_role(&node.role) || node.in_web_doc)
- .min_by_key(|node| node.depth);
+ let document_is_separate = visited.iter().any(|node| {
+ scoped_frame.is_none_or(|scope| node.frame_ordinal == scope) && node.on_web_process_bus
+ });
+ // Only a correlated AX frame proves these document dimensions belong to
+ // the named client; an application-wide walk could select a sibling.
+ let hyprland_window = if document_is_separate
+ && scoped_frame.is_some()
+ && xid != 0
+ && crate::wayland::hyprland::is_session()
+ {
+ crate::wayland::hyprland::accessibility_window(xid, pid)
+ .map(|window| (window.address, window.pid, window.width, window.height))
+ } else {
+ None
+ };
+ // Hyprland's inferred inset must use dimensions from the WebProcess whose
+ // descendants receive that inset, not a shallower application-bus document.
+ let document = select_web_document(
+ visited
+ .iter()
+ .filter(|node| scoped_frame.is_none_or(|scope| node.frame_ordinal == scope))
+ .filter(|node| node.has_component)
+ .filter(|node| is_document_role(&node.role) || node.in_web_doc)
+ .map(|node| (node, node.depth, node.on_web_process_bus)),
+ hyprland_window.is_some(),
+ );
let document = if let Some(document) = document {
match call(document.acc.proxies()).await {
Some(Ok(proxies)) => match call(proxies.component()).await {
Some(Ok(component)) => match call(component.get_extents(CoordType::Window)).await {
Some(Ok((x, y, width, height))) if x >= 0 && y >= 0 => {
+ dlog!(
+ "Wayland web document extents: target={xid:#x} pid={pid} document=({x},{y},{width},{height}) hyprland={hyprland_window:?}"
+ );
let inferred_top = match (compositor, sway_window.as_ref()) {
(Some((_, 0)), Some(window))
if width > 0
@@ -2743,7 +3173,13 @@ async fn web_document_origin_for_visited(
}
_ => 0,
};
- Some((x, y.max(inferred_top)))
+ let top = hyprland_document_top_inset(
+ (xid, pid),
+ hyprland_window,
+ (x, y, width, height),
+ )
+ .unwrap_or(y.max(inferred_top));
+ Some((x, top))
}
_ => None,
},
@@ -2754,9 +3190,6 @@ async fn web_document_origin_for_visited(
} else {
None
};
- let document_is_separate = visited.iter().any(|node| {
- scoped_frame.is_none_or(|scope| node.frame_ordinal == scope) && node.on_web_process_bus
- });
let combined = combine_wayland_content_offsets(compositor, document, document_is_separate);
dlog!(
"Wayland web content offset: compositor={compositor:?} document={document:?} separate_process={document_is_separate} combined={combined:?}"
@@ -2801,6 +3234,36 @@ fn rebase_renderer_window_offset(
offset
}
+fn project_screen_extents(
+ (x, y, w, h): (i32, i32, i32, i32),
+ (offset_x, offset_y): (i32, i32),
+ document_origin: Option<(i32, i32)>,
+) -> Option<(i32, i32, u32, u32)> {
+ // Reject unrealized-widget sentinels before applying any offsets.
+ if !crate::snapshot_queries::plausible_raw_extents((x, y, w, h)) {
+ return None;
+ }
+ let (document_x, document_y) = document_origin.unwrap_or((0, 0));
+ Some((
+ x + offset_x + document_x,
+ y + offset_y + document_y,
+ w as u32,
+ h as u32,
+ ))
+}
+
+fn scoped_component_nodes<'a, T>(
+ nodes: &'a [T],
+ scoped_frame: Option<usize>,
+ component: impl Fn(&T) -> (usize, bool) + 'a,
+) -> impl Iterator<Item = (usize, &'a T)> + 'a {
+ // Filter after enumeration: public element indices belong to the whole app.
+ nodes.iter().enumerate().filter(move |(_, node)| {
+ let (frame, has_component) = component(node);
+ has_component && scoped_frame.is_none_or(|scope| scope == frame)
+ })
+}
+
/// Screen-coordinate bounds for the exact visited sequence rendered into the
/// current snapshot. Nodes without a usable Component interface, or whose
/// extents query fails/times out, are omitted rather than borrowing another
@@ -2921,7 +3384,7 @@ async fn element_bounds_for_visited(
// descendants only. Electron commonly contributes zero for both; WebKitGTK
// under Sway needs the sum.
let web_document_origin = if offset.is_some() {
- web_document_origin_for_visited(visited, pid, scoped_frame).await
+ web_document_origin_for_visited(visited, pid, xid, scoped_frame).await
} else {
None
};
@@ -2942,56 +3405,38 @@ async fn element_bounds_for_visited(
// in time, but do not impose an index-based node cap: a cap silently
// stripped frames from valid controls later in renderer trees and
// made PX targeting depend on DOM order.
- let deadline = std::time::Instant::now() + Duration::from_secs(20);
- let mut out = Vec::with_capacity(action_nodes.len());
- for (idx, node) in action_nodes.iter().enumerate() {
- if scoped_frame.is_some_and(|scope| node.frame_ordinal != scope) {
- continue;
- }
- if std::time::Instant::now() >= deadline {
- dlog!(
- "snapshot bounds: 20s budget exhausted at node {idx}; returning {} bound(s)",
- out.len()
- );
- break;
- }
- if !node.has_component {
- continue;
- }
- let proxies = match call(node.acc.proxies()).await {
- Some(Ok(p)) => p,
- _ => continue,
- };
- let comp = match call(proxies.component()).await {
- Some(Ok(c)) => c,
- _ => continue,
- };
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(20);
+ // Bounds are independent read-only queries. Overlap a bounded number of
+ // calls instead of serializing thousands of unrealized menu components.
+ // Preserve original indices, all extents checks, and per-call timeouts.
+ let queries = scoped_component_nodes(&action_nodes, scoped_frame, |node| {
+ (node.frame_ordinal, node.has_component)
+ })
+ .map(|(idx, node)| async move {
+ let proxies = call(node.acc.proxies()).await?.ok()?;
+ let comp = call(proxies.component()).await?.ok()?;
if let Some(Ok((x, y, w, h))) = call(comp.get_extents(coord)).await {
- // Unrealized widgets (e.g. items inside closed menus/popovers)
- // report GetExtents as the i32::MIN sentinel and/or a degenerate
- // 0x0 / 1x1 size. Emitting those poisons downstream consumers
- // (overlay renderers, click targeting), so keep only elements
- // with plausible on-screen geometry. (Validate the raw extents,
- // before applying the screen offset, so the sentinel check still
- // catches unrealized widgets.)
- if x == i32::MIN || y == i32::MIN || x < -16384 || y < -16384 || w <= 1 || h <= 1 {
- continue;
- }
- let (document_x, document_y) = if node.in_web_doc {
- web_document_origin.unwrap_or((0, 0))
+ let document_origin = if node.in_web_doc {
+ web_document_origin
} else {
- (0, 0)
+ None
};
- out.push((
- idx,
- x + offset_x + document_x,
- y + offset_y + document_y,
- w as u32,
- h as u32,
- ));
+ return project_screen_extents((x, y, w, h), (offset_x, offset_y), document_origin)
+ .map(|bounds| (idx, bounds));
}
+ None
+ });
+ let collected = crate::snapshot_queries::collect_indexed(queries, deadline).await;
+ if tokio::time::Instant::now() >= deadline {
+ dlog!(
+ "snapshot bounds: 20s budget exhausted; returning {} bound(s)",
+ collected.len()
+ );
}
- out
+ collected
+ .into_iter()
+ .map(|(idx, (x, y, w, h))| (idx, x, y, w, h))
+ .collect()
}
#[cfg(test)]
@@ -3102,9 +3547,11 @@ mod coord_tests {
use super::parse_gtk_frame_extents;
use super::{
activation_index, before_snapshot_deadline, combine_wayland_content_offsets,
- is_activation_action, is_enabled_state, is_indexable_capabilities, is_passive_role,
- is_web_process_bus, prefer_authoritative_wayland_origin, rebase_renderer_window_offset,
- screen_extent_rebase, select_click_target, ApplicationSelection,
+ hyprland_document_top_inset, is_activation_action, is_enabled_state,
+ is_indexable_capabilities, is_passive_role, is_web_process_bus,
+ prefer_authoritative_wayland_origin, project_screen_extents, rebase_renderer_window_offset,
+ scoped_component_nodes, screen_extent_rebase, select_click_target, select_web_document,
+ ApplicationSelection,
};
use atspi::{State, StateSet};
use std::time::Duration;
@@ -3320,6 +3767,53 @@ mod coord_tests {
);
}
+ #[test]
+ fn point_hit_combines_negative_renderer_origin_and_web_process_inset() {
+ let offset = rebase_renderer_window_offset((100, 50), Some((-8, -29)));
+ let document = combine_wayland_content_offsets(None, Some((0, 47)), true);
+ let (x, y, w, h) = project_screen_extents((450, 270, 40, 20), offset, document).unwrap();
+ assert_eq!((x, y, w, h), (558, 396, 40, 20));
+ // Keep the application-wide index and prefer the button over its label.
+ let frames = [(82, x, y, w, h, false), (83, x + 1, y + 1, 38, 18, true)];
+ assert_eq!(select_click_target(&frames, 569, 404), Some(82));
+ assert_eq!(select_click_target(&frames, 569, 375), None);
+ assert_eq!(
+ project_screen_extents((450, 270, 40, 20), offset, None),
+ Some((558, 349, 40, 20))
+ );
+ }
+
+ #[test]
+ fn point_hit_projection_rejects_unrealized_extents_before_offsets() {
+ for raw in [(i32::MIN, 0, 40, 20), (0, i32::MIN, 40, 20), (0, 0, 1, 1)] {
+ assert_eq!(project_screen_extents(raw, (108, 79), Some((0, 47))), None);
+ }
+ }
+
+ #[test]
+ fn scoped_bounds_keep_application_indices_and_original_target_nodes() {
+ let nodes = [
+ (0, true, "sibling button"),
+ (1, false, "target without geometry"),
+ (1, true, "target button"),
+ (0, true, "sibling entry"),
+ (1, true, "target entry"),
+ ];
+ let scoped: Vec<_> = scoped_component_nodes(&nodes, Some(1), |node| (node.0, node.1))
+ .map(|(index, node)| (index, node.2))
+ .collect();
+ assert_eq!(scoped, [(2, "target button"), (4, "target entry")]);
+ assert_eq!(nodes[scoped[0].0].2, "target button");
+ let all: Vec<_> = scoped_component_nodes(&nodes, None, |node| (node.0, node.1))
+ .map(|(index, _)| index)
+ .collect();
+ assert_eq!(all, [0, 2, 3, 4]);
+ assert_eq!(
+ scoped_component_nodes(&nodes, Some(2), |node| (node.0, node.1)).count(),
+ 0
+ );
+ }
+
#[test]
fn compositor_origin_wins_over_stale_accessibility_observation() {
assert_eq!(
@@ -3349,6 +3843,79 @@ mod coord_tests {
assert_eq!(combine_wayland_content_offsets(None, None, true), None);
}
+ #[test]
+ fn hyprland_document_selection_requires_its_own_web_process_bus() {
+ let mixed_bus_documents = [("application", 1, false), ("web-process", 3, true)];
+ assert_eq!(
+ select_web_document(mixed_bus_documents.into_iter(), true),
+ Some("web-process")
+ );
+ // Sway retains its existing shallowest-document selection.
+ assert_eq!(
+ select_web_document(mixed_bus_documents.into_iter(), false),
+ Some("application")
+ );
+ assert_eq!(
+ select_web_document([("application", 1, false)].into_iter(), true),
+ None
+ );
+ }
+
+ #[test]
+ fn hyprland_document_infers_csd_without_double_counting() {
+ let target = (0x1234_5678_9abc, 42);
+ let window = Some((target.0, target.1, 940, 700));
+ for y in [0, 20, 47] {
+ assert_eq!(
+ hyprland_document_top_inset(target, window, (0, y, 940, 653)),
+ Some(47)
+ );
+ }
+ assert_eq!(
+ combine_wayland_content_offsets(None, Some((0, 47)), false),
+ None
+ );
+ }
+
+ #[test]
+ fn hyprland_document_rejects_invalid_or_partial_dimensions() {
+ let target = (0x1234_5678_9abc, 42);
+ let window = Some((target.0, target.1, 940, 700));
+ for document in [
+ (0, 0, 0, 653),
+ (0, 0, 940, 0),
+ (0, 0, -1, 653),
+ (0, 0, 940, -1),
+ (0, 0, 935, 653),
+ (0, 0, 945, 653),
+ (0, 0, 940, 700),
+ (0, 0, 940, 701),
+ (0, 0, 940, 500),
+ (1, 0, 940, 653),
+ (0, -1, 940, 653),
+ ] {
+ assert_eq!(hyprland_document_top_inset(target, window, document), None);
+ }
+ }
+
+ #[test]
+ fn hyprland_document_requires_full_address_and_pid() {
+ let target = (0x1234_5678_9abc, 42);
+ let document = (0, 0, 940, 653);
+ for window in [
+ None,
+ Some((0x5678_9abc, 42, 940, 700)),
+ Some((0x1234_5678_9abd, 42, 940, 700)),
+ Some((target.0, 43, 940, 700)),
+ ] {
+ assert_eq!(hyprland_document_top_inset(target, window, document), None);
+ }
+ assert_eq!(
+ hyprland_document_top_inset((0, 42), Some((0, 42, 940, 700)), document),
+ None
+ );
+ }
+
#[test]
fn chromium_window_extents_do_not_double_count_document_origin() {
assert_eq!(
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
index a4e17cac25..61ebbe607c 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
@@ -27,6 +27,22 @@ fn refusal(code: BrowserRefusalCode, message: impl Into<String>) -> BrowserRefus
BrowserRefusal::new(code, message)
}
+fn hyprland_identity_matches(pid: u32, window_id: u64, owner_pid: u32, address: u64) -> bool {
+ pid != 0 && window_id != 0 && owner_pid == pid && address == window_id
+}
+
+fn hyprland_is_only_owned_window(
+ pid: u32,
+ window_id: u64,
+ identities: impl IntoIterator<Item = (u32, u64)>,
+) -> bool {
+ let mut owned = identities.into_iter().filter(|(owner, _)| *owner == pid);
+ let Some((owner, address)) = owned.next() else {
+ return false;
+ };
+ hyprland_identity_matches(pid, window_id, owner, address) && owned.next().is_none()
+}
+
fn run_existing_profile_cleanup<T: Send + 'static>(
cleanup: impl FnOnce() -> T + Send + 'static,
) -> Result<T, BrowserRefusal> {
@@ -553,6 +569,46 @@ impl BrowserPlatform for LinuxBrowserPlatform {
)
})?;
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
+ if crate::wayland::hyprland::is_session() {
+ let window = tokio::task::spawn_blocking(move || {
+ crate::wayland::hyprland::window_for_address(window_id)
+ })
+ .await
+ .ok()
+ .flatten()
+ .ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "Hyprland could not attest the exact mapped browser window",
+ )
+ })?;
+ if !hyprland_identity_matches(pid_u32, window_id, window.pid, window.address) {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "Hyprland browser window does not match the requested pid and full address",
+ ));
+ }
+ return Ok(NativeWindowInfo {
+ pid,
+ window_id,
+ title: window.title,
+ bounds: Rect::new(
+ f64::from(window.x),
+ f64::from(window.y),
+ f64::from(window.width),
+ f64::from(window.height),
+ ),
+ geometry_exact: true,
+ ownership: NativeOwnershipProof {
+ method: NativeOwnershipMethod::WindowServerOwner,
+ owner_pid: pid,
+ detail: Some(
+ "authenticated Hyprland IPC pid, full address, and mapped window rect"
+ .to_owned(),
+ ),
+ },
+ });
+ }
if let Some(window) = crate::wayland::sway_ipc::window_for_id(window_id) {
if window.pid != pid_u32 {
return Err(refusal(
@@ -686,6 +742,27 @@ impl BrowserPlatform for LinuxBrowserPlatform {
)
})?;
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
+ if crate::wayland::hyprland::is_session() {
+ let windows = tokio::task::spawn_blocking(crate::wayland::hyprland::list_windows)
+ .await
+ .ok()
+ .and_then(Result::ok)
+ .ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "Hyprland could not attest browser window cardinality",
+ )
+ })?;
+ // Count every mapped client owned by the PID, including hidden
+ // and off-workspace clients; visibility cannot prove uniqueness.
+ return Ok(Some(hyprland_is_only_owned_window(
+ pid_u32,
+ window_id,
+ windows
+ .into_iter()
+ .map(|window| (window.pid, window.address)),
+ )));
+ }
let Some(windows) = crate::wayland::sway_ipc::list_windows() else {
if let Some(owned) =
crate::wayland::shell_helper::trusted_window_ids_for_pid(pid_u32)
@@ -1202,6 +1279,40 @@ impl BrowserPlatform for LinuxBrowserPlatform {
mod tests {
use super::*;
+ #[test]
+ fn hyprland_browser_identity_requires_exact_pid_and_full_native_address() {
+ let address = 0x1234_0000_0042;
+ assert!(hyprland_identity_matches(42, address, 42, address));
+ assert!(!hyprland_identity_matches(43, address, 42, address));
+ assert!(!hyprland_identity_matches(42, 0x42, 42, address));
+ assert!(!hyprland_identity_matches(42, address + 1, 42, address));
+ assert!(!hyprland_identity_matches(0, address, 0, address));
+ assert!(!hyprland_identity_matches(42, 0, 42, 0));
+ }
+
+ #[test]
+ fn hyprland_browser_cardinality_requires_one_exact_owned_surface() {
+ let address = 0x1234_0000_0042;
+ assert!(hyprland_is_only_owned_window(42, address, [(42, address)]));
+ assert!(hyprland_is_only_owned_window(
+ 42,
+ address,
+ [(7, address + 1), (42, address)],
+ ));
+ for identities in [
+ vec![],
+ vec![(7, address)],
+ vec![(42, 0x42)],
+ vec![(42, address + 1)],
+ vec![(42, address), (42, address + 1)],
+ vec![(42, address), (42, address)],
+ ] {
+ assert!(!hyprland_is_only_owned_window(42, address, identities));
+ }
+ assert!(!hyprland_is_only_owned_window(0, address, [(0, address)]));
+ assert!(!hyprland_is_only_owned_window(42, 0, [(42, 0)]));
+ }
+
#[tokio::test(flavor = "multi_thread")]
async fn existing_profile_cleanup_can_drive_atspi_runtime_from_async_session_teardown() {
let cleaned = run_existing_profile_cleanup(|| {
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/capture.rs b/libs/cua-driver/rust/crates/platform-linux/src/capture.rs
index e8b414d4bb..bf6cd24fc4 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/capture.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/capture.rs
@@ -1293,6 +1293,9 @@ mod tests {
"0",
"640x480x24",
"-ac",
+ // The readiness probe drops its connection before the
+ // fixture connects. Do not reset in that empty-client gap.
+ "-noreset",
"-nolisten",
"tcp",
])
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
index c13985260f..879aa53db5 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
@@ -52,6 +52,9 @@ mod clipboard;
#[cfg(target_os = "linux")]
pub mod atspi;
+#[cfg(any(target_os = "linux", test))]
+mod snapshot_queries;
+
#[cfg(target_os = "linux")]
pub mod a11y;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs
index 508521f6e5..1bbb008449 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/recording_hooks.rs
@@ -93,12 +93,77 @@ fn element_window_local_xy_blocking(
let (screen_x, screen_y, width, height) =
crate::atspi::get_element_bounds_for_window(pid, window_id, element_index as usize).ok()?;
let window = resolve_window_for_recording(pid, Some(window_id))?;
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ let (display_width, display_height, _) = crate::wayland::hyprland::screen_size().ok()?;
+ // This hook retains the whole output, not the window-local tool image.
+ return hyprland_recording_point(
+ (screen_x, screen_y, width, height),
+ (window.x, window.y, window.width, window.height),
+ (display_width, display_height),
+ );
+ }
Some((
- f64::from(screen_x - window.x) + f64::from(width) / 2.0,
- f64::from(screen_y - window.y) + f64::from(height) / 2.0,
+ f64::from(screen_x) - f64::from(window.x) + f64::from(width) / 2.0,
+ f64::from(screen_y) - f64::from(window.y) + f64::from(height) / 2.0,
))
}
+#[cfg(any(target_os = "linux", test))]
+fn hyprland_recording_point(
+ element: (i32, i32, u32, u32),
+ window: (i32, i32, u32, u32),
+ display: (u32, u32),
+) -> Option<(f64, f64)> {
+ let (x, y, width, height) = element;
+ if width == 0 || height == 0 || window.2 == 0 || window.3 == 0 {
+ return None;
+ }
+ let cx = f64::from(x) + f64::from(width) / 2.0;
+ let cy = f64::from(y) + f64::from(height) / 2.0;
+ hyprland_output_point((cx, cy), window, display)
+}
+
+#[cfg(any(target_os = "linux", test))]
+fn hyprland_output_point(
+ (cx, cy): (f64, f64),
+ window: (i32, i32, u32, u32),
+ display: (u32, u32),
+) -> Option<(f64, f64)> {
+ let in_window = cx >= f64::from(window.0)
+ && cy >= f64::from(window.1)
+ && cx < f64::from(window.0) + f64::from(window.2)
+ && cy < f64::from(window.1) + f64::from(window.3);
+ let in_display =
+ cx >= 0.0 && cy >= 0.0 && cx < f64::from(display.0) && cy < f64::from(display.1);
+ (in_window && in_display).then_some((cx, cy))
+}
+
+#[cfg(target_os = "linux")]
+pub fn hyprland_pixel_recording_point(
+ window_id: Option<u64>,
+ pid: Option<i64>,
+ x: f64,
+ y: f64,
+) -> Option<(f64, f64)> {
+ let (width, height, _) = crate::wayland::hyprland::screen_size().ok()?;
+ match (window_id, pid) {
+ (Some(window_id), Some(pid)) => {
+ let pid = u32::try_from(pid).ok()?;
+ let window = resolve_window_for_recording(pid, Some(window_id))?;
+ if window.pid != Some(pid) {
+ return None;
+ }
+ hyprland_output_point(
+ (f64::from(window.x) + x, f64::from(window.y) + y),
+ (window.x, window.y, window.width, window.height),
+ (width, height),
+ )
+ }
+ (None, None) => hyprland_output_point((x, y), (0, 0, width, height), (width, height)),
+ _ => None,
+ }
+}
+
#[cfg(target_os = "linux")]
fn resolve_window_for_recording(
pid: u32,
@@ -142,3 +207,44 @@ pub fn element_window_local_xy(
) -> Option<(f64, f64)> {
None
}
+
+#[cfg(test)]
+mod tests {
+ use super::{hyprland_output_point, hyprland_recording_point};
+
+ #[test]
+ fn hyprland_marker_uses_retained_output_coordinates() {
+ assert_eq!(
+ hyprland_recording_point((130, 250, 20, 30), (100, 200, 940, 780), (1920, 1080)),
+ Some((140.0, 265.0))
+ );
+ }
+
+ #[test]
+ fn hyprland_marker_does_not_invent_an_offscreen_point() {
+ for element in [(10, 800, 20, 20), (-30, 10, 20, 20), (10, 10, 0, 20)] {
+ assert_eq!(
+ hyprland_recording_point(element, (0, 0, 940, 780), (1920, 1080)),
+ None
+ );
+ }
+ assert_eq!(
+ hyprland_recording_point((1900, 10, 80, 20), (1800, 0, 940, 780), (1920, 1080)),
+ None
+ );
+ }
+
+ #[test]
+ fn hyprland_pixel_marker_keeps_fractional_output_coordinates() {
+ assert_eq!(
+ hyprland_output_point((130.5, 250.25), (100, 200, 940, 780), (1920, 1080)),
+ Some((130.5, 250.25))
+ );
+ for point in [(f64::NAN, 200.0), (100.0, f64::INFINITY), (99.0, 200.0)] {
+ assert_eq!(
+ hyprland_output_point(point, (100, 200, 940, 780), (1920, 1080)),
+ None
+ );
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/snapshot_queries.rs b/libs/cua-driver/rust/crates/platform-linux/src/snapshot_queries.rs
new file mode 100644
index 0000000000..a0f84b1a9d
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/snapshot_queries.rs
@@ -0,0 +1,161 @@
+//! Bounded, borrowed observation queries. No tasks outlive their snapshot.
+
+use std::future::Future;
+
+use futures_util::{stream, StreamExt};
+use tokio::time::{timeout_at, Instant};
+
+pub(crate) const SNAPSHOT_QUERY_CONCURRENCY: usize = 8;
+
+/// Keep the existing pre-offset rule for unrealized or degenerate components.
+pub(crate) fn plausible_raw_extents((x, y, w, h): (i32, i32, i32, i32)) -> bool {
+ !(x == i32::MIN || y == i32::MIN || x < -16384 || y < -16384 || w <= 1 || h <= 1)
+}
+
+/// Keep original element indices while overlapping independent read-only calls.
+/// The deadline covers the whole collection, including queued work. Dropping
+/// this future drops every in-flight query; nothing is spawned or cached.
+pub(crate) async fn collect_indexed<T, F>(
+ queries: impl IntoIterator<Item = F>,
+ deadline: Instant,
+) -> Vec<(usize, T)>
+where
+ F: Future<Output = Option<(usize, T)>>,
+{
+ let pending = stream::iter(queries).buffer_unordered(SNAPSHOT_QUERY_CONCURRENCY);
+ futures_util::pin_mut!(pending);
+ let mut collected = Vec::new();
+ while Instant::now() < deadline {
+ match timeout_at(deadline, pending.next()).await {
+ Ok(Some(Some(value))) => collected.push(value),
+ Ok(Some(None)) => {}
+ Ok(None) | Err(_) => break,
+ }
+ }
+ collected.sort_unstable_by_key(|(index, _)| *index);
+ collected
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{collect_indexed, plausible_raw_extents, SNAPSHOT_QUERY_CONCURRENCY};
+ use std::{cell::Cell, future::pending, rc::Rc, time::Duration};
+ use tokio::time::{sleep, timeout, Instant};
+
+ struct Active(Rc<Cell<usize>>);
+
+ impl Drop for Active {
+ fn drop(&mut self) {
+ self.0.set(self.0.get() - 1);
+ }
+ }
+
+ #[test]
+ fn raw_extent_acceptance_is_unchanged_before_coordinate_offsets() {
+ for raw in [
+ (i32::MIN, 0, 10, 10),
+ (0, i32::MIN, 10, 10),
+ (-16385, 0, 10, 10),
+ (0, -16385, 10, 10),
+ (0, 0, 1, 10),
+ (0, 0, 10, 1),
+ (0, 0, -1, 10),
+ ] {
+ assert!(!plausible_raw_extents(raw), "{raw:?}");
+ }
+ for raw in [(0, 0, 2, 2), (-16384, 0, 2, 2), (0, -16384, 2, 2)] {
+ assert!(plausible_raw_extents(raw), "{raw:?}");
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn preserves_original_indices_despite_out_of_order_completion_and_omissions() {
+ let completed = Rc::new(Cell::new(0));
+ let queries = [19, 3, 41, 7].into_iter().map(|index| {
+ let completed = completed.clone();
+ async move {
+ sleep(Duration::from_millis(index as u64)).await;
+ completed.set(completed.get() + 1);
+ (index != 7).then_some((index, index * 2))
+ }
+ });
+ let result = collect_indexed(queries, Instant::now() + Duration::from_secs(1)).await;
+ assert_eq!(result, [(3, 6), (19, 38), (41, 82)]);
+ assert_eq!(completed.get(), 4);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn concurrency_is_bounded_and_queued_work_is_not_started_after_deadline() {
+ let active = Rc::new(Cell::new(0));
+ let started = Rc::new(Cell::new(0));
+ let queries = (0..100).map(|index| {
+ let (active, started) = (active.clone(), started.clone());
+ async move {
+ started.set(started.get() + 1);
+ active.set(active.get() + 1);
+ assert!(active.get() <= SNAPSHOT_QUERY_CONCURRENCY);
+ let _guard = Active(active);
+ pending::<()>().await;
+ Some((index, ()))
+ }
+ });
+ let result = collect_indexed(queries, Instant::now() + Duration::from_secs(1)).await;
+ assert!(result.is_empty());
+ assert_eq!(started.get(), SNAPSHOT_QUERY_CONCURRENCY);
+ assert_eq!(active.get(), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn retains_completed_values_when_sibling_queries_stall() {
+ let active = Rc::new(Cell::new(0));
+ let queries = (0..20).map(|index| {
+ let active = active.clone();
+ async move {
+ active.set(active.get() + 1);
+ let _guard = Active(active);
+ if index % 2 == 0 {
+ pending::<()>().await;
+ }
+ sleep(Duration::from_millis(1)).await;
+ Some((index, index))
+ }
+ });
+ let result = collect_indexed(queries, Instant::now() + Duration::from_secs(1)).await;
+ assert_eq!(
+ result,
+ (1..14).step_by(2).map(|i| (i, i)).collect::<Vec<_>>()
+ );
+ assert_eq!(active.get(), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn caller_cancellation_drops_every_borrowed_query() {
+ let active = Rc::new(Cell::new(0));
+ let queries = (0..20).map(|index| {
+ let active = active.clone();
+ async move {
+ active.set(active.get() + 1);
+ let _guard = Active(active);
+ pending::<()>().await;
+ Some((index, ()))
+ }
+ });
+ let result = timeout(
+ Duration::from_secs(1),
+ collect_indexed(queries, Instant::now() + Duration::from_secs(20)),
+ )
+ .await;
+ assert!(result.is_err());
+ assert_eq!(active.get(), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn expired_deadline_does_not_poll_any_query() {
+ let queries = std::iter::once(async {
+ panic!("expired work must not start");
+ #[allow(unreachable_code)]
+ Some((0, ()))
+ });
+ assert!(collect_indexed(queries, Instant::now()).await.is_empty());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index b6d079ae63..7d8a240a76 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -2079,6 +2079,649 @@ fn linux_input_error(error: anyhow::Error) -> ToolResult {
}
}
+fn isolated_hyprland_background(delivery: crate::input::delivery::DeliveryMode) -> bool {
+ !delivery.is_foreground() && crate::wayland::hyprland_input::enabled()
+}
+
+fn hyprland_foreground(delivery: crate::input::delivery::DeliveryMode) -> bool {
+ delivery.is_foreground()
+ && crate::wayland::wayland_input_enabled()
+ && crate::wayland::hyprland::is_session()
+}
+
+fn element_click_prefers_ax(
+ hyprland_foreground: bool,
+ button: u8,
+ count: usize,
+ has_modifiers: bool,
+) -> bool {
+ !has_modifiers && (!hyprland_foreground || (button == 1 && count == 1))
+}
+
+fn foreground_ax_click_unknown(pid: u32, idx: usize) -> ToolResult {
+ use cua_driver_core::action_record::{
+ ActionEffect, ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
+ };
+ let record = ActionExecutionRecord::builder(
+ ActionEffect::Unverifiable,
+ ActionTransport::LinuxAtSpiAction,
+ RequestedDelivery::Foreground,
+ )
+ .actual_delivery(ActualDelivery::Unknown)
+ .build()
+ .expect("uncertain semantic activation has no delivered count or replay");
+ let public = serde_json::to_value(record.public_result().unwrap()).unwrap();
+ ToolResult::error(format!(
+ "click: AT-SPI activation outcome is unknown for element [{idx}] (pid {pid}); refresh state before another action."
+ ))
+ .with_structured(public)
+ .with_action_record(record)
+}
+
+#[cfg(test)]
+#[test]
+fn foreground_ax_click_error_does_not_claim_delivery_or_request_replay() {
+ let result = foreground_ax_click_unknown(123, 4);
+ assert_eq!(result.is_error, Some(true));
+ let wire = serde_json::to_value(&result).unwrap();
+ assert_eq!(wire["isError"], true);
+ let public = &wire["structuredContent"];
+ assert_eq!(
+ *public,
+ serde_json::to_value(result.action_record.unwrap().public_result().unwrap()).unwrap()
+ );
+ assert_eq!(public["effect"], "unverifiable");
+ assert_eq!(public["route"], "accessibility");
+ assert_eq!(public["delivery"]["mode"], "unknown");
+ assert!(public.get("escalation").is_none());
+ assert!(public["delivery"].get("delivered_count").is_none());
+}
+
+#[cfg(test)]
+#[test]
+fn hyprland_foreground_semantic_click_preserves_pointer_gestures() {
+ assert!(element_click_prefers_ax(true, 1, 1, false));
+ for (button, count) in [(2, 1), (3, 1), (1, 0), (1, 2), (1, 3), (2, 2), (3, 3)] {
+ assert!(!element_click_prefers_ax(true, button, count, false));
+ }
+ // Preserve the existing AT-SPI eligibility for all other delivery routes.
+ for button in [1, 2, 3] {
+ for count in [0, 1, 2, 3] {
+ assert!(element_click_prefers_ax(false, button, count, false));
+ assert!(!element_click_prefers_ax(false, button, count, true));
+ assert!(!element_click_prefers_ax(true, button, count, true));
+ }
+ }
+}
+
+fn isolated_hyprland_refusal(detail: impl Into<String>) -> ToolResult {
+ let detail = detail.into();
+ ToolResult::error(format!("background_unavailable: {detail}")).with_structured(json!({
+ "ok": false, "code": "background_unavailable", "reason": "unsupported_operation",
+ "detail": detail, "route": "synthetic_events", "verified": false, "effect": "refused"
+ }))
+}
+
+fn isolated_hyprland_result(result: anyhow::Result<Value>) -> ToolResult {
+ hyprland_input_result(result, false)
+}
+
+fn hyprland_input_result(result: anyhow::Result<Value>, foreground: bool) -> ToolResult {
+ use cua_driver_core::action_record::{
+ ActionEffect, ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
+ };
+ let record = |effect| {
+ ActionExecutionRecord::builder(
+ effect,
+ if foreground {
+ ActionTransport::LinuxHyprlandForegroundInput
+ } else {
+ ActionTransport::LinuxHyprlandIsolatedInput
+ },
+ if foreground {
+ RequestedDelivery::Foreground
+ } else {
+ RequestedDelivery::Background
+ },
+ )
+ };
+ let actual = if foreground {
+ ActualDelivery::Foreground
+ } else {
+ ActualDelivery::Background
+ };
+ let unavailable = if foreground {
+ "foreground_unavailable"
+ } else {
+ "background_unavailable"
+ };
+ match result {
+ Ok(value) if value["ok"] == true => ToolResult::text(
+ "Dispatched exact-target Hyprland input; application effect is unverifiable.",
+ )
+ .with_action_record(
+ record(ActionEffect::Unverifiable)
+ .actual_delivery(actual)
+ .build()
+ .expect("isolated input record is valid"),
+ ),
+ Ok(mut value) => {
+ if foreground && value["code"] == "foreground_partial_unknown" {
+ return hyprland_input_result(
+ Err(crate::wayland::hyprland_input::unknown_dispatch(
+ anyhow::anyhow!(
+ "{}",
+ value["detail"]
+ .as_str()
+ .unwrap_or("foreground acquisition may have changed focus")
+ ),
+ value["delivery"]["delivered_count"]
+ .as_u64()
+ .and_then(|count| u32::try_from(count).ok())
+ .unwrap_or(0),
+ )),
+ true,
+ );
+ }
+ let code = value["code"]
+ .as_str()
+ .unwrap_or("protocol_error")
+ .to_owned();
+ let detail = value["detail"]
+ .as_str()
+ .unwrap_or("input refused")
+ .to_owned();
+ value["reason"] = json!(code);
+ value["code"] = json!(unavailable);
+ value["route"] = json!(if foreground {
+ "global_input"
+ } else {
+ "synthetic_events"
+ });
+ value["verified"] = json!(false);
+ let delivered = value["delivery"]["delivered_count"]
+ .as_u64()
+ .and_then(|count| u32::try_from(count).ok())
+ .filter(|count| *count > 0);
+ let outcome = if value["effect"] == "partial"
+ && delivered.is_some_and(|count| foreground || count == 1)
+ {
+ record(ActionEffect::Partial)
+ .actual_delivery(actual)
+ .delivered_count(delivered.unwrap())
+ } else {
+ value["effect"] = json!("refused");
+ value
+ .as_object_mut()
+ .expect("protocol reply is an object")
+ .remove("delivery");
+ record(ActionEffect::Refused)
+ }
+ .detail(&detail)
+ .build()
+ .expect("isolated input outcome is valid");
+ ToolResult::error(format!("{unavailable} ({code}): {detail}"))
+ .with_structured(value)
+ .with_action_record(outcome)
+ }
+ Err(error) if error.is::<crate::wayland::hyprland_input::LaneBusy>() => {
+ hyprland_input_result(
+ Ok(json!({
+ "ok": false, "code": "lane_busy", "detail": error.to_string()
+ })),
+ foreground,
+ )
+ }
+ Err(error) if error.is::<crate::wayland::hyprland_input::ActionCancelled>() => {
+ hyprland_input_result(
+ Ok(json!({
+ "ok": false, "code": "cancelled", "detail": error.to_string()
+ })),
+ foreground,
+ )
+ }
+ Err(error) => {
+ let count = error
+ .downcast_ref::<crate::wayland::hyprland_input::DispatchUnknown>()
+ .map(|error| error.acknowledged_phases)
+ .filter(|count| *count > 0);
+ let effect = if count.is_some() {
+ ActionEffect::Partial
+ } else {
+ ActionEffect::Unverifiable
+ };
+ let mut outcome = record(effect)
+ .actual_delivery(ActualDelivery::Unknown)
+ .detail(error.to_string());
+ if let Some(count) = count {
+ outcome = outcome.delivered_count(count);
+ }
+ let outcome = outcome
+ .build()
+ .expect("unknown delivery preserves acknowledged progress");
+ let mut value = serde_json::to_value(outcome.public_result().unwrap()).unwrap();
+ value["ok"] = json!(false);
+ value["code"] = json!(unavailable);
+ value["reason"] = json!("transport_or_protocol_error");
+ value["detail"] = json!(error.to_string());
+ ToolResult::error(format!("{unavailable}: {error}"))
+ .with_structured(value)
+ .with_action_record(outcome)
+ }
+ }
+}
+
+fn isolated_hyprland_task_error(error: tokio::task::JoinError, acknowledged: bool) -> ToolResult {
+ isolated_hyprland_result(Err(crate::wayland::hyprland_input::unknown_dispatch(
+ error.into(),
+ u32::from(acknowledged),
+ )))
+}
+
+fn spawn_isolated_hyprland(
+ args: &Value,
+ work: impl FnOnce(crate::wayland::hyprland_input::ActionCancellation) -> anyhow::Result<Value>
+ + Send
+ + 'static,
+) -> Result<
+ (
+ crate::wayland::hyprland_input::CancelOnDrop,
+ tokio::task::JoinHandle<anyhow::Result<Value>>,
+ ),
+ ToolResult,
+> {
+ use cua_driver_core::session;
+ let owner = named_session_cursor_key(args)
+ .ok_or_else(|| isolated_hyprland_refusal("authenticated lifecycle required"))?;
+ let transport_owner = args
+ .get("_transport_session_id")
+ .and_then(Value::as_str)
+ .unwrap_or(&owner);
+ let snapshot = session::session_snapshot(&owner, transport_owner, std::time::Duration::ZERO)
+ .ok_or_else(|| isolated_hyprland_refusal("admitted lifecycle required"))?;
+ // Retain admission before spawning: aborting the async caller must not
+ // complete session teardown while its native worker still owns input.
+ let lifecycle = session::begin_session_dispatch(
+ &owner,
+ snapshot.public_label.as_deref(),
+ transport_owner,
+ snapshot.implicit,
+ snapshot.transport,
+ snapshot.client_kind,
+ )
+ .map_err(isolated_hyprland_refusal)?;
+ let (guard, cancellation) = crate::wayland::hyprland_input::ActionCancellation::invocation();
+ let dispatch = tokio::task::spawn_blocking(move || {
+ let _lifecycle = lifecycle;
+ work(cancellation)
+ });
+ Ok((guard, dispatch))
+}
+
+async fn isolated_hyprland_action(
+ args: &Value,
+ pid: u32,
+ xid: u64,
+ action: crate::wayland::hyprland_input::Action,
+) -> ToolResult {
+ let owner = named_session_cursor_key(args);
+ let (_cancellation, dispatch) = match spawn_isolated_hyprland(args, move |cancellation| {
+ crate::wayland::hyprland_input::execute(owner, pid, xid, action, cancellation)
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(refusal) => return refusal,
+ };
+ match dispatch.await {
+ Ok(result) => isolated_hyprland_result(result),
+ Err(error) => isolated_hyprland_task_error(error, false),
+ }
+}
+
+fn foreground_hyprland_refusal(detail: impl Into<String>) -> ToolResult {
+ hyprland_input_result(
+ Ok(json!({
+ "ok": false, "code": "unsupported_operation", "detail": detail.into()
+ })),
+ true,
+ )
+}
+
+async fn foreground_hyprland_action(
+ args: &Value,
+ pid: u32,
+ xid: u64,
+ action: crate::wayland::hyprland_input::Action,
+) -> ToolResult {
+ if !crate::wayland::hyprland_input::enabled() {
+ return foreground_hyprland_refusal("production Hyprland input plugin is unavailable");
+ }
+ let owner = named_session_cursor_key(args);
+ let (_cancellation, dispatch) = match spawn_isolated_hyprland(args, move |cancellation| {
+ crate::wayland::hyprland_input::execute_foreground(owner, pid, xid, action, cancellation)
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(_) => return foreground_hyprland_refusal("authenticated admitted lifecycle required"),
+ };
+ hyprland_input_result(
+ match dispatch.await {
+ Ok(result) => result,
+ Err(error) => Err(crate::wayland::hyprland_input::unknown_dispatch(
+ error.into(),
+ 0,
+ )),
+ },
+ true,
+ )
+}
+
+fn foreground_hyprland_key(
+ key: String,
+ mut modifiers: Vec<String>,
+) -> Result<crate::wayland::hyprland_input::Action, ToolResult> {
+ let parts: Vec<&str> = key.split('+').collect();
+ let key = if parts.len() > 1 && key != "+" {
+ if parts[..parts.len() - 1]
+ .iter()
+ .any(|part| !is_modifier(part))
+ || parts.last() == Some(&"")
+ {
+ return Err(foreground_hyprland_refusal("invalid modified key chord"));
+ }
+ modifiers.extend(
+ parts[..parts.len() - 1]
+ .iter()
+ .map(|part| part.to_lowercase()),
+ );
+ parts.last().unwrap().to_string()
+ } else {
+ key
+ };
+ Ok(crate::wayland::hyprland_input::Action::Key { key, modifiers })
+}
+
+async fn focus_hyprland_foreground(
+ state: &Arc<ToolState>,
+ args: &Value,
+ pid: u32,
+ xid: u64,
+ element: Option<usize>,
+ pixel: Option<(f64, f64)>,
+) -> Result<(), ToolResult> {
+ if !crate::wayland::hyprland_input::enabled() {
+ return Err(foreground_hyprland_refusal(
+ "production Hyprland input plugin is unavailable",
+ ));
+ }
+ if let Some((x, y)) = pixel {
+ return focus_by_pixel(
+ state,
+ pid,
+ Some(xid),
+ x,
+ y,
+ true,
+ args,
+ args.bool_or("from_zoom", false),
+ )
+ .await;
+ }
+ if let Some(index) = element {
+ let activation = foreground_hyprland_action(
+ args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Activate,
+ )
+ .await;
+ if activation.is_error == Some(true) {
+ return Err(activation);
+ }
+ match tokio::task::spawn_blocking(move || crate::atspi::focus_element(pid, index)).await {
+ Ok(Ok(true)) => {}
+ _ => return Err(foreground_hyprland_refusal("AT-SPI child focus failed")),
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+#[tokio::test]
+async fn isolated_worker_retains_lifecycle_until_native_work_exits() {
+ use cua_driver_core::session::{self, SessionClientKind, SessionTransport};
+ let sid = "isolated-worker-lifecycle-test";
+ let owner = "isolated-worker-transport-test";
+ let caller = session::begin_session_dispatch(
+ sid,
+ None,
+ owner,
+ true,
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ .unwrap();
+ let (started, ready) = tokio::sync::oneshot::channel();
+ let (release, released) = std::sync::mpsc::channel();
+ let (cancellation, dispatch) = spawn_isolated_hyprland(
+ &json!({"_session_id":sid,"_transport_session_id":owner}),
+ move |_| {
+ started.send(()).unwrap();
+ released.recv().unwrap();
+ Ok(json!({"ok":true}))
+ },
+ )
+ .unwrap();
+ ready.await.unwrap();
+ drop(cancellation);
+ drop(caller);
+ assert!(session::end_session_for_owner(sid, owner));
+ assert!(session::is_session_ending(sid));
+ assert!(!session::is_session_ended(sid));
+ release.send(()).unwrap();
+ dispatch.await.unwrap().unwrap();
+ assert!(session::is_session_ended(sid));
+}
+
+#[cfg(test)]
+#[test]
+fn isolated_background_routes_do_not_reprobe_availability_before_primary_fallback() {
+ // Structural regression for the availability-loss race: each tool keeps
+ // the decision that bypassed background refusal until its returning
+ // native branch. A second probe here could select primary-seat input.
+ let source = include_str!("impl_.rs");
+ for (start, end) in [
+ ("impl Tool for ClickTool {", "impl Tool for TypeTextTool {"),
+ (
+ "impl Tool for ScrollTool {",
+ "impl Tool for DoubleClickTool {",
+ ),
+ (
+ "impl Tool for DragTool {",
+ "impl Tool for MouseButtonDownTool {",
+ ),
+ ] {
+ let body = source
+ .rsplit_once(start)
+ .unwrap()
+ .1
+ .split_once(end)
+ .unwrap()
+ .0;
+ let invoke = body.split_once("async fn invoke").unwrap().1;
+ assert_eq!(
+ invoke
+ .matches("isolated_hyprland_background(delivery)")
+ .count(),
+ 1,
+ "{start}"
+ );
+ let native = invoke.split_once("if isolated_background {").unwrap().1;
+ assert!(native.contains("return match dispatch.await"), "{start}");
+ }
+}
+
+#[cfg(test)]
+#[test]
+fn isolated_hyprland_refused_partial_and_unknown_outcomes_stay_distinct() {
+ let busy = isolated_hyprland_result(Err(crate::wayland::hyprland_input::LaneBusy.into()));
+ let content = busy.structured_content.as_ref().unwrap();
+ assert_eq!(content["reason"], "lane_busy");
+ assert_eq!(content["effect"], "refused");
+ assert!(content.get("delivery").is_none());
+ assert!(busy
+ .action_record
+ .unwrap()
+ .public_result()
+ .unwrap()
+ .delivery
+ .is_none());
+
+ let refused = isolated_hyprland_result(Ok(
+ json!({"ok":false,"code":"stale_target","detail":"stale_target"}),
+ ));
+ assert_eq!(
+ refused.structured_content.as_ref().unwrap()["effect"],
+ "refused"
+ );
+ let public = refused.action_record.unwrap().public_result().unwrap();
+ assert!(public.delivery.is_none());
+ public.validate_invariants().unwrap();
+
+ let partial = isolated_hyprland_result(Ok(
+ json!({"ok":false,"code":"cancelled","detail":"cancelled",
+ "effect":"partial","delivery":{"mode":"background","delivered_count":1}}),
+ ));
+ let public = partial.action_record.unwrap().public_result().unwrap();
+ assert_eq!(public.effect, cua_driver_contract::ActionEffect::Partial);
+ assert_eq!(public.delivery.unwrap().delivered_count, Some(1));
+
+ let unknown = isolated_hyprland_result(Err(anyhow::anyhow!("connection lost")));
+ let public = unknown.action_record.unwrap().public_result().unwrap();
+ assert_eq!(
+ public.effect,
+ cua_driver_contract::ActionEffect::Unverifiable
+ );
+ assert_eq!(
+ public.delivery.as_ref().unwrap().mode,
+ cua_driver_contract::ActionDeliveryMode::Unknown
+ );
+ assert_eq!(public.delivery.unwrap().delivered_count, None);
+
+ let unknown_after_start = isolated_hyprland_result(Err(
+ crate::wayland::hyprland_input::unknown_dispatch(anyhow::anyhow!("connection lost"), 1),
+ ));
+ let public = unknown_after_start
+ .action_record
+ .unwrap()
+ .public_result()
+ .unwrap();
+ public.validate_invariants().unwrap();
+ assert_eq!(public.effect, cua_driver_contract::ActionEffect::Partial);
+ let delivery = public.delivery.unwrap();
+ assert_eq!(
+ delivery.mode,
+ cua_driver_contract::ActionDeliveryMode::Unknown
+ );
+ assert_eq!(delivery.delivered_count, Some(1));
+}
+
+#[cfg(test)]
+#[test]
+fn experimental_pending_grant_is_an_error_with_operator_context() {
+ let result = isolated_hyprland_result(Ok(json!({
+ "ok": false, "code": "permission_required", "detail": "external approval pending",
+ "epoch": "epoch", "challenge": "challenge", "target": "target", "revision": 3
+ })));
+ assert_eq!(result.is_error, Some(true));
+ let value = result.structured_content.unwrap();
+ assert_eq!(value["code"], "background_unavailable");
+ assert_eq!(value["reason"], "permission_required");
+ assert_eq!(value["challenge"], "challenge");
+ assert_eq!(value["target"], "target");
+ assert_eq!(value["revision"], 3);
+ assert_eq!(value["verified"], false);
+}
+
+#[cfg(test)]
+#[test]
+fn experimental_dispatch_does_not_claim_application_success() {
+ let result = isolated_hyprland_result(Ok(json!({
+ "ok": true, "effect": "unverifiable", "route": "synthetic_events"
+ })));
+ assert_ne!(result.is_error, Some(true));
+ let public = result.action_record.unwrap().public_result().unwrap();
+ public.validate_invariants().unwrap();
+ let value = serde_json::to_value(public).unwrap();
+ assert_eq!(value["effect"], "unverifiable");
+ assert_eq!(value["route"], "synthetic_events");
+ assert!(value.get("verified").is_none());
+}
+
+#[cfg(test)]
+#[test]
+fn foreground_hyprland_reports_foreground_and_preserves_partial_progress() {
+ use cua_driver_core::action_record::{ActionTransport, RequestedDelivery};
+ for (reply, expected_effect, count) in [
+ (json!({"ok":true}), "unverifiable", None),
+ (
+ json!({"ok":false,"code":"stale_target","detail":"stale"}),
+ "refused",
+ None,
+ ),
+ (
+ json!({"ok":false,"code":"cancelled","detail":"cancelled","effect":"partial",
+ "delivery":{"mode":"foreground","delivered_count":3}}),
+ "partial",
+ Some(3),
+ ),
+ ] {
+ let result = hyprland_input_result(Ok(reply), true);
+ let record = result.action_record.unwrap();
+ assert_eq!(
+ record.transport,
+ ActionTransport::LinuxHyprlandForegroundInput
+ );
+ assert_eq!(record.requested_delivery, RequestedDelivery::Foreground);
+ let public = record.public_result().unwrap();
+ public.validate_invariants().unwrap();
+ let value = serde_json::to_value(public).unwrap();
+ assert_eq!(value["route"], "global_input");
+ assert_eq!(value["effect"], expected_effect);
+ if expected_effect == "refused" {
+ assert!(value.get("delivery").is_none());
+ } else {
+ assert_eq!(value["delivery"]["mode"], "foreground");
+ assert_eq!(value["delivery"]["delivered_count"].as_u64(), count);
+ }
+ }
+ for reply in [
+ Err(crate::wayland::hyprland_input::unknown_dispatch(
+ anyhow::anyhow!("lost"),
+ 2,
+ )),
+ Ok(json!({"ok":false,"code":"foreground_partial_unknown","detail":"focus changed"})),
+ ] {
+ let unknown = hyprland_input_result(reply, true);
+ let value =
+ serde_json::to_value(unknown.action_record.unwrap().public_result().unwrap()).unwrap();
+ assert_eq!(value["delivery"]["mode"], "unknown");
+ assert_ne!(value["effect"], "refused");
+ }
+}
+
+#[cfg(test)]
+#[test]
+fn foreground_hyprland_chords_preserve_all_modifiers() {
+ let action = foreground_hyprland_key("Ctrl+Shift+H".into(), vec!["alt".into()]).unwrap();
+ match action {
+ crate::wayland::hyprland_input::Action::Key { key, modifiers } => {
+ assert_eq!(key, "H");
+ assert_eq!(modifiers, ["alt", "ctrl", "shift"]);
+ }
+ _ => panic!("expected a key chord"),
+ }
+ assert!(foreground_hyprland_key("bogus+H".into(), vec![]).is_err());
+}
+
#[cfg(test)]
#[test]
fn uinput_failure_has_a_stable_structured_code() {
@@ -2402,29 +3045,83 @@ async fn track_overlay_drag_for(
duration_ms: u64,
steps: usize,
) {
- crate::overlay::send_command_for(
- cursor_id.clone(),
- cursor_overlay::OverlayCommand::SetEnabled(true),
- );
- crate::overlay::send_command_for(
- cursor_id.clone(),
- cursor_overlay::OverlayCommand::SetPressed(true),
- );
+ track_overlay_drag_with(
+ |command| crate::overlay::send_command_for(cursor_id.clone(), command),
+ from,
+ to,
+ duration_ms,
+ steps,
+ )
+ .await;
+}
+
+async fn track_overlay_drag_with(
+ send: impl Fn(cursor_overlay::OverlayCommand),
+ from: (f64, f64),
+ to: (f64, f64),
+ duration_ms: u64,
+ steps: usize,
+) {
+ send(cursor_overlay::OverlayCommand::SetEnabled(true));
+ let _pressed = cursor_overlay::PressedVisualGuard::new(&send);
let steps = steps.max(1);
let step_delay = std::time::Duration::from_millis(duration_ms / steps as u64);
for index in 0..=steps {
let t = index as f64 / steps as f64;
let x = from.0 + (to.0 - from.0) * t;
let y = from.1 + (to.1 - from.1) * t;
- crate::overlay::send_command_for(
- cursor_id.clone(),
- cursor_overlay::track_pointer_command(x, y),
- );
+ send(cursor_overlay::track_pointer_command(x, y));
if index < steps && !step_delay.is_zero() {
tokio::time::sleep(step_delay).await;
}
}
- crate::overlay::send_command_for(cursor_id, cursor_overlay::OverlayCommand::SetPressed(false));
+}
+
+#[cfg(test)]
+#[tokio::test]
+async fn cancelled_overlay_drag_releases_visual_press_without_native_commands() {
+ use std::{cell::RefCell, future::Future, task::Context};
+ let commands = RefCell::new(Vec::new());
+ let mut drag = Box::pin(track_overlay_drag_with(
+ |command| commands.borrow_mut().push(command),
+ (10.0, 20.0),
+ (30.0, 40.0),
+ 2000,
+ 20,
+ ));
+ let mut context = Context::from_waker(std::task::Waker::noop());
+ assert!(drag.as_mut().poll(&mut context).is_pending());
+ assert!(matches!(
+ commands.borrow()[1],
+ cursor_overlay::OverlayCommand::SetPressed(true)
+ ));
+ drop(drag);
+ let commands = commands.borrow();
+ assert_eq!(commands.len(), 4);
+ assert!(matches!(
+ commands.last(),
+ Some(cursor_overlay::OverlayCommand::SetPressed(false))
+ ));
+}
+
+#[cfg(test)]
+#[tokio::test]
+async fn completed_overlay_drag_balances_visual_press_once() {
+ use std::cell::RefCell;
+ let pressed = RefCell::new(Vec::new());
+ track_overlay_drag_with(
+ |command| {
+ if let cursor_overlay::OverlayCommand::SetPressed(value) = command {
+ pressed.borrow_mut().push(value);
+ }
+ },
+ (10.0, 20.0),
+ (30.0, 40.0),
+ 0,
+ 2,
+ )
+ .await;
+ assert_eq!(*pressed.borrow(), vec![true, false]);
}
fn process_name(pid: u32) -> Option<String> {
@@ -2690,6 +3387,7 @@ impl Tool for ClickTool {
};
let delivery = crate::input::delivery::DeliveryMode::from_args(&args);
let count = args.u64_or("count", 1) as usize;
+ let isolated_background = isolated_hyprland_background(delivery);
// Surface 5: reject unknown buttons so a typo can't silently fall through
// to a left-click. Empty string keeps back-compat with old clients.
let button_str_raw = args.str_or("button", "left").to_lowercase();
@@ -2770,7 +3468,15 @@ impl Tool for ClickTool {
// Chromium can execute a genuine AT-SPI action without focus. Try
// that route before applying its background synthetic-input gate.
- if modifiers.is_empty() {
+ // Plain Hyprland foreground clicks also retain semantic activation
+ // for offscreen controls; other pointer gestures need raw input.
+ let foreground_hyprland = hyprland_foreground(delivery);
+ if foreground_hyprland && window_id_resolved.is_none() {
+ return foreground_hyprland_refusal(
+ "an exact window_id or window-bound element token is required",
+ );
+ }
+ if element_click_prefers_ax(foreground_hyprland, button, count, !modifiers.is_empty()) {
let ax_result =
tokio::task::spawn_blocking(move || crate::atspi::perform_action(pid, idx))
.await;
@@ -2786,6 +3492,82 @@ impl Tool for ClickTool {
return ToolResult::text(format!("Clicked element [{idx}] (pid {pid})."))
.with_structured(structured);
}
+ // AT-SPI errors can arrive after dispatch. Do not introduce a
+ // primary-seat replay when its semantic outcome is uncertain.
+ if foreground_hyprland {
+ return foreground_ax_click_unknown(pid, idx);
+ }
+ }
+ if foreground_hyprland {
+ if !modifiers.is_empty() {
+ return foreground_hyprland_refusal("modified clicks are unsupported");
+ }
+ let Some(xid) = window_id_resolved else {
+ return foreground_hyprland_refusal(
+ "an exact window_id or window-bound element token is required",
+ );
+ };
+ let point = tokio::task::spawn_blocking(move || {
+ resolve_element_local_coords(pid, idx, Some(xid))
+ })
+ .await;
+ let (x, y) = match point {
+ Ok(Ok((_, x, y))) => (x, y),
+ _ => {
+ return foreground_hyprland_refusal(
+ "could not resolve exact element coordinates",
+ )
+ }
+ };
+ return foreground_hyprland_action(
+ &args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Click {
+ x,
+ y,
+ button: u32::from(button),
+ count,
+ },
+ )
+ .await;
+ }
+ if isolated_background {
+ if !modifiers.is_empty() {
+ return isolated_hyprland_refusal(
+ "modified element clicks are unavailable on native Wayland: \
+ isolated input does not carry pointer modifier state",
+ );
+ }
+ let Some(exact_xid) = window_id_resolved else {
+ return isolated_hyprland_refusal(
+ "an exact window_id or window-bound element token is required",
+ );
+ };
+ let owner = named_session_cursor_key(&args);
+ let (_cancellation, dispatch) =
+ match spawn_isolated_hyprland(&args, move |cancellation| {
+ let (_, x, y) = resolve_element_local_coords(pid, idx, Some(exact_xid))?;
+ crate::wayland::hyprland_input::execute(
+ owner,
+ pid,
+ exact_xid,
+ crate::wayland::hyprland_input::Action::Click {
+ x,
+ y,
+ button: u32::from(button),
+ count,
+ },
+ cancellation,
+ )
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(refusal) => return refusal,
+ };
+ return match dispatch.await {
+ Ok(result) => isolated_hyprland_result(result),
+ Err(error) => isolated_hyprland_task_error(error, false),
+ };
}
if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
return refusal;
@@ -2851,8 +3633,10 @@ impl Tool for ClickTool {
};
}
- if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
- return refusal;
+ if !isolated_background {
+ if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
+ return refusal;
+ }
}
// Coordinate-based path.
@@ -2908,9 +3692,59 @@ impl Tool for ClickTool {
if let Some((sx, sy)) = glide_target {
reveal_pointer_action_for(&self.state, &cursor_id, sx, sy, true).await;
}
-
- let (xi, yi) = (x as i32, y as i32);
- let (output_x, output_y) = wayland_output_point.unwrap_or((xi, yi));
+
+ let (xi, yi) = (x as i32, y as i32);
+ let (output_x, output_y) = wayland_output_point.unwrap_or((xi, yi));
+ if hyprland_foreground(delivery) {
+ if !modifiers.is_empty() {
+ return foreground_hyprland_refusal("modified clicks are unsupported");
+ }
+ if window_id_resolved.is_none() {
+ return foreground_hyprland_refusal("an exact window_id is required");
+ }
+ return foreground_hyprland_action(
+ &args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Click {
+ x,
+ y,
+ button: u32::from(button),
+ count,
+ },
+ )
+ .await;
+ }
+ if isolated_background {
+ if !modifiers.is_empty() {
+ return isolated_hyprland_refusal(
+ "modified clicks are unsupported by isolated input",
+ );
+ }
+ if button == 1 && count == 1 {
+ let semantic = tokio::task::spawn_blocking(move || {
+ crate::atspi::perform_action_at_screen_point(pid, xid, output_x, output_y)
+ })
+ .await;
+ if matches!(semantic, Ok(Ok(Some(_)))) {
+ return ToolResult::text("Dispatched AT-SPI click.").with_structured(json!({
+ "path": "wayland_atspi", "verified": false, "effect": "unverifiable"
+ }));
+ }
+ }
+ return isolated_hyprland_action(
+ &args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Click {
+ x,
+ y,
+ button: u32::from(button),
+ count,
+ },
+ )
+ .await;
+ }
let cursor_id_for_task = cursor_id.clone();
let modifiers_for_task = modifiers.clone();
// delivery_mode: background (default) = no-focus-steal injection;
@@ -3049,10 +3883,7 @@ impl Tool for ClickTool {
/// translation + delivery_mode so it lands on the same pixel a px-click would.
/// `Ok(())` on success; `Err(ToolResult)` short-circuits the caller.
///
-/// Mirrors macOS `tools::focus_by_pixel`. Linux differences: `pid` is `u32`,
-/// `window_id` is `u64` (the X11 XID / window id), and there is no `_session_id`
-/// field — the Linux ClickTool resolves the agent cursor from `session` /
-/// `cursor_id` only (`resolve_cursor_key`).
+/// Retains the parent's authenticated session admission for the nested click.
async fn focus_by_pixel(
state: &Arc<ToolState>,
pid: u32,
@@ -3060,7 +3891,7 @@ async fn focus_by_pixel(
x: f64,
y: f64,
foreground: bool,
- session: Option<String>,
+ parent_args: &Value,
from_zoom: bool,
) -> Result<(), ToolResult> {
let mut click_args = json!({
@@ -3070,8 +3901,15 @@ async fn focus_by_pixel(
if let Some(wid) = window_id {
click_args["window_id"] = json!(wid);
}
- if let Some(s) = session {
- click_args["session"] = json!(s);
+ for field in [
+ "session",
+ "_session_id",
+ "_transport_session_id",
+ "cursor_id",
+ ] {
+ if let Some(value) = parent_args.get(field) {
+ click_args[field] = value.clone();
+ }
}
if from_zoom {
click_args["from_zoom"] = json!(true);
@@ -3082,9 +3920,7 @@ async fn focus_by_pixel(
.invoke(click_args)
.await;
if focus.is_error == Some(true) {
- return Err(ToolResult::error(format!(
- "focus pixel-click at ({x:.0},{y:.0}) failed."
- )));
+ return Err(focus);
}
// Brief settle so the renderer registers focus before the keystrokes.
tokio::time::sleep(std::time::Duration::from_millis(120)).await;
@@ -3261,6 +4097,76 @@ impl Tool for TypeTextTool {
);
}
+ if hyprland_foreground(delivery) {
+ if xid_opt.is_none() {
+ return foreground_hyprland_refusal("an exact window_id is required");
+ }
+ // Native editables retain their verifiable, addressed AT-SPI route.
+ if !is_chromium_embedder(pid) && !is_webkitgtk_embedder(pid) {
+ if let Some(index) = resolved_elem_idx {
+ let text_ax = text.clone();
+ if matches!(
+ tokio::task::spawn_blocking(move || crate::atspi::type_into_editable_at(
+ pid, index, &text_ax
+ ))
+ .await,
+ Ok(Ok(()))
+ ) {
+ return type_text_ax_result(
+ pid,
+ text.chars().count(),
+ "via targeted AT-SPI",
+ );
+ }
+ }
+ }
+ match crate::wayland::hyprland_input::foreground_text_actions(&text) {
+ Ok(actions) if !actions.is_empty() => {}
+ Ok(_) => return foreground_hyprland_refusal("foreground text must not be empty"),
+ Err(error) => return foreground_hyprland_refusal(error.to_string()),
+ }
+ if let Err(error) = focus_hyprland_foreground(
+ &self.state,
+ &args,
+ pid,
+ xid,
+ resolved_elem_idx,
+ px.zip(py),
+ )
+ .await
+ {
+ return error;
+ }
+ let owner = named_session_cursor_key(&args);
+ let (_cancellation, dispatch) =
+ match spawn_isolated_hyprland(&args, move |cancellation| {
+ crate::wayland::hyprland_input::execute_foreground_text(
+ owner,
+ pid,
+ xid,
+ &text,
+ cancellation,
+ )
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(_) => {
+ return foreground_hyprland_refusal(
+ "authenticated admitted lifecycle required",
+ )
+ }
+ };
+ return hyprland_input_result(
+ match dispatch.await {
+ Ok(result) => result,
+ Err(error) => Err(crate::wayland::hyprland_input::unknown_dispatch(
+ error.into(),
+ 0,
+ )),
+ },
+ true,
+ );
+ }
+
position_named_session_keyboard_cursor(
&self.state,
&args,
@@ -3338,7 +4244,7 @@ impl Tool for TypeTextTool {
cx,
cy,
delivery.is_foreground(),
- args.opt_str("session"),
+ &args,
from_zoom,
)
.await
@@ -3868,6 +4774,31 @@ impl Tool for PressKeyTool {
// background path (the focus-click already handled fronting when fg). Pass x,y
// (no element_index) for Chromium/Electron surfaces the AX path can't focus.
let delivery = crate::input::delivery::DeliveryMode::from_args(&args);
+ if isolated_hyprland_background(delivery) {
+ if xid_opt.is_none() {
+ return isolated_hyprland_refusal(
+ "an exact window_id is required for isolated keys",
+ );
+ }
+ if resolved_element_index.is_some()
+ || args.get("x").is_some()
+ || args.get("y").is_some()
+ {
+ return isolated_hyprland_refusal(
+ "isolated keys address the exact top-level; first click the child explicitly",
+ );
+ }
+ return isolated_hyprland_action(
+ &args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Key {
+ key,
+ modifiers: mods,
+ },
+ )
+ .await;
+ }
if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
return refusal;
}
@@ -3893,6 +4824,29 @@ impl Tool for PressKeyTool {
);
}
+ if hyprland_foreground(delivery) {
+ if xid_opt.is_none() {
+ return foreground_hyprland_refusal("an exact window_id is required");
+ }
+ let action = match foreground_hyprland_key(key, mods) {
+ Ok(action) => action,
+ Err(error) => return error,
+ };
+ if let Err(error) = focus_hyprland_foreground(
+ &self.state,
+ &args,
+ pid,
+ xid,
+ resolved_element_index,
+ px.zip(py),
+ )
+ .await
+ {
+ return error;
+ }
+ return foreground_hyprland_action(&args, pid, xid, action).await;
+ }
+
position_named_session_keyboard_cursor(
&self.state,
&args,
@@ -3946,7 +4900,7 @@ impl Tool for PressKeyTool {
cx,
cy,
delivery.is_foreground(),
- args.opt_str("session"),
+ &args,
from_zoom,
)
.await
@@ -4219,6 +5173,42 @@ impl Tool for HotkeyTool {
let mods_for_wayland = mods.clone();
let delivery = crate::input::delivery::DeliveryMode::from_args(&args);
+ if isolated_hyprland_background(delivery) {
+ if xid_opt.is_none() {
+ return isolated_hyprland_refusal(
+ "an exact window_id is required for isolated hotkeys",
+ );
+ }
+ if resolved_element_index.is_some()
+ || args.get("x").is_some()
+ || args.get("y").is_some()
+ {
+ return isolated_hyprland_refusal("isolated hotkeys address the exact top-level; first click the child explicitly");
+ }
+ if let Some(keys) = args.get("keys").and_then(Value::as_array) {
+ if keys
+ .iter()
+ .filter(|value| value.as_str().is_some_and(|key| !is_modifier(key)))
+ .count()
+ != 1
+ || keys.iter().any(|value| !value.is_string())
+ {
+ return isolated_hyprland_refusal(
+ "isolated hotkeys require exactly one non-modifier key",
+ );
+ }
+ }
+ return isolated_hyprland_action(
+ &args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Key {
+ key,
+ modifiers: mods,
+ },
+ )
+ .await;
+ }
if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
return refusal;
}
@@ -4243,6 +5233,42 @@ impl Tool for HotkeyTool {
);
}
+ if hyprland_foreground(delivery) {
+ if xid_opt.is_none() {
+ return foreground_hyprland_refusal("an exact window_id is required");
+ }
+ if let Some(keys) = args.get("keys").and_then(Value::as_array) {
+ if keys.iter().any(|key| !key.is_string())
+ || keys
+ .iter()
+ .filter(|key| key.as_str().is_some_and(|key| !is_modifier(key)))
+ .count()
+ != 1
+ {
+ return foreground_hyprland_refusal(
+ "hotkeys require exactly one non-modifier key",
+ );
+ }
+ }
+ let action = match foreground_hyprland_key(key, mods) {
+ Ok(action) => action,
+ Err(error) => return error,
+ };
+ if let Err(error) = focus_hyprland_foreground(
+ &self.state,
+ &args,
+ pid,
+ xid,
+ resolved_element_index,
+ px.zip(py),
+ )
+ .await
+ {
+ return error;
+ }
+ return foreground_hyprland_action(&args, pid, xid, action).await;
+ }
+
position_named_session_keyboard_cursor(
&self.state,
&args,
@@ -4292,17 +5318,8 @@ impl Tool for HotkeyTool {
Ok(Err(error)) => return ToolResult::error(error.to_string()),
Err(error) => return ToolResult::error(format!("Task error: {error}")),
};
- if let Err(error) = focus_by_pixel(
- &self.state,
- pid,
- Some(xid),
- x,
- y,
- true,
- args.opt_str("session"),
- false,
- )
- .await
+ if let Err(error) =
+ focus_by_pixel(&self.state, pid, Some(xid), x, y, true, &args, false).await
{
return error;
}
@@ -4340,7 +5357,7 @@ impl Tool for HotkeyTool {
cx,
cy,
delivery.is_foreground(),
- args.opt_str("session"),
+ &args,
from_zoom,
)
.await
@@ -4479,6 +5496,89 @@ impl Tool for SetValueTool {
pub struct ScrollTool {
state: Arc<ToolState>,
}
+
+fn atspi_scroll_result(progress: crate::atspi::ScrollProgress, foreground: bool) -> ToolResult {
+ use cua_driver_core::action_record::{
+ ActionEffect, ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
+ };
+ let effect = if !progress.complete && progress.acknowledged > 0 {
+ ActionEffect::Partial
+ } else {
+ ActionEffect::Unverifiable
+ };
+ let mut record = ActionExecutionRecord::builder(
+ effect,
+ ActionTransport::LinuxAtSpiAction,
+ if foreground {
+ RequestedDelivery::Foreground
+ } else {
+ RequestedDelivery::Background
+ },
+ )
+ .actual_delivery(if !progress.complete {
+ ActualDelivery::Unknown
+ } else if foreground {
+ ActualDelivery::Foreground
+ } else {
+ ActualDelivery::Background
+ });
+ if progress.acknowledged > 0 {
+ record = record.delivered_count(progress.acknowledged);
+ }
+ let text = if progress.complete {
+ format!(
+ "AT-SPI acknowledged {} scroll action(s); effect remains unverified.",
+ progress.acknowledged
+ )
+ } else {
+ format!("AT-SPI scroll stopped after {} acknowledged action(s): {}. Refresh state before another action.", progress.acknowledged, progress.detail.as_deref().unwrap_or("unknown outcome"))
+ };
+ let record = record
+ .detail(text.clone())
+ .build()
+ .expect("AT-SPI scroll preserves acknowledged progress");
+ let public = serde_json::to_value(record.public_result().unwrap()).unwrap();
+ let result = if progress.complete {
+ ToolResult::text(text)
+ } else {
+ ToolResult::error(text)
+ };
+ result.with_structured(public).with_action_record(record)
+}
+
+#[test]
+fn atspi_scroll_outcomes_preserve_uncertainty_and_acknowledged_count() {
+ use cua_driver_core::action_record::ActionEffect;
+ for (complete, acknowledged, effect) in [
+ (false, 0, ActionEffect::Unverifiable),
+ (false, 1, ActionEffect::Partial),
+ (true, 2, ActionEffect::Unverifiable),
+ ] {
+ let result = atspi_scroll_result(
+ crate::atspi::ScrollProgress {
+ acknowledged,
+ complete,
+ detail: None,
+ },
+ false,
+ );
+ let record = result.action_record.unwrap();
+ assert_eq!(record.effect, effect);
+ let public = serde_json::to_value(record.public_result().unwrap()).unwrap();
+ assert_eq!(
+ public["delivery"]["mode"],
+ if complete { "background" } else { "unknown" }
+ );
+ assert_eq!(
+ public["delivery"]["delivered_count"],
+ if acknowledged == 0 {
+ Value::Null
+ } else {
+ json!(acknowledged)
+ }
+ );
+ }
+}
static SCROLL_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
#[async_trait]
@@ -4566,6 +5666,12 @@ impl Tool for ScrollTool {
Err(e) => return e,
};
let amount = args.u64_or("amount", 3).clamp(1, 50) as usize;
+ let by = match serde_json::from_value::<cua_driver_contract::ScrollBy>(
+ args.get("by").cloned().unwrap_or(json!("line")),
+ ) {
+ Ok(by) => by,
+ Err(error) => return ToolResult::error(format!("Invalid scroll by: {error}")),
+ };
// Surface 6: resolve element_token / element_index. The Linux
// scroll implementation today doesn't actually pre-focus the
// element (X11 scroll buttons go to the window root), but the
@@ -4652,8 +5758,45 @@ impl Tool for ScrollTool {
}
let delivery = crate::input::delivery::DeliveryMode::from_args(&args);
- if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
- return refusal;
+ let isolated_background = isolated_hyprland_background(delivery);
+ if !isolated_background {
+ if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
+ return refusal;
+ }
+ }
+ if hyprland_foreground(delivery) {
+ if xid_opt.is_none() {
+ return foreground_hyprland_refusal(
+ "an exact window_id or window-bound element token is required",
+ );
+ }
+ let point = if let Some(index) = resolved_element_index {
+ match tokio::task::spawn_blocking(move || {
+ resolve_element_local_coords(pid, index, Some(xid))
+ })
+ .await
+ {
+ Ok(Ok((_, x, y))) => Some((x, y)),
+ _ => {
+ return foreground_hyprland_refusal(
+ "could not resolve exact element coordinates",
+ )
+ }
+ }
+ } else {
+ pixel_target
+ };
+ return foreground_hyprland_action(
+ &args,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Scroll {
+ point,
+ direction,
+ amount,
+ },
+ )
+ .await;
}
if let cua_driver_core::element_token::ResolvedElement::Element { element_index, .. } =
&resolved
@@ -4666,27 +5809,64 @@ impl Tool for ScrollTool {
if !(crate::wayland::wayland_input_enabled() && is_webkitgtk_embedder(pid)) {
let direction_for_ax = direction.clone();
let ax_result = tokio::task::spawn_blocking(move || {
- crate::atspi::scroll_element(pid, idx, &direction_for_ax, amount)
+ crate::atspi::scroll_element(pid, idx, &direction_for_ax, amount, by)
})
.await;
- if matches!(ax_result, Ok(Ok(()))) {
- let mode = if delivery.is_foreground() {
- "foreground"
- } else {
- "background"
- };
- return ToolResult::text(format!(
- "Scrolled {direction} {amount} ticks via AT-SPI (delivery_mode:{mode})."
- ))
- .with_structured(json!({
- "path": "atspi",
- "verified": false,
- "delivery_mode": mode
- }));
+ match ax_result {
+ Ok(Ok(progress)) => {
+ return atspi_scroll_result(progress, delivery.is_foreground())
+ }
+ Err(error) => {
+ return atspi_scroll_result(
+ crate::atspi::ScrollProgress {
+ acknowledged: 0,
+ complete: false,
+ detail: Some(error.to_string()),
+ },
+ delivery.is_foreground(),
+ )
+ }
+ Ok(Err(_)) => {}
}
}
}
+ if isolated_background {
+ if xid_opt.is_none() {
+ return isolated_hyprland_refusal(
+ "an exact window_id or window-bound element token is required",
+ );
+ }
+ let owner = named_session_cursor_key(&args);
+ let (_cancellation, dispatch) =
+ match spawn_isolated_hyprland(&args, move |cancellation| {
+ let point = if let Some(idx) = resolved_element_index {
+ let (_, x, y) = resolve_element_local_coords(pid, idx, Some(xid))?;
+ Some((x, y))
+ } else {
+ pixel_target
+ };
+ crate::wayland::hyprland_input::execute(
+ owner,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Scroll {
+ point,
+ direction,
+ amount,
+ },
+ cancellation,
+ )
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(refusal) => return refusal,
+ };
+ return match dispatch.await {
+ Ok(result) => isolated_hyprland_result(result),
+ Err(error) => isolated_hyprland_task_error(error, false),
+ };
+ }
+
if crate::wayland::is_inject_mode() {
let Some((x, y)) = pixel_target else {
return crate::input::delivery::background_unavailable_error(
@@ -4956,6 +6136,17 @@ impl Tool for DoubleClickTool {
if let Some(refusal) = unavailable_wayland_focused_input_background(delivery, true) {
return refusal;
}
+ if hyprland_foreground(delivery) {
+ // Share exact-target validation and the admitted native click lifecycle.
+ let mut args = args;
+ args["button"] = json!("left");
+ args["count"] = json!(2);
+ return ClickTool {
+ state: self.state.clone(),
+ }
+ .invoke(args)
+ .await;
+ }
// Surface 6: element_token / element_index precedence.
let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
@@ -5184,6 +6375,17 @@ impl Tool for RightClickTool {
if let Some(refusal) = unavailable_wayland_focused_input_background(delivery, true) {
return refusal;
}
+ if hyprland_foreground(delivery) {
+ // Share exact-target validation and the admitted native click lifecycle.
+ let mut args = args;
+ args["button"] = json!("right");
+ args["count"] = json!(1);
+ return ClickTool {
+ state: self.state.clone(),
+ }
+ .invoke(args)
+ .await;
+ }
// Surface 6: element_token / element_index precedence.
let resolved = match cua_driver_core::element_token::resolve_element_args_wide(
pid as i32,
@@ -5369,6 +6571,18 @@ static DRAG_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
#[async_trait]
impl Tool for DragTool {
+ fn has_independent_input_lane(&self, args: &Value) -> bool {
+ // This opt-in branch below either uses its own leased synthetic seat
+ // or refuses. It never falls back to primary-seat input. All ordinary
+ // Linux routes retain the common process-wide input coordinator.
+ // Socket availability can change between admission and invocation.
+ // Native Hyprland window drags remain fail-closed on their own lane.
+ args.opt_str("scope").as_deref() != Some("desktop")
+ && !crate::input::delivery::DeliveryMode::from_args(args).is_foreground()
+ && crate::wayland::wayland_input_enabled()
+ && crate::wayland::hyprland::is_session()
+ }
+
fn def(&self) -> &ToolDef {
DRAG_DEF.get_or_init(|| ToolDef {
name: "drag".into(),
@@ -5464,17 +6678,20 @@ impl Tool for DragTool {
None => return ToolResult::error("window_id is required on Linux."),
};
let delivery = crate::input::delivery::DeliveryMode::from_args(&args);
- if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
- return refusal;
- }
- if let Some(refusal) = unavailable_webkit_background(pid, delivery) {
- return refusal;
- }
- if let Some(refusal) = unavailable_gtk_pointer_background(pid, delivery) {
- return refusal;
- }
- if let Some(refusal) = unavailable_wayland_focused_input_background(delivery, true) {
- return refusal;
+ let isolated_background = isolated_hyprland_background(delivery);
+ if !isolated_background {
+ if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
+ return refusal;
+ }
+ if let Some(refusal) = unavailable_webkit_background(pid, delivery) {
+ return refusal;
+ }
+ if let Some(refusal) = unavailable_gtk_pointer_background(pid, delivery) {
+ return refusal;
+ }
+ if let Some(refusal) = unavailable_wayland_focused_input_background(delivery, true) {
+ return refusal;
+ }
}
let coerce = |key: &str| -> Option<f64> {
@@ -5527,6 +6744,129 @@ impl Tool for DragTool {
to_y *= ratio;
}
+ if hyprland_foreground(delivery) {
+ if button_str != "left" || args.get("modifier").is_some_and(|value| !value.is_null()) {
+ return foreground_hyprland_refusal(
+ "foreground drag supports only an unmodified left button",
+ );
+ }
+ if !crate::wayland::hyprland_input::enabled() {
+ return foreground_hyprland_refusal(
+ "production Hyprland input plugin is unavailable",
+ );
+ }
+ let owner = named_session_cursor_key(&args);
+ let from = crate::wayland::window_local_to_output(
+ xid,
+ from_x.round() as i32,
+ from_y.round() as i32,
+ );
+ let to = crate::wayland::window_local_to_output(
+ xid,
+ to_x.round() as i32,
+ to_y.round() as i32,
+ );
+ let (started, acknowledged) = tokio::sync::oneshot::channel();
+ let (_cancellation, mut dispatch) =
+ match spawn_isolated_hyprland(&args, move |cancellation| {
+ crate::wayland::hyprland_input::execute_foreground_with_started(
+ owner,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Drag {
+ from: (from_x, from_y),
+ to: (to_x, to_y),
+ duration_ms,
+ },
+ Some(started),
+ cancellation,
+ )
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(_) => {
+ return foreground_hyprland_refusal(
+ "authenticated admitted lifecycle required",
+ )
+ }
+ };
+ let acknowledged = acknowledged.await.is_ok();
+ let result = if acknowledged {
+ overlay_snap_to_for(&cursor_id, from.0 as f64, from.1 as f64, None);
+ tokio::select! {
+ result = &mut dispatch => result,
+ () = track_overlay_drag_for(cursor_id.clone(), (from.0 as f64, from.1 as f64),
+ (to.0 as f64, to.1 as f64), duration_ms, steps) => dispatch.await,
+ }
+ } else {
+ dispatch.await
+ };
+ return hyprland_input_result(
+ match result {
+ Ok(result) => result,
+ Err(error) => Err(crate::wayland::hyprland_input::unknown_dispatch(
+ error.into(),
+ u32::from(acknowledged),
+ )),
+ },
+ true,
+ );
+ }
+
+ if isolated_background {
+ if button_str != "left" || args.get("modifier").is_some_and(|value| !value.is_null()) {
+ return isolated_hyprland_refusal(
+ "isolated drag supports only an unmodified left button",
+ );
+ }
+ let owner = named_session_cursor_key(&args);
+ let from = crate::wayland::window_local_to_output(
+ xid,
+ from_x.round() as i32,
+ from_y.round() as i32,
+ );
+ let to = crate::wayland::window_local_to_output(
+ xid,
+ to_x.round() as i32,
+ to_y.round() as i32,
+ );
+ let (started, acknowledged) = tokio::sync::oneshot::channel();
+ let (_cancellation, mut dispatch) =
+ match spawn_isolated_hyprland(&args, move |cancellation| {
+ crate::wayland::hyprland_input::execute_with_started(
+ owner,
+ pid,
+ xid,
+ crate::wayland::hyprland_input::Action::Drag {
+ from: (from_x, from_y),
+ to: (to_x, to_y),
+ duration_ms,
+ },
+ Some(started),
+ cancellation,
+ )
+ }) {
+ Ok(dispatch) => dispatch,
+ Err(refusal) => return refusal,
+ };
+ // Do not animate a drag that was refused. The compositor starts
+ // the overlay clock only after accepting and pressing the button.
+ let acknowledged = acknowledged.await.is_ok();
+ if acknowledged {
+ overlay_snap_to_for(&cursor_id, from.0 as f64, from.1 as f64, None);
+ tokio::select! {
+ result = &mut dispatch => {
+ return match result { Ok(result) => isolated_hyprland_result(result), Err(error) => isolated_hyprland_task_error(error, acknowledged) };
+ }
+ () = track_overlay_drag_for(cursor_id.clone(), (from.0 as f64, from.1 as f64),
+ (to.0 as f64, to.1 as f64), duration_ms, steps) => {}
+ }
+ }
+ return match dispatch.await {
+ Ok(result) => isolated_hyprland_result(result),
+ Err(error) => isolated_hyprland_task_error(error, acknowledged),
+ };
+ }
+
crate::overlay::send_command_for(
cursor_id.clone(),
cursor_overlay::OverlayCommand::PinAbove(xid),
@@ -6638,10 +7978,17 @@ impl Tool for GetScreenSizeTool {
return result;
}
let result = tokio::task::spawn_blocking(|| {
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ // Shared manifest admission needs content-free display
+ // metadata even when this native desktop has no X11 DISPLAY.
+ // The adapter attests the IPC/Wayland compositor peer and
+ // refuses layouts outside its qualified 1:1 single-output frame.
+ return crate::wayland::hyprland::screen_size();
+ }
// X11 reports pixel dimensions; scale factor on X11 is not
// well-defined per-monitor, so report 1.0 (matches DPI-unaware
- // assumption). Wayland/HiDPI X11 callers should query
- // `xrandr --query` for true scale.
+ // assumption). Other Wayland compositors retain their existing
+ // limitation; do not infer native metadata support there.
let (w, h) = x11_screen_size()?;
Ok::<(u32, u32, f64), anyhow::Error>((w, h, 1.0))
})
@@ -8179,6 +9526,18 @@ impl Tool for BringToFrontTool {
}
},
};
+ if crate::wayland::wayland_input_enabled() && crate::wayland::hyprland::is_session() {
+ if args.opt_u64("window_id").is_none() {
+ return foreground_hyprland_refusal("an exact window_id is required");
+ }
+ return foreground_hyprland_action(
+ &args,
+ pid,
+ window_id,
+ crate::wayland::hyprland_input::Action::Activate,
+ )
+ .await;
+ }
let result = tokio::task::spawn_blocking(move || {
crate::wayland::activate_window_for_input_target(window_id, Some(pid))
})
@@ -8244,6 +9603,26 @@ pub fn build_registry_with_provider(
provider: Option<std::sync::Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
) -> ToolRegistry {
let state = ToolState::new();
+ let mut r = ToolRegistry::new_with_protected_consent_provider(provider);
+ if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {
+ let recording_state = Arc::downgrade(&state);
+ r.recording
+ .set_pixel_point_fn(move |args, window_id, pid, mut x, mut y| {
+ let state = recording_state.upgrade()?;
+ if let Some(pid) = pid {
+ let pid = u32::try_from(pid).ok()?;
+ // Match ClickTool's screenshot and zoom conversion before
+ // translating to the recording's full-output image.
+ if args.bool_or("from_zoom", false) {
+ (x, y) = state.zoom_registry.get(pid)?.zoom_to_window(x, y);
+ } else if let Some(ratio) = state.resize_registry.ratio(pid) {
+ x *= ratio;
+ y *= ratio;
+ }
+ }
+ crate::recording_hooks::hyprland_pixel_recording_point(window_id, pid, x, y)
+ });
+ }
let cursor_outcome_reader = {
let cursor_registry = state.cursor_registry.clone();
cua_driver_core::session::register_scoped_cursor_outcome_reader(std::sync::Arc::new(
@@ -8291,13 +9670,13 @@ pub fn build_registry_with_provider(
.unwrap()
.remove(session_id);
crate::input::forget_master_pointer(session_id);
+ crate::wayland::hyprland_input::cleanup_session(session_id);
})
};
let session_revive_hook =
cua_driver_core::session::register_scoped_session_revive_hook(move |session_id| {
crate::overlay::revive_cursor(session_id.to_owned());
});
- let mut r = ToolRegistry::new_with_protected_consent_provider(provider);
r.retain_cursor_outcome_reader(cursor_outcome_reader);
r.retain_session_end_hook(session_end_hook);
r.retain_session_revive_hook(session_revive_hook);
@@ -8305,6 +9684,7 @@ pub fn build_registry_with_provider(
let prefix = format!("__cua_runtime_{runtime_scope}:");
let cursor_registry = state.cursor_registry.clone();
r.retain_runtime_cleanup(move || {
+ crate::wayland::hyprland_input::cleanup_runtime(&prefix);
for cursor in cursor_registry
.all_states()
.into_iter()
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
index d92df0bab4..e1bbb6ae7c 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland.rs
@@ -6,13 +6,16 @@
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::collections::HashSet;
-use std::io::{Read, Write};
+use std::io::{self, Read, Write};
use std::os::fd::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::time::{Duration, Instant};
const QUERY_TIMEOUT: Duration = Duration::from_secs(1);
+const QUERY_TOTAL_TIMEOUT: Duration = Duration::from_secs(3);
+const QUERY_RETRY_BACKOFF: Duration = Duration::from_millis(50);
+const QUERY_MAX_ATTEMPTS: usize = 2;
const MAX_REPLY_BYTES: usize = 4 * 1024 * 1024;
const MAX_LOGICAL_PIXELS: u64 = 64 * 1024 * 1024;
@@ -42,6 +45,16 @@ struct Monitor {
special_workspace: Workspace,
}
+#[derive(Clone, Debug, Deserialize)]
+struct DisplayMonitor {
+ width: u32,
+ height: u32,
+ scale: f64,
+ x: i32,
+ y: i32,
+ transform: u32,
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Window {
pub address: u64,
@@ -103,8 +116,12 @@ pub(super) fn peer_pid(fd: RawFd) -> Result<libc::pid_t> {
}
fn ipc_connection() -> Result<UnixStream> {
+ ipc_connection_with_timeout(QUERY_TIMEOUT)
+}
+
+fn ipc_connection_with_timeout(timeout: Duration) -> Result<UnixStream> {
let socket = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None)?;
- socket.connect_timeout(&socket2::SockAddr::unix(ipc_path()?)?, QUERY_TIMEOUT)?;
+ socket.connect_timeout(&socket2::SockAddr::unix(ipc_path()?)?, timeout)?;
Ok(socket.into())
}
@@ -112,6 +129,10 @@ fn ipc_connection() -> Result<UnixStream> {
/// WAYLAND_SOCKET descriptors are deliberately unsupported here: this adapter
/// opens independent, attested connections for each observation.
pub(super) fn wayland_connection() -> Result<wayland_client::Connection> {
+ wayland_connection_with_timeout(QUERY_TIMEOUT)
+}
+
+fn wayland_connection_with_timeout(timeout: Duration) -> Result<wayland_client::Connection> {
if std::env::var_os("WAYLAND_SOCKET").is_some() {
bail!("Hyprland observation requires a named WAYLAND_DISPLAY socket");
}
@@ -131,7 +152,7 @@ pub(super) fn wayland_connection() -> Result<wayland_client::Connection> {
runtime.join(display)
};
let socket = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None)?;
- socket.connect_timeout(&socket2::SockAddr::unix(path)?, QUERY_TIMEOUT)?;
+ socket.connect_timeout(&socket2::SockAddr::unix(path)?, timeout)?;
wayland_client::Connection::from_socket(socket.into()).context("Wayland connection failed")
}
@@ -145,15 +166,93 @@ pub(super) fn verify_capture_peer(connection: &wayland_client::Connection) -> Re
}
fn query<T: serde::de::DeserializeOwned>(command: &str) -> Result<T> {
- let mut ipc = ipc_connection()?;
- // A stale inherited instance signature must not supply geometry for a
- // different nested Wayland desktop. No protocol roundtrip is needed.
- let wayland = wayland_connection()?;
- if peer_pid(ipc.as_raw_fd())? != peer_pid(wayland.backend().poll_fd().as_raw_fd())? {
- bail!("Hyprland IPC and WAYLAND_DISPLAY name different compositor processes");
+ let mut expected_peer = None;
+ query_with(
+ command,
+ QUERY_TIMEOUT,
+ QUERY_TOTAL_TIMEOUT,
+ QUERY_RETRY_BACKOFF,
+ |deadline| {
+ let ipc = ipc_connection_with_timeout(query_time_remaining(deadline)?)?;
+ // A stale inherited instance signature must not supply geometry for
+ // a different nested desktop. Re-attest both sockets on every try.
+ let wayland = wayland_connection_with_timeout(query_time_remaining(deadline)?)?;
+ let peer = peer_pid(ipc.as_raw_fd())?;
+ if peer != peer_pid(wayland.backend().poll_fd().as_raw_fd())? {
+ bail!("Hyprland IPC and WAYLAND_DISPLAY name different compositor processes");
+ }
+ if expected_peer.is_some_and(|expected| expected != peer) {
+ bail!("Hyprland compositor changed during observation retry");
+ }
+ expected_peer = Some(peer);
+ Ok(ipc)
+ },
+ )
+}
+
+fn query_time_remaining(deadline: Instant) -> Result<Duration> {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return Err(io::Error::new(io::ErrorKind::TimedOut, "Hyprland IPC query timed out").into());
}
- let reply = read_reply(&mut ipc, command.as_bytes(), QUERY_TIMEOUT)?;
- serde_json::from_slice(&reply).context("invalid Hyprland IPC JSON")
+ Ok(remaining)
+}
+
+fn is_query_timeout(error: &anyhow::Error) -> bool {
+ error.downcast_ref::<io::Error>().is_some_and(|error| {
+ matches!(
+ error.kind(),
+ io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
+ )
+ })
+}
+
+/// Retry only a timed-out observation, never an action or an identity failure.
+/// Each attempt discards all previous bytes and opens newly attested sockets.
+fn query_with<T: serde::de::DeserializeOwned>(
+ command: &str,
+ per_attempt: Duration,
+ total: Duration,
+ backoff: Duration,
+ mut connect: impl FnMut(Instant) -> Result<UnixStream>,
+) -> Result<T> {
+ let deadline = Instant::now() + total;
+ // Keep this a closed list: a generic "j/" prefix also admits JSON-formatted
+ // dispatch commands. JSON output does not imply a read-only operation.
+ let read_only = matches!(command, "j/monitors" | "j/clients" | "j/activewindow");
+ for attempt in 1..=QUERY_MAX_ATTEMPTS {
+ query_time_remaining(deadline)?;
+ let attempt_deadline = deadline.min(Instant::now() + per_attempt);
+ // Connection and peer-attestation errors are permanent. Only read-only
+ // request/reply timeouts below are eligible for a new query.
+ let mut ipc = connect(attempt_deadline)?;
+ let reply = query_time_remaining(attempt_deadline)
+ .and_then(|remaining| read_reply(&mut ipc, command.as_bytes(), remaining));
+ match reply {
+ Ok(bytes) => {
+ return serde_json::from_slice(&bytes).context("invalid Hyprland IPC JSON")
+ }
+ Err(error) => {
+ if !read_only
+ || !is_query_timeout(&error)
+ || attempt == QUERY_MAX_ATTEMPTS
+ || deadline.saturating_duration_since(Instant::now()) <= backoff
+ {
+ return Err(error).with_context(|| {
+ format!("Hyprland IPC observation failed after {attempt} attempt(s)")
+ });
+ }
+ drop(ipc);
+ tracing::warn!(
+ command,
+ attempt,
+ "Hyprland IPC observation timed out; retrying on a fresh connection"
+ );
+ std::thread::sleep(backoff);
+ }
+ }
+ }
+ unreachable!("the final query attempt always returns")
}
fn read_reply(stream: &mut UnixStream, command: &[u8], timeout: Duration) -> Result<Vec<u8>> {
@@ -163,10 +262,7 @@ fn read_reply(stream: &mut UnixStream, command: &[u8], timeout: Duration) -> Res
let mut reply = Vec::new();
let mut chunk = [0u8; 8192];
loop {
- let remaining = deadline.saturating_duration_since(Instant::now());
- if remaining.is_zero() {
- bail!("Hyprland IPC query timed out");
- }
+ let remaining = query_time_remaining(deadline)?;
stream.set_read_timeout(Some(remaining))?;
let count = stream
.read(&mut chunk)
@@ -214,6 +310,26 @@ fn valid_dimensions(width: u32, height: u32) -> bool {
width > 0 && height > 0 && u64::from(width) * u64::from(height) <= MAX_LOGICAL_PIXELS
}
+/// Content-free geometry for the qualified single-output, 1:1 desktop.
+/// The common policy adapter uses this for display-scoped observation. Never
+/// substitute a screenshot, XWayland root, or guessed primary monitor here.
+pub fn screen_size() -> Result<(u32, u32, f64)> {
+ screen_size_from_monitors(query("j/monitors")?)
+}
+
+fn screen_size_from_monitors(monitors: Vec<DisplayMonitor>) -> Result<(u32, u32, f64)> {
+ let [monitor] = monitors.as_slice() else {
+ bail!("Hyprland display identity requires exactly one active output");
+ };
+ if monitor.scale != 1.0 || monitor.transform != 0 || monitor.x != 0 || monitor.y != 0 {
+ bail!("Hyprland display identity requires an unscaled, unrotated output at the origin");
+ }
+ if !valid_dimensions(monitor.width, monitor.height) {
+ bail!("invalid Hyprland display dimensions");
+ }
+ Ok((monitor.width, monitor.height, monitor.scale))
+}
+
pub fn list_windows() -> Result<Vec<Window>> {
let monitors: Vec<Monitor> = query("j/monitors")?;
let active = monitors
@@ -381,10 +497,298 @@ mod tests {
assert!(start.elapsed() < Duration::from_secs(1));
}
+ fn replying_ipc(bytes: Vec<u8>, delay: Duration) -> UnixStream {
+ let (client, mut server) = UnixStream::pair().unwrap();
+ std::thread::spawn(move || {
+ server
+ .set_read_timeout(Some(Duration::from_secs(1)))
+ .unwrap();
+ let mut request = [0; 128];
+ assert!(server.read(&mut request).unwrap() > 0);
+ std::thread::sleep(delay);
+ // An oversized reply may be rejected before the writer finishes.
+ let _ = server.write_all(&bytes);
+ });
+ client
+ }
+
+ #[test]
+ fn timed_out_observation_uses_fresh_connection_and_discards_partial_bytes() {
+ let mut attempts = 0;
+ let mut stalled = Vec::new();
+ let value: serde_json::Value = query_with(
+ "j/clients",
+ Duration::from_millis(30),
+ Duration::from_secs(1),
+ Duration::from_millis(1),
+ |_| {
+ attempts += 1;
+ if attempts == 1 {
+ let (client, mut server) = UnixStream::pair()?;
+ server.write_all(b"{\"stale\":")?;
+ stalled.push(server);
+ Ok(client)
+ } else {
+ Ok(replying_ipc(b"[]".to_vec(), Duration::ZERO))
+ }
+ },
+ )
+ .unwrap();
+ assert_eq!(value, serde_json::json!([]));
+ assert_eq!(attempts, 2);
+ }
+
+ #[test]
+ fn healthy_slow_observation_is_not_retried() {
+ let mut attempts = 0;
+ let value: serde_json::Value = query_with(
+ "j/monitors",
+ Duration::from_secs(1),
+ Duration::from_secs(2),
+ Duration::from_millis(1),
+ |_| {
+ attempts += 1;
+ Ok(replying_ipc(b"[]".to_vec(), Duration::from_millis(30)))
+ },
+ )
+ .unwrap();
+ assert_eq!(value, serde_json::json!([]));
+ assert_eq!(attempts, 1);
+ }
+
+ #[test]
+ fn observation_connection_and_attestation_errors_are_not_retried() {
+ for timeout in [false, true] {
+ let mut attempts = 0;
+ let error = query_with::<serde_json::Value>(
+ "j/clients",
+ QUERY_TIMEOUT,
+ QUERY_TOTAL_TIMEOUT,
+ QUERY_RETRY_BACKOFF,
+ |_| {
+ attempts += 1;
+ if timeout {
+ return Err(io::Error::from(io::ErrorKind::TimedOut).into());
+ }
+ bail!("could not verify same-user compositor peer");
+ },
+ )
+ .unwrap_err();
+ assert_eq!(attempts, 1);
+ assert!(timeout || error.to_string().contains("same-user compositor peer"));
+ }
+ }
+
+ #[test]
+ fn observation_retry_must_pass_fresh_attestation() {
+ let mut attempts = 0;
+ let mut stalled = Vec::new();
+ let error = query_with::<serde_json::Value>(
+ "j/activewindow",
+ Duration::from_millis(30),
+ Duration::from_secs(1),
+ Duration::from_millis(1),
+ |_| {
+ attempts += 1;
+ if attempts == 2 {
+ bail!("Hyprland compositor changed during observation retry");
+ }
+ let (client, server) = UnixStream::pair()?;
+ stalled.push(server);
+ Ok(client)
+ },
+ )
+ .unwrap_err();
+ assert_eq!(attempts, 2);
+ assert!(error.to_string().contains("compositor changed"));
+ }
+
+ #[test]
+ fn malformed_truncated_and_oversized_observations_are_not_retried() {
+ for bytes in [
+ b"invalid".to_vec(),
+ b"{\"pid\"".to_vec(),
+ vec![b' '; MAX_REPLY_BYTES + 1],
+ ] {
+ let mut attempts = 0;
+ assert!(query_with::<serde_json::Value>(
+ "j/clients",
+ QUERY_TIMEOUT,
+ QUERY_TOTAL_TIMEOUT,
+ QUERY_RETRY_BACKOFF,
+ |_| {
+ attempts += 1;
+ Ok(replying_ipc(bytes.clone(), Duration::ZERO))
+ },
+ )
+ .is_err());
+ assert_eq!(attempts, 1);
+ }
+ }
+
+ #[test]
+ fn observation_total_deadline_includes_connect_and_read() {
+ let mut attempts = 0;
+ let mut stalled = Vec::new();
+ let start = Instant::now();
+ let error = query_with::<serde_json::Value>(
+ "j/clients",
+ Duration::from_millis(80),
+ Duration::from_millis(110),
+ Duration::from_millis(1),
+ |deadline| {
+ attempts += 1;
+ assert!(
+ deadline.saturating_duration_since(Instant::now()) <= Duration::from_millis(80)
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ let (client, server) = UnixStream::pair()?;
+ stalled.push(server);
+ Ok(client)
+ },
+ )
+ .unwrap_err();
+ assert!(is_query_timeout(&error));
+ assert!(attempts <= QUERY_MAX_ATTEMPTS);
+ assert!(start.elapsed() < Duration::from_secs(1));
+ }
+
+ #[test]
+ fn observation_attempt_cap_applies_with_a_generous_total_budget() {
+ let mut attempts = 0;
+ let mut stalled = Vec::new();
+ let error = query_with::<serde_json::Value>(
+ "j/clients",
+ Duration::from_millis(30),
+ Duration::from_secs(10),
+ Duration::from_millis(1),
+ |_| {
+ attempts += 1;
+ let (client, server) = UnixStream::pair()?;
+ stalled.push(server);
+ Ok(client)
+ },
+ )
+ .unwrap_err();
+ assert!(is_query_timeout(&error));
+ assert_eq!(attempts, 2);
+ }
+
+ #[test]
+ fn observation_never_writes_after_connect_consumes_total_deadline() {
+ let (client, mut server) = UnixStream::pair().unwrap();
+ let mut client = Some(client);
+ let mut attempts = 0;
+ let error = query_with::<serde_json::Value>(
+ "j/clients",
+ Duration::from_millis(10),
+ Duration::from_millis(10),
+ Duration::from_millis(1),
+ |_| {
+ attempts += 1;
+ std::thread::sleep(Duration::from_millis(30));
+ Ok(client.take().unwrap())
+ },
+ )
+ .unwrap_err();
+ assert!(is_query_timeout(&error));
+ assert_eq!(attempts, 1);
+ // The client was dropped without sending a request: EOF, not bytes.
+ assert_eq!(server.read(&mut [0; 64]).unwrap(), 0);
+ }
+
+ #[test]
+ fn input_and_unknown_json_commands_are_never_retried() {
+ for command in ["dispatch nop", "j/dispatch nop", "j/unknown"] {
+ let mut attempts = 0;
+ let mut stalled = Vec::new();
+ assert!(query_with::<serde_json::Value>(
+ command,
+ Duration::from_millis(30),
+ Duration::from_secs(1),
+ Duration::from_millis(1),
+ |_| {
+ attempts += 1;
+ let (client, server) = UnixStream::pair()?;
+ stalled.push(server);
+ Ok(client)
+ },
+ )
+ .is_err());
+ assert_eq!(attempts, 1);
+ }
+ }
+
+ #[test]
+ fn observation_timeout_classifier_is_closed() {
+ for (kind, expected) in [
+ (io::ErrorKind::WouldBlock, true),
+ (io::ErrorKind::TimedOut, true),
+ (io::ErrorKind::ConnectionRefused, false),
+ (io::ErrorKind::ConnectionReset, false),
+ (io::ErrorKind::Interrupted, false),
+ (io::ErrorKind::UnexpectedEof, false),
+ (io::ErrorKind::PermissionDenied, false),
+ (io::ErrorKind::InvalidData, false),
+ ] {
+ let error = anyhow::Error::from(io::Error::from(kind)).context("query");
+ assert_eq!(is_query_timeout(&error), expected);
+ }
+ assert!(!is_query_timeout(&anyhow::anyhow!("identity unproven")));
+ assert!(is_query_timeout(
+ &query_time_remaining(Instant::now()).unwrap_err()
+ ));
+ }
+
#[test]
fn logical_resize_is_bounded_before_allocation() {
assert!(valid_dimensions(3840, 2160));
assert!(!valid_dimensions(0, 1));
assert!(!valid_dimensions(u32::MAX, u32::MAX));
}
+
+ fn display_monitor() -> DisplayMonitor {
+ serde_json::from_value(serde_json::json!({
+ "width": 1920, "height": 1080, "scale": 1.0,
+ "x": 0, "y": 0, "transform": 0,
+ }))
+ .unwrap()
+ }
+
+ #[test]
+ fn display_identity_accepts_qualified_native_geometry() {
+ assert_eq!(
+ screen_size_from_monitors(vec![display_monitor()]).unwrap(),
+ (1920, 1080, 1.0)
+ );
+ }
+
+ #[test]
+ fn display_identity_rejects_ambiguous_outputs_and_unsupported_frames() {
+ assert!(screen_size_from_monitors(vec![]).is_err());
+ assert!(screen_size_from_monitors(vec![display_monitor(), display_monitor()]).is_err());
+ for scale in [0.0, 1.25, 2.0, f64::NAN, f64::INFINITY] {
+ let mut monitor = display_monitor();
+ monitor.scale = scale;
+ assert!(screen_size_from_monitors(vec![monitor]).is_err());
+ }
+ for (x, y, transform) in [(100, 0, 0), (0, -100, 0), (0, 0, 1), (0, 0, 7)] {
+ let mut monitor = display_monitor();
+ (monitor.x, monitor.y, monitor.transform) = (x, y, transform);
+ assert!(screen_size_from_monitors(vec![monitor]).is_err());
+ }
+ }
+
+ #[test]
+ fn display_identity_rejects_empty_oversized_and_missing_geometry() {
+ for (width, height) in [(0, 1080), (1920, 0), (u32::MAX, u32::MAX)] {
+ let mut monitor = display_monitor();
+ (monitor.width, monitor.height) = (width, height);
+ assert!(screen_size_from_monitors(vec![monitor]).is_err());
+ }
+ let value = serde_json::json!({
+ "width": 1920, "height": 1080, "scale": 1.0, "x": 0, "y": 0,
+ });
+ assert!(serde_json::from_value::<DisplayMonitor>(value).is_err());
+ }
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_compatibility.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_compatibility.rs
new file mode 100644
index 0000000000..5d14aeb27a
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_compatibility.rs
@@ -0,0 +1,100 @@
+//! Compatibility admission for the initial native Hyprland input package.
+//! This is not a security boundary against same-user code. Unknown package
+//! versions refuse until the native operation matrix is qualified for them.
+
+use std::io::Read;
+use std::path::{Path, PathBuf};
+
+struct QualifiedPackage {
+ name: &'static str,
+ version: &'static str,
+ executable: &'static str,
+}
+
+const PACKAGES: &[QualifiedPackage] = &[
+ QualifiedPackage {
+ name: "libreoffice-fresh",
+ version: "26.2.5-3",
+ executable: "/usr/lib/libreoffice/program/soffice.bin",
+ },
+ QualifiedPackage {
+ name: "inkscape",
+ version: "1.4.4-6",
+ executable: "/usr/bin/inkscape",
+ },
+];
+
+fn field<'a>(description: &'a str, name: &str) -> Option<&'a str> {
+ let mut lines = description.lines();
+ while let Some(line) = lines.next() {
+ if line == name {
+ return lines.next().filter(|value| !value.is_empty());
+ }
+ }
+ None
+}
+
+fn read_bounded(path: &Path) -> Result<String, &'static str> {
+ let file = std::fs::File::open(path).map_err(|_| "client_qualification_unavailable")?;
+ let mut content = String::new();
+ file.take(1024 * 1024 + 1)
+ .read_to_string(&mut content)
+ .map_err(|_| "client_qualification_unavailable")?;
+ if content.len() > 1024 * 1024 {
+ return Err("client_qualification_unavailable");
+ }
+ Ok(content)
+}
+
+pub(super) fn qualify(pid: u32) -> Result<(), &'static str> {
+ let process_exe = PathBuf::from(format!("/proc/{pid}/exe"));
+ let executable =
+ std::fs::read_link(&process_exe).map_err(|_| "client_qualification_unavailable")?;
+ let package = PACKAGES
+ .iter()
+ .find(|package| {
+ std::fs::canonicalize(package.executable).ok().as_ref() == Some(&executable)
+ })
+ .ok_or("client_not_qualified")?;
+ let directory = PathBuf::from("/var/lib/pacman/local")
+ .join(format!("{}-{}", package.name, package.version));
+ let description = read_bounded(&directory.join("desc"))?;
+ if field(&description, "%NAME%") != Some(package.name)
+ || field(&description, "%VERSION%") != Some(package.version)
+ {
+ return Err("client_not_qualified");
+ }
+ let files = read_bounded(&directory.join("files"))?;
+ if !files
+ .lines()
+ .any(|line| line == package.executable.trim_start_matches('/'))
+ {
+ return Err("client_not_qualified");
+ }
+ // Detect replacement between initial identification and admission. The
+ // compositor independently verifies its exact live target at dispatch.
+ if std::fs::read_link(process_exe).ok().as_ref() != Some(&executable) {
+ return Err("client_qualification_unavailable");
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn alpm_identity_requires_exact_package_and_version_fields() {
+ let description = "%NAME%\ninkscape\n\n%VERSION%\n1.4.4-6\n\n";
+ assert_eq!(field(description, "%NAME%"), Some("inkscape"));
+ assert_eq!(field(description, "%VERSION%"), Some("1.4.4-6"));
+ assert_eq!(field("%VERSION%\n", "%VERSION%"), None);
+ assert_eq!(field("%VERSION%\n\n", "%VERSION%"), None);
+ assert_eq!(field("prefix%NAME%\ninkscape", "%NAME%"), None);
+ }
+
+ #[test]
+ fn nonexistent_process_cannot_be_qualified() {
+ assert!(qualify(u32::MAX).is_err());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rs
new file mode 100644
index 0000000000..1ae47d7139
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rs
@@ -0,0 +1,2910 @@
+//! Local Hyprland input after the common Driver registry admits the action.
+//! Production v3 uses per-action target binding, not a second approval system.
+//! Protocol 0 remains an explicitly selected, nonshipping test experiment.
+
+use std::collections::HashMap;
+use std::os::fd::AsRawFd;
+use std::os::unix::fs::{FileTypeExt, MetadataExt};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, MutexGuard, OnceLock, TryLockError};
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, ensure, Context, Result};
+use serde_json::{json, Value};
+
+const TIMEOUT: Duration = Duration::from_secs(3);
+const CANCELLATION_POLL: Duration = Duration::from_millis(25);
+const MAX_PACKET: usize = 2048;
+const MAX_LANES: usize = 2;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum DeliveryRoute {
+ Background,
+ Foreground,
+}
+
+impl DeliveryRoute {
+ fn mode(self) -> &'static str {
+ match self {
+ Self::Background => "background",
+ Self::Foreground => "foreground",
+ }
+ }
+
+ fn acknowledgement(self) -> &'static str {
+ match self {
+ Self::Background => "synthetic_events",
+ Self::Foreground => "primary_foreground",
+ }
+ }
+}
+
+fn validate_target_route(target: &Value, route: DeliveryRoute) -> Result<()> {
+ if route == DeliveryRoute::Foreground {
+ ensure!(
+ target["route"] == "primary_foreground",
+ "foreground target route mismatch"
+ );
+ }
+ Ok(())
+}
+
+/// Validate the whole string before dispatching any keys. Physical key delivery
+/// uses the compositor's keyboard layout; these codes describe US ASCII keys.
+pub(crate) fn foreground_text_actions(text: &str) -> Result<Vec<Action>> {
+ ensure!(
+ text.len() <= 4096 && text.is_ascii(),
+ "foreground text requires at most 4096 ASCII bytes"
+ );
+ text.bytes()
+ .map(|byte| {
+ let (keycode, shift) = match byte {
+ b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => (
+ super::key_to_evdev(&(byte as char).to_string())
+ .context("unsupported text key")?,
+ byte.is_ascii_uppercase(),
+ ),
+ b' ' => (57, false),
+ b'\t' => (15, false),
+ b'\n' => (28, false),
+ b'-' => (12, false),
+ b'_' => (12, true),
+ b'=' => (13, false),
+ b'+' => (13, true),
+ b'[' => (26, false),
+ b'{' => (26, true),
+ b']' => (27, false),
+ b'}' => (27, true),
+ b';' => (39, false),
+ b':' => (39, true),
+ b'\'' => (40, false),
+ b'"' => (40, true),
+ b'`' => (41, false),
+ b'~' => (41, true),
+ b'\\' => (43, false),
+ b'|' => (43, true),
+ b',' => (51, false),
+ b'<' => (51, true),
+ b'.' => (52, false),
+ b'>' => (52, true),
+ b'/' => (53, false),
+ b'?' => (53, true),
+ b'!' => (2, true),
+ b'@' => (3, true),
+ b'#' => (4, true),
+ b'$' => (5, true),
+ b'%' => (6, true),
+ b'^' => (7, true),
+ b'&' => (8, true),
+ b'*' => (9, true),
+ b'(' => (10, true),
+ b')' => (11, true),
+ _ => bail!("unsupported foreground text control character"),
+ };
+ Ok(Action::TextKey { keycode, shift })
+ })
+ .collect()
+}
+
+/// Cancellation belongs to one invocation, never to its session's next call.
+#[derive(Clone, Default)]
+pub(crate) struct ActionCancellation(Arc<AtomicBool>);
+
+pub(crate) struct CancelOnDrop(ActionCancellation);
+
+impl ActionCancellation {
+ pub(crate) fn invocation() -> (CancelOnDrop, Self) {
+ let cancellation = Self::default();
+ (CancelOnDrop(cancellation.clone()), cancellation)
+ }
+
+ fn check(&self) -> Result<()> {
+ if self.0.load(Ordering::Acquire) {
+ return Err(ActionCancelled.into());
+ }
+ Ok(())
+ }
+}
+
+impl Drop for CancelOnDrop {
+ fn drop(&mut self) {
+ self.0 .0.store(true, Ordering::Release);
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct ActionCancelled;
+
+impl std::fmt::Display for ActionCancelled {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("Hyprland input invocation cancelled")
+ }
+}
+
+impl std::error::Error for ActionCancelled {}
+
+/// Both reservations are explicitly occupied; no target or action was sent.
+#[derive(Debug)]
+pub(crate) struct LaneBusy;
+
+impl std::fmt::Display for LaneBusy {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("both isolated input lanes are in use; end an owning session first")
+ }
+}
+
+impl std::error::Error for LaneBusy {}
+
+/// A sent action has no trustworthy final reply. The count describes only
+/// acknowledged gesture phases (drag start or completed text keys), never a
+/// total event count or proof that no later events landed.
+#[derive(Debug)]
+pub struct DispatchUnknown {
+ pub acknowledged_phases: u32,
+ detail: String,
+}
+
+impl std::fmt::Display for DispatchUnknown {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}; final input delivery is unknown", self.detail)
+ }
+}
+
+impl std::error::Error for DispatchUnknown {}
+
+pub(crate) fn unknown_dispatch(error: anyhow::Error, acknowledged_phases: u32) -> anyhow::Error {
+ DispatchUnknown {
+ acknowledged_phases,
+ detail: error.to_string(),
+ }
+ .into()
+}
+
+pub fn enabled() -> bool {
+ super::wayland_input_enabled()
+ && super::hyprland::is_session()
+ && (protocol() == InputProtocol::Experiment
+ || (0..MAX_LANES).any(|lane| {
+ socket_path(lane).ok().is_some_and(|path| {
+ std::fs::symlink_metadata(path)
+ .ok()
+ .is_some_and(|metadata| {
+ metadata.file_type().is_socket()
+ && metadata.uid() == unsafe { libc::geteuid() }
+ })
+ })
+ }))
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum InputProtocol {
+ Production,
+ Experiment,
+}
+
+fn protocol() -> InputProtocol {
+ if std::env::var("CUA_DRIVER_EXPERIMENTAL_HYPRLAND_INPUT").as_deref() == Ok("1") {
+ InputProtocol::Experiment
+ } else {
+ InputProtocol::Production
+ }
+}
+
+impl InputProtocol {
+ fn version(self) -> u64 {
+ match self {
+ Self::Production => 3,
+ Self::Experiment => 0,
+ }
+ }
+
+ fn socket_name(self, lane: usize) -> Result<&'static str> {
+ Ok(match (self, lane) {
+ (Self::Production, 0) => "cua-input-v3.sock",
+ (Self::Production, 1) => "cua-input-v3-2.sock",
+ (Self::Experiment, 0) => "cua-input-test.sock",
+ (Self::Experiment, 1) => "cua-input-test-2.sock",
+ _ => bail!("invalid isolated input lane"),
+ })
+ }
+}
+
+/// Coordinates are window-local logical units. Hyprland's existing capture()
+/// normalizes physical buffers to logical dimensions; tool routes undo only
+/// the later preview resize (or zoom), so no additional scale division belongs
+/// here. TARGET bounds and revision remain authoritative at dispatch.
+pub enum Action {
+ Activate,
+ TextKey {
+ keycode: u32,
+ shift: bool,
+ },
+ Click {
+ x: f64,
+ y: f64,
+ button: u32,
+ count: usize,
+ },
+ Key {
+ key: String,
+ modifiers: Vec<String>,
+ },
+ Scroll {
+ point: Option<(f64, f64)>,
+ direction: String,
+ amount: usize,
+ },
+ Drag {
+ from: (f64, f64),
+ to: (f64, f64),
+ duration_ms: u64,
+ },
+}
+
+struct Client {
+ socket: socket2::Socket,
+ cancellation: ActionCancellation,
+ protocol: InputProtocol,
+ foreground_supported: bool,
+ delivery_route: Option<DeliveryRoute>,
+ // Assigned by the compositor to this connection, never by the local pool.
+ lane: Option<usize>,
+ owner: String,
+ path: PathBuf,
+ pid: u32,
+ address: u64,
+ epoch: String,
+ challenge: String,
+ sequence: u64,
+}
+
+fn socket_path(lane: usize) -> Result<PathBuf> {
+ let runtime =
+ PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR").context("missing XDG_RUNTIME_DIR")?);
+ let signature =
+ std::env::var("HYPRLAND_INSTANCE_SIGNATURE").context("missing Hyprland instance")?;
+ ensure!(runtime.is_absolute(), "XDG_RUNTIME_DIR must be absolute");
+ ensure!(
+ !signature.is_empty()
+ && signature
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
+ && signature != "."
+ && signature != "..",
+ "invalid Hyprland instance"
+ );
+ Ok(runtime
+ .join("hypr")
+ .join(signature)
+ .join(protocol().socket_name(lane)?))
+}
+
+fn hex_field(value: &Value, name: &str) -> Result<String> {
+ let field = value[name].as_str().context("missing protocol hex field")?;
+ ensure!(
+ field.len() == 32
+ && field
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
+ "invalid {name}"
+ );
+ Ok(field.to_owned())
+}
+
+fn validate_reply(value: &Value) -> Result<()> {
+ match value["ok"].as_bool() {
+ Some(true) => Ok(()),
+ Some(false) => {
+ ensure!(
+ value["code"].as_str().is_some() && value["detail"].as_str().is_some(),
+ "malformed refusal"
+ );
+ Ok(())
+ }
+ None => bail!("missing protocol result"),
+ }
+}
+
+fn wait(
+ socket: &socket2::Socket,
+ owner: &str,
+ cancellation: &ActionCancellation,
+ events: i16,
+ deadline: Instant,
+) -> Result<()> {
+ loop {
+ cancellation.check()?;
+ ensure!(
+ !cua_driver_core::session::is_session_ending(owner),
+ "Hyprland input session ending; dispatch effect is unknown"
+ );
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ ensure!(
+ !remaining.is_zero(),
+ "Hyprland input timeout; dispatch effect is unknown"
+ );
+ let mut fd = libc::pollfd {
+ fd: socket.as_raw_fd(),
+ events,
+ revents: 0,
+ };
+ let interval = remaining.min(CANCELLATION_POLL);
+ let result = unsafe { libc::poll(&mut fd, 1, interval.as_millis().max(1) as i32) };
+ if result < 0 {
+ let error = std::io::Error::last_os_error();
+ if error.kind() == std::io::ErrorKind::Interrupted {
+ continue;
+ }
+ return Err(error.into());
+ }
+ if result == 0 {
+ continue;
+ }
+ cancellation.check()?;
+ ensure!(
+ !cua_driver_core::session::is_session_ending(owner),
+ "Hyprland input session ending; dispatch effect is unknown"
+ );
+ ensure!(
+ fd.revents & (libc::POLLERR | libc::POLLNVAL) == 0,
+ "Hyprland input connection failed"
+ );
+ ensure!(fd.revents & events != 0, "Hyprland input disconnected");
+ return Ok(());
+ }
+}
+
+impl Client {
+ fn peer_closed(&self) -> bool {
+ let mut fd = libc::pollfd {
+ fd: self.socket.as_raw_fd(),
+ events: libc::POLLRDHUP,
+ revents: 0,
+ };
+ // A zero-length SEQPACKET is valid, so recv/peek returning zero is
+ // not proof of EOF. Poll only for hangup, without reading any queued
+ // replies or waiting while the pool mutex is held. Uncertain results
+ // (including an interrupted poll) keep the existing reservation.
+ let result = unsafe { libc::poll(&mut fd, 1, 0) };
+ result > 0 && fd.revents & (libc::POLLHUP | libc::POLLRDHUP) != 0
+ }
+
+ fn attest(&self) -> Result<()> {
+ let wayland = super::hyprland::wayland_connection()?;
+ super::hyprland::verify_capture_peer(&wayland)?;
+ ensure!(
+ super::hyprland::peer_pid(self.socket.as_raw_fd())?
+ == super::hyprland::peer_pid(wayland.backend().poll_fd().as_raw_fd())?,
+ "input plugin and Wayland name different compositor processes"
+ );
+ Ok(())
+ }
+
+ fn connect(
+ path: PathBuf,
+ owner: String,
+ pid: u32,
+ address: u64,
+ lane: usize,
+ cancellation: ActionCancellation,
+ ) -> Result<Option<Self>> {
+ cancellation.check()?;
+ let socket = socket2::Socket::new(
+ socket2::Domain::UNIX,
+ socket2::Type::from(libc::SOCK_SEQPACKET),
+ None,
+ )?;
+ socket.connect_timeout(&socket2::SockAddr::unix(&path)?, TIMEOUT)?;
+ socket.set_nonblocking(true)?;
+ let mut client = Self {
+ socket,
+ cancellation,
+ protocol: protocol(),
+ foreground_supported: false,
+ delivery_route: None,
+ lane: None,
+ owner,
+ path,
+ pid,
+ address,
+ epoch: String::new(),
+ challenge: String::new(),
+ sequence: 0,
+ };
+ if client.attest_and_handshake(lane, Self::attest)? {
+ Ok(Some(client))
+ } else {
+ Ok(None)
+ }
+ }
+
+ fn attest_and_handshake(
+ &mut self,
+ lane: usize,
+ attest: impl FnOnce(&Self) -> Result<()>,
+ ) -> Result<bool> {
+ attest(self)?;
+ self.handshake(lane)
+ }
+
+ /// Only an explicit busy reservation permits another endpoint attempt.
+ /// Malformed replies and connection errors have unknown outcomes.
+ fn handshake(&mut self, expected_lane: usize) -> Result<bool> {
+ ensure!(expected_lane < MAX_LANES, "invalid isolated input lane");
+ let hello = self.request("HELLO")?;
+ ensure!(
+ hello["ok"] == true && hello["protocol"].as_u64() == Some(self.protocol.version()),
+ "isolated input protocol mismatch; no downgrade is permitted"
+ );
+ self.epoch = hex_field(&hello, "epoch")?;
+ self.foreground_supported =
+ self.protocol == InputProtocol::Production && hello["foreground_target"] == true;
+ if self.protocol == InputProtocol::Experiment {
+ self.challenge = hex_field(&hello, "challenge")?;
+ } else {
+ ensure!(
+ hello.get("challenge").is_none(),
+ "production input unexpectedly requires a signer"
+ );
+ }
+ let claim = self.request("CLAIM")?;
+ if claim["ok"] == false {
+ if claim["code"] == "lane_busy" && claim["detail"] == "lane_busy" {
+ return Ok(false);
+ }
+ bail!("isolated input lane claim refused: {claim}");
+ }
+ ensure!(
+ claim["lane"].as_u64() == Some(expected_lane as u64),
+ "invalid isolated input lane claim"
+ );
+ self.lane = Some(expected_lane);
+ Ok(true)
+ }
+
+ fn request(&self, packet: &str) -> Result<Value> {
+ let deadline = Instant::now() + TIMEOUT;
+ self.send_packet(packet, deadline)?;
+ self.receive(deadline)
+ }
+
+ fn send_packet(&self, packet: &str, deadline: Instant) -> Result<()> {
+ ensure!(
+ packet.len() <= MAX_PACKET && packet.is_ascii(),
+ "invalid input packet"
+ );
+ loop {
+ wait(
+ &self.socket,
+ &self.owner,
+ &self.cancellation,
+ libc::POLLOUT,
+ deadline,
+ )?;
+ let count = unsafe {
+ libc::send(
+ self.socket.as_raw_fd(),
+ packet.as_ptr().cast(),
+ packet.len(),
+ libc::MSG_NOSIGNAL,
+ )
+ };
+ if count < 0 {
+ let error = std::io::Error::last_os_error();
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
+ ) {
+ continue;
+ }
+ return Err(error.into());
+ }
+ ensure!(count as usize == packet.len(), "partial input packet");
+ break;
+ }
+ Ok(())
+ }
+
+ fn receive(&self, deadline: Instant) -> Result<Value> {
+ let mut bytes = [0u8; MAX_PACKET];
+ loop {
+ wait(
+ &self.socket,
+ &self.owner,
+ &self.cancellation,
+ libc::POLLIN,
+ deadline,
+ )?;
+ let count = unsafe {
+ libc::recv(
+ self.socket.as_raw_fd(),
+ bytes.as_mut_ptr().cast(),
+ bytes.len(),
+ libc::MSG_TRUNC,
+ )
+ };
+ if count < 0 {
+ let error = std::io::Error::last_os_error();
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
+ ) {
+ continue;
+ }
+ return Err(error.into());
+ }
+ ensure!(
+ count > 0 && count as usize <= MAX_PACKET,
+ "closed or oversized input reply"
+ );
+ let value: Value = serde_json::from_slice(&bytes[..count as usize])?;
+ validate_reply(&value)?;
+ return Ok(value);
+ }
+ }
+
+ fn execute_routed(
+ &mut self,
+ action: Action,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ route: DeliveryRoute,
+ ) -> Result<Value> {
+ self.cancellation.check()?;
+ ensure!(self.lane.is_some(), "isolated input lane is not claimed");
+ self.check_route(route)?;
+ ensure!(
+ route == DeliveryRoute::Foreground
+ || !matches!(&action, Action::Activate | Action::TextKey { .. }),
+ "action requires foreground input"
+ );
+ ensure!(
+ self.delivery_route.is_none_or(|bound| bound == route),
+ "input route is immutable"
+ );
+ self.delivery_route = Some(route);
+ // Foreground attests once per logical call in dispatch_in_slot, before
+ // any text keys. Each key still needs a fresh exact target grant below.
+ if route == DeliveryRoute::Background {
+ self.attest()?;
+ }
+ let target = self.bind_target(&action, route)?;
+ if target["ok"] == false {
+ return Ok(target);
+ }
+ let token = hex_field(&target, "target")?;
+ let revision = target["revision"]
+ .as_u64()
+ .context("missing target revision")?;
+ let width = target["width"].as_f64().context("missing target width")?;
+ let height = target["height"].as_f64().context("missing target height")?;
+ ensure!(
+ width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0,
+ "invalid target geometry"
+ );
+ self.sequence = self.sequence.checked_add(1).context("sequence exhausted")?;
+ let is_drag = matches!(&action, Action::Drag { .. });
+ let packet = action.packet(self.sequence, &token, revision, width, height)?;
+ let mut reply = self.dispatch_routed(&packet, is_drag, started, route)?;
+ if reply["ok"] == false && self.protocol == InputProtocol::Experiment {
+ // Never report a pending operator grant as successful dispatch.
+ reply["epoch"] = json!(self.epoch);
+ reply["challenge"] = json!(self.challenge);
+ reply["target"] = json!(token);
+ reply["revision"] = json!(revision);
+ }
+ Ok(reply)
+ }
+
+ #[cfg(test)]
+ fn dispatch(
+ &self,
+ packet: &str,
+ is_drag: bool,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ ) -> Result<Value> {
+ self.dispatch_routed(packet, is_drag, started, DeliveryRoute::Background)
+ }
+
+ fn dispatch_routed(
+ &self,
+ packet: &str,
+ is_drag: bool,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ route: DeliveryRoute,
+ ) -> Result<Value> {
+ let deadline = Instant::now() + TIMEOUT;
+ self.send_packet(packet, deadline).map_err(|error| {
+ // Cancellation here precedes sending the action. Once sent, even
+ // cancellation while waiting for its first reply is indeterminate.
+ if error.is::<ActionCancelled>() {
+ error
+ } else {
+ unknown_dispatch(error, 0)
+ }
+ })?;
+ let mut reply = self
+ .receive(deadline)
+ .map_err(|error| unknown_dispatch(error, 0))?;
+ let acknowledged = reply["ok"] == true && reply["phase"] == "started";
+ if acknowledged {
+ if !is_drag {
+ return Err(unknown_dispatch(
+ anyhow::anyhow!("unexpected input start acknowledgement"),
+ 0,
+ ));
+ }
+ if let Some(started) = started {
+ let _ = started.send(());
+ }
+ reply = self
+ .receive(Instant::now() + TIMEOUT)
+ .map_err(|error| unknown_dispatch(error, 1))?;
+ }
+ if route == DeliveryRoute::Foreground
+ && reply["ok"] == false
+ && reply["code"] == "foreground_partial_unknown"
+ {
+ return Err(unknown_dispatch(
+ anyhow::anyhow!("foreground activation or input may have started"),
+ u32::from(acknowledged),
+ ));
+ }
+ if reply["ok"] == true {
+ if reply["effect"] != "unverifiable" || reply["route"] != route.acknowledgement() {
+ return Err(unknown_dispatch(
+ anyhow::anyhow!("invalid action acknowledgement"),
+ u32::from(acknowledged),
+ ));
+ }
+ } else if acknowledged {
+ reply["effect"] = json!("partial");
+ reply["delivery"] = json!({"mode":route.mode(),"delivered_count":1});
+ }
+ Ok(reply)
+ }
+
+ #[cfg(test)]
+ fn target_packet(&self, action: &Action) -> String {
+ self.target_packet_routed(action, DeliveryRoute::Background)
+ }
+
+ fn check_route(&self, route: DeliveryRoute) -> Result<()> {
+ ensure!(
+ route == DeliveryRoute::Background
+ || (self.protocol == InputProtocol::Production && self.foreground_supported),
+ "Hyprland foreground input is unavailable; no fallback or downgrade is permitted"
+ );
+ Ok(())
+ }
+
+ fn bind_target(&self, action: &Action, route: DeliveryRoute) -> Result<Value> {
+ self.check_route(route)?;
+ let target = self.request(&self.target_packet_routed(action, route))?;
+ if target["ok"] == true {
+ validate_target_route(&target, route)?;
+ }
+ Ok(target)
+ }
+
+ fn target_packet_routed(&self, action: &Action, route: DeliveryRoute) -> String {
+ let command = match route {
+ DeliveryRoute::Background => "TARGET",
+ DeliveryRoute::Foreground => "FOREGROUND_TARGET",
+ };
+ let target = format!("{command} {} {:x}", self.pid, self.address);
+ if self.protocol == InputProtocol::Production {
+ format!("{target} {}", action.capability())
+ } else {
+ target
+ }
+ }
+}
+
+impl Action {
+ fn capability(&self) -> u8 {
+ match self {
+ Self::Activate => 16,
+ Self::Click { .. } => 1,
+ Self::Key { .. } | Self::TextKey { .. } => 2,
+ Self::Scroll { .. } => 4,
+ Self::Drag { .. } => 8,
+ }
+ }
+
+ fn packet(
+ self,
+ sequence: u64,
+ token: &str,
+ revision: u64,
+ width: f64,
+ height: f64,
+ ) -> Result<String> {
+ let point = |x: f64, y: f64| -> Result<()> {
+ ensure!(
+ x.is_finite() && y.is_finite() && x >= 0.0 && y >= 0.0 && x < width && y < height,
+ "input point outside attested logical target geometry"
+ );
+ Ok(())
+ };
+ let prefix = format!("{sequence} {token} {revision}");
+ Ok(match self {
+ Self::Activate => format!("ACTIVATE {prefix}"),
+ Self::TextKey { keycode, shift } => {
+ ensure!((1..=57).contains(&keycode), "unsupported text key");
+ format!("KEY {prefix} {keycode} {}", u8::from(shift))
+ }
+ Self::Click {
+ x,
+ y,
+ button,
+ count,
+ } => {
+ point(x, y)?;
+ ensure!(
+ (1..=2).contains(&count),
+ "isolated input supports only single or double clicks"
+ );
+ let button = match button {
+ 1 => 272,
+ 2 => 274,
+ 3 => 273,
+ _ => bail!("unsupported click button"),
+ };
+ format!("CLICK {prefix} {x} {y} {button} {count}")
+ }
+ Self::Key { key, modifiers } => {
+ let keycode = super::key_to_evdev(&key)
+ .context("key has no evdev mapping; Unicode text is unsupported")?;
+ let mut mask = 0;
+ for modifier in modifiers {
+ mask |= match modifier.to_ascii_lowercase().as_str() {
+ "shift" => 1,
+ "ctrl" | "control" => 2,
+ "alt" | "option" => 4,
+ "super" | "meta" | "cmd" | "command" | "win" => 8,
+ _ => bail!("unsupported modifier"),
+ };
+ }
+ format!("KEY {prefix} {keycode} {mask}")
+ }
+ Self::Scroll {
+ point: position,
+ direction,
+ amount,
+ } => {
+ let (x, y) = position.unwrap_or((width / 2.0, height / 2.0));
+ point(x, y)?;
+ ensure!((1..=100).contains(&amount), "unsupported scroll amount");
+ let (axis, sign) = match direction.as_str() {
+ "up" => (0, -1),
+ "down" => (0, 1),
+ "left" => (1, -1),
+ "right" => (1, 1),
+ _ => bail!("unsupported scroll direction"),
+ };
+ let value = amount as i32 * 10 * sign;
+ format!("SCROLL {prefix} {x} {y} {axis} {value}")
+ }
+ Self::Drag {
+ from: (x1, y1),
+ to: (x2, y2),
+ duration_ms,
+ } => {
+ point(x1, y1)?;
+ point(x2, y2)?;
+ ensure!(
+ (50..=2000).contains(&duration_ms),
+ "isolated drag duration must be 50–2000 ms"
+ );
+ format!("DRAG {prefix} {x1} {y1} {x2} {y2} {duration_ms}")
+ }
+ })
+ }
+}
+
+struct SessionClient {
+ client: Mutex<Option<Client>>,
+}
+
+impl SessionClient {
+ fn lock(&self, cancellation: &ActionCancellation) -> Result<MutexGuard<'_, Option<Client>>> {
+ loop {
+ cancellation.check()?;
+ match self.client.try_lock() {
+ Ok(mut slot) => {
+ // Cancellation may race with the previous owner releasing.
+ // Refuse before touching its connection or sending packets.
+ cancellation.check()?;
+ // The compositor can expire an idle connection while its
+ // owner remains active. Reconnect before any new dispatch,
+ // keeping queued callers on this same serialization mutex.
+ if slot.as_ref().is_some_and(Client::peer_closed) {
+ *slot = None;
+ }
+ return Ok(slot);
+ }
+ Err(TryLockError::WouldBlock) => std::thread::sleep(CANCELLATION_POLL),
+ Err(TryLockError::Poisoned(_)) => bail!("input connection poisoned"),
+ }
+ }
+ }
+}
+
+/// The compositor owns the cross-process allocation. No target or action has
+/// been sent while this bounded search is running, and errors never fall back.
+fn claim_available(mut connect: impl FnMut(usize) -> Result<Option<Client>>) -> Result<Client> {
+ for lane in 0..MAX_LANES {
+ if let Some(client) = connect(lane)? {
+ return Ok(client);
+ }
+ }
+ Err(LaneBusy.into())
+}
+
+static CLIENTS: OnceLock<Mutex<HashMap<String, Arc<SessionClient>>>> = OnceLock::new();
+
+fn clients() -> &'static Mutex<HashMap<String, Arc<SessionClient>>> {
+ CLIENTS.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+/// The registry supplies a runtime-private lifecycle identity. Public labels
+/// are already namespaced there; labels never grant input authority here.
+fn session_client(owner: &str) -> Result<Arc<SessionClient>> {
+ ensure!(
+ !owner.is_empty() && owner != "default",
+ "authenticated lifecycle required"
+ );
+ let mut clients = clients()
+ .lock()
+ .map_err(|_| anyhow::anyhow!("input pool poisoned"))?;
+ if let Some(client) = clients.get(owner) {
+ return Ok(client.clone());
+ }
+ // Failed claims leave empty slots; the compositor may also close idle
+ // connections without their owning sessions making another call.
+ // Reclaim only idle entries: queued callers must keep the same mutex.
+ // Never wait for a per-session mutex while holding the pool lock.
+ clients.retain(|_, client| {
+ Arc::strong_count(client) > 1
+ || client.client.try_lock().map_or(true, |slot| {
+ slot.as_ref().is_some_and(|client| !client.peer_closed())
+ })
+ });
+ if clients.len() >= MAX_LANES {
+ return Err(LaneBusy.into());
+ }
+ let client = Arc::new(SessionClient {
+ client: Mutex::new(None),
+ });
+ clients.insert(owner.to_owned(), client.clone());
+ Ok(client)
+}
+
+pub fn cleanup_session(owner: &str) {
+ let client = clients().lock().unwrap().get(owner).cloned();
+ if let Some(client) = client {
+ // In-flight waits observe the common termination signal and drop
+ // their owned socket promptly. Final cleanup still uses the barrier.
+ // Closing the exact connection revokes this lane, never another one.
+ *client.client.lock().unwrap() = None;
+ clients().lock().unwrap().remove(owner);
+ }
+}
+
+/// Runtime teardown must also reclaim leases that never acquired an overlay.
+/// The prefix comes from the trusted registry, never a public session label.
+pub fn cleanup_runtime(prefix: &str) {
+ let owners: Vec<_> = clients()
+ .lock()
+ .unwrap()
+ .keys()
+ .filter(|owner| owner.starts_with(prefix))
+ .cloned()
+ .collect();
+ for owner in owners {
+ cleanup_session(&owner);
+ }
+}
+
+/// Only same-lifecycle actions serialize. Independent authenticated sessions
+/// use independent sockets/seats and may overlap. Never retry unknown effects.
+pub(crate) fn execute(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ action: Action,
+ cancellation: ActionCancellation,
+) -> Result<Value> {
+ execute_with_started(owner, pid, address, action, None, cancellation)
+}
+
+pub(crate) fn execute_with_started(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ action: Action,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ cancellation: ActionCancellation,
+) -> Result<Value> {
+ execute_routed(
+ owner,
+ pid,
+ address,
+ action,
+ started,
+ cancellation,
+ DeliveryRoute::Background,
+ )
+}
+
+pub(crate) fn execute_foreground(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ action: Action,
+ cancellation: ActionCancellation,
+) -> Result<Value> {
+ execute_foreground_with_started(owner, pid, address, action, None, cancellation)
+}
+
+pub(crate) fn execute_foreground_with_started(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ action: Action,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ cancellation: ActionCancellation,
+) -> Result<Value> {
+ execute_routed(
+ owner,
+ pid,
+ address,
+ action,
+ started,
+ cancellation,
+ DeliveryRoute::Foreground,
+ )
+}
+
+fn execute_routed(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ action: Action,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ cancellation: ActionCancellation,
+ route: DeliveryRoute,
+) -> Result<Value> {
+ execute_actions_routed(
+ owner,
+ pid,
+ address,
+ vec![action],
+ started,
+ cancellation,
+ route,
+ false,
+ )
+}
+
+pub(crate) fn execute_foreground_text(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ text: &str,
+ cancellation: ActionCancellation,
+) -> Result<Value> {
+ let actions = foreground_text_actions(text)?;
+ ensure!(!actions.is_empty(), "foreground text must not be empty");
+ execute_actions_routed(
+ owner,
+ pid,
+ address,
+ actions,
+ None,
+ cancellation,
+ DeliveryRoute::Foreground,
+ true,
+ )
+}
+
+fn execute_actions_routed(
+ owner: Option<String>,
+ pid: u32,
+ address: u64,
+ actions: Vec<Action>,
+ started: Option<tokio::sync::oneshot::Sender<()>>,
+ cancellation: ActionCancellation,
+ route: DeliveryRoute,
+ text: bool,
+) -> Result<Value> {
+ cancellation.check()?;
+ ensure!(enabled(), "Hyprland isolated input is unavailable");
+ ensure!(
+ pid > 0 && address > 0,
+ "exact pid and window address required"
+ );
+ let owner = owner.context("authenticated lifecycle required")?;
+ ensure!(
+ route == DeliveryRoute::Background || protocol() == InputProtocol::Production,
+ "foreground input requires production protocol; no downgrade is permitted"
+ );
+ if route == DeliveryRoute::Background && protocol() == InputProtocol::Production {
+ if let Err(reason) = super::hyprland_compatibility::qualify(pid) {
+ return Ok(json!({"ok":false,"code":reason,"detail":reason}));
+ }
+ }
+ let client = session_client(&owner)?;
+ let mut slot = client.lock(&cancellation)?;
+ if let Some(client) = slot.as_ref() {
+ let lane = client.lane.context("missing claimed input lane")?;
+ if client.pid != pid
+ || client.address != address
+ || client.path != socket_path(lane)?
+ || client.protocol != protocol()
+ || client.delivery_route.is_some_and(|bound| bound != route)
+ {
+ *slot = None;
+ }
+ }
+ if slot.is_none() {
+ *slot = Some(claim_available(|lane| {
+ Client::connect(
+ socket_path(lane)?,
+ owner.clone(),
+ pid,
+ address,
+ lane,
+ cancellation.clone(),
+ )
+ })?);
+ }
+ slot.as_mut()
+ .context("missing input connection")?
+ .cancellation = cancellation;
+ dispatch_in_slot(
+ &mut slot,
+ |client| {
+ if route == DeliveryRoute::Foreground {
+ client.attest()?;
+ }
+ Ok(())
+ },
+ |client| {
+ if !text {
+ return client.execute_routed(
+ actions.into_iter().next().context("missing input action")?,
+ started,
+ route,
+ );
+ }
+ execute_text_actions(actions, |action| client.execute_routed(action, None, route))
+ },
+ )
+}
+
+fn execute_text_actions(
+ actions: Vec<Action>,
+ mut dispatch: impl FnMut(Action) -> Result<Value>,
+) -> Result<Value> {
+ let route = DeliveryRoute::Foreground;
+ let mut delivered = 0u32;
+ for action in actions {
+ match dispatch(action) {
+ Ok(mut reply) if reply["ok"] == false => {
+ reply["effect"] = json!(if delivered > 0 { "partial" } else { "none" });
+ reply["delivery"] = json!({"mode":route.mode(),"delivered_count":delivered});
+ return Ok(reply);
+ }
+ Ok(_) => delivered += 1,
+ Err(error) => {
+ if let Some(unknown) = error.downcast_ref::<DispatchUnknown>() {
+ return Err(unknown_dispatch(
+ anyhow::anyhow!(unknown.detail.clone()),
+ delivered + unknown.acknowledged_phases,
+ ));
+ }
+ if delivered == 0 {
+ return Err(error);
+ }
+ return Ok(
+ json!({"ok":false,"code":"text_interrupted","detail":error.to_string(),
+ "effect":"partial","delivery":{"mode":route.mode(),"delivered_count":delivered}}),
+ );
+ }
+ }
+ }
+ Ok(
+ json!({"ok":true,"effect":"unverifiable","route":route.acknowledgement(),
+ "delivery":{"mode":route.mode(),"delivered_count":delivered}}),
+ )
+}
+
+fn dispatch_in_slot(
+ slot: &mut Option<Client>,
+ attest: impl FnOnce(&Client) -> Result<()>,
+ dispatch: impl FnOnce(&mut Client) -> Result<Value>,
+) -> Result<Value> {
+ let lane = slot
+ .as_ref()
+ .and_then(|client| client.lane)
+ .context("missing claimed input lane")?;
+ let client = slot.as_mut().context("missing input connection")?;
+ // Revalidate live compositor identity on each logical foreground call,
+ // including reuse: the selected Wayland display can change while pooled.
+ // An attestation failure follows the same discard path as dispatch errors.
+ let mut result = attest(client).and_then(|()| dispatch(client));
+ if result.as_ref().map_or(true, terminal_connection_result) {
+ *slot = None;
+ }
+ if let Ok(value) = &mut result {
+ // Report the compositor-assigned lane for diagnostics. It is not a
+ // credential or a caller-selected seat.
+ value["lane"] = json!(lane);
+ }
+ result
+}
+
+fn terminal_connection_result(value: &Value) -> bool {
+ value["ok"] == false
+ && (value["effect"] == "partial"
+ || matches!(
+ value["code"].as_str(),
+ Some(
+ "desktop_changed"
+ | "plugin_disabled"
+ | "plugin_shutdown"
+ | "generation_exhausted"
+ | "text_interrupted"
+ )
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::os::fd::FromRawFd;
+ const TOKEN: &str = "0123456789abcdef0123456789abcdef";
+ static POOL_TEST_LOCK: Mutex<()> = Mutex::new(());
+
+ #[test]
+ fn foreground_text_attests_each_logical_call_once_and_binds_every_key() {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(
+ json!({"ok":true,"protocol":3,"epoch":TOKEN,"foreground_target":true})
+ .to_string()
+ .as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ peer.send(br#"{"ok":true,"lane":0}"#).unwrap();
+ for (sequence, keycode) in [(1, 30), (2, 48), (3, 46), (4, 32), (5, 18)] {
+ assert_eq!(read_packet(&peer), "FOREGROUND_TARGET 1 1 2");
+ let token = format!("{sequence:032x}");
+ peer.send(
+ json!({"ok":true,"route":"primary_foreground","target":token,
+ "revision":sequence,"width":100,"height":100})
+ .to_string()
+ .as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(
+ read_packet(&peer),
+ format!("KEY {sequence} {token} {sequence} {keycode} 0")
+ );
+ peer.send(br#"{"ok":true,"effect":"unverifiable","route":"primary_foreground"}"#)
+ .unwrap();
+ }
+ });
+ let mut attestations = 0;
+ assert!(client
+ .attest_and_handshake(0, |_| {
+ attestations += 1;
+ Ok(())
+ })
+ .unwrap());
+ assert_eq!(attestations, 1);
+ let mut slot = Some(client);
+ for (call, text) in ["abc", "de"].into_iter().enumerate() {
+ let result = dispatch_in_slot(
+ &mut slot,
+ |_| {
+ attestations += 1;
+ Ok(())
+ },
+ |client| {
+ execute_text_actions(foreground_text_actions(text).unwrap(), |action| {
+ client.execute_routed(action, None, DeliveryRoute::Foreground)
+ })
+ },
+ )
+ .unwrap();
+ assert_eq!(result["delivery"]["delivered_count"], text.len());
+ assert_eq!(attestations, call + 2);
+ assert!(slot.is_some());
+ }
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn failed_call_attestation_discards_reused_slot_without_sending_packets() {
+ let (mut client, peer) = test_connection();
+ client.lane = Some(0);
+ client.delivery_route = Some(DeliveryRoute::Foreground);
+ let mut slot = Some(client);
+ let error = dispatch_in_slot(
+ &mut slot,
+ |_| bail!("compositor identity mismatch"),
+ |_| panic!("failed attestation must prevent the entire text call"),
+ )
+ .unwrap_err();
+ assert_eq!(error.to_string(), "compositor identity mismatch");
+ assert!(slot.is_none());
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ }
+
+ #[test]
+ fn failed_initial_attestation_sends_no_handshake_or_action() {
+ let (mut client, peer) = test_connection();
+ assert!(client
+ .attest_and_handshake(0, |_| bail!("compositor identity mismatch"))
+ .is_err());
+ assert!(client.lane.is_none());
+ drop(client);
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ }
+
+ #[test]
+ fn foreground_text_stops_at_revoked_target_without_replay() {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ client.foreground_supported = true;
+ client.lane = Some(0);
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "FOREGROUND_TARGET 1 1 2");
+ peer.send(
+ json!({"ok":true,"route":"primary_foreground","target":TOKEN,
+ "revision":1,"width":100,"height":100})
+ .to_string()
+ .as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(read_packet(&peer), format!("KEY 1 {TOKEN} 1 30 0"));
+ peer.send(br#"{"ok":true,"effect":"unverifiable","route":"primary_foreground"}"#)
+ .unwrap();
+ assert_eq!(read_packet(&peer), "FOREGROUND_TARGET 1 1 2");
+ peer.send(br#"{"ok":false,"code":"desktop_changed","detail":"desktop_changed"}"#)
+ .unwrap();
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ let mut slot = Some(client);
+ let result = dispatch_in_slot(
+ &mut slot,
+ |_| Ok(()),
+ |client| {
+ execute_text_actions(foreground_text_actions("abc").unwrap(), |action| {
+ client.execute_routed(action, None, DeliveryRoute::Foreground)
+ })
+ },
+ )
+ .unwrap();
+ assert_eq!(result["code"], "desktop_changed");
+ assert_eq!(result["effect"], "partial");
+ assert_eq!(result["delivery"]["delivered_count"], 1);
+ assert!(slot.is_none());
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn foreground_text_later_key_refusal_discards_slot_without_replay() {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ client.foreground_supported = true;
+ client.lane = Some(0);
+ let server = std::thread::spawn(move || {
+ for (sequence, keycode) in [(1, 30), (2, 48)] {
+ assert_eq!(read_packet(&peer), "FOREGROUND_TARGET 1 1 2");
+ peer.send(
+ json!({"ok":true,"route":"primary_foreground","target":TOKEN,
+ "revision":1,"width":100,"height":100})
+ .to_string()
+ .as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(
+ read_packet(&peer),
+ format!("KEY {sequence} {TOKEN} 1 {keycode} 0")
+ );
+ let reply = if sequence == 1 {
+ json!({"ok":true,"effect":"unverifiable","route":"primary_foreground"})
+ } else {
+ json!({"ok":false,"code":"target_changed","detail":"target_changed"})
+ };
+ peer.send(reply.to_string().as_bytes()).unwrap();
+ }
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ let mut slot = Some(client);
+ let result = dispatch_in_slot(
+ &mut slot,
+ |_| Ok(()),
+ |client| {
+ execute_text_actions(foreground_text_actions("abc").unwrap(), |action| {
+ client.execute_routed(action, None, DeliveryRoute::Foreground)
+ })
+ },
+ )
+ .unwrap();
+ assert_eq!(result["code"], "target_changed");
+ assert_eq!(result["effect"], "partial");
+ assert_eq!(result["delivery"]["delivered_count"], 1);
+ assert!(slot.is_none());
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn background_action_still_requires_live_compositor_attestation() {
+ let (mut client, peer) = test_connection();
+ client.lane = Some(0);
+ // This socket's peer is the test process, never the Wayland compositor.
+ assert!(client
+ .execute_routed(
+ Action::Key {
+ key: "a".into(),
+ modifiers: vec![]
+ },
+ None,
+ DeliveryRoute::Background,
+ )
+ .is_err());
+ drop(client);
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ }
+
+ #[test]
+ fn foreground_requires_advertisement_and_production_without_sending_target() {
+ for protocol in [InputProtocol::Production, InputProtocol::Experiment] {
+ let (mut client, peer) = test_connection();
+ client.protocol = protocol;
+ client.foreground_supported = protocol == InputProtocol::Experiment;
+ assert!(client
+ .bind_target(&Action::Activate, DeliveryRoute::Foreground)
+ .is_err());
+ drop(client);
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ }
+ }
+
+ #[test]
+ fn foreground_target_checks_route_and_never_retries_background() {
+ for reply in [
+ json!({"ok":true,"route":"primary_foreground"}),
+ json!({"ok":true,"route":"synthetic_events"}),
+ json!({"ok":true}),
+ json!({"ok":false,"code":"unsupported","detail":"unsupported"}),
+ ] {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ client.foreground_supported = true;
+ let expected_ok = reply["ok"] == false || reply["route"] == "primary_foreground";
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "FOREGROUND_TARGET 1 1 16");
+ peer.send(reply.to_string().as_bytes()).unwrap();
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ assert_eq!(
+ client
+ .bind_target(&Action::Activate, DeliveryRoute::Foreground)
+ .is_ok(),
+ expected_ok
+ );
+ drop(client);
+ server.join().unwrap();
+ }
+ }
+
+ #[test]
+ fn foreground_handshake_records_capability_and_exact_claim() {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(
+ json!({"ok":true,"protocol":3,"epoch":TOKEN,"foreground_target":true})
+ .to_string()
+ .as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ peer.send(br#"{"ok":true,"lane":0}"#).unwrap();
+ });
+ assert!(client.handshake(0).unwrap());
+ assert!(client.foreground_supported);
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn foreground_drag_refusal_preserves_started_phase_and_foreground_count() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "DRAG synthetic");
+ peer.send(br#"{"ok":true,"phase":"started"}"#).unwrap();
+ peer.send(br#"{"ok":false,"code":"cancelled","detail":"cancelled"}"#)
+ .unwrap();
+ });
+ let (started, acknowledgement) = tokio::sync::oneshot::channel();
+ let reply = client
+ .dispatch_routed(
+ "DRAG synthetic",
+ true,
+ Some(started),
+ DeliveryRoute::Foreground,
+ )
+ .unwrap();
+ assert!(acknowledgement.blocking_recv().is_ok());
+ assert_eq!(reply["effect"], "partial");
+ assert_eq!(
+ reply["delivery"],
+ json!({"mode":"foreground","delivered_count":1})
+ );
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn foreground_action_cannot_acknowledge_background_delivery() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "KEY synthetic");
+ peer.send(br#"{"ok":true,"effect":"unverifiable","route":"synthetic_events"}"#)
+ .unwrap();
+ });
+ assert!(client
+ .dispatch_routed("KEY synthetic", false, None, DeliveryRoute::Foreground)
+ .unwrap_err()
+ .is::<DispatchUnknown>());
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn foreground_partial_unknown_keeps_only_proven_acknowledgements() {
+ for started in [false, true] {
+ let (client, peer) = test_connection();
+ let packet = if started {
+ "DRAG synthetic"
+ } else {
+ "KEY synthetic"
+ };
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), packet);
+ if started {
+ peer.send(br#"{"ok":true,"phase":"started"}"#).unwrap();
+ }
+ peer.send(br#"{"ok":false,"code":"foreground_partial_unknown","detail":"foreground_partial_unknown"}"#).unwrap();
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ let error = client
+ .dispatch_routed(packet, started, None, DeliveryRoute::Foreground)
+ .unwrap_err();
+ assert_eq!(
+ error
+ .downcast_ref::<DispatchUnknown>()
+ .unwrap()
+ .acknowledged_phases,
+ u32::from(started)
+ );
+ drop(client);
+ server.join().unwrap();
+ }
+ }
+
+ #[test]
+ fn foreground_text_partial_unknown_counts_prior_completed_keys() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "KEY synthetic");
+ peer.send(br#"{"ok":true,"effect":"unverifiable","route":"primary_foreground"}"#)
+ .unwrap();
+ assert_eq!(read_packet(&peer), "KEY synthetic");
+ peer.send(br#"{"ok":false,"code":"foreground_partial_unknown","detail":"foreground_partial_unknown"}"#).unwrap();
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ let error = execute_text_actions(foreground_text_actions("abc").unwrap(), |_| {
+ client.dispatch_routed("KEY synthetic", false, None, DeliveryRoute::Foreground)
+ })
+ .unwrap_err();
+ assert_eq!(
+ error
+ .downcast_ref::<DispatchUnknown>()
+ .unwrap()
+ .acknowledged_phases,
+ 1
+ );
+ drop(client);
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn foreground_unknown_code_does_not_change_background_refusals() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "KEY synthetic");
+ peer.send(br#"{"ok":false,"code":"foreground_partial_unknown","detail":"foreground_partial_unknown"}"#).unwrap();
+ });
+ let reply = client.dispatch("KEY synthetic", false, None).unwrap();
+ assert_eq!(reply["ok"], false);
+ assert_eq!(reply["code"], "foreground_partial_unknown");
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn foreground_text_is_bounded_and_fully_prevalidated() {
+ for text in ["valid prefix\u{00e9}", "valid prefix\0", "\r", "\u{007f}"] {
+ assert!(foreground_text_actions(text).is_err());
+ }
+ assert!(foreground_text_actions(&"a".repeat(4097)).is_err());
+ assert_eq!(
+ foreground_text_actions(&"a".repeat(4096)).unwrap().len(),
+ 4096
+ );
+ let actions = foreground_text_actions("Aa!? \t\n").unwrap();
+ let packets: Vec<_> = actions
+ .into_iter()
+ .map(|action| action.packet(1, TOKEN, 1, 1.0, 1.0).unwrap())
+ .collect();
+ for (packet, suffix) in packets
+ .iter()
+ .zip(["30 1", "30 0", "2 1", "53 1", "57 0", "15 0", "28 0"])
+ {
+ assert_eq!(*packet, format!("KEY 1 {TOKEN} 1 {suffix}"));
+ }
+ assert_eq!(
+ foreground_text_actions(&(32u8..127).map(char::from).collect::<String>())
+ .unwrap()
+ .len(),
+ 95
+ );
+ }
+
+ #[test]
+ fn foreground_text_stops_after_refusal_or_cancellation_without_replay() {
+ for cancel in [false, true] {
+ let mut calls = 0;
+ let reply = execute_text_actions(foreground_text_actions("abc").unwrap(), |_| {
+ calls += 1;
+ match calls {
+ 1 => Ok(json!({"ok":true})),
+ 2 if cancel => Err(ActionCancelled.into()),
+ 2 => Ok(json!({"ok":false,"code":"target_changed","detail":"target_changed"})),
+ _ => panic!("replayed text after interrupted dispatch"),
+ }
+ })
+ .unwrap();
+ assert_eq!(calls, 2);
+ assert_eq!(reply["ok"], false);
+ assert_eq!(reply["effect"], "partial");
+ assert_eq!(
+ reply["delivery"],
+ json!({"mode":"foreground","delivered_count":1})
+ );
+ assert!(terminal_connection_result(&reply));
+ }
+ }
+
+ #[test]
+ fn foreground_text_unknown_delivery_keeps_only_acknowledged_key_count() {
+ let mut calls = 0;
+ let error = execute_text_actions(foreground_text_actions("abc").unwrap(), |_| {
+ calls += 1;
+ if calls == 1 {
+ Ok(json!({"ok":true}))
+ } else {
+ Err(unknown_dispatch(anyhow::anyhow!("peer closed"), 0))
+ }
+ })
+ .unwrap_err();
+ assert_eq!(calls, 2);
+ assert_eq!(
+ error
+ .downcast_ref::<DispatchUnknown>()
+ .unwrap()
+ .acknowledged_phases,
+ 1
+ );
+ }
+
+ #[test]
+ fn cancelled_foreground_target_sends_no_input() {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ client.foreground_supported = true;
+ let (guard, cancellation) = ActionCancellation::invocation();
+ client.cancellation = cancellation;
+ drop(guard);
+ assert!(client
+ .bind_target(&Action::Activate, DeliveryRoute::Foreground)
+ .unwrap_err()
+ .is::<ActionCancelled>());
+ drop(client);
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ }
+
+ #[test]
+ fn revoked_connections_are_dropped_without_replaying_the_action() {
+ for code in [
+ "desktop_changed",
+ "plugin_disabled",
+ "plugin_shutdown",
+ "generation_exhausted",
+ ] {
+ assert!(terminal_connection_result(
+ &json!({"ok": false, "code": code})
+ ));
+ }
+ for value in [
+ json!({"ok": true}),
+ json!({"ok": false, "code": "pending_operator_approval"}),
+ json!({"ok": false, "code": "primary_target_busy"}),
+ json!({"ok": false, "code": "target_changed", "effect": "none"}),
+ ] {
+ assert!(!terminal_connection_result(&value));
+ }
+ }
+
+ #[test]
+ fn independent_lifecycles_have_bounded_serialization_slots_and_cleanup() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ assert!(session_client("").is_err());
+ assert!(session_client("default").is_err());
+ let a = session_client("input-pool-test-a").unwrap();
+ let b = session_client("input-pool-test-b").unwrap();
+ let pool = Arc::new(Mutex::new([None, None]));
+ *a.client.lock().unwrap() = Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ *b.client.lock().unwrap() = Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ assert!(!Arc::ptr_eq(&a, &b));
+ assert!(Arc::ptr_eq(
+ &a,
+ &session_client("input-pool-test-a").unwrap()
+ ));
+ assert!(session_client("input-pool-test-c")
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ let a_lock = a.client.lock().unwrap();
+ // No global action mutex: another seat remains independently usable.
+ assert!(b.client.try_lock().is_ok());
+ drop(a_lock);
+ cleanup_session("input-pool-test-a");
+ let c = session_client("input-pool-test-c").unwrap();
+ assert!(!Arc::ptr_eq(&c, &a));
+ let reclaimed = claim_available(|lane| fake_claim(lane, &pool)).unwrap();
+ assert_eq!(reclaimed.lane, Some(0));
+ *c.client.lock().unwrap() = Some(reclaimed);
+ assert!(Arc::ptr_eq(
+ &b,
+ &session_client("input-pool-test-b").unwrap()
+ ));
+ cleanup_session("input-pool-test-b");
+ cleanup_session("input-pool-test-c");
+ let runtime = session_client("__cua_runtime_test:pending").unwrap();
+ let other = session_client("__cua_runtime_other:pending").unwrap();
+ cleanup_runtime("__cua_runtime_test:");
+ assert!(Arc::ptr_eq(
+ &other,
+ &session_client("__cua_runtime_other:pending").unwrap()
+ ));
+ let reused = session_client("input-pool-test-reused").unwrap();
+ assert!(!Arc::ptr_eq(&reused, &runtime));
+ cleanup_session("__cua_runtime_other:pending");
+ cleanup_session("input-pool-test-reused");
+ }
+
+ #[test]
+ fn failed_owners_do_not_exhaust_local_lanes() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ for failure in ["connect", "HELLO", "CLAIM"] {
+ for owner in ["input-failed-a", "input-failed-b"] {
+ let client = session_client(owner).unwrap();
+ let mut slot = client.client.lock().unwrap();
+ let mut attempts = Vec::new();
+ let result = claim_available(|lane| {
+ attempts.push(lane);
+ if failure == "connect" {
+ bail!("connection unavailable");
+ }
+ let (mut client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ if failure == "CLAIM" {
+ peer.send(hello_reply().to_string().as_bytes()).unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ }
+ peer.send(b"not-json").unwrap();
+ });
+ let result = client.handshake(lane);
+ server.join().unwrap();
+ result.map(|claimed| claimed.then_some(client))
+ });
+ assert!(result.is_err());
+ assert_eq!(attempts, [0]);
+ *slot = result.ok();
+ }
+ let pool = Arc::new(Mutex::new([None, None]));
+ let third = session_client("input-failed-third").unwrap();
+ *third.client.lock().unwrap() =
+ Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ assert_eq!(third.client.lock().unwrap().as_ref().unwrap().lane, Some(0));
+ cleanup_session("input-failed-third");
+ cleanup_session("input-failed-a");
+ cleanup_session("input-failed-b");
+ }
+ }
+
+ #[test]
+ fn failed_reconnect_reclaims_only_the_empty_owner() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ let pool = Arc::new(Mutex::new([None, None]));
+ for owner in ["input-reconnect-a", "input-reconnect-b"] {
+ let client = session_client(owner).unwrap();
+ *client.client.lock().unwrap() =
+ Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ }
+ assert!(session_client("input-reconnect-c")
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ {
+ let client = session_client("input-reconnect-a").unwrap();
+ let mut slot = client.client.lock().unwrap();
+ *slot = None;
+ assert!(claim_available(|_| bail!("reconnect unavailable")).is_err());
+ }
+ let c = session_client("input-reconnect-c").unwrap();
+ *c.client.lock().unwrap() = Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ assert_eq!(c.client.lock().unwrap().as_ref().unwrap().lane, Some(0));
+ let b = session_client("input-reconnect-b").unwrap();
+ assert_eq!(b.client.lock().unwrap().as_ref().unwrap().lane, Some(1));
+ for owner in [
+ "input-reconnect-a",
+ "input-reconnect-b",
+ "input-reconnect-c",
+ ] {
+ cleanup_session(owner);
+ }
+ }
+
+ #[test]
+ fn closed_idle_peers_do_not_exhaust_local_lanes() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ let pool = Arc::new(Mutex::new([None, None]));
+ for owner in ["input-idle-a", "input-idle-b"] {
+ let client = session_client(owner).unwrap();
+ *client.client.lock().unwrap() =
+ Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ }
+ assert!(session_client("input-idle-c")
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ // The compositor revokes both idle connections; neither owner calls
+ // again to discover EOF or explicitly clean up its cached client.
+ *pool.lock().unwrap() = [None, None];
+ let c = session_client("input-idle-c").unwrap();
+ *c.client.lock().unwrap() = Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ assert_eq!(c.client.lock().unwrap().as_ref().unwrap().lane, Some(0));
+ let clients = clients().lock().unwrap();
+ assert!(!clients.contains_key("input-idle-a"));
+ assert!(!clients.contains_key("input-idle-b"));
+ drop(clients);
+ cleanup_session("input-idle-c");
+ }
+
+ #[test]
+ fn same_owner_resumes_after_idle_eof_under_the_existing_mutex() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ let owner = "input-idle-resume";
+ let session = session_client(owner).unwrap();
+ let (mut client, peer) = test_connection();
+ client.lane = Some(0);
+ let (previous_guard, previous_cancellation) = ActionCancellation::invocation();
+ client.cancellation = previous_cancellation;
+ *session.client.lock().unwrap() = Some(client);
+ drop(previous_guard);
+ drop(peer);
+
+ let resumed = session_client(owner).unwrap();
+ assert!(Arc::ptr_eq(&session, &resumed));
+ let (_guard, cancellation) = ActionCancellation::invocation();
+ let mut slot = resumed.lock(&cancellation).unwrap();
+ assert!(
+ slot.is_none(),
+ "closed idle peer must be discarded before dispatch"
+ );
+ assert!(session.client.try_lock().is_err());
+ let (mut replacement, peer) = test_connection();
+ replacement.cancellation = cancellation;
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(hello_reply().to_string().as_bytes()).unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ peer.send(br#"{"ok":true,"lane":0}"#).unwrap();
+ assert_eq!(read_packet(&peer), "TARGET synthetic");
+ peer.send(br#"{"ok":true}"#).unwrap();
+ assert_eq!(read_packet(&peer), "CLICK synthetic");
+ peer.send(br#"{"ok":true,"effect":"unverifiable","route":"synthetic_events"}"#)
+ .unwrap();
+ // Keep the peer open until the reply has been consumed.
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ let mut replacement = Some(replacement);
+ let mut claims = 0;
+ *slot = Some(
+ claim_available(|lane| {
+ claims += 1;
+ let mut client = replacement.take().unwrap();
+ assert!(client.handshake(lane)?);
+ Ok(Some(client))
+ })
+ .unwrap(),
+ );
+ let reply = dispatch_in_slot(
+ &mut slot,
+ |_| Ok(()),
+ |client| {
+ client.request("TARGET synthetic")?;
+ client.dispatch("CLICK synthetic", false, None)
+ },
+ )
+ .unwrap();
+ assert_eq!(claims, 1);
+ assert_eq!(reply["ok"], true);
+ assert_eq!(reply["lane"], 0);
+ drop(slot);
+ cleanup_session(owner);
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn uncertain_io_after_reuse_is_an_error_without_replay() {
+ for malformed_reply in [false, true] {
+ let (mut client, peer) = test_connection();
+ client.lane = Some(0);
+ let session = SessionClient {
+ client: Mutex::new(Some(client)),
+ };
+ let mut slot = session.lock(&ActionCancellation::default()).unwrap();
+ assert!(slot.is_some(), "a live peer must remain reusable");
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "CLICK synthetic");
+ if malformed_reply {
+ peer.send(b"not-json").unwrap();
+ } else {
+ peer.shutdown(std::net::Shutdown::Write).unwrap();
+ }
+ // The uncertain connection must close without another packet.
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ });
+ let mut dispatches = 0;
+ let error = dispatch_in_slot(
+ &mut slot,
+ |_| Ok(()),
+ |client| {
+ dispatches += 1;
+ client.dispatch("CLICK synthetic", false, None)
+ },
+ )
+ .unwrap_err();
+ assert!(error.is::<DispatchUnknown>());
+ assert_eq!(dispatches, 1);
+ assert!(slot.is_none());
+ server.join().unwrap();
+ }
+ }
+
+ #[test]
+ fn live_idle_peers_with_pending_packets_keep_their_lanes() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ let pool = Arc::new(Mutex::new([None, None]));
+ for owner in ["input-live-a", "input-live-b"] {
+ let client = session_client(owner).unwrap();
+ *client.client.lock().unwrap() =
+ Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ }
+ {
+ let pool = pool.lock().unwrap();
+ pool[0].as_ref().unwrap().send(b"").unwrap();
+ pool[1].as_ref().unwrap().send(b"pending reply").unwrap();
+ }
+ assert!(session_client("input-live-c")
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ // Reclaim only the closed peer, preserving the other idle client.
+ pool.lock().unwrap()[0] = None;
+ let c = session_client("input-live-c").unwrap();
+ *c.client.lock().unwrap() = Some(claim_available(|lane| fake_claim(lane, &pool)).unwrap());
+ assert_eq!(c.client.lock().unwrap().as_ref().unwrap().lane, Some(0));
+ let b = session_client("input-live-b").unwrap();
+ let slot = b.client.lock().unwrap();
+ assert_eq!(slot.as_ref().unwrap().lane, Some(1));
+ assert_eq!(read_packet(&slot.as_ref().unwrap().socket), "pending reply");
+ drop(slot);
+ cleanup_session("input-live-b");
+ cleanup_session("input-live-c");
+ }
+
+ #[test]
+ fn pending_same_owner_callers_keep_their_serialization_slot() {
+ let _pool_test = POOL_TEST_LOCK.lock().unwrap();
+ let owner = "input-pending-a";
+ let active = session_client(owner).unwrap();
+ let (client, peer) = test_connection();
+ *active.client.lock().unwrap() = Some(client);
+ // Even a conclusively closed socket must not replace the mutex while
+ // active or queued callers still hold this owner's serialization slot.
+ drop(peer);
+ let slot = active.client.lock().unwrap();
+ let queued = session_client(owner).unwrap();
+ let (ready, waiting) = std::sync::mpsc::channel();
+ let (release, released) = std::sync::mpsc::channel();
+ let waiter = std::thread::spawn(move || {
+ ready.send(()).unwrap();
+ let _slot = queued.client.lock().unwrap();
+ released.recv().unwrap();
+ });
+ waiting.recv().unwrap();
+ let b = session_client("input-pending-b").unwrap();
+ assert!(session_client("input-pending-c")
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ assert!(Arc::ptr_eq(&active, &session_client(owner).unwrap()));
+ drop(slot);
+ drop(active);
+ assert!(session_client("input-pending-c")
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ release.send(()).unwrap();
+ waiter.join().unwrap();
+ let c = session_client("input-pending-c").unwrap();
+ assert!(Arc::ptr_eq(&b, &session_client("input-pending-b").unwrap()));
+ drop(c);
+ for owner in [owner, "input-pending-b", "input-pending-c"] {
+ cleanup_session(owner);
+ }
+ }
+
+ #[test]
+ fn click_is_exact_and_maps_right_button() {
+ assert_eq!(
+ Action::Click {
+ x: 2.5,
+ y: 3.0,
+ button: 3,
+ count: 2
+ }
+ .packet(7, TOKEN, 4, 100.0, 80.0)
+ .unwrap(),
+ format!("CLICK 7 {TOKEN} 4 2.5 3 273 2")
+ );
+ }
+
+ #[test]
+ fn unsafe_geometry_and_unsupported_actions_refuse() {
+ for x in [f64::NAN, f64::INFINITY, -1.0, 100.0] {
+ assert!(Action::Click {
+ x,
+ y: 1.0,
+ button: 1,
+ count: 1
+ }
+ .packet(1, TOKEN, 1, 100.0, 80.0)
+ .is_err());
+ }
+ assert!(Action::Key {
+ key: "🙂".into(),
+ modifiers: vec![]
+ }
+ .packet(1, TOKEN, 1, 100.0, 80.0)
+ .is_err());
+ assert!(Action::Drag {
+ from: (1.0, 1.0),
+ to: (2.0, 2.0),
+ duration_ms: 2001
+ }
+ .packet(1, TOKEN, 1, 100.0, 80.0)
+ .is_err());
+ }
+
+ #[test]
+ fn hotkey_and_scroll_are_bounded_complete_packets() {
+ assert_eq!(
+ Action::Key {
+ key: "a".into(),
+ modifiers: vec!["ctrl".into(), "shift".into()]
+ }
+ .packet(2, TOKEN, 8, 100.0, 80.0)
+ .unwrap(),
+ format!("KEY 2 {TOKEN} 8 30 3")
+ );
+ assert_eq!(
+ Action::Scroll {
+ point: None,
+ direction: "up".into(),
+ amount: 3
+ }
+ .packet(3, TOKEN, 8, 100.0, 80.0)
+ .unwrap(),
+ format!("SCROLL 3 {TOKEN} 8 50 40 0 -30")
+ );
+ }
+
+ #[test]
+ fn malformed_responses_and_tokens_refuse() {
+ assert!(validate_reply(&json!({"ok": false})).is_err());
+ assert!(validate_reply(
+ &json!({"ok":false,"code":"permission_required","detail":"pending"})
+ )
+ .is_ok());
+ assert!(hex_field(&json!({"target":"../invalid"}), "target").is_err());
+ assert_eq!(
+ hex_field(&json!({"target":TOKEN}), "target").unwrap(),
+ TOKEN
+ );
+ }
+
+ fn test_connection() -> (Client, socket2::Socket) {
+ let mut fds = [-1; 2];
+ assert_eq!(
+ unsafe {
+ libc::socketpair(
+ libc::AF_UNIX,
+ libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC,
+ 0,
+ fds.as_mut_ptr(),
+ )
+ },
+ 0
+ );
+ let socket = unsafe { socket2::Socket::from_raw_fd(fds[0]) };
+ let peer = unsafe { socket2::Socket::from_raw_fd(fds[1]) };
+ socket.set_nonblocking(true).unwrap();
+ peer.set_read_timeout(Some(TIMEOUT)).unwrap();
+ (
+ Client {
+ socket,
+ cancellation: ActionCancellation::default(),
+ protocol: InputProtocol::Experiment,
+ foreground_supported: false,
+ delivery_route: None,
+ lane: None,
+ owner: "input-unregistered-test-client".into(),
+ path: PathBuf::new(),
+ pid: 1,
+ address: 1,
+ epoch: TOKEN.into(),
+ challenge: TOKEN.into(),
+ sequence: 0,
+ },
+ peer,
+ )
+ }
+
+ fn read_packet(peer: &socket2::Socket) -> String {
+ let mut bytes = [0u8; MAX_PACKET];
+ let count =
+ unsafe { libc::recv(peer.as_raw_fd(), bytes.as_mut_ptr().cast(), bytes.len(), 0) };
+ assert!(count > 0);
+ String::from_utf8(bytes[..count as usize].to_vec()).unwrap()
+ }
+
+ #[test]
+ fn peer_closure_probe_is_nonblocking_and_does_not_consume_packets() {
+ let (client, peer) = test_connection();
+ let started = Instant::now();
+ assert!(!client.peer_closed());
+ assert!(started.elapsed() < TIMEOUT);
+
+ peer.send(b"").unwrap();
+ peer.send(b"pending reply").unwrap();
+ assert!(!client.peer_closed());
+ assert!(!client.peer_closed());
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe {
+ libc::recv(
+ client.socket.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ byte.len(),
+ libc::MSG_DONTWAIT,
+ )
+ },
+ 0
+ );
+ assert_eq!(read_packet(&client.socket), "pending reply");
+ assert!(!client.peer_closed());
+
+ peer.send(b"last reply").unwrap();
+ drop(peer);
+ assert!(client.peer_closed());
+ assert_eq!(read_packet(&client.socket), "last reply");
+ assert!(client.peer_closed());
+ }
+
+ #[test]
+ fn peer_write_shutdown_is_conclusive_even_with_a_pending_empty_packet() {
+ let (client, peer) = test_connection();
+ peer.send(b"").unwrap();
+ peer.shutdown(std::net::Shutdown::Write).unwrap();
+ assert!(client.peer_closed());
+ }
+
+ #[tokio::test]
+ async fn aborted_queued_invocation_never_targets_or_changes_the_active_connection() {
+ let (client, peer) = test_connection();
+ let session = Arc::new(SessionClient {
+ client: Mutex::new(Some(client)),
+ });
+ let first = session.client.lock().unwrap();
+ let queued = session.clone();
+ let (started, waiting) = tokio::sync::oneshot::channel();
+ let (finished, done) = tokio::sync::oneshot::channel();
+ let call = tokio::spawn(async move {
+ let (_guard, cancellation) = ActionCancellation::invocation();
+ tokio::task::spawn_blocking(move || {
+ started.send(()).unwrap();
+ let result = queued
+ .lock(&cancellation)
+ .and_then(|slot| slot.as_ref().unwrap().request("TARGET synthetic"));
+ finished.send(result).unwrap();
+ })
+ .await
+ .unwrap();
+ });
+ waiting.await.unwrap();
+ call.abort();
+ assert!(call.await.unwrap_err().is_cancelled());
+ // The canceled queue entry exits even while the first owns the lane.
+ assert!(tokio::time::timeout(Duration::from_secs(1), done)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap_err()
+ .is::<ActionCancelled>());
+ assert!(first.is_some());
+ drop(first);
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ 1,
+ libc::MSG_DONTWAIT,
+ )
+ },
+ -1
+ );
+ assert_eq!(
+ std::io::Error::last_os_error().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ // The first connection is still usable; cancellation didn't clear it.
+ peer.send(br#"{"ok":true}"#).unwrap();
+ assert_eq!(
+ session
+ .client
+ .lock()
+ .unwrap()
+ .as_ref()
+ .unwrap()
+ .receive(Instant::now() + TIMEOUT)
+ .unwrap()["ok"],
+ true
+ );
+ }
+
+ #[tokio::test]
+ async fn aborted_acknowledged_drag_disconnects_only_its_own_lane_without_replay() {
+ let (mut client, peer) = test_connection();
+ client.lane = Some(0);
+ let (other, other_peer) = test_connection();
+ let (started, acknowledged) = tokio::sync::oneshot::channel();
+ let (finished, done) = tokio::sync::oneshot::channel();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "DRAG synthetic");
+ peer.send(br#"{"ok":true,"phase":"started"}"#).unwrap();
+ let mut bytes = [0u8; MAX_PACKET];
+ // EOF is the plugin's connection-scoped revoke/release signal.
+ // There must be no replay or unrelated release packet.
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), bytes.as_mut_ptr().cast(), bytes.len(), 0) },
+ 0
+ );
+ });
+ let call = tokio::spawn(async move {
+ let (_guard, cancellation) = ActionCancellation::invocation();
+ tokio::task::spawn_blocking(move || {
+ client.cancellation = cancellation;
+ let mut slot = Some(client);
+ let result = dispatch_in_slot(
+ &mut slot,
+ |_| Ok(()),
+ |client| client.dispatch("DRAG synthetic", true, Some(started)),
+ );
+ assert!(slot.is_none());
+ finished.send(result).unwrap();
+ })
+ .await
+ .unwrap();
+ });
+ acknowledged.await.unwrap();
+ call.abort();
+ assert!(call.await.unwrap_err().is_cancelled());
+ let error = tokio::time::timeout(Duration::from_secs(1), done)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap_err();
+ assert_eq!(
+ error
+ .downcast_ref::<DispatchUnknown>()
+ .unwrap()
+ .acknowledged_phases,
+ 1
+ );
+ server.join().unwrap();
+ other_peer.send(br#"{"ok":true}"#).unwrap();
+ assert_eq!(other.receive(Instant::now() + TIMEOUT).unwrap()["ok"], true);
+ }
+
+ fn hello_reply() -> Value {
+ json!({"ok":true,"protocol":0,"epoch":TOKEN,"challenge":TOKEN})
+ }
+
+ #[test]
+ fn canceled_invocation_cannot_send_on_a_ready_socket() {
+ let (mut client, peer) = test_connection();
+ let (guard, cancellation) = ActionCancellation::invocation();
+ client.cancellation = cancellation;
+ drop(guard);
+ for packet in [
+ "HELLO",
+ "CLAIM",
+ "TARGET synthetic",
+ "CLICK synthetic",
+ "DRAG synthetic",
+ ] {
+ assert!(client.request(packet).unwrap_err().is::<ActionCancelled>());
+ }
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ 1,
+ libc::MSG_DONTWAIT,
+ )
+ },
+ -1
+ );
+ assert_eq!(
+ std::io::Error::last_os_error().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ }
+
+ #[test]
+ fn cancelled_dispatch_before_send_is_an_exact_refusal() {
+ for route in [DeliveryRoute::Background, DeliveryRoute::Foreground] {
+ let (mut client, peer) = test_connection();
+ let (guard, cancellation) = ActionCancellation::invocation();
+ client.cancellation = cancellation;
+ drop(guard);
+ let error = client
+ .dispatch_routed("CLICK synthetic", false, None, route)
+ .unwrap_err();
+ assert!(error.is::<ActionCancelled>());
+ assert!(!error.is::<DispatchUnknown>());
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ byte.len(),
+ libc::MSG_DONTWAIT,
+ )
+ },
+ -1
+ );
+ assert_eq!(
+ std::io::Error::last_os_error().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ }
+ }
+
+ #[test]
+ fn cancelled_dispatch_after_send_preserves_unknown_progress() {
+ for route in [DeliveryRoute::Background, DeliveryRoute::Foreground] {
+ for is_drag in [false, true] {
+ let (mut client, peer) = test_connection();
+ let (guard, cancellation) = ActionCancellation::invocation();
+ client.cancellation = cancellation;
+ let (started, acknowledged) = tokio::sync::oneshot::channel();
+ let (finished, done) = std::sync::mpsc::channel();
+ let packet = if is_drag {
+ "DRAG synthetic"
+ } else {
+ "CLICK synthetic"
+ };
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), packet);
+ if is_drag {
+ peer.send(br#"{"ok":true,"phase":"started"}"#).unwrap();
+ acknowledged.blocking_recv().unwrap();
+ }
+ drop(guard);
+ // Keep the peer open until dispatch returns so cancellation,
+ // rather than EOF, determines the result.
+ done.recv_timeout(TIMEOUT).unwrap();
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ byte.len(),
+ libc::MSG_DONTWAIT,
+ )
+ },
+ -1
+ );
+ assert_eq!(
+ std::io::Error::last_os_error().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ });
+ let error = client
+ .dispatch_routed(packet, is_drag, Some(started), route)
+ .unwrap_err();
+ let unknown = error.downcast_ref::<DispatchUnknown>().unwrap();
+ assert_eq!(unknown.acknowledged_phases, u32::from(is_drag));
+ assert_eq!(unknown.detail, ActionCancelled.to_string());
+ assert!(!error.is::<ActionCancelled>());
+ finished.send(()).unwrap();
+ server.join().unwrap();
+ }
+ }
+ }
+
+ #[test]
+ fn interrupted_drag_preserves_acknowledged_progress_and_never_replays() {
+ for final_reply in [
+ Some(json!({"ok":false,"code":"cancelled","detail":"cancelled"})),
+ None,
+ Some(json!({"ok":true,"effect":"invalid"})),
+ ] {
+ let (client, peer) = test_connection();
+ let expected_cancel = final_reply
+ .as_ref()
+ .is_some_and(|value| value["ok"] == false);
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "DRAG synthetic");
+ peer.send(br#"{"ok":true,"phase":"started"}"#).unwrap();
+ if let Some(reply) = final_reply {
+ peer.send(reply.to_string().as_bytes()).unwrap();
+ }
+ });
+ let (started, acknowledged) = tokio::sync::oneshot::channel();
+ let result = client.dispatch("DRAG synthetic", true, Some(started));
+ assert!(acknowledged.blocking_recv().is_ok());
+ if expected_cancel {
+ let reply = result.unwrap();
+ assert_eq!(reply["effect"], "partial");
+ assert_eq!(
+ reply["delivery"],
+ json!({"mode":"background","delivered_count":1})
+ );
+ } else {
+ assert_eq!(
+ result
+ .unwrap_err()
+ .downcast_ref::<DispatchUnknown>()
+ .unwrap()
+ .acknowledged_phases,
+ 1
+ );
+ }
+ server.join().unwrap();
+ }
+ }
+
+ #[test]
+ fn missing_initial_action_reply_cannot_claim_acknowledged_progress() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "CLICK synthetic");
+ });
+ let result = client.dispatch("CLICK synthetic", false, None).unwrap_err();
+ assert_eq!(
+ result
+ .downcast_ref::<DispatchUnknown>()
+ .unwrap()
+ .acknowledged_phases,
+ 0
+ );
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn production_handshake_has_no_signer_and_claims_exact_lane() {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ client.challenge.clear();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(
+ json!({"ok":true,"protocol":3,"epoch":TOKEN})
+ .to_string()
+ .as_bytes(),
+ )
+ .unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ peer.send(br#"{"ok":true,"lane":1}"#).unwrap();
+ });
+ assert!(client.handshake(1).unwrap());
+ server.join().unwrap();
+ assert_eq!(client.lane, Some(1));
+ assert!(client.challenge.is_empty());
+ }
+
+ #[test]
+ fn production_refuses_experiment_and_unexpected_signer_without_claiming() {
+ for hello in [
+ hello_reply(),
+ json!({"ok":true,"protocol":3,"epoch":TOKEN,"challenge":TOKEN}),
+ ] {
+ let (mut client, peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(hello.to_string().as_bytes()).unwrap();
+ let mut bytes = [0u8; MAX_PACKET];
+ // Closing after the refused HELLO must be the next event:
+ // no CLAIM, TARGET, APPROVE, or input packet is sent.
+ let count = unsafe {
+ libc::recv(peer.as_raw_fd(), bytes.as_mut_ptr().cast(), bytes.len(), 0)
+ };
+ assert_eq!(count, 0);
+ });
+ assert!(client.handshake(0).is_err());
+ assert!(client.lane.is_none());
+ drop(client);
+ server.join().unwrap();
+ }
+ }
+
+ #[test]
+ fn production_targets_bind_one_exact_operation_and_use_distinct_endpoints() {
+ let (mut client, _peer) = test_connection();
+ client.protocol = InputProtocol::Production;
+ for (action, capability) in [
+ (
+ Action::Click {
+ x: 1.0,
+ y: 2.0,
+ button: 1,
+ count: 1,
+ },
+ 1,
+ ),
+ (
+ Action::Key {
+ key: "a".into(),
+ modifiers: vec![],
+ },
+ 2,
+ ),
+ (
+ Action::Scroll {
+ point: None,
+ direction: "up".into(),
+ amount: 1,
+ },
+ 4,
+ ),
+ (
+ Action::Drag {
+ from: (1.0, 2.0),
+ to: (3.0, 4.0),
+ duration_ms: 100,
+ },
+ 8,
+ ),
+ ] {
+ assert_eq!(
+ client.target_packet(&action),
+ format!("TARGET 1 1 {capability}")
+ );
+ }
+ for lane in 0..MAX_LANES {
+ assert_ne!(
+ InputProtocol::Production.socket_name(lane).unwrap(),
+ InputProtocol::Experiment.socket_name(lane).unwrap()
+ );
+ }
+ assert!(InputProtocol::Production.socket_name(MAX_LANES).is_err());
+ }
+
+ // A compositor-side pool, deliberately independent of Driver's CLIENTS.
+ // Retaining the peer models a reservation until the claimant disconnects.
+ fn fake_claim(
+ lane: usize,
+ pool: &Arc<Mutex<[Option<socket2::Socket>; MAX_LANES]>>,
+ ) -> Result<Option<Client>> {
+ let (mut client, peer) = test_connection();
+ let pool = pool.clone();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(hello_reply().to_string().as_bytes()).unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ let mut pool = pool.lock().unwrap();
+ if let Some(occupied) = pool[lane].as_ref() {
+ let mut byte = [0u8];
+ let count = unsafe {
+ libc::recv(
+ occupied.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ 1,
+ libc::MSG_DONTWAIT,
+ )
+ };
+ if count == 0 {
+ pool[lane] = None;
+ } else {
+ assert_eq!(count, -1);
+ assert_eq!(
+ std::io::Error::last_os_error().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ }
+ }
+ if pool[lane].is_some() {
+ peer.send(br#"{"ok":false,"code":"lane_busy","detail":"lane_busy"}"#)
+ .unwrap();
+ } else {
+ peer.send(json!({"ok":true,"lane":lane}).to_string().as_bytes())
+ .unwrap();
+ pool[lane] = Some(peer);
+ }
+ });
+ let result = client.handshake(lane);
+ server.join().unwrap();
+ result.map(|claimed| claimed.then_some(client))
+ }
+
+ #[test]
+ fn independent_claimants_use_compositor_reservations_and_disconnect_reuses_lane() {
+ let pool = Arc::new(Mutex::new([None, None]));
+ let mut attempts = Vec::new();
+ let a = claim_available(|lane| {
+ attempts.push(lane);
+ fake_claim(lane, &pool)
+ })
+ .unwrap();
+ assert_eq!(a.lane, Some(0));
+ assert_eq!(attempts, [0]);
+ attempts.clear();
+ let b = claim_available(|lane| {
+ attempts.push(lane);
+ fake_claim(lane, &pool)
+ })
+ .unwrap();
+ assert_eq!(b.lane, Some(1));
+ assert_eq!(attempts, [0, 1]);
+ attempts.clear();
+ assert!(claim_available(|lane| {
+ attempts.push(lane);
+ fake_claim(lane, &pool)
+ })
+ .err()
+ .unwrap()
+ .is::<LaneBusy>());
+ assert_eq!(attempts, [0, 1]);
+ drop(a);
+ let c = claim_available(|lane| fake_claim(lane, &pool)).unwrap();
+ assert_eq!(c.lane, Some(0));
+ assert_eq!(b.lane, Some(1));
+ drop(b);
+ let d = claim_available(|lane| fake_claim(lane, &pool)).unwrap();
+ assert_eq!(d.lane, Some(1));
+ }
+
+ #[test]
+ fn malformed_or_unexpected_handshake_never_tries_another_lane() {
+ let cases = [
+ (
+ json!({"ok":true,"protocol":1,"epoch":TOKEN,"challenge":TOKEN}),
+ None,
+ ),
+ (
+ json!({"ok":true,"protocol":0,"epoch":"bad","challenge":TOKEN}),
+ None,
+ ),
+ (
+ json!({"ok":false,"code":"lane_busy","detail":"lane_busy"}),
+ None,
+ ),
+ (hello_reply(), Some(json!({"ok":true}))),
+ (hello_reply(), Some(json!({"ok":true,"lane":1}))),
+ (hello_reply(), Some(json!({"ok":true,"lane":2}))),
+ (hello_reply(), Some(json!({"ok":true,"lane":"0"}))),
+ (hello_reply(), Some(json!({"ok":false,"code":"lane_busy"}))),
+ (
+ hello_reply(),
+ Some(json!({"ok":false,"code":"lane_busy","detail":"unknown"})),
+ ),
+ (
+ hello_reply(),
+ Some(json!({"ok":false,"code":"stopped","detail":"stopped"})),
+ ),
+ ];
+ for (hello, claim) in cases {
+ let mut attempts = Vec::new();
+ assert!(claim_available(|lane| {
+ attempts.push(lane);
+ let (mut client, peer) = test_connection();
+ let hello = hello.clone();
+ let claim = claim.clone();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(hello.to_string().as_bytes()).unwrap();
+ if let Some(claim) = claim {
+ assert_eq!(read_packet(&peer), "CLAIM");
+ peer.send(claim.to_string().as_bytes()).unwrap();
+ }
+ });
+ let result = client.handshake(lane);
+ server.join().unwrap();
+ assert!(client.lane.is_none());
+ result.map(|claimed| claimed.then_some(client))
+ })
+ .is_err());
+ assert_eq!(attempts, [0]);
+ }
+ }
+
+ #[test]
+ fn unknown_claim_outcome_and_connection_errors_never_try_another_lane() {
+ for reply in [None, Some("not-json")] {
+ let mut attempts = Vec::new();
+ assert!(claim_available(|lane| {
+ attempts.push(lane);
+ let (mut client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ assert_eq!(read_packet(&peer), "HELLO");
+ peer.send(hello_reply().to_string().as_bytes()).unwrap();
+ assert_eq!(read_packet(&peer), "CLAIM");
+ if let Some(reply) = reply {
+ peer.send(reply.as_bytes()).unwrap();
+ }
+ // The claim may have succeeded before connection loss.
+ });
+ let result = client.handshake(lane);
+ server.join().unwrap();
+ result.map(|claimed| claimed.then_some(client))
+ })
+ .is_err());
+ assert_eq!(attempts, [0]);
+ }
+ let mut attempts = Vec::new();
+ assert!(claim_available(|lane| {
+ attempts.push(lane);
+ bail!("connection unavailable")
+ })
+ .is_err());
+ assert_eq!(attempts, [0]);
+ }
+
+ #[test]
+ fn pending_termination_interrupts_receive_before_cleanup_barrier() {
+ use cua_driver_core::session::{self, SessionClientKind, SessionTransport};
+ let owner = "input-cancellation-owner";
+ let sid = "input-cancellation-runtime-id";
+ let guard = session::begin_session_dispatch(
+ sid,
+ None,
+ owner,
+ true,
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ .unwrap();
+ let (mut client, peer) = test_connection();
+ client.owner = sid.into();
+ let terminator = std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(50));
+ assert!(session::end_session_for_owner(sid, owner));
+ });
+ let start = Instant::now();
+ assert!(client
+ .receive(start + TIMEOUT)
+ .unwrap_err()
+ .to_string()
+ .contains("session ending"));
+ assert!(start.elapsed() < Duration::from_millis(750));
+ terminator.join().unwrap();
+ assert!(
+ !session::is_session_ended(sid),
+ "cleanup still waits for the guard"
+ );
+ drop(client); // execute_with_started drops exactly this connection on error.
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe { libc::recv(peer.as_raw_fd(), byte.as_mut_ptr().cast(), 1, 0) },
+ 0
+ );
+ let (other, other_peer) = test_connection();
+ other_peer.send(br#"{"ok":true}"#).unwrap();
+ assert_eq!(other.receive(Instant::now() + TIMEOUT).unwrap()["ok"], true);
+ drop(guard);
+ assert!(session::is_session_ended(sid));
+ }
+
+ #[test]
+ fn terminated_session_never_sends_even_when_socket_is_ready() {
+ let (mut client, peer) = test_connection();
+ client.owner = "input-terminated-runtime-id".into();
+ cua_driver_core::session::end_session(&client.owner);
+ assert!(client
+ .request("HELLO")
+ .unwrap_err()
+ .to_string()
+ .contains("session ending"));
+ let mut byte = [0u8];
+ assert_eq!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ byte.as_mut_ptr().cast(),
+ 1,
+ libc::MSG_DONTWAIT,
+ )
+ },
+ -1
+ );
+ assert_eq!(
+ std::io::Error::last_os_error().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ }
+
+ #[test]
+ fn pending_refusal_keeps_seqpacket_connection_usable() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ for _ in 0..2 {
+ let mut packet = [0u8; 64];
+ assert!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ packet.as_mut_ptr().cast(),
+ packet.len(),
+ 0,
+ )
+ } > 0
+ );
+ peer.send(br#"{"ok":false,"code":"permission_required","detail":"pending"}"#)
+ .unwrap();
+ }
+ });
+ for _ in 0..2 {
+ assert_eq!(
+ client.request("HELLO").unwrap()["code"],
+ "permission_required"
+ );
+ }
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn oversized_seqpacket_reply_refuses_without_truncation() {
+ let (client, peer) = test_connection();
+ let server = std::thread::spawn(move || {
+ let mut packet = [0u8; 64];
+ assert!(
+ unsafe {
+ libc::recv(
+ peer.as_raw_fd(),
+ packet.as_mut_ptr().cast(),
+ packet.len(),
+ 0,
+ )
+ } > 0
+ );
+ peer.send(&vec![b' '; MAX_PACKET + 1]).unwrap();
+ });
+ assert!(client
+ .request("HELLO")
+ .unwrap_err()
+ .to_string()
+ .contains("oversized"));
+ server.join().unwrap();
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
index f1079159d4..ca0b7691e3 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
@@ -13,11 +13,14 @@ pub mod ext_screencopy;
pub mod ext_toplevel;
pub mod hyprland;
pub mod hyprland_capture;
+mod hyprland_compatibility;
+pub mod hyprland_input;
pub mod kwin_helper;
pub mod overlay;
pub mod persistent_vptr;
pub(crate) mod portal;
pub mod portal_screenshot;
+mod primary_seat;
pub mod shell_helper;
pub mod sway_ipc;
mod virtual_keyboard;
@@ -385,7 +388,7 @@ struct State {
// Live handles + a seat, kept so `click` can `activate` a target toplevel by
// its window_id (foreign-toplevel protocol id) — the focus-based input model.
handles: HashMap<u32, ZwlrForeignToplevelHandleV1>,
- seat: Option<WlSeat>,
+ seats: primary_seat::Seats<WlSeat>,
// Virtual-pointer manager + output dimensions, so `click` can land a real
// button press at the output centre (over the just-activated window).
vptr_manager: Option<ZwlrVirtualPointerManagerV1>,
@@ -419,7 +422,9 @@ impl Dispatch<wl_registry::WlRegistry, ()> for State {
Some(registry.bind::<ZwlrForeignToplevelManagerV1, _, _>(name, v, qh, ()));
} else if interface == WlSeat::interface().name {
let v = version.min(7);
- state.seat = Some(registry.bind::<WlSeat, _, _>(name, v, qh, ()));
+ state
+ .seats
+ .add(registry.bind::<WlSeat, _, _>(name, v, qh, ()));
} else if interface == ZwlrVirtualPointerManagerV1::interface().name {
state.vptr_manager = Some(registry.bind::<ZwlrVirtualPointerManagerV1, _, _>(
name,
@@ -448,15 +453,16 @@ impl Dispatch<wl_registry::WlRegistry, ()> for State {
impl Dispatch<WlSeat, ()> for State {
fn event(
- _: &mut Self,
- _: &WlSeat,
- _: wayland_client::protocol::wl_seat::Event,
+ state: &mut Self,
+ seat: &WlSeat,
+ event: wayland_client::protocol::wl_seat::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
- // Seat name/capabilities events are irrelevant here — we only need the
- // seat object to pass to foreign-toplevel `activate`.
+ if let wayland_client::protocol::wl_seat::Event::Name { name } = event {
+ state.seats.name(seat, name);
+ }
}
}
@@ -1306,7 +1312,7 @@ pub fn open_vptr_session(activate_window_id: Option<u64>) -> anyhow::Result<Vptr
anyhow::bail!("compositor does not expose zwlr_foreign_toplevel_manager_v1");
}
- let seat = state.seat.clone().ok_or_else(|| {
+ let seat = state.seats.selected().ok_or_else(|| {
anyhow::anyhow!("compositor exposed no wl_seat for virtual-pointer input")
})?;
@@ -1383,7 +1389,7 @@ pub fn activate_window_for_input_target(
if let (Some(_), Some(seat), Some(handle)) = (
state.manager.as_ref(),
- state.seat.clone(),
+ state.seats.selected(),
matching_handle(&state, window_id),
) {
let protocol_id = handle.id().protocol_id();
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
index 129a51ced5..c271faab8e 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
@@ -111,7 +111,8 @@ fn tx() -> Option<&'static Sender<WlOverlayCmd>> {
}
/// Lazily start the owner thread. Idempotent — safe to call from every
-/// MCP tool invocation; subsequent calls are no-ops.
+/// MCP tool invocation; subsequent calls are no-ops. The thread connects to
+/// Wayland only after receiving a renderer command for a live cursor key.
pub fn ensure_started() -> bool {
if !CONFIG_ENABLED.load(Ordering::Acquire) {
return false;
@@ -139,17 +140,10 @@ pub fn forward(msg: &OverlayMsg) -> bool {
if !should_forward(CONFIG_ENABLED.load(Ordering::Acquire), msg) {
return false;
}
- // If the owner has never started, it cannot hold a tombstone. Accept the
- // lifecycle transition without paying the compositor startup cost.
- if matches!(msg, OverlayMsg::Revive(_)) && tx().is_none() {
- return true;
- }
- // Lazy startup: spawning the layer-shell owner thread + connecting to
- // the Wayland compositor takes 100-300ms. Doing that at cua-driver mcp
- // boot (the old eager-init path) was tipping the borderline CI
- // cursor-click-gif test over its 20s budget. ensure_started is
- // idempotent so calling it on every forward is fine — the OnceLock
- // bypasses the spawn after the first call.
+ // All lifecycle transitions share the owner's command queue so a cold
+ // Remove still suppresses late commands, and Revive preserves ordering.
+ // Starting this thread does not connect to Wayland: lifecycle-only cleanup
+ // must never create layer surfaces just to destroy them again.
if !ensure_started() {
return false;
}
@@ -558,14 +552,58 @@ fn ensure_layer_surface(state: &mut OverlayState, id: u32, qh: &QueueHandle<Over
output.layer_surface = Some(layer_surface);
}
+/// Retain lifecycle and visual metadata without touching the compositor.
+/// Session labels and BeginAction/EndAction also arrive for observation and
+/// refused actions; none has a position to paint. Return the first positioned
+/// command unapplied so the active loop can drain it and later transitions
+/// together, in their original order.
+fn wait_for_renderer_command(
+ rx: &Receiver<WlOverlayCmd>,
+ state: &mut OverlayState,
+) -> Option<WlOverlayCmd> {
+ while let Ok(command) = rx.recv() {
+ match command {
+ WlOverlayCmd::Shutdown => return None,
+ WlOverlayCmd::Remove(key) => {
+ remove_keyed_core(&mut state.cores, &mut state.ended, key);
+ }
+ WlOverlayCmd::Revive(key) => revive_key(&mut state.ended, key),
+ WlOverlayCmd::Cmd { ref key, ref cmd } if !state.ended.contains(key) => {
+ if matches!(
+ cmd,
+ OverlayCommand::MoveTo { .. }
+ | OverlayCommand::SnapTo { .. }
+ | OverlayCommand::ClickPulse { .. }
+ ) {
+ return Some(command);
+ }
+ apply_keyed_command(
+ &mut state.cores,
+ &state.template,
+ &state.ended,
+ key.clone(),
+ cmd.clone(),
+ );
+ }
+ WlOverlayCmd::Cmd { .. } => {}
+ }
+ }
+ None
+}
+
fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
+ let template = CONFIG_TEMPLATE.get().cloned().unwrap_or_default();
+ let mut state = OverlayState::new(template);
+ let Some(first_command) = wait_for_renderer_command(&rx, &mut state) else {
+ return Ok(());
+ };
+
+ dbg("connecting after positioned cursor command");
let conn = Connection::connect_to_env()?;
let mut queue = conn.new_event_queue::<OverlayState>();
let qh = queue.handle();
let _registry = conn.display().get_registry(&qh, ());
- let template = CONFIG_TEMPLATE.get().cloned().unwrap_or_default();
- let mut state = OverlayState::new(template);
queue.roundtrip(&mut state)?;
state
@@ -625,9 +663,14 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
// observed; full-display SHM work remains limited to visual changes.
let mut last_tick = Instant::now();
let mut frame_tick_needed = false;
+ let mut startup_command = Some(first_command);
loop {
let wait = next_wait(&state.cores, frame_tick_needed, state.topology_dirty);
- let (first_cmd, timed_out) = match wait_for_work(&rx, wait) {
+ let wake = startup_command
+ .take()
+ .map(WlWake::Command)
+ .unwrap_or_else(|| wait_for_work(&rx, wait));
+ let (first_cmd, timed_out) = match wake {
WlWake::Command(cmd) => (Some(cmd), None),
WlWake::Timeout => (None, Some(wait)),
WlWake::Disconnected => break,
@@ -1606,6 +1649,197 @@ mod tests {
));
}
+ fn snap_command(key: &str) -> WlOverlayCmd {
+ WlOverlayCmd::Cmd {
+ key: key.to_owned(),
+ cmd: OverlayCommand::SnapTo {
+ x: 100.0,
+ y: 100.0,
+ heading_radians: None,
+ },
+ }
+ }
+
+ #[test]
+ fn cold_remove_suppresses_stale_commands_without_renderer_startup() {
+ let (tx, rx) = bounded(8);
+ tx.send(WlOverlayCmd::Revive("session-a".to_owned()))
+ .unwrap();
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ tx.send(snap_command("session-a")).unwrap();
+ tx.send(WlOverlayCmd::Shutdown).unwrap();
+
+ let mut state = OverlayState::new(CursorConfig::default());
+ assert!(wait_for_renderer_command(&rx, &mut state).is_none());
+ assert!(state.ended.contains("session-a"));
+ assert!(!state.cores.contains_key("session-a"));
+ assert!(state.outputs.is_empty());
+ }
+
+ fn cold_metadata(key: &str) -> Vec<WlOverlayCmd> {
+ use cursor_overlay::CursorAction;
+ [
+ OverlayCommand::SetSessionLabel("Synthetic session".into()),
+ OverlayCommand::SetEnabled(true),
+ OverlayCommand::PinAbove(42),
+ OverlayCommand::SetPressed(false),
+ OverlayCommand::BeginAction {
+ action: CursorAction::Observe,
+ delivery: None,
+ target: None,
+ },
+ OverlayCommand::EndAction(CursorAction::Observe),
+ OverlayCommand::BeginAction {
+ action: CursorAction::Drag,
+ delivery: None,
+ target: None,
+ },
+ OverlayCommand::EndAction(CursorAction::Drag),
+ ]
+ .into_iter()
+ .map(|cmd| WlOverlayCmd::Cmd {
+ key: key.to_owned(),
+ cmd,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn cold_observation_and_refused_action_metadata_never_connects_to_wayland() {
+ for end_session in [false, true] {
+ let (tx, rx) = bounded(16);
+ for command in cold_metadata("session-a") {
+ tx.send(command).unwrap();
+ }
+ if end_session {
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ }
+ drop(tx);
+ // The real owner must finish without connecting, even when the
+ // process exits with observation/action metadata still queued.
+ assert!(owner_thread(rx).is_ok());
+ }
+ }
+
+ #[test]
+ fn cold_metadata_is_retained_before_first_positioned_command() {
+ let (tx, rx) = bounded(16);
+ for command in cold_metadata("session-a") {
+ tx.send(command).unwrap();
+ }
+ tx.send(snap_command("session-a")).unwrap();
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ drop(tx);
+ let mut state = OverlayState::new(CursorConfig::default());
+ assert!(matches!(
+ wait_for_renderer_command(&rx, &mut state),
+ Some(WlOverlayCmd::Cmd {
+ cmd: OverlayCommand::SnapTo { .. },
+ ..
+ })
+ ));
+ let core = state.cores.get("session-a").unwrap();
+ assert_eq!(core.session_label.as_deref(), Some("Synthetic session"));
+ assert!(core.pos.0 < -50.0);
+ assert!(state.outputs.is_empty());
+ assert!(matches!(
+ rx.try_recv(),
+ Ok(WlOverlayCmd::Remove(key)) if key == "session-a"
+ ));
+ }
+
+ #[test]
+ fn cold_revive_allows_startup_and_preserves_other_tombstones_and_queue_order() {
+ let (tx, rx) = bounded(8);
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ tx.send(WlOverlayCmd::Remove("session-b".to_owned()))
+ .unwrap();
+ tx.send(snap_command("session-a")).unwrap();
+ tx.send(WlOverlayCmd::Revive("session-a".to_owned()))
+ .unwrap();
+ tx.send(snap_command("session-a")).unwrap();
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ tx.send(snap_command("session-a")).unwrap();
+ drop(tx);
+
+ let mut state = OverlayState::new(CursorConfig::default());
+ assert!(matches!(
+ wait_for_renderer_command(&rx, &mut state),
+ Some(WlOverlayCmd::Cmd { key, .. }) if key == "session-a"
+ ));
+ assert!(!state.ended.contains("session-a"));
+ assert!(state.ended.contains("session-b"));
+ // Startup must not consume the later Remove or reorder it behind the
+ // stale command. The active loop receives both in their original order.
+ assert!(matches!(
+ rx.try_recv(),
+ Ok(WlOverlayCmd::Remove(key)) if key == "session-a"
+ ));
+ assert!(matches!(
+ rx.try_recv(),
+ Ok(WlOverlayCmd::Cmd { key, .. }) if key == "session-a"
+ ));
+ }
+
+ #[test]
+ fn cold_fresh_key_starts_with_ended_session_still_suppressed() {
+ let (tx, rx) = bounded(4);
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ tx.send(snap_command("session-a")).unwrap();
+ tx.send(snap_command("session-b")).unwrap();
+ drop(tx);
+
+ let mut state = OverlayState::new(CursorConfig::default());
+ let Some(WlOverlayCmd::Cmd { key, cmd }) = wait_for_renderer_command(&rx, &mut state)
+ else {
+ panic!("fresh session should start the renderer");
+ };
+ assert_eq!(key, "session-b");
+ assert!(apply_keyed_command(
+ &mut state.cores,
+ &state.template,
+ &state.ended,
+ key,
+ cmd,
+ ));
+ assert!(state.cores.contains_key("session-b"));
+ let WlOverlayCmd::Cmd { key, cmd } = snap_command("session-a") else {
+ unreachable!();
+ };
+ assert!(!apply_keyed_command(
+ &mut state.cores,
+ &state.template,
+ &state.ended,
+ key,
+ cmd,
+ ));
+ assert!(!state.cores.contains_key("session-a"));
+ }
+
+ #[test]
+ fn cold_shutdown_and_channel_close_exit_owner_without_wayland() {
+ for shutdown in [false, true] {
+ let (tx, rx) = bounded(4);
+ tx.send(WlOverlayCmd::Remove("session-a".to_owned()))
+ .unwrap();
+ tx.send(WlOverlayCmd::Revive("session-a".to_owned()))
+ .unwrap();
+ if shutdown {
+ tx.send(WlOverlayCmd::Shutdown).unwrap();
+ }
+ drop(tx);
+ // Exercise the actual owner entry point: it must return before
+ // attempting Connection::connect_to_env, even without a compositor.
+ assert!(owner_thread(rx).is_ok());
+ }
+ }
+
#[test]
fn named_cursors_render_on_independent_outputs_and_removal_clears_only_one() {
let template = CursorConfig::default();
@@ -1768,6 +2002,14 @@ mod tests {
});
let had_thread = TX.get().is_some();
assert!(!should_forward(false, &msg));
+ assert!(!should_forward(
+ false,
+ &OverlayMsg::Remove("session-a".to_owned())
+ ));
+ assert!(!should_forward(
+ false,
+ &OverlayMsg::Revive("session-a".to_owned())
+ ));
assert!(!ensure_started());
assert_eq!(TX.get().is_some(), had_thread);
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/primary_seat.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/primary_seat.rs
new file mode 100644
index 0000000000..1bac1b4a32
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/primary_seat.rs
@@ -0,0 +1,83 @@
+//! Keep synthetic delivery seats out of the existing foreground input path.
+//! Preserve the legacy last-advertised-seat choice among ordinary seats.
+
+pub(super) struct Seats<T> {
+ entries: Vec<(T, Option<String>)>,
+}
+
+impl<T> Default for Seats<T> {
+ fn default() -> Self {
+ Self {
+ entries: Vec::new(),
+ }
+ }
+}
+
+impl<T: Clone + PartialEq> Seats<T> {
+ pub(super) fn add(&mut self, seat: T) {
+ self.entries.push((seat, None));
+ }
+
+ pub(super) fn name(&mut self, seat: &T, name: String) {
+ if let Some(entry) = self.entries.iter_mut().find(|entry| &entry.0 == seat) {
+ entry.1 = Some(name);
+ }
+ }
+
+ pub(super) fn selected(&self) -> Option<T> {
+ self.entries
+ .iter()
+ .rev()
+ .find(|entry| {
+ !entry.1.as_deref().is_some_and(|name| {
+ name == "Cua-Test-Agent"
+ || name.starts_with("Cua-Test-Agent-")
+ || name == "Cua-Agent"
+ || name == "Cua-Agent-2"
+ })
+ })
+ .map(|entry| entry.0.clone())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Seats;
+
+ #[test]
+ fn experimental_seat_never_replaces_primary_after_names_arrive() {
+ for order in [[1, 2], [2, 1]] {
+ let mut seats = Seats::default();
+ for seat in order {
+ seats.add(seat);
+ }
+ seats.name(&1, "seat0".into());
+ seats.name(&2, "Cua-Test-Agent".into());
+ assert_eq!(seats.selected(), Some(1));
+ }
+ }
+
+ #[test]
+ fn no_primary_seat_refuses_and_legacy_selection_is_preserved() {
+ let mut seats = Seats::default();
+ seats.add(2);
+ seats.name(&2, "Cua-Test-Agent".into());
+ assert_eq!(seats.selected(), None);
+ seats.add(4);
+ seats.name(&4, "Cua-Test-Agent-2".into());
+ assert_eq!(seats.selected(), None);
+ seats.add(1);
+ seats.add(3);
+ assert_eq!(seats.selected(), Some(3));
+ }
+
+ #[test]
+ fn production_seats_never_replace_the_primary_seat() {
+ let mut seats = Seats::default();
+ for (id, name) in [(1, "seat0"), (2, "Cua-Agent"), (3, "Cua-Agent-2")] {
+ seats.add(id);
+ seats.name(&id, name.into());
+ }
+ assert_eq!(seats.selected(), Some(1));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs
index 5a57436ace..9a1dabb523 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs
@@ -37,7 +37,7 @@ const KEY_PRESSED: u32 = 1;
#[derive(Default)]
struct State {
- seat: Option<WlSeat>,
+ seats: super::primary_seat::Seats<WlSeat>,
manager: Option<ZwpVirtualKeyboardManagerV1>,
}
@@ -57,7 +57,7 @@ impl Dispatch<wl_registry::WlRegistry, ()> for State {
} = event
{
if interface == WlSeat::interface().name {
- state.seat = Some(registry.bind(name, version.min(7), qh, ()));
+ state.seats.add(registry.bind(name, version.min(7), qh, ()));
} else if interface == ZwpVirtualKeyboardManagerV1::interface().name {
state.manager = Some(registry.bind(name, version.min(1), qh, ()));
}
@@ -67,13 +67,16 @@ impl Dispatch<wl_registry::WlRegistry, ()> for State {
impl Dispatch<WlSeat, ()> for State {
fn event(
- _: &mut Self,
- _: &WlSeat,
- _: <WlSeat as Proxy>::Event,
+ state: &mut Self,
+ seat: &WlSeat,
+ event: <WlSeat as Proxy>::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
+ if let wayland_client::protocol::wl_seat::Event::Name { name } = event {
+ state.seats.name(seat, name);
+ }
}
}
@@ -112,8 +115,8 @@ pub(super) fn hotkey(modifiers: &[String], key: &str) -> anyhow::Result<()> {
queue.roundtrip(&mut state)?;
let seat = state
- .seat
- .clone()
+ .seats
+ .selected()
.ok_or_else(|| anyhow::anyhow!("compositor exposes no wl_seat"))?;
let manager = state
.manager
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/capture.rs b/libs/cua-driver/rust/crates/platform-windows/src/capture.rs
index 1dbee84781..eb2e52c298 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/capture.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/capture.rs
@@ -37,6 +37,108 @@ use windows::Win32::Graphics::Gdi::{GetWindowDC, ReleaseDC};
use windows::Win32::Storage::Xps::{PrintWindow, PRINT_WINDOW_FLAGS};
const PW_RENDERFULLCONTENT: PRINT_WINDOW_FLAGS = PRINT_WINDOW_FLAGS(2u32);
+mod frame_geometry {
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub(super) struct FrameGeometry {
+ pub left: i32,
+ pub top: i32,
+ pub width: i32,
+ pub height: i32,
+ }
+
+ impl FrameGeometry {
+ pub fn from_bounds((left, top, right, bottom): (i32, i32, i32, i32)) -> Option<Self> {
+ let width = right.checked_sub(left)?;
+ let height = bottom.checked_sub(top)?;
+ (width > 0 && height > 0).then_some(Self {
+ left,
+ top,
+ width,
+ height,
+ })
+ }
+
+ pub fn cropped(self, bounds: Option<(i32, i32, i32, i32)>) -> Self {
+ let crop = bounds.and_then(|(left, top, right, bottom)| {
+ Self::from_bounds((
+ left.checked_add(1)?,
+ top.checked_add(1)?,
+ right.checked_sub(1)?,
+ bottom.checked_sub(1)?,
+ ))
+ });
+ crop.filter(|crop| {
+ let x = i64::from(crop.left) - i64::from(self.left);
+ let y = i64::from(crop.top) - i64::from(self.top);
+ x >= 0
+ && y >= 0
+ && x + i64::from(crop.width) <= i64::from(self.width)
+ && y + i64::from(crop.height) <= i64::from(self.height)
+ })
+ .unwrap_or(self)
+ }
+
+ pub fn local_point(self, x: i32, y: i32) -> Option<(f64, f64)> {
+ let x = i64::from(x) - i64::from(self.left);
+ let y = i64::from(y) - i64::from(self.top);
+ (x >= 0 && y >= 0 && x < i64::from(self.width) && y < i64::from(self.height))
+ .then_some((x as f64, y as f64))
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::FrameGeometry;
+
+ #[test]
+ fn dwm_crop_maps_screen_point_to_actual_frame() {
+ let frame = FrameGeometry::from_bounds((-100, 20, 300, 320)).unwrap();
+ let crop = frame.cropped(Some((-92, 20, 292, 312)));
+ assert_eq!(
+ crop,
+ FrameGeometry {
+ left: -91,
+ top: 21,
+ width: 382,
+ height: 290
+ }
+ );
+ assert_eq!(crop.local_point(-90, 22), Some((1.0, 1.0)));
+ assert_eq!(crop.local_point(291, 22), None);
+ assert_eq!(crop.local_point(-92, 22), None);
+ assert_eq!(crop.local_point(-90, 311), None);
+ assert_eq!(crop.local_point(-90, 20), None);
+ }
+
+ #[test]
+ fn failed_or_outside_crop_keeps_window_rect_origin() {
+ let frame = FrameGeometry::from_bounds((100, -200, 500, 100)).unwrap();
+ for bounds in [
+ None,
+ Some((0, 0, 100, 100)),
+ Some((100, -200, 600, 100)),
+ Some((100, -200, 101, -199)),
+ ] {
+ assert_eq!(frame.cropped(bounds), frame);
+ }
+ assert_eq!(frame.local_point(100, -200), Some((0.0, 0.0)));
+ assert_eq!(frame.local_point(499, 99), Some((399.0, 299.0)));
+ }
+
+ #[test]
+ fn extreme_bounds_and_points_do_not_overflow() {
+ assert_eq!(FrameGeometry::from_bounds((i32::MIN, 0, i32::MAX, 1)), None);
+ assert_eq!(FrameGeometry::from_bounds((0, 0, 1, 0)), None);
+ let frame = FrameGeometry::from_bounds((0, 0, 100, 100)).unwrap();
+ assert_eq!(frame.cropped(Some((i32::MAX, 0, i32::MIN, 100))), frame);
+ assert_eq!(frame.cropped(Some((i32::MIN, 0, i32::MAX, 100))), frame);
+ assert_eq!(frame.local_point(i32::MIN, i32::MAX), None);
+ }
+ }
+}
+
+use frame_geometry::FrameGeometry;
+
/// After GetDIBits we have BGRA bytes from PrintWindow. If essentially every
/// pixel is fully-transparent black or fully-opaque black, treat the capture
/// as "PrintWindow didn't render this surface" and let the caller fall back
@@ -131,7 +233,7 @@ unsafe fn target_is_obscured(target: HWND) -> bool {
/// by `hwnd`'s on-screen bounds. Works for UWP / WinUI3 / DirectComposition
/// surfaces that PrintWindow can't reach, as long as the window is on-screen
/// (the daemon's typical case — see module docs).
-unsafe fn screenshot_via_screen_region(hwnd: HWND) -> Result<(Vec<u8>, i32, i32)> {
+unsafe fn screenshot_via_screen_region(hwnd: HWND) -> Result<(Vec<u8>, i32, i32, FrameGeometry)> {
use windows::Win32::Foundation::RECT;
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
@@ -146,11 +248,10 @@ unsafe fn screenshot_via_screen_region(hwnd: HWND) -> Result<(Vec<u8>, i32, i32)
let physical_left = rect.left;
let physical_top = rect.top;
- let w = rect.right - rect.left;
- let h = rect.bottom - rect.top;
- if w <= 0 || h <= 0 {
- bail!("screen-region fallback: window has zero/negative bounds: {w}x{h}");
- }
+ let geometry = FrameGeometry::from_bounds((rect.left, rect.top, rect.right, rect.bottom))
+ .ok_or_else(|| anyhow::anyhow!("screen-region fallback: invalid window bounds"))?;
+ let w = geometry.width;
+ let h = geometry.height;
let screen_dc = GetDC(HWND(std::ptr::null_mut())); // NULL HWND → desktop DC
let mem_dc = CreateCompatibleDC(screen_dc);
@@ -206,7 +307,7 @@ unsafe fn screenshot_via_screen_region(hwnd: HWND) -> Result<(Vec<u8>, i32, i32)
if ok == 0 {
bail!("screen-region fallback: GetDIBits returned 0");
}
- Ok((pixels, w, h))
+ Ok((pixels, w, h, geometry))
}
/// Capture a window by HWND, returning raw PNG bytes.
@@ -222,6 +323,25 @@ pub fn screenshot_window_bytes(hwnd: u64) -> Result<Vec<u8>> {
/// user / LLM should attach an explicit warning. See `target_is_obscured`
/// for the sampling heuristic.
pub fn screenshot_window_bytes_with_occlusion(hwnd: u64) -> Result<(Vec<u8>, bool)> {
+ screenshot_window_mapped(hwnd).map(|(png, occluded, _)| (png, occluded))
+}
+
+/// Capture the final input point against the exact source frame. WGC supplies
+/// no proven screen origin, so it cannot produce mapped click evidence yet.
+pub(crate) fn screenshot_window_click_target(
+ hwnd: u64,
+ screen_x: i32,
+ screen_y: i32,
+) -> Option<(Vec<u8>, f64, f64)> {
+ let (png, occluded, geometry) = screenshot_window_mapped(hwnd).ok()?;
+ if occluded {
+ return None;
+ }
+ let (x, y) = geometry?.local_point(screen_x, screen_y)?;
+ Some((png, x, y))
+}
+
+fn screenshot_window_mapped(hwnd: u64) -> Result<(Vec<u8>, bool, Option<FrameGeometry>)> {
match unsafe { screenshot_window_bytes_with_occlusion_unsafe(hwnd) } {
Ok(capture) => Ok(capture),
Err(primary_error) => {
@@ -236,6 +356,7 @@ pub fn screenshot_window_bytes_with_occlusion(hwnd: u64) -> Result<(Vec<u8>, boo
Ok((pixels, width, height)) => Ok((
cua_driver_core::image_utils::encode_bgra_to_png(&pixels, width, height)?,
false,
+ None,
)),
Err(wgc_error) => {
// Headless/virtualized Windows sessions can expose DWM but
@@ -245,13 +366,14 @@ pub fn screenshot_window_bytes_with_occlusion(hwnd: u64) -> Result<(Vec<u8>, boo
let target = HWND(hwnd as *mut _);
let occluded = unsafe { target_is_obscured(target) };
match unsafe { screenshot_via_screen_region(target) } {
- Ok((pixels, width, height)) => Ok((
+ Ok((pixels, width, height, geometry)) => Ok((
cua_driver_core::image_utils::encode_bgra_to_png(
&pixels,
width as u32,
height as u32,
)?,
occluded,
+ Some(geometry),
)),
Err(screen_error) => Err(primary_error.context(format!(
"Windows.Graphics.Capture fallback failed: {wgc_error}; \
@@ -278,7 +400,9 @@ pub fn screenshot_window(hwnd: u64) -> Result<(String, u32, u32)> {
Ok((BASE64.encode(&png_bytes), w, h))
}
-unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Vec<u8>, bool)> {
+unsafe fn screenshot_window_bytes_with_occlusion_unsafe(
+ hwnd: u64,
+) -> Result<(Vec<u8>, bool, Option<FrameGeometry>)> {
use windows::Win32::Foundation::RECT;
use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, IsIconic};
@@ -324,6 +448,7 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
return Ok((
cua_driver_core::image_utils::encode_bgra_to_png(&pixels, w, h)?,
false, // WGC reads target's own pixels — never occluded by definition
+ None,
));
}
Err(e) => {
@@ -336,10 +461,11 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
}
let occluded = target_is_obscured(hwnd);
match screenshot_via_screen_region(hwnd) {
- Ok((pixels, w, h)) => {
+ Ok((pixels, w, h, geometry)) => {
return Ok((
cua_driver_core::image_utils::encode_bgra_to_png(&pixels, w as u32, h as u32)?,
occluded,
+ Some(geometry),
));
}
Err(e) => {
@@ -374,11 +500,11 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
// matching the bitmap.
let mut win_rect = RECT::default();
GetWindowRect(hwnd, &mut win_rect)?;
- let w = win_rect.right - win_rect.left;
- let h = win_rect.bottom - win_rect.top;
- if w <= 0 || h <= 0 {
- bail!("Window has zero/negative size: {}x{}", w, h);
- }
+ let geometry =
+ FrameGeometry::from_bounds((win_rect.left, win_rect.top, win_rect.right, win_rect.bottom))
+ .ok_or_else(|| anyhow::anyhow!("Window has invalid bounds"))?;
+ let w = geometry.width;
+ let h = geometry.height;
let screen_dc = GetWindowDC(hwnd);
let mem_dc = CreateCompatibleDC(screen_dc);
@@ -462,32 +588,23 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
// captured bitmap. A 1-px inset on each side removes the hairline
// without losing actual UI content — anything that close to the
// edge is window-frame chrome, not content.
- const DWM_CROP_INSET_PX: i32 = 1;
- let (pixels, w, h) = if let Some(dwm) = dwm_rect {
- let off_x = (dwm.left - win_rect.left) as i32 + DWM_CROP_INSET_PX;
- let off_y = (dwm.top - win_rect.top) as i32 + DWM_CROP_INSET_PX;
- let crop_w = (dwm.right - dwm.left) as i32 - 2 * DWM_CROP_INSET_PX;
- let crop_h = (dwm.bottom - dwm.top) as i32 - 2 * DWM_CROP_INSET_PX;
- if off_x >= 0
- && off_y >= 0
- && crop_w > 0
- && crop_h > 0
- && off_x + crop_w <= w
- && off_y + crop_h <= h
- {
- let stride_full = (w * 4) as usize;
- let stride_crop = (crop_w * 4) as usize;
- let mut cropped = vec![0u8; (crop_w * crop_h * 4) as usize];
- for row in 0..crop_h as usize {
- let src_row = (off_y as usize + row) * stride_full + (off_x as usize) * 4;
- let dst_row = row * stride_crop;
- cropped[dst_row..dst_row + stride_crop]
- .copy_from_slice(&pixels[src_row..src_row + stride_crop]);
- }
- (cropped, crop_w, crop_h)
- } else {
- (pixels, w, h)
+ let cropped_geometry =
+ geometry.cropped(dwm_rect.map(|dwm| (dwm.left, dwm.top, dwm.right, dwm.bottom)));
+ let (pixels, w, h) = if cropped_geometry != geometry {
+ let off_x = cropped_geometry.left - geometry.left;
+ let off_y = cropped_geometry.top - geometry.top;
+ let crop_w = cropped_geometry.width;
+ let crop_h = cropped_geometry.height;
+ let stride_full = (w * 4) as usize;
+ let stride_crop = (crop_w * 4) as usize;
+ let mut cropped = vec![0u8; (crop_w * crop_h * 4) as usize];
+ for row in 0..crop_h as usize {
+ let src_row = (off_y as usize + row) * stride_full + (off_x as usize) * 4;
+ let dst_row = row * stride_crop;
+ cropped[dst_row..dst_row + stride_crop]
+ .copy_from_slice(&pixels[src_row..src_row + stride_crop]);
}
+ (cropped, crop_w, crop_h)
} else {
(pixels, w, h)
};
@@ -499,12 +616,14 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
// not covered).
// The WGC-first ordering covers backgrounded UWP targets the
// screen-region path mishandles (returns covering window's pixels).
- if is_mostly_black_bgra(&pixels) {
+ let mostly_black = is_mostly_black_bgra(&pixels);
+ if mostly_black {
match crate::wgc::screenshot_window_via_wgc(hwnd_raw) {
Ok((alt_pixels, w, h)) => {
return Ok((
cua_driver_core::image_utils::encode_bgra_to_png(&alt_pixels, w, h)?,
false,
+ None,
));
}
Err(e) => {
@@ -517,7 +636,7 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
}
let occluded = target_is_obscured(hwnd);
match screenshot_via_screen_region(hwnd) {
- Ok((alt_pixels, alt_w, alt_h)) => {
+ Ok((alt_pixels, alt_w, alt_h, geometry)) => {
return Ok((
cua_driver_core::image_utils::encode_bgra_to_png(
&alt_pixels,
@@ -525,6 +644,7 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
alt_h as u32,
)?,
occluded,
+ Some(geometry),
));
}
Err(e) => {
@@ -552,6 +672,7 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve
Ok((
cua_driver_core::image_utils::encode_bgra_to_png(&pixels, w as u32, h as u32)?,
false,
+ (!mostly_black).then_some(cropped_geometry),
))
}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs
index aa29319b4e..78e454b33c 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs
@@ -93,6 +93,15 @@ pub fn screenshot_for_recording(window_id: Option<u64>, pid: Option<i64>) -> Scr
}
}
+/// Called on the dispatch task after scrolling has resolved the final point.
+/// Keep capture inside the lazy callback so private/unrecorded turns do no work.
+#[cfg(target_os = "windows")]
+pub(crate) fn capture_dispatch_click_target(window_id: u64, pid: u32, x: i32, y: i32) {
+ cua_driver_core::recording::capture_dispatch_click_target(window_id, i64::from(pid), || {
+ crate::capture::screenshot_window_click_target(window_id, x, y)
+ });
+}
+
#[cfg(target_os = "windows")]
pub fn app_state_json_for(window_id: Option<u64>, pid: Option<i64>) -> Option<Vec<u8>> {
let pid = u32::try_from(pid?).ok()?;
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index c4aad564c9..cefdd2817c 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -1,6 +1,7 @@
//! Real Windows tool implementations (compiled only on Windows).
use async_trait::async_trait;
+use cua_driver_core::action_record::ActionTransport;
/// Pin the agent-cursor overlay above `hwnd` in the z-order, normalising to
/// the **root** ancestor so the pin lands on the window that actually appears
@@ -2955,6 +2956,61 @@ fn posted_pixel_click_result(pid: u32, click_word: &str) -> ToolResult {
}))
}
+enum BackgroundElementClick {
+ Semantic {
+ message: String,
+ transport: ActionTransport,
+ failed_calls: Vec<ActionTransport>,
+ },
+ Inject {
+ x: i32,
+ y: i32,
+ failed_calls: Vec<ActionTransport>,
+ },
+ Post {
+ x: i32,
+ y: i32,
+ failed_calls: Vec<ActionTransport>,
+ },
+}
+
+fn background_element_click_result(
+ message: String,
+ transport: ActionTransport,
+ failed_calls: Vec<ActionTransport>,
+) -> ToolResult {
+ use cua_driver_core::action_record::{
+ ActionAttempt, ActionEffect, ActionExecutionRecord, ActionFallback, ActualDelivery,
+ RequestedDelivery,
+ };
+ let path = match transport {
+ ActionTransport::WindowsTargetedInjection => "pixel",
+ ActionTransport::WindowsPostMessage => "post_message",
+ _ => "ax",
+ };
+ let mut record = ActionExecutionRecord::new(
+ ActionEffect::Unverifiable,
+ transport,
+ RequestedDelivery::Background,
+ );
+ record.actual_delivery = Some(ActualDelivery::Background);
+ for (index, attempted) in failed_calls.iter().copied().enumerate() {
+ record.attempts.push(ActionAttempt {
+ transport: attempted,
+ delivery: ActualDelivery::Background,
+ detail: Some("UIA provider action returned an error".into()),
+ });
+ record.fallbacks.push(ActionFallback {
+ from: attempted,
+ to: failed_calls.get(index + 1).copied().unwrap_or(transport),
+ reason: "Previous UIA provider action failed".into(),
+ });
+ }
+ ToolResult::text(message)
+ .with_structured(json!({ "path": path, "verified": false, "effect": "unverifiable" }))
+ .with_action_record(record)
+}
+
pub struct ClickTool {
state: Arc<ToolState>,
}
@@ -3449,6 +3505,7 @@ impl Tool for ClickTool {
// ScrollViewers report a clipped item as on-screen because its
// stale rectangle is still inside the outer HWND. Ask the item
// to scroll itself into view before trusting that rectangle.
+ let recorded_center = (cx, cy);
let (cx, cy) = if !modifiers.is_empty() {
self.state
.element_cache
@@ -3483,6 +3540,9 @@ impl Tool for ClickTool {
let prev_fg_addr = unsafe {
windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow().0 as usize
};
+ if (cx, cy) != recorded_center {
+ crate::recording_hooks::capture_dispatch_click_target(hwnd, pid, cx, cy);
+ }
let send_result = tokio::task::spawn_blocking(move || {
let mod_refs: Vec<&str> = mods_owned.iter().map(String::as_str).collect();
crate::input::send_click_synthesized_active_mods(
@@ -3534,15 +3594,14 @@ impl Tool for ClickTool {
})
.await;
return match posted {
- Ok(Ok(())) => ToolResult::text(format!(
- "✅ Posted click on Chromium element [{idx}] at screen ({cx},{cy}) \
+ Ok(Ok(())) => background_element_click_result(
+ format!(
+ "✅ Posted click on Chromium element [{idx}] at screen ({cx},{cy}) \
(background, no foreground swap)."
- ))
- .with_structured(json!({
- "path": "post_message",
- "verified": false,
- "effect": "unverifiable"
- })),
+ ),
+ ActionTransport::WindowsPostMessage,
+ vec![],
+ ),
Ok(Err(error)) => ToolResult::error(error.to_string()),
Err(error) => ToolResult::error(format!("Task error: {error}")),
};
@@ -3559,7 +3618,8 @@ impl Tool for ClickTool {
// concept — PostMessage produces the actual WM_LBUTTONDBLCLK)
let state_clone = self.state.clone();
let use_uia_invoke = (btn == "left" || btn == "middle") && count == 1;
- let result = tokio::task::spawn_blocking(move || -> anyhow::Result<String> {
+ let result = tokio::task::spawn_blocking(move || -> anyhow::Result<BackgroundElementClick> {
+ let mut failed_calls = Vec::new();
// Direct Chromium UIA Invoke can return S_OK without firing a
// DOM event while occluded. Try the honest coordinate actuator
// first: it lands while visible and reports occlusion without
@@ -3571,13 +3631,7 @@ impl Tool for ClickTool {
&state_clone.element_cache, pid, hwnd, idx, cx, cy, "clicking",
)
.map_err(|result| anyhow::anyhow!(tool_result_text(result)))?;
- return crate::input::inject_click_screen(hwnd, cx, cy, count, &btn)
- .map(|()| format!(
- "✅ Injected click on [{idx}] (screen ({cx},{cy}), background, no foreground swap)."
- ))
- .map_err(|error| anyhow::anyhow!(
- "__CUA_BG_UNAVAILABLE_CLICK__{error}"
- ));
+ return Ok(BackgroundElementClick::Inject { x: cx, y: cy, failed_calls });
}
if use_uia_invoke {
// Retain the element out of the cache (AddRef under the
@@ -3619,13 +3673,14 @@ impl Tool for ClickTool {
match outcome {
Ok(()) => {
std::mem::forget(elem);
- return Ok(format!(
+ return Ok(BackgroundElementClick::Semantic { message: format!(
"✅ Performed UIA Invoke on [{idx}] (screen ({cx},{cy}))."
- ));
+ ), transport: ActionTransport::WindowsUiaInvoke, failed_calls });
}
Err(e) => tracing::debug!(target: "click",
"UIA Invoke on [{idx}]: {e}, trying Toggle"),
}
+ failed_calls.push(ActionTransport::WindowsUiaInvoke);
}
}
let toggle_result = unsafe { elem.GetCurrentPattern(UIA_TogglePatternId) };
@@ -3635,10 +3690,11 @@ impl Tool for ClickTool {
hwnd as isize, || unsafe { tg.Toggle() });
if outcome.is_ok() {
std::mem::forget(elem);
- return Ok(format!(
+ return Ok(BackgroundElementClick::Semantic { message: format!(
"✅ Performed UIA Toggle on [{idx}] (screen ({cx},{cy}))."
- ));
+ ), transport: ActionTransport::WindowsUiaToggle, failed_calls });
}
+ failed_calls.push(ActionTransport::WindowsUiaToggle);
}
}
let sel_result = unsafe { elem.GetCurrentPattern(UIA_SelectionItemPatternId) };
@@ -3648,10 +3704,11 @@ impl Tool for ClickTool {
hwnd as isize, || unsafe { si.Select() });
if outcome.is_ok() {
std::mem::forget(elem);
- return Ok(format!(
+ return Ok(BackgroundElementClick::Semantic { message: format!(
"✅ Performed UIA SelectionItem.Select on [{idx}] (screen ({cx},{cy}))."
- ));
+ ), transport: ActionTransport::WindowsUiaSelection, failed_calls });
}
+ failed_calls.push(ActionTransport::WindowsUiaSelection);
}
}
let exp_result = unsafe { elem.GetCurrentPattern(UIA_ExpandCollapsePatternId) };
@@ -3661,10 +3718,11 @@ impl Tool for ClickTool {
hwnd as isize, || unsafe { ec.Expand() });
if outcome.is_ok() {
std::mem::forget(elem);
- return Ok(format!(
+ return Ok(BackgroundElementClick::Semantic { message: format!(
"✅ Performed UIA ExpandCollapse.Expand on [{idx}] (screen ({cx},{cy}))."
- ));
+ ), transport: ActionTransport::WindowsUiaExpandCollapse, failed_calls });
}
+ failed_calls.push(ActionTransport::WindowsUiaExpandCollapse);
}
}
std::mem::forget(elem);
@@ -3686,43 +3744,67 @@ impl Tool for ClickTool {
"clicking",
)
.map_err(|result| anyhow::anyhow!(tool_result_text(result)))?;
- return crate::input::inject_click_screen(hwnd, cx, cy, count, &btn)
- .map(|()| {
- format!(
- "✅ Injected click on [{idx}] (screen ({cx},{cy}), background, no foreground swap)."
- )
- })
- .map_err(|error| {
- anyhow::anyhow!("__CUA_BG_UNAVAILABLE_CLICK__{error}")
- });
+ return Ok(BackgroundElementClick::Inject { x: cx, y: cy, failed_calls });
}
- crate::input::post_click_screen(hwnd, cx, cy, count, &btn)?;
- let action_name = match btn.as_str() {
- "right" => "ShowMenu",
- _ => "PostMessage click",
- };
- Ok(format!("✅ Performed {action_name} on [{idx}] (screen ({cx},{cy}))."))
+ Ok(BackgroundElementClick::Post { x: cx, y: cy, failed_calls })
}).await;
- match result {
- // UIA Invoke/Toggle/SelectionItem (or the PostMessage/injection
- // fallback) dispatched, but none of these is driver-verifiable —
- // UIA Invoke has no read-back. `effect: unverifiable`; the caller
- // confirms via screenshot. (The would_be_silently_dropped surfaces
- // are diverted to `background_unavailable` below before reaching
- // here, so a success here always means a real dispatch.)
- Ok(Ok(msg)) => ToolResult::text(msg).with_structured(
- json!({ "path": "ax", "verified": false, "effect": "unverifiable" }),
- ),
- Ok(Err(e)) if e.to_string().contains("__CUA_BG_UNAVAILABLE_CLICK__") => {
- let cause = e.to_string().replace("__CUA_BG_UNAVAILABLE_CLICK__", "");
+ let plan = match result {
+ Ok(Ok(plan)) => plan,
+ Ok(Err(e)) => return ToolResult::error(e.to_string()),
+ Err(e) => return ToolResult::error(format!("Task error: {e}")),
+ };
+ let (x, y, failed_calls, inject) = match plan {
+ BackgroundElementClick::Semantic {
+ message,
+ transport,
+ failed_calls,
+ } => {
+ return background_element_click_result(message, transport, failed_calls);
+ }
+ BackgroundElementClick::Inject { x, y, failed_calls } => (x, y, failed_calls, true),
+ BackgroundElementClick::Post { x, y, failed_calls } => (x, y, failed_calls, false),
+ };
+ // Return to the dispatch task before capturing: task-local recording
+ // context does not propagate into the blocking scroll resolver.
+ if (x, y) != (cx, cy) {
+ crate::recording_hooks::capture_dispatch_click_target(hwnd, pid, x, y);
+ }
+ let btn = button.clone();
+ let action_name = if btn == "right" {
+ "ShowMenu"
+ } else {
+ "PostMessage click"
+ };
+ let sent = tokio::task::spawn_blocking(move || {
+ if inject {
+ crate::input::inject_click_screen(hwnd, x, y, count, &btn)
+ } else {
+ crate::input::post_click_screen(hwnd, x, y, count, &btn)
+ }
+ })
+ .await;
+ match sent {
+ Ok(Ok(())) => {
+ let (message, transport) = if inject {
+ (format!("✅ Injected click on [{idx}] (screen ({x},{y}), background, no foreground swap)."),
+ ActionTransport::WindowsTargetedInjection)
+ } else {
+ (
+ format!("✅ Performed {action_name} on [{idx}] (screen ({x},{y}))."),
+ ActionTransport::WindowsPostMessage,
+ )
+ };
+ background_element_click_result(message, transport, failed_calls)
+ }
+ Ok(Err(error)) if inject => {
crate::input::delivery::background_unavailable_error_with_cause(
hwnd,
EventKind::MouseClick,
- cause,
+ error.to_string(),
)
}
- Ok(Err(e)) => ToolResult::error(e.to_string()),
- Err(e) => ToolResult::error(format!("Task error: {e}")),
+ Ok(Err(error)) => ToolResult::error(error.to_string()),
+ Err(error) => ToolResult::error(format!("Task error: {error}")),
}
} else if let (Some(mut px), Some(mut py)) = (x, y) {
let from_zoom = args
@@ -3995,6 +4077,73 @@ mod pixel_click_transport_tests {
}
}
+#[cfg(test)]
+mod background_element_click_record_tests {
+ use super::{background_element_click_result, ActionTransport};
+
+ #[test]
+ fn raw_fallback_reports_its_physical_transport() {
+ for (transport, path) in [
+ (ActionTransport::WindowsTargetedInjection, "pixel"),
+ (ActionTransport::WindowsPostMessage, "post_message"),
+ ] {
+ let result = background_element_click_result(
+ "physical fallback".into(),
+ transport,
+ vec![ActionTransport::WindowsUiaInvoke],
+ );
+ assert_eq!(result.structured_content.as_ref().unwrap()["path"], path);
+ let record = result.action_record.unwrap();
+ assert_eq!(record.transport, transport);
+ let truth = record.debug_json();
+ assert_ne!(truth["route"], "accessibility");
+ assert_eq!(
+ record.attempts[0].transport,
+ ActionTransport::WindowsUiaInvoke
+ );
+ assert_eq!(record.fallbacks[0].to, transport);
+ }
+ }
+
+ #[test]
+ fn failed_provider_calls_disqualify_single_action_marker_exemption() {
+ let result = background_element_click_result(
+ "semantic success after provider failure".into(),
+ ActionTransport::WindowsUiaToggle,
+ vec![ActionTransport::WindowsUiaInvoke],
+ );
+ let record = result.action_record.unwrap();
+ assert_eq!(record.transport, ActionTransport::WindowsUiaToggle);
+ assert_eq!(record.attempts.len(), 1);
+ assert_eq!(record.fallbacks.len(), 1);
+ assert_eq!(record.fallbacks[0].from, ActionTransport::WindowsUiaInvoke);
+ assert_eq!(record.fallbacks[0].to, ActionTransport::WindowsUiaToggle);
+ // Point-free recording requires an empty fallback journal.
+ assert!(!record.debug_json()["fallbacks"]
+ .as_array()
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn single_provider_success_has_no_invented_attempts() {
+ for transport in [
+ ActionTransport::WindowsUiaInvoke,
+ ActionTransport::WindowsUiaToggle,
+ ActionTransport::WindowsUiaSelection,
+ ActionTransport::WindowsUiaExpandCollapse,
+ ] {
+ let result =
+ background_element_click_result("semantic success".into(), transport, vec![]);
+ assert_eq!(result.structured_content.as_ref().unwrap()["path"], "ax");
+ let record = result.action_record.unwrap();
+ assert_eq!(record.transport, transport);
+ assert!(record.attempts.is_empty());
+ assert!(record.fallbacks.is_empty());
+ }
+ }
+}
+
// ── type_text ─────────────────────────────────────────────────────────────────
/// px-focus for the keyboard family (type_text / press_key / hotkey): pixel-click
@@ -6526,6 +6675,7 @@ impl Tool for DoubleClickTool {
))
}
};
+ let recorded_center = (cx, cy);
let (cx, cy) = match resolve_onscreen_point_with_scroll(
&self.state.element_cache,
pid,
@@ -6567,6 +6717,9 @@ impl Tool for DoubleClickTool {
// actuator (system input queue, NO foreground swap), exactly like
// ClickTool, instead of refusing. Only error if injection can't
// express this click (e.g. right/middle on such a target).
+ if (cx, cy) != recorded_center {
+ crate::recording_hooks::capture_dispatch_click_target(hwnd, pid, cx, cy);
+ }
if delivery == DeliveryMode::Background
&& crate::input::delivery::would_be_silently_dropped(hwnd, EventKind::MouseClick)
{
@@ -6873,6 +7026,7 @@ impl Tool for RightClickTool {
))
}
};
+ let recorded_center = (cx, cy);
let (cx, cy) = match resolve_onscreen_point_with_scroll(
&self.state.element_cache,
pid,
@@ -6909,6 +7063,9 @@ impl Tool for RightClickTool {
// delivery_mode:"background" (default): try coordinate injection (no
// foreground swap) for drop-prone targets (#1984); a right-click
// injection that the actuator can't express falls back to the error.
+ if (cx, cy) != recorded_center {
+ crate::recording_hooks::capture_dispatch_click_target(hwnd, pid, cx, cy);
+ }
if delivery == DeliveryMode::Background
&& crate::input::delivery::would_be_silently_dropped(hwnd, EventKind::MouseClick)
{
diff --git a/libs/cua-driver/tests/fixtures/apps/linux/isolated-input/main.py b/libs/cua-driver/tests/fixtures/apps/linux/isolated-input/main.py
new file mode 100644
index 0000000000..5a0fea495d
--- /dev/null
+++ b/libs/cua-driver/tests/fixtures/apps/linux/isolated-input/main.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+"""Native GTK3 raw-event fixture; no accessibility action emulates input.
+
+Run each actor as a separate process. WAYLAND_DEBUG=1 supplies an independent
+wire-level primary-pointer oracle in addition to this application journal.
+"""
+import argparse
+import json
+import time
+from pathlib import Path
+import gi
+
+gi.require_version("Gtk", "3.0")
+from gi.repository import Gtk, Gdk, GLib
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--actor", choices=["Background", "Foreground"], required=True)
+parser.add_argument("--journal", required=True)
+parser.add_argument("--metrics", type=Path, help="Optional live test counters; no fabricated defaults")
+args = parser.parse_args()
+journal = open(args.journal, "x", buffering=1)
+state = {"clicks": 0, "keys": "", "scroll": 0, "motion": 0, "held": False}
+metrics = None
+trail = []
+
+
+def record(kind, **values):
+ journal.write(json.dumps({"kind": kind, "time": time.monotonic_ns(), **values}) + "\n")
+
+
+window = Gtk.Window(title="Cua Isolated Input " + args.actor)
+window.set_default_size(600, 500)
+canvas = Gtk.DrawingArea()
+canvas.set_can_focus(True)
+canvas.add_events(Gdk.EventMask.ALL_EVENTS_MASK)
+window.add(canvas)
+
+
+def draw(widget, cr):
+ cr.set_source_rgb(0.08, 0.13, 0.18)
+ cr.paint()
+ cr.set_source_rgb(0.75, 0.9, 0.75)
+ cr.select_font_face("sans-serif", 0, 0)
+ cr.set_font_size(28)
+ lines = [args.actor + " — raw Wayland events", "clicks=" + str(state["clicks"]),
+ "keys=" + state["keys"][-25:], "scroll=" + str(state["scroll"]),
+ "motion=" + str(state["motion"]), "held=" + str(state["held"])]
+ for index, text in enumerate(lines):
+ cr.move_to(25, 55 + index * 48)
+ cr.show_text(text)
+ if args.metrics:
+ cr.set_font_size(22)
+ values = (["Measurement: " + metrics.get("status", "inconclusive"),
+ "Cursor violations: " + str(metrics.get("cursor_violations", "unknown")),
+ "Focus events: " + str(metrics.get("focus_events", "unknown")),
+ "Unexpected releases: " + str(metrics.get("releases", "unknown")),
+ "Completed actions: " + str(metrics.get("actions", "unknown"))]
+ if metrics is not None else ["Measurement: waiting for telemetry"])
+ for index, text in enumerate(values):
+ cr.move_to(25, 410 + index * 35)
+ cr.show_text(text)
+ if trail:
+ cr.set_source_rgb(0.9, 0.65, 0.25)
+ cr.set_line_width(4)
+ cr.move_to(*trail[0])
+ for point in trail[1:]:
+ cr.line_to(*point)
+ cr.stroke()
+ return False
+
+
+def event(widget, e):
+ kind = e.type.value_nick
+ data = {}
+ if e.type in (Gdk.EventType.BUTTON_PRESS, Gdk.EventType.BUTTON_RELEASE,
+ Gdk.EventType.MOTION_NOTIFY, Gdk.EventType.SCROLL):
+ data.update(x=e.x, y=e.y)
+ if e.type in (Gdk.EventType.BUTTON_PRESS, Gdk.EventType.BUTTON_RELEASE):
+ state["held"] = e.type == Gdk.EventType.BUTTON_PRESS
+ if not state["held"]:
+ state["clicks"] += 1
+ _ok, button_number = e.get_button()
+ data["button"] = int(button_number)
+ canvas.grab_focus() # Widget-local focus, not a compositor activation.
+ elif e.type == Gdk.EventType.MOTION_NOTIFY:
+ state["motion"] += 1
+ if state["held"]:
+ trail.append((e.x, e.y))
+ del trail[:-1000]
+ elif e.type in (Gdk.EventType.KEY_PRESS, Gdk.EventType.KEY_RELEASE):
+ name = Gdk.keyval_name(e.keyval)
+ if e.type == Gdk.EventType.KEY_PRESS:
+ state["keys"] += (name if len(name) == 1 else "[" + name + "]")
+ data.update(key=name, modifiers=int(e.state))
+ elif e.type == Gdk.EventType.SCROLL:
+ state["scroll"] += 1
+ if e.type not in (Gdk.EventType.EXPOSE, Gdk.EventType.CONFIGURE):
+ record(kind, **data)
+ canvas.queue_draw()
+ return False
+
+
+canvas.connect("draw", draw)
+canvas.connect("event", event)
+window.connect("destroy", Gtk.main_quit)
+window.show_all()
+canvas.grab_focus()
+record("ready", name=args.actor)
+
+
+def heartbeat():
+ global metrics
+ if args.metrics:
+ try:
+ metrics = json.loads(args.metrics.read_text())
+ except (OSError, ValueError):
+ metrics = None
+ canvas.queue_draw()
+ record("state", **state)
+ return True
+
+
+GLib.timeout_add(250, heartbeat)
+Gtk.main()
+journal.close()
diff --git a/libs/cua-driver/tests/fixtures/shared/web/index.html b/libs/cua-driver/tests/fixtures/shared/web/index.html
index 23a860cece..5df42346c2 100644
--- a/libs/cua-driver/tests/fixtures/shared/web/index.html
+++ b/libs/cua-driver/tests/fixtures/shared/web/index.html
@@ -332,6 +332,11 @@
const entry = { text: (element.textContent || '').trim() };
if ('value' in element) entry.value = element.value;
if ('checked' in element) entry.checked = element.checked;
+ if (element.dataset.cuaId === 'scroll-tall') {
+ // Scroll-event mirrors can lag the actual DOM offset.
+ entry.scrollTop = element.scrollTop;
+ entry.clientHeight = element.clientHeight;
+ }
state[element.dataset.cuaId] = entry;
});
if (window.cuaE2E?.publishFixtureState) {
diff --git a/libs/cua-driver/tests/fixtures/shared/web/journal.test.cjs b/libs/cua-driver/tests/fixtures/shared/web/journal.test.cjs
new file mode 100644
index 0000000000..2d51ad78a1
--- /dev/null
+++ b/libs/cua-driver/tests/fixtures/shared/web/journal.test.cjs
@@ -0,0 +1,55 @@
+const assert = require('node:assert/strict');
+const { readFileSync } = require('node:fs');
+const { join } = require('node:path');
+const { test } = require('node:test');
+const { runInNewContext } = require('node:vm');
+
+test('journal samples live scroll geometry without an event or DOM mutation', () => {
+ const html = readFileSync(join(__dirname, 'index.html'), 'utf8');
+ const source = html.match(/\(function startFixtureJournal\(\) \{[\s\S]*?\n \}\)\(\);/);
+ assert.ok(source, 'shared fixture journal exists');
+ const scroll = { dataset: { cuaId: 'scroll-tall' }, textContent: 'contents', scrollTop: 208, clientHeight: 128 };
+ const mirror = { dataset: { cuaId: 'lbl-scroll-offset' }, textContent: 'scroll_offset=104', scrollTop: 0, clientHeight: 16 };
+ const field = { dataset: { cuaId: 'input' }, textContent: '', value: '42', checked: false, scrollTop: 0, clientHeight: 20 };
+ const readonly = value => new Proxy(value, {
+ get(target, key) {
+ const result = target[key];
+ return result && typeof result === 'object' ? readonly(result) : result;
+ },
+ set() { assert.fail('journal must not mutate DOM state'); },
+ deleteProperty() { assert.fail('journal must not delete DOM state'); },
+ defineProperty() { assert.fail('journal must not define DOM state'); },
+ });
+ const publications = [];
+ const timers = [];
+ let periodic;
+ runInNewContext(source[0], {
+ document: {
+ body: {},
+ querySelectorAll(selector) {
+ assert.equal(selector, '[data-cua-id]');
+ return [scroll, mirror, field].map(readonly);
+ },
+ addEventListener() {},
+ },
+ window: {
+ cuaE2E: {
+ journalUrl: 'http://fixture.invalid',
+ publishFixtureState(state) { publications.push(JSON.parse(JSON.stringify(state))); },
+ },
+ addEventListener(name, callback) { assert.equal(name, 'load'); callback(); },
+ },
+ MutationObserver: class { observe() {} },
+ setTimeout(callback, delay) { assert.equal(delay, 0); timers.push(callback); },
+ setInterval(callback, delay) { assert.equal(delay, 250); periodic = callback; },
+ });
+ timers.shift()();
+ assert.deepEqual(publications[0]['scroll-tall'], { text: 'contents', scrollTop: 208, clientHeight: 128 });
+ assert.deepEqual(publications[0]['lbl-scroll-offset'], { text: 'scroll_offset=104' });
+ assert.deepEqual(publications[0].input, { text: '', value: '42', checked: false });
+ scroll.scrollTop = 320;
+ periodic();
+ timers.shift()();
+ assert.equal(publications[1]['scroll-tall'].scrollTop, 320);
+ assert.deepEqual(publications[1]['lbl-scroll-offset'], { text: 'scroll_offset=104' });
+});
diff --git a/rfcs/3550-hyprland-isolated-input.md b/rfcs/3550-hyprland-isolated-input.md
index b7e1079655..abf38ddfb9 100644
--- a/rfcs/3550-hyprland-isolated-input.md
+++ b/rfcs/3550-hyprland-isolated-input.md
@@ -366,6 +366,19 @@ approval requirement. Measure cleanup with a
responsive compositor and report stalls separately: Stop is neither undo nor
instantaneous cleanup under every fault.
+The [maintainer's passive-focus clarification](https://github.com/trycua/cua/issues/3550#issuecomment-5560882875)
+permits inert internal pointer focus to survive owner cancellation, disconnect,
+or idle expiry. This is separate from Driver's visible cursor overlay: existing
+idle fade and session-end removal remain unchanged. Release every held button
+and key, clear keyboard focus, and revoke action authority immediately. Retained
+focus must have an independent, lifetime-safe target reference, not a pointer to
+a destroyed owner or a reservation for a disconnected runtime. Continue to
+handle target destruction/replacement, geometry changes, primary and other-lane
+conflicts, and desktop/keymap/configuration transitions safely. A retained hover
+is neither admission for another action nor acknowledgement that the client has
+processed a release. Native application-state and isolation evidence remain
+required.
+
Do not equate the private transport's cancellation messages with cancellation
on every public transport. Direct stdio MCP executes calls serially and ignores
cancellation notifications. An `end_session` call or input EOF waits behind the
@@ -558,6 +571,36 @@ Use the canonical commands in
typed catalog, not replace it with an unrelated scripted demo. Do not assume
an unmerged PR's runner is present on main.
+The 2026-09-07 validation-strategy decision uses
+`scripts/ci/linux/run-rust-e2e.sh` with its complete `all` suite in the prepared
+native Hyprland desktop at the exact candidate SHA. This supplies canonical
+fixture regression coverage. Preserve required cells, assertions, and evidence
+checks, and report environment failures explicitly. Ordinary GTK, Electron,
+and Tauri fixtures are outside `hyprland_compatibility.rs`'s background production
+package gate; their v3 background raw-input refusals do not establish delivered
+plugin input. Do not broaden background admission or introduce a test bypass.
+The accepted foreground scope adjustment below adds a distinct production route
+for ordinary native top-level fixtures. Its GTK3, Electron, and Tauri foreground
+cells must pass the existing complete suite without changing the runner,
+assertions, or evidence checks. These cells are not yet certified.
+
+Short production real-app smoke and instrumented isolation checks on native
+Calc `26.2.5-3` and Inkscape `1.4.4-6` remain required supporting compatibility
+evidence for actual plugin delivery, app effects, primary-seat isolation, and
+cleanup. Retain focused proof of the supported operations and two-lane behavior
+being promoted. An uninstrumented smoke without plugin transport attribution
+cannot prove continuous isolation, and an all-refusal canonical result cannot
+replace positive delivery evidence. The
+[production proof guide](../libs/cua-driver/hyprland-plugin/tests/production-proof.md)
+documents the bounded plans and their limits.
+
+Three whole repetitions of the long Python Calc/Inkscape plan, including 34
+policy cases across both apps, are no longer a merge requirement. Extended Python
+stress runs are diagnostics for specific unresolved failures. Shared policy
+coverage and focused native checks must still substantiate the claims below;
+the decision changes the test strategy, not production qualification or action
+admission. It records no completed native certification.
+
| Gate | Required evidence |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Protocol and authority | Malformed/oversized requests, quota exhaustion, wrong target/epoch/sequence, expired bindings, disconnect races, and incompatible protocols refuse without unsafe dispatch. Standard/unrestricted manifest and no-manifest cases, bounded allow/deny, managed/user policy, and cached-connection re-admission prove the common contract. Public labels/arguments cannot confer ownership; policy denial causes no plugin mutation. |
@@ -612,8 +655,9 @@ later executable, harness, or environment change. Retain sanitized results,
environment/package identities, and source provenance. Post-merge smoke and
release-path checks remain separate delivery requirements.
-Define the repeat set before execution, preserve sanitized diagnostics for
-discovery/IPC failures, and diagnose every recurrence rather than retrying a
+When a failure needs repeat diagnostics, define that repeat set before
+execution. Preserve sanitized diagnostics for discovery/IPC failures, and
+diagnose every recurrence rather than retrying a
failed cell into a pass. Passing repeats do not identify a historical failure's
cause. Test both an instrumented candidate for detailed event/cleanup evidence
and an uninstrumented production package; neither portable tests nor an
@@ -660,8 +704,26 @@ owner-scoped cancellation, and restart-required package replacement. Discovery
v2 remains unchanged. There is no automatic replay, foreground fallback, wake,
or unlock.
-The decision preserves the contributor feedback and alternatives above. It
-rejects borrowing primary-seat focus and the earlier separate consent/signer
+The [2026-09-06 cleanup clarification](https://github.com/trycua/cua/issues/3550#issuecomment-5560882875)
+allows owner-independent inert pointer focus after cancellation or disconnection,
+without changing visible cursor behavior, held-state cleanup, or fresh-action
+admission. It selects an implementation direction for native verification; it
+does not certify cancellation recovery or authorize a release before the gates
+below pass.
+
+The 2026-09-07 maintainer validation-strategy addendum selects the canonical
+Linux Rust harness in native Hyprland and retires the requirement for three
+complete long Python Calc/Inkscape repetitions. Short real-app production and
+instrumented isolation evidence remains necessary to prove the actual plugin
+path within its existing qualification limits. Extended Python stress plans
+remain diagnostic. This supersedes the earlier repetition requirement while
+preserving historical results, failures, and design decisions. It adds no
+approval UI, test bypass, or new passing certification claim. Implementation
+merge still requires passing affected CI and E2E evidence; release, Fleet,
+and physical-host requirements retain their separate scope.
+
+The background decision preserves the contributor feedback and alternatives above. It
+rejects borrowing primary-seat focus for background input and the earlier separate consent/signer
requirements. A patched compositor, direct-resource delivery, and portable
standards work remain separate alternatives rather than silent substitutions.
@@ -677,3 +739,37 @@ permission-UI choices. Keep status `accepted` until the required criteria ship;
then record completion. Certify and release the Driver/plugin dependency chain
before publishing the final supported Fleet image. No upstream Hyprland
endorsement or physical-host parity is implied.
+
+### Accepted exact-target foreground scope adjustment
+
+The [maintainer's foreground scope adjustment](https://github.com/trycua/cua/issues/3550#issuecomment-5564996417)
+accepts a separate production foreground route. It extends the accepted design
+without changing the earlier background decisions, qualification, or contributor
+credit. `HELLO` explicitly advertises `foreground_target:true`.
+`FOREGROUND_TARGET <pid> <hex-address> <capability>` binds the exact live native
+top-level surface to `primary_foreground`. Background `TARGET` remains unchanged.
+The plugin validates identity, lifetime, geometry, and route on the compositor
+thread at admission and dispatch; discovery followed by global `wtype` input is
+not an exact-target fallback.
+
+The foreground route supports the existing complete click (1), key (2), scroll
+(4), and bounded drag (8) operations and adds foreground-only activation (16)
+through `ACTIVATE <sequence> <target> <revision>`. Activation and primary-cursor
+movement are intentional. There is no focus or cursor restoration promise and
+no escalation from a refused background action. Driver's shared permission and
+lifecycle checks remain in force, without a separate approval UI.
+
+Foreground admission has no Calc/Inkscape package gate, but supports only ordinary
+native top-level surfaces. Driver expands bounded ASCII text into complete key
+operations under the exact compiled US keymap; Unicode and IME input remain
+outside scope. Held physical keys/buttons, grabs, pointer constraints, and
+drag-and-drop must refuse before primary takeover. Cancellation of foreground
+drags on primary-input and focus transitions remains under review and requires
+native verification; acceptance does not establish that behavior as proven.
+
+Native GTK3, Electron, and Tauri foreground coverage is planned. The extension
+must pass the existing complete canonical Linux Rust suite on native Hyprland at
+the candidate SHA. This adjustment neither records a passing certification nor
+changes canonical runner/tests. Background Calc/Inkscape qualification and its
+supporting isolation evidence remain required; the extension does not promote
+generic fixtures to background raw-input support.