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.

docs(cua-driver): complete Linux startup and integration instructions (#3561)

Francesco Bonacciaf52877b7a96
diff --git a/.github/workflows/docs-driver-first-run-smoke.yml b/.github/workflows/docs-driver-first-run-smoke.yml
new file mode 100644
index 0000000000..f5c29df5be
--- /dev/null
+++ b/.github/workflows/docs-driver-first-run-smoke.yml
@@ -0,0 +1,58 @@
+name: "Docs: Driver first-run Linux smoke"
+
+on:
+ pull_request:
+ paths:
+ - docs/content/docs/tutorials/drive-your-first-app.mdx
+ - docs/content/docs/how-to-guides/driver/install.mdx
+ - docs/content/docs/how-to-guides/driver/update.mdx
+ - docs/scripts/verify-driver-first-run-linux.py
+ - docs/scripts/tests/test_driver_first_run_smoke.py
+ - .github/workflows/docs-driver-first-run-smoke.yml
+ - libs/cua-driver/scripts/install.sh
+ - libs/cua-driver/scripts/_install-rust.sh
+ - libs/cua-driver/scripts/_install-common.sh
+ workflow_dispatch:
+
+# Public PR code runs only on a disposable GitHub-hosted runner, without secrets.
+permissions:
+ contents: read
+
+jobs:
+ first-run:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - name: Test the display-result oracle
+ run: python3 -m unittest discover -s docs/scripts/tests -p test_driver_first_run_smoke.py
+ - name: Install disposable desktop dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends \
+ xvfb xauth dbus-x11 at-spi2-core openbox picom galculator \
+ libxi6 libxtst6 libglib2.0-bin gsettings-desktop-schemas \
+ x11-utils xdotool tesseract-ocr
+ - name: Verify the Linux tutorial from a cold start
+ env:
+ CUA_DOCS_SOURCE_SHA: ${{ github.sha }}
+ CUA_DOCS_EVIDENCE: ${{ runner.temp }}/docs-driver-first-run-evidence
+ XDG_SESSION_TYPE: x11
+ GDK_BACKEND: x11
+ GTK_MODULES: gail:atk-bridge
+ NO_AT_BRIDGE: "0"
+ LC_ALL: C.UTF-8
+ run: |
+ xvfb-run -a --server-args="-screen 0 1280x960x24" \
+ dbus-run-session -- python3 docs/scripts/verify-driver-first-run-linux.py
+ - name: Upload synthetic first-run evidence
+ if: always()
+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4
+ with:
+ name: docs-driver-first-run-linux-${{ github.sha }}
+ path: ${{ runner.temp }}/docs-driver-first-run-evidence
+ if-no-files-found: error
+ retention-days: 14
diff --git a/docs/content/docs/how-to-guides/driver/install.mdx b/docs/content/docs/how-to-guides/driver/install.mdx
index ce38a52997..f908c5ce0b 100644
--- a/docs/content/docs/how-to-guides/driver/install.mdx
+++ b/docs/content/docs/how-to-guides/driver/install.mdx
@@ -60,6 +60,11 @@ sudo apt install libxi6 at-spi2-core
The installer downloads the binary to `~/.cua-driver/packages/releases/`, points `~/.cua-driver/packages/current` at that release, and creates the `~/.local/bin/cua-driver` symlink. It does not use sudo.
+If `cua-driver` is not found, open a new terminal to pick up the installer's
+PATH change. Installing the binary does not start the Linux daemon. Follow
+[Start the daemon on Linux](#start-the-daemon-on-linux) below before calling
+desktop tools.
+
X11 is fully supported. Native Wayland remains opt-in with
`CUA_DRIVER_RS_ENABLE_WAYLAND=1` and has compositor-specific limits. Sway is
supported with limits, GNOME requires the maintained WinRects helper, and KDE
@@ -75,6 +80,9 @@ server.
## Verify the install
+The version and paths in the following output are illustrative; your installed
+release and machine determine the actual values.
+
```bash
cua-driver --version
# cua-driver 0.13.0
@@ -90,7 +98,11 @@ cua-driver doctor
# ...
```
-`doctor` checks the version, install layout, and telemetry setup on every platform. It also runs platform probes for TCC on macOS, the interactive session on Windows, and AT-SPI plus the display server on Linux.
+`doctor` checks the version, install layout, and telemetry setup on every
+platform. It also probes the interactive session on Windows and AT-SPI plus
+the display server on Linux. On macOS, use `cua-driver permissions status`
+after starting the daemon to check its Accessibility and Screen Recording
+grants.
## Follow the nightly channel
@@ -127,7 +139,9 @@ cua-driver update --apply
Nightlies are immutable builds of exact `main` commits. Copy the full
`nightly-cua-driver-rs-v…` tag from the component's GitHub release, then pin
-that tag during installation:
+that tag during installation. The tag below illustrates the format and is
+not a verified release: replace the entire tag with one that exists and has
+an asset for your platform before running either command.
<Tabs items={['macOS and Linux', 'Windows']}>
<Tab value="macOS and Linux">
@@ -190,6 +204,20 @@ open -n -g -a CuaDriver --args serve \
See [Permission modes](/reference/cua-driver/permission-modes) for exactly what each profile allows, and [Write a capability manifest](/how-to-guides/driver/write-a-bounded-manifest) for a tested manifest. To keep a non-default profile across reboots, its flags belong in the autostart entry — see [Pin a permission mode](/how-to-guides/driver/keep-running#pin-a-permission-mode).
+## Start the daemon on Linux
+
+In a terminal inside your graphical desktop session, start the daemon:
+
+```bash
+cua-driver serve
+```
+
+Leave that terminal open. `serve` stays in the foreground; it must have access
+to the same display and accessibility bus as the apps you want to drive. Run
+the readiness checks below from a second terminal in that session. To start
+the daemon automatically at sign-in, see
+[Keep Cua Driver running](/how-to-guides/driver/keep-running).
+
## Grant TCC permissions (macOS only)
**Start the daemon first** so macOS attributes the TCC request to `CuaDriver.app` instead of your terminal:
@@ -251,6 +279,26 @@ cua-driver permissions status
`cua-driver permissions status` reads the driver's actual grant state through the daemon. When no daemon is running, it reports `❓ unknown` instead of reporting your terminal's grants, and it does not claim `granted` unless the driver has that permission.
</Callout>
+## Verify desktop readiness
+
+After starting the daemon and granting any required platform permissions, run:
+
+```bash
+cua-driver status
+cua-driver doctor
+cua-driver call list_apps
+```
+
+`status` should report `Cua Driver daemon is running`. Read the `doctor` report
+for interactive-session, display, or accessibility-bus warnings and errors;
+warnings can still produce a zero exit code. On macOS, confirm both grants
+with `cua-driver permissions status`. Then confirm that `list_apps` includes a GUI app you recognize. If the list is
+empty, open an app in the same desktop session and retry. A version string
+alone verifies the binary, not desktop access.
+
+If the Windows autostart task was not registered, run `cua-driver serve` in an
+interactive desktop terminal and use a second terminal for these checks.
+
## Next steps
- [Choose a Cua Driver integration](/concepts/choose-a-cua-driver-integration): decide whether your agent or product should use MCP, the SDK, or an app-hosted service.
diff --git a/docs/content/docs/how-to-guides/driver/update.mdx b/docs/content/docs/how-to-guides/driver/update.mdx
index e74f98bd5d..665ea2a4cf 100644
--- a/docs/content/docs/how-to-guides/driver/update.mdx
+++ b/docs/content/docs/how-to-guides/driver/update.mdx
@@ -7,6 +7,10 @@ import { Callout } from 'fumadocs-ui/components/callout';
Cua Driver gives you three update paths: a passive banner at launch time, a CLI command that only checks, and a separate command that installs the update. Keep the **check and apply steps separate** so you can decide when to change the installed binary.
+Version numbers, timestamps, and release links in the sample output below are
+illustrative. Use your command's actual output to identify the installed and
+available releases; the 0.13.0 migration notes describe that historical upgrade.
+
## Before updating from 0.12.x to 0.13.0
The installer command, CLI/MCP connection flow, tool names, and Python and
@@ -36,10 +40,15 @@ restarting a long-running daemon or worker.
## Check for updates
Checks use the saved channel. Existing installations default to `stable`.
-Inspect or change it with:
+Inspect it with:
```bash
cua-driver channel status
+```
+
+To switch to nightly and install that channel's release:
+
+```bash
cua-driver channel set nightly
cua-driver update --apply
```
@@ -95,12 +104,29 @@ Installed Cua Driver 0.13.0.
`update --apply` calls the canonical installer script, the same one-line installer used for the first install.
-If the daemon was running before the update, restart it so it uses the new binary:
+If the daemon was running before the update, restart it so it uses the new
+binary. Stop it first:
```bash
-cua-driver stop && cua-driver serve
+cua-driver stop
```
+The installer may already have stopped the old daemon. If `stop` reports that
+it is not running, continue with startup.
+
+Then use your platform's startup command: on macOS, run
+`open -n -g -a CuaDriver --args serve` to preserve app-bundle permission
+attribution; on Windows with autostart enabled, run `cua-driver autostart kick`;
+on Linux or Windows without autostart, run `cua-driver serve` and leave that
+terminal open. Preserve any non-default permission-mode flags from your
+original launch.
+
+In a second terminal if `serve` occupies the first, run `cua-driver --version`,
+`cua-driver status`, and `cua-driver call list_apps`. Confirm the expected
+installed version, a running daemon, and access to a known GUI app. See
+[Verify desktop readiness](/how-to-guides/driver/install#verify-desktop-readiness)
+if the daemon cannot reach your desktop.
+
On Windows with autostart enabled, the Scheduled Task uses the new binary on its next invocation. `autostart enable` is idempotent, and the task path resolves through the `current` junction.
## Scripted check (CI / agents)
diff --git a/docs/content/docs/tutorials/drive-your-first-app.mdx b/docs/content/docs/tutorials/drive-your-first-app.mdx
index b342b444af..c6da960390 100644
--- a/docs/content/docs/tutorials/drive-your-first-app.mdx
+++ b/docs/content/docs/tutorials/drive-your-first-app.mdx
@@ -1,6 +1,6 @@
---
title: Drive your first app with Cua Driver
-description: Install Cua Driver, connect your agent, and ask it in plain English to drive a desktop app in the background on macOS, Windows, or Linux.
+description: Install Cua Driver, connect your agent, and verify a result in a desktop app on macOS, Windows, or Linux.
---
import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
@@ -8,8 +8,9 @@ import { Callout } from 'fumadocs-ui/components/callout';
By the end of this tutorial, your agent will open Calculator, compute 6 × 7,
and report 42 through **Cua Driver**. You will install the driver, connect
-Claude Code, Codex, Prime Agent, or Hermes, and run the same prompt on macOS, Windows, or
-Linux.
+your agent, and run a prompt that matches its integration on macOS, Windows, or
+Linux. Have an agent installed and a desktop calculator available before you
+begin. On Linux, use your distribution's calculator, such as GNOME Calculator.
New to agents that operate applications? Start with [What is computer use?](/concepts/what-is-computer-use) for the model behind the workflow, then return here to build one.
@@ -89,16 +90,29 @@ Use the same one-line installer on every platform; it picks the right path for t
cua-driver autostart kick
```
- The installer registers Cua Driver to start automatically at sign-in. `kick` starts it immediately, so you do not need to sign out or restart Windows before continuing.
+ The installer attempts to register Cua Driver to start automatically at sign-in. `kick` starts that task immediately. If registration was skipped or failed, run `cua-driver serve` in a terminal in the interactive desktop session and leave it open. Use a second terminal for the checks below.
</Tab>
<Tab value="Linux">
Requires an x86_64 Linux desktop session with X11 or XWayland, plus AT-SPI 2.
+ On a minimal Debian or Ubuntu image, install `libxi6` and `at-spi2-core`
+ first; see [Linux requirements](/how-to-guides/driver/install). Run this
+ tutorial inside the desktop session, where the driver can reach its display
+ and accessibility bus.
```bash
/bin/bash -c "$(curl -fsSL https://cua.ai/driver/install.sh)"
```
+ Start the daemon from a terminal in the same desktop session:
+
+ ```bash
+ cua-driver serve
+ ```
+
+ Leave that terminal open. Run the verification commands below in a second
+ terminal in the same desktop session.
+
</Tab>
</Tabs>
@@ -108,7 +122,14 @@ Use the same one-line installer on every platform; it picks the right path for t
## 2. Verify it is working
-Before you hand control to an agent, confirm the driver can see your desktop. Run the cross-platform probe:
+First confirm that the daemon is reachable:
+
+```bash
+cua-driver status
+```
+
+Expect `Cua Driver daemon is running`. If it is not running, repeat your
+platform's startup step above. Then check the environment:
```bash
cua-driver doctor
@@ -120,20 +141,34 @@ Then list the running GUI apps the driver can reach:
cua-driver call list_apps
```
-If you see your running apps listed, the plumbing works. That is the only CLI you run by hand; from here the agent does the driving.
+Read the `doctor` report, including warnings: a zero exit code does not prove
+desktop readiness. On macOS, also confirm both grants with
+`cua-driver permissions status`. Continue when the required permissions and
+desktop services are available, and `list_apps` includes a GUI app you recognize. An
+empty list is not a successful desktop check: open Calculator in that session
+and retry. Resolve permission or display errors before connecting the agent.
## 3. Connect your agent
-Register Cua Driver with your agent harness once.
+Choose one integration for your agent. A skill teaches the agent to use the
+Cua Driver CLI; MCP registration exposes Cua Driver as a tool server.
+`mcp-config` only prints setup instructions: you must run the registration
+command it prints. Use the output from your machine, not the illustrative
+paths below.
<Tabs items={['Claude Code', 'Codex', 'Prime Agent', 'OpenClaw', 'Hermes']}>
<Tab value="Claude Code">
- Install the Claude Code skill. This is turnkey: the skill teaches Claude Code how to drive apps through Cua Driver, and you then ask in plain English.
+ Install the Cua Driver skill for Claude Code:
```bash
cua-driver skills install
+ cua-driver skills status
```
+ Confirm that the status includes a Claude Code skill link, then start a
+ fresh Claude Code session. If the link is missing, follow
+ [Install the agent skill](/how-to-guides/driver/install-agent-skill).
+
Prefer plain MCP instead of the skill? Print the Claude Code registration command:
```bash
@@ -159,7 +194,9 @@ Register Cua Driver with your agent harness once.
codex mcp add cua-driver -- /Users/you/.local/bin/cua-driver mcp
```
- Restart Codex or open a fresh Codex session after registration so the new tools appear.
+ Run `codex mcp list` to confirm the `cua-driver` registration. Start a fresh
+ Codex session and use `/mcp` to check that the server is active. See the
+ [official Codex MCP instructions](https://learn.chatgpt.com/docs/extend/mcp).
</Tab>
<Tab value="Prime Agent">
Install the Cua Driver skill pack. Prime Agent discovers it from its native
@@ -168,7 +205,7 @@ Register Cua Driver with your agent harness once.
```bash
cua-driver skills install
- cua-driver mcp-config --client prime-agent
+ cua-driver skills status
```
Run `/reload` in Prime Agent or start a new session after installation so
@@ -213,64 +250,74 @@ Using Cursor, Gemini/Antigravity, OpenCode, or Pi instead? See [Connect your age
## 4. Ask your agent
-You can now prompt your agent in plain English, and it will drive Cua Driver for you.
+Use the prompt that matches the setup you chose. Ask the agent to read the
+calculator's displayed result after acting, so it verifies the GUI instead of
+answering the arithmetic from memory.
-<Tabs items={['Claude Code', 'Codex', 'Prime Agent']}>
+<Tabs items={['Claude Code', 'Codex', 'Prime Agent', 'OpenClaw', 'Hermes']}>
<Tab value="Claude Code">
```text
- > Using the cua-computer-use MCP, open the Calculator, compute 6 × 7, and tell me the result.
-
- → launch_app Calculator
- → get_window_state
- → click 7 [element_index=12]
- → click × [element_index=20]
- → click 6 [element_index=11]
- → click = [element_index=22]
- → get_window_state
- ✓ The result is 42.
+ Using the Cua Driver skill, open the installed calculator app,
+ compute 6 × 7, and read the displayed result back from a fresh snapshot.
```
+
+ If you chose MCP registration instead, replace “Cua Driver skill” with
+ “cua-computer-use MCP server.”
</Tab>
<Tab value="Codex">
```text
- > Using the Cua Driver skill, open the Calculator, compute 6 × 7, and read the result back.
-
- → launch_app Calculator
- → get_window_state
- → click 7 [element_index=12]
- → click × [element_index=20]
- → click 6 [element_index=11]
- → click = [element_index=22]
- → get_window_state
- ✓ The result is 42.
+ Using the cua-driver MCP server, open the installed calculator app,
+ compute 6 × 7, and read the displayed result back from a fresh snapshot.
```
</Tab>
<Tab value="Prime Agent">
```text
- > Using the Cua Driver skill, open the Calculator, compute 6 × 7, and read the result back.
-
- → launch_app Calculator
- → get_window_state
- → click 7
- → click ×
- → click 6
- → click =
- → verify_state
- ✓ The result is 42.
+ Using the Cua Driver skill, open the installed calculator app,
+ compute 6 × 7, and read the displayed result back from a fresh snapshot.
+ ```
+ </Tab>
+ <Tab value="OpenClaw">
+ ```text
+ Using the cua-driver MCP server, open the installed calculator app,
+ compute 6 × 7, and read the displayed result back from a fresh snapshot.
+ ```
+ </Tab>
+ <Tab value="Hermes">
+ ```text
+ Using the computer_use toolset, open the installed calculator app,
+ compute 6 × 7, and read the displayed result back from a fresh snapshot.
```
</Tab>
</Tabs>
-Everything runs in the background, and the agent picks the right calculator for your OS (Calculator on macOS and Windows, the system calculator on Linux), so the same prompt works on all three platforms.
+The app name, controls, and action sequence vary by platform and calculator.
+The agent must discover them from fresh state; element indices from another
+run are not reusable. If no calculator is installed, install one through your
+platform's normal app or package manager, then repeat the prompt.
To understand capture and delivery modes, see [Capture and delivery modalities](/concepts/capture-and-delivery-modalities).
## 5. Confirm what happened
-The agent reports 42. Cua Driver kept the calculator in the background the whole time. It never stole your keyboard focus and never moved your cursor. That is best-effort background: the agent drives the app while you keep working. See [Best-effort background](/concepts/the-no-foreground-contract).
+Confirm that the calculator displays **42** and that the agent's final
+observation reports that value. A correct answer alone does not prove that the
+agent operated the app.
+
+Cua Driver uses best-effort background delivery. Observe whether your active
+app, keyboard focus, and real pointer stay unchanged during the interaction;
+do not infer this from the answer. The visible agent cursor is a separate
+overlay. macOS and Windows accessibility actions can operate supported
+controls in the background, but some apps require explicit foreground
+delivery. Linux AT-SPI actions and X11 routes can also work in the background;
+native Wayland depends on compositor support and has raw-keyboard limits.
+Launching an app can itself raise a window. See
+[Best-effort background](/concepts/the-no-foreground-contract) for these
+platform differences.
## What you did
-You installed Cua Driver, verified it could see your desktop, connected your agent harness, and asked in plain English for a result computed inside a real desktop app. The agent did the driving through Cua Driver, in the background, on your platform.
+You installed Cua Driver, checked its daemon and desktop access, connected your
+agent, and verified a result computed inside a desktop app.
## Next steps
diff --git a/docs/scripts/tests/test_driver_first_run_smoke.py b/docs/scripts/tests/test_driver_first_run_smoke.py
new file mode 100644
index 0000000000..c30612ec68
--- /dev/null
+++ b/docs/scripts/tests/test_driver_first_run_smoke.py
@@ -0,0 +1,39 @@
+"""Synthetic result-oracle checks; importing the runner does not install anything."""
+
+import importlib.util
+from pathlib import Path
+import unittest
+
+
+spec = importlib.util.spec_from_file_location(
+ "driver_first_run", Path(__file__).parents[1] / "verify-driver-first-run-linux.py"
+)
+runner = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(runner)
+
+
+class DisplayResultTests(unittest.TestCase):
+ def test_gtk_text_label(self):
+ self.assertTrue(runner.displays_42({
+ "elements": [{"role": "text", "label": "42", "value": None}]
+ }))
+
+ def test_accessible_text_value(self):
+ self.assertTrue(runner.displays_42({
+ "elements": [{"role": "entry", "label": "Result", "value": "42"}]
+ }))
+
+ def test_other_controls_numbers_and_snapshot_indices_do_not_pass(self):
+ for element in (
+ {"role": "toggle button", "label": "42"},
+ {"role": "text", "label": "642"},
+ {"role": "text", "label": "7", "element_index": 42},
+ ):
+ with self.subTest(element=element):
+ self.assertFalse(runner.displays_42({
+ "elements": [element], "tree_markdown": '[42] text "7"'
+ }))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/docs/scripts/verify-driver-first-run-linux.py b/docs/scripts/verify-driver-first-run-linux.py
new file mode 100644
index 0000000000..d1439c9b5b
--- /dev/null
+++ b/docs/scripts/verify-driver-first-run-linux.py
@@ -0,0 +1,399 @@
+#!/usr/bin/env python3
+"""Disposable Ubuntu X11 tutorial smoke; never run on a personal desktop.
+
+Tests the checked-out canonical installer and its published component release,
+not a source-built Driver. No LLM account or client registration is exercised.
+The tutorial's standard profile is overridden with the explicitly authorized
+test-only --dangerously-bypass-approvals on this disposable desktop.
+
+The source installer is unchanged. Audited Linux recursive deletion paths are:
+its mktemp staging directory, package lock/current links, old release directories,
+and the fixed legacy ~/.cua-driver-rs. Fresh task directories and disabled GC
+confine the former; an absence precondition makes legacy/local cleanup dormant.
+macOS app-bundle deletion branches cannot run here. The shared installer also
+stops all named Driver processes/services: require a cold runner before calling
+it. HOME is never reassigned. All cleanup here terminates owned processes only;
+GitHub discards the VM and task directories after artifact collection.
+"""
+
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import queue
+import re
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import tomllib
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def require(condition, message):
+ if not condition:
+ raise RuntimeError(message)
+
+
+def run(args, *, env=None, timeout=30, check=True):
+ result = subprocess.run(args, cwd=ROOT, env=env, text=True,
+ capture_output=True, timeout=timeout)
+ if check:
+ require(result.returncode == 0,
+ f"{args[0]} failed ({result.returncode}): {result.stderr[-2000:]}")
+ return result
+
+
+def save(directory, name, value):
+ (directory / name).write_text(
+ value if isinstance(value, str) else json.dumps(value, indent=2) + "\n")
+
+
+def stop(process):
+ if process is not None and process.poll() is None:
+ # Each process was created with start_new_session=True in this runner.
+ os.killpg(process.pid, signal.SIGTERM)
+ try:
+ process.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=5)
+
+
+class MCP:
+ """One newline-delimited JSON-RPC transport for the entire GUI loop."""
+
+ def __init__(self, binary, endpoint, env, evidence):
+ self.evidence = evidence
+ self.sequence = 0
+ self.lines = queue.Queue()
+ self.log = (evidence / "mcp-stderr.log").open("w")
+ self.process = subprocess.Popen(
+ [str(binary), "mcp", "--socket", str(endpoint)], cwd=ROOT, env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log,
+ text=True, bufsize=1, start_new_session=True)
+ threading.Thread(target=self.read_lines, daemon=True).start()
+
+ def read_lines(self):
+ for line in self.process.stdout:
+ self.lines.put(line)
+ self.lines.put(None)
+
+ def request(self, method, params):
+ self.sequence += 1
+ request = {"jsonrpc": "2.0", "id": self.sequence,
+ "method": method, "params": params}
+ self.process.stdin.write(json.dumps(request) + "\n")
+ self.process.stdin.flush()
+ deadline = time.monotonic() + 45
+ while True:
+ try:
+ line = self.lines.get(timeout=max(0.01, deadline - time.monotonic()))
+ except queue.Empty as error:
+ raise RuntimeError(f"MCP {method} response timed out") from error
+ require(line is not None, "MCP transport closed before response")
+ response = json.loads(line)
+ if response.get("id") == self.sequence:
+ require("error" not in response, f"MCP error: {response.get('error')}")
+ return response["result"]
+ require(time.monotonic() < deadline, "MCP response timeout")
+
+ def call(self, name, arguments, label):
+ result = self.request("tools/call", {"name": name, "arguments": arguments})
+ # Keep real PNGs separately, never huge base64 blobs in semantic evidence.
+ images = []
+ for index, content in enumerate(result.get("content", [])):
+ if content.get("type") == "image":
+ require(content.get("mimeType") == "image/png", "Expected a PNG snapshot")
+ data = base64.b64decode(content["data"], validate=True)
+ require(data.startswith(b"\x89PNG\r\n\x1a\n"), "Invalid PNG evidence")
+ image = self.evidence / f"{label}-{index}.png"
+ image.write_bytes(data)
+ images.append(image)
+ content["data"] = f"[saved to {image.name}]"
+ save(self.evidence, f"{label}.json", result)
+ require(not result.get("isError"), f"{name} reported an error; see {label}.json")
+ payload = result.get("structuredContent")
+ if payload is None:
+ texts = [c["text"] for c in result.get("content", []) if c.get("type") == "text"]
+ require(len(texts) == 1, f"{name} omitted structured content")
+ payload = json.loads(texts[0])
+ return payload, images
+
+ def close(self):
+ stop(self.process)
+ self.log.close()
+
+
+def observe(evidence, label):
+ """Read actual X state; never use Driver return values as focus proof."""
+ root = run(["xprop", "-root", "_NET_ACTIVE_WINDOW", "_NET_CLIENT_LIST_STACKING"]).stdout
+ focus = run(["xdotool", "getwindowfocus"]).stdout.strip()
+ pointer = run(["xdotool", "getmouselocation", "--shell"]).stdout
+ active = re.search(r"_NET_ACTIVE_WINDOW.*?(0x[0-9a-fA-F]+)", root)
+ stack_line = next((line for line in root.splitlines()
+ if line.startswith("_NET_CLIENT_LIST_STACKING")), "")
+ state = {"active_window": active.group(1) if active else None,
+ "keyboard_focus": focus,
+ "stacking_bottom_to_top": re.findall(r"0x[0-9a-fA-F]+", stack_line),
+ "real_pointer": dict(line.split("=", 1) for line in pointer.splitlines()),
+ "raw_root_properties": root}
+ save(evidence, f"{label}-external.json", state)
+ require(focus.isdigit() and {"X", "Y", "SCREEN"}.issubset(state["real_pointer"]),
+ "External focus/pointer observation is incomplete")
+ require("_NET_CLIENT_LIST_STACKING" in root, "Window manager did not expose stacking")
+ return state
+
+
+def compare_observations(before, after):
+ # Cursor overlay windows may appear. Compare the relative order of the
+ # existing application windows, recording the unfiltered stacking as well.
+ original = before["stacking_bottom_to_top"]
+ return {
+ "active_window_unchanged": before["active_window"] == after["active_window"],
+ "keyboard_focus_unchanged": before["keyboard_focus"] == after["keyboard_focus"],
+ "real_pointer_unchanged": all(before["real_pointer"].get(k) == after["real_pointer"].get(k)
+ for k in ("X", "Y", "SCREEN")),
+ "existing_stacking_unchanged": original == [w for w in after["stacking_bottom_to_top"]
+ if w in original],
+ }
+
+
+def button(snapshot, labels):
+ matches = [e for e in snapshot.get("elements", [])
+ if "button" in e.get("role", "").lower()
+ and e.get("label", "").strip().lower() in labels
+ and e.get("enabled", True)]
+ require(len(matches) == 1, f"Expected one calculator button in {sorted(labels)}, found {len(matches)}")
+ require(matches[0].get("element_token"), "Button lacks a fresh snapshot-bound token")
+ return matches[0]
+
+
+def snapshot(mcp, target, label):
+ state, images = mcp.call("get_window_state", target, label)
+ require(images, f"{label} did not produce an actual snapshot image")
+ require(not state.get("degraded") and state.get("elements"),
+ f"{label} lacks usable AT-SPI controls")
+ return state, images[0]
+
+
+def displays_42(state):
+ # GTK's read-only Calculator display exposes its AT-SPI text as the
+ # accessible label, not Value. Ignore buttons and snapshot indices so a
+ # matching control name or element number cannot masquerade as the result.
+ text_roles = {"text", "label", "entry", "statictext", "text field"}
+ return any(
+ str(element.get("role", "")).lower() in text_roles
+ and any(str(element.get(field, "")).strip() == "42"
+ for field in ("value", "label"))
+ for element in state.get("elements", [])
+ )
+
+
+def doctor(binary, env, evidence, label, *, require_window):
+ result = run([str(binary), "doctor", "--json"], env=env)
+ report = json.loads(result.stdout)
+ save(evidence, f"{label}.json", report)
+ probes = {p["label"]: p for p in report["probes"]}
+ for name in ("display server", "AT-SPI") + (("X11 connection",) if require_window else ()):
+ require(probes.get(name, {}).get("status") == "ok", f"doctor readiness failed: {name}")
+
+
+def main():
+ require(sys.platform == "linux" and platform.machine() == "x86_64",
+ "Only disposable Linux x86_64 runners are supported")
+ require(os.environ.get("GITHUB_ACTIONS") == "true"
+ and os.environ.get("RUNNER_ENVIRONMENT") == "github-hosted"
+ and os.geteuid() != 0, "Refusing installation outside an unprivileged GitHub-hosted runner")
+ temporary = Path(os.environ["RUNNER_TEMP"]).resolve(strict=True)
+ evidence = Path(os.environ["CUA_DOCS_EVIDENCE"]).resolve()
+ require(evidence.parent == temporary, "Evidence must be directly under RUNNER_TEMP")
+ evidence.mkdir(exist_ok=False)
+ processes = []
+ mcp = None
+ try:
+ top = Path(run(["git", "rev-parse", "--show-toplevel"]).stdout.strip()).resolve()
+ sha = run(["git", "rev-parse", "HEAD"]).stdout.strip()
+ dirty = run(["git", "status", "--porcelain"]).stdout
+ branch = run(["git", "symbolic-ref", "--short", "HEAD"], check=False).stdout.strip() or "detached HEAD"
+ scripts = ROOT / "libs/cua-driver/scripts"
+ package = tomllib.loads((ROOT / "libs/cua-driver/rust/Cargo.toml").read_text())
+ source_version = package["workspace"]["package"]["version"]
+ helper = (scripts / "_install-rust.sh").read_text()
+ baked = re.search(r'^CUA_DRIVER_RS_BAKED_VERSION="([0-9.]+)"', helper, re.M).group(1)
+ provenance = {"source_path": str(ROOT), "git_top_level": str(top), "branch": branch,
+ "checkout_sha": sha, "dirty_status": dirty, "source_version": source_version,
+ "installer_baked_version": baked, "upstream_comparison": "not requested",
+ "installer_sha256": {name: hashlib.sha256((scripts / name).read_bytes()).hexdigest()
+ for name in ("install.sh", "_install-rust.sh", "_install-common.sh")},
+ "coverage": "source-tree release installer + published Linux component binary",
+ "permission_override": "test-only unrestricted; tutorial recommends standard"}
+ save(evidence, "provenance.json", provenance)
+ require(top == ROOT and sha == os.environ["CUA_DOCS_SOURCE_SHA"] and not dirty,
+ "Source preflight must match the exact clean checkout SHA")
+ require(source_version == baked, "Source and baked release differ; review the intended release before running")
+ # Fixed legacy cleanup is outside the overridden package home. Refuse
+ # any existing installation, symlink or service rather than sweeping it.
+ for relative in (".cua-driver-rs", ".cua-driver", ".local/bin/cua-driver",
+ ".config/systemd/user/cua-driver-rs.service"):
+ path = Path.home() / relative
+ require(not path.exists() and not path.is_symlink(), f"Cold-install precondition failed: {relative}")
+ require(run(["pgrep", "-x", "cua-driver"], check=False).returncode == 1,
+ "A Driver process already exists; refusing the installer's process cleanup")
+ task = Path(tempfile.mkdtemp(prefix="docs-driver-first-run-", dir=temporary)).resolve()
+ require(task.parent == temporary and ROOT not in task.parents, "Invalid isolated install directory")
+ env = os.environ.copy()
+ for key in ("GH_TOKEN", "GITHUB_TOKEN", "CUA_DRIVER_RS_VERSION", "CUA_DRIVER_VERSION",
+ "CUA_DRIVER_PERMISSION_MODE", "CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS",
+ "WAYLAND_DISPLAY"):
+ env.pop(key, None)
+ for name, leaf in (("CUA_DRIVER_RS_HOME", "package"), ("CUA_DRIVER_RS_INSTALL_DIR", "bin"),
+ ("TMPDIR", "staging"), ("XDG_DATA_HOME", "data"),
+ ("XDG_CONFIG_HOME", "config"), ("XDG_CACHE_HOME", "cache")):
+ location = task / leaf
+ location.mkdir()
+ env[name] = str(location)
+ env.update(CUA_DRIVER_RS_KEEP_VERSIONS="0", CUA_DRIVER_RS_TELEMETRY_ENABLED="false",
+ CUA_DRIVER_RS_UPDATE_CHECK="false", CUA_TELEMETRY_ENABLED="false")
+ save(evidence, "installer-boundaries.json", {
+ "task_directory": str(task), "home_reassigned": False,
+ "active_cleanup_targets": [str(task / "staging"), str(task / "package/packages"), str(task / "bin")],
+ "legacy_cleanup": "absent, checked before install", "prior_local_cleanup": "fresh empty package home",
+ "release_gc": "disabled", "macos_cleanup": "unreachable on Linux",
+ "process_cleanup": "no matching Driver process or user service before install"})
+ installed = run(["bash", str(scripts / "install.sh"), "--no-modify-path"], env=env,
+ timeout=300, check=False)
+ save(evidence, "installer.log", installed.stdout + installed.stderr)
+ require(installed.returncode == 0, "Canonical installer failed; see installer.log")
+ binary = task / "bin/cua-driver"
+ resolved = binary.resolve(strict=True)
+ require(resolved.is_relative_to(task / "package/packages/releases"), "Installed binary escaped task package home")
+ version = run([str(binary), "--version"], env=env).stdout.strip()
+ require(re.search(rf"(?<![\d.]){re.escape(baked)}(?![\d.])", version), "Installed version differs from baked release")
+ url = f"https://github.com/trycua/cua/releases/download/cua-driver-rs-v{baked}/cua-driver-rs-{baked}-linux-x86_64-binary.tar.gz"
+ require(url in installed.stdout, "Installer did not report the expected exact component asset URL")
+ provenance.update(installed_path=str(binary), resolved_binary=str(resolved), installed_version=version,
+ binary_sha256=hashlib.sha256(resolved.read_bytes()).hexdigest(), component_asset_url=url)
+ save(evidence, "provenance.json", provenance)
+ endpoint = task / "driver.sock"
+ cold = run([str(binary), "status", "--socket", str(endpoint)], env=env, check=False)
+ save(evidence, "cold-status.log", cold.stdout + cold.stderr)
+ require("daemon is not running" in cold.stdout + cold.stderr, "Cold-start daemon precondition failed")
+ for name, args in (("openbox", ["openbox"]),
+ ("picom", ["picom", "--backend", "xrender", "--config", "/dev/null"])):
+ with (evidence / f"{name}.log").open("w") as log:
+ processes.append(subprocess.Popen(args, env=env, stdout=log, stderr=log,
+ start_new_session=True))
+ time.sleep(2)
+ require(all(p.poll() is None for p in processes), "Disposable window manager/compositor failed")
+ run(["gsettings", "set", "org.gnome.desktop.interface", "toolkit-accessibility", "true"], env=env)
+ with (evidence / "serve.log").open("w") as log:
+ daemon = subprocess.Popen([str(binary), "serve", "--socket", str(endpoint),
+ "--dangerously-bypass-approvals"], env=env,
+ stdout=log, stderr=log, start_new_session=True)
+ processes.append(daemon)
+ # serve remains alive in its own process (the tutorial's first terminal).
+ # Independent subprocesses below model the second terminal on the same bus.
+ for _ in range(30):
+ require(daemon.poll() is None, "Foreground serve exited before readiness")
+ status = run([str(binary), "status", "--socket", str(endpoint)], env=env, check=False)
+ if "daemon is running" in status.stdout:
+ break
+ time.sleep(1)
+ save(evidence, "running-status.log", status.stdout + status.stderr)
+ require(status.returncode == 0 and "daemon is running" in status.stdout, "Daemon never became ready")
+ doctor(binary, env, evidence, "doctor-before-launch", require_window=False)
+ apps = run([str(binary), "call", "list_apps", "--socket", str(endpoint)], env=env)
+ save(evidence, "list-apps-before-launch.json", apps.stdout)
+ # A new Openbox desktop may have no GUI apps yet. As the tutorial says,
+ # launch Calculator and repeat readiness; never accept an empty list.
+ mcp = MCP(binary, endpoint, env, evidence)
+ save(evidence, "mcp-initialize.json", mcp.request("initialize", {
+ "protocolVersion": "2024-11-05", "capabilities": {},
+ "clientInfo": {"name": "docs-first-run-smoke", "version": "1"}}))
+ mcp.process.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
+ mcp.process.stdin.flush()
+ listing = mcp.request("tools/list", {})
+ save(evidence, "mcp-tools.json", listing)
+ require({"launch_app", "get_window_state", "click", "get_desktop_state"}.issubset(
+ {tool["name"] for tool in listing["tools"]}), "MCP discovery lacks required tools")
+ mcp.call("get_desktop_state", {}, "before-launch-desktop")
+ before_launch = observe(evidence, "before-launch")
+ launch, _ = mcp.call("launch_app", {"name": "galculator"}, "launch-calculator")
+ pid = launch.get("pid")
+ require(isinstance(pid, int) and pid > 0, "Calculator launch lacks a PID")
+ windows = launch.get("windows", [])
+ if not windows:
+ for attempt in range(10):
+ listing, _ = mcp.call("list_windows", {"pid": pid}, f"launch-windows-{attempt}")
+ windows = listing.get("windows", []) if isinstance(listing, dict) else listing
+ if windows:
+ break
+ time.sleep(0.5)
+ require(len(windows) == 1, "Expected one calculator window; refusing ambiguous targeting")
+ target = {"pid": pid, "window_id": windows[0]["window_id"]}
+ state, _ = snapshot(mcp, target, "calculator-initial")
+ after_launch = observe(evidence, "after-launch")
+ require(hex(target["window_id"]) in after_launch["stacking_bottom_to_top"],
+ "External X11 observation did not find the calculator window")
+ save(evidence, "launch-external-comparison.json", compare_observations(before_launch, after_launch))
+ doctor(binary, env, evidence, "doctor-with-calculator", require_window=True)
+ apps = run([str(binary), "call", "list_apps", "--socket", str(endpoint)], env=env)
+ save(evidence, "list-apps-with-calculator.json", apps.stdout)
+ require("galculator" in apps.stdout.lower() and re.search(rf'"pid"\s*:\s*{pid}\b', apps.stdout),
+ "Second-terminal list_apps did not find the running calculator")
+ observations = []
+ for step, labels in enumerate(({"6"}, {"*", "×", "multiply", "multiplication"}, {"7"}, {"=", "equals", "equal"}), 1):
+ # The previous post-action observation is the next action's fresh
+ # snapshot. No tokens survive another snapshot of this target.
+ element = button(state, labels)
+ before = observe(evidence, f"step-{step}-before")
+ mcp.call("click", {**target, "element_token": element["element_token"],
+ "delivery_mode": "background"}, f"step-{step}-click")
+ state, final_image = snapshot(mcp, target, f"step-{step}-after")
+ after = observe(evidence, f"step-{step}-after")
+ observations.append(compare_observations(before, after))
+ save(evidence, "action-external-comparisons.json", observations)
+ # AT-SPI value and independently decoded screenshot must both show 42.
+ # Allow the native toolkit to publish the final value after its action
+ # callback returns. Refresh observations only; never repeat a click.
+ for attempt in range(6):
+ if displays_42(state):
+ break
+ time.sleep(0.5)
+ state, final_image = snapshot(mcp, target, f"result-settle-{attempt}")
+ ocr = run(["tesseract", str(final_image), "stdout", "--psm", "11"]).stdout
+ save(evidence, "final-image-ocr.txt", ocr)
+ require(displays_42(state), "Fresh AT-SPI display value did not prove 42")
+ require(re.search(r"(?<!\d)42(?!\d)", ocr), "Actual final PNG did not independently show 42 via OCR")
+ require(all(all(checks.values()) for checks in observations),
+ "A background action changed external focus, pointer or stacking; see comparisons")
+ require(daemon.poll() is None, "The original foreground serve process exited")
+ save(evidence, "result.json", {"status": "passed", "displayed_result": "42",
+ "target": target, "checkout_sha": sha, "installed_version": version,
+ "limitations": ["Linux X11/AT-SPI only; not cross-platform certification",
+ "published component binary, not built from checkout SHA",
+ "MCP protocol client, not agent registration or LLM execution",
+ "test-only unrestricted profile; standard profile not tested",
+ "focus/stack/pointer sampled before and after, not continuously",
+ "no occlusion or foreground escalation coverage",
+ "OCR evidence retained for human visual review"]})
+ print("PASS: canonical release install, cold serve, readiness, MCP and native Calculator display 42")
+ except Exception as error:
+ save(evidence, "result.json", {"status": "failed", "error": str(error)})
+ raise
+ finally:
+ if mcp is not None:
+ mcp.close()
+ for process in reversed(processes):
+ stop(process)
+
+
+if __name__ == "__main__":
+ main()