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.

ci: docs-only PRs skip the 77-minute E2E: cua SDK (#5820)

Francesco Bonacci91367419023b
diff --git a/.github/scripts/e2e_cua_sdk_scope.py b/.github/scripts/e2e_cua_sdk_scope.py
new file mode 100644
index 0000000000..16cff5896f
--- /dev/null
+++ b/.github/scripts/e2e_cua_sdk_scope.py
@@ -0,0 +1,298 @@
+#!/usr/bin/env python3
+"""Decide whether a pull request needs the `E2E: cua SDK` suite (about 77 minutes).
+
+The workflow's `paths:` filter (e2e-cua-sdk.yml) decides whether the workflow
+starts at all. Every entry in it is an input of the suite except one:
+`docs/content/docs/**`. The suite reads the docs only through the fenced code
+blocks of the pages (tests/e2e/cua-sdk/docs/extract.py: the `docs` lane runs
+the blocks tagged test="..." and the coverage check joins them back to the
+tags), so a page edit can change a result only if it changes a fence. This
+script keeps the docs entry in the filter, so a PR that does change a tagged
+block, or adds or removes one, still runs the suite, and drops it for
+prose-only edits.
+
+Output (stdout and $GITHUB_OUTPUT): `run=true|false` and `reason=...`.
+
+It runs the suite (fails closed) when:
+ * the event is not a pull request (nightly, manual dispatch);
+ * the changed-file list is empty, or any file or git object cannot be read;
+ * any changed path matches PATHS (the suite's non-docs inputs; a test pins
+ this list to the workflow's `paths:`);
+ * a changed docs page has a different fence list (language, info string, code)
+ at the base and at the head, and either side has a test="..." fence;
+ * a docs page is added, deleted, renamed or copied and either side has a
+ test="..." fence.
+
+Changed files outside both lists (the repo README, other apps) are ignored, as
+the workflow's own `paths:` filter ignores them. Docs files that are not pages
+(meta.json, redirects, images) are ignored: the suite does not read them.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import re
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Optional, Sequence
+
+REPO = Path(__file__).resolve().parents[2]
+EXTRACT = REPO / "tests" / "e2e" / "cua-sdk" / "docs" / "extract.py"
+
+DOCS_ROOT = "docs/content/docs/"
+DOCS_GLOB = DOCS_ROOT + "**"
+PAGE_SUFFIXES = (".md", ".mdx")
+
+# Everything in e2e-cua-sdk.yml `on.pull_request.paths` except DOCS_GLOB.
+PATHS = (
+ "libs/cua/**",
+ "libs/cua-spacesd/**",
+ "libs/images/**",
+ "libs/python/cua-sandbox/**",
+ # The cua-driver crates the static cua-spacesd build compiles, the closure
+ # `cargo metadata --filter-platform x86_64-unknown-linux-musl` reports from
+ # libs/cua-spacesd, and the files they include at compile time. Their
+ # manifests inherit from the driver workspace root. The macOS and Windows
+ # platform crates are not compiled on this Linux runner, but cargo's
+ # lockfile covers them, so only their manifests count (`--locked`).
+ # test_driver_closure_is_listed walks the Cargo.toml path dependencies and
+ # fails when a crate is missing here.
+ *(
+ f"libs/cua-driver/rust/crates/{crate}/**"
+ for crate in (
+ "cua-cursor-motion",
+ "cua-driver-contract",
+ "cua-driver-core",
+ "cua-driver-sdk",
+ "cursor-overlay",
+ "pip-preview",
+ "platform-linux",
+ )
+ ),
+ "libs/cua-driver/rust/crates/platform-macos/Cargo.toml",
+ "libs/cua-driver/rust/crates/platform-windows/Cargo.toml",
+ "libs/cua-driver/rust/Cargo.toml",
+ "libs/cua-driver/rust/Skills/**", # include_str! in cua-driver-core
+ "libs/cua-driver/rust/include/**", # include_str! in cua-driver-sdk
+ "libs/cua-driver/wayland-helper/**", # include_str! in platform-linux
+ "tests/e2e/cua-sdk/**",
+ # The browse-the-web scenario's MCP client session.
+ "tests/e2e/browse/**",
+ # The docs lane's tag policy.
+ "docs/code-block-policy.json",
+ # What the job runs around the suite: gVisor, the toolchain, the cache, the scope script.
+ "scripts/images/install-gvisor.sh",
+ ".github/actions/linux-rust-prep/**",
+ ".github/actions/setup-protoc/**",
+ ".github/actions/rust-cache/**",
+ ".github/scripts/e2e_cua_sdk_scope.py",
+ ".github/workflows/e2e-cua-sdk.yml",
+)
+
+
+def _glob(pattern: str) -> re.Pattern[str]:
+ """A GitHub `paths:` glob: `**` crosses `/`, `*` and `?` do not."""
+ out, i = [], 0
+ while i < len(pattern):
+ if pattern.startswith("**", i):
+ out.append(".*")
+ i += 2
+ elif pattern[i] == "*":
+ out.append("[^/]*")
+ i += 1
+ elif pattern[i] == "?":
+ out.append("[^/]")
+ i += 1
+ else:
+ out.append(re.escape(pattern[i]))
+ i += 1
+ return re.compile("".join(out) + r"\Z")
+
+
+_INPUTS = [_glob(p) for p in PATHS]
+
+
+def is_input(path: str) -> bool:
+ return any(rx.match(path) for rx in _INPUTS)
+
+
+def is_page(path: str) -> bool:
+ return path.startswith(DOCS_ROOT) and path.endswith(PAGE_SUFFIXES)
+
+
+@dataclass(frozen=True)
+class Change:
+ status: str # git name-status letter: A, M, D, R, C, T
+ path: str # the path at the head (at the base for D)
+ old_path: Optional[str] = None # the path at the base, for R and C
+
+
+Reader = Callable[[str, str], Optional[str]] # (side: "base" | "head", path) -> text or None
+
+
+class Unreadable(Exception):
+ pass
+
+
+def _extract():
+ spec = importlib.util.spec_from_file_location("e2e_docs_extract", EXTRACT)
+ if spec is None or spec.loader is None:
+ raise Unreadable(f"cannot load {EXTRACT}")
+ module = importlib.util.module_from_spec(spec)
+ # dataclasses resolves string annotations through sys.modules.
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+class _Text:
+ """The one thing extract.fences asks of a path: read_text."""
+
+ def __init__(self, text: str) -> None:
+ self._text = text
+
+ def read_text(self, encoding: str = "utf-8") -> str:
+ return self._text
+
+
+def _fences(extract, text: Optional[str], path: str):
+ if text is None:
+ raise Unreadable(f"{path} is not readable")
+ return extract.fences(_Text(text), path)
+
+
+def _tagged(fences) -> bool:
+ return any("test" in f.attrs for f in fences)
+
+
+def _signature(fences) -> list[tuple[str, str, bool]]:
+ return [(f.info, f.code, f.generated) for f in fences]
+
+
+def page_effect(change: Change, read: Reader, extract) -> Optional[str]:
+ """Why this docs page change can change a suite result, or None."""
+ base_path = change.old_path or change.path
+ base = head = None
+ if change.status != "A":
+ base = _fences(extract, read("base", base_path), base_path)
+ if change.status != "D":
+ head = _fences(extract, read("head", change.path), change.path)
+ sides = [f for f in (base, head) if f is not None]
+ if not any(_tagged(f) for f in sides):
+ return None # no tagged block before or after: nothing the suite runs
+ if change.status == "M":
+ if _signature(base) != _signature(head):
+ return f"{change.path} changes a code block on a page with tagged blocks"
+ return None # prose only
+ return f"{change.path} ({change.status}) has tagged blocks"
+
+
+def decide(
+ changes: Sequence[Change],
+ read: Reader,
+ event: str = "pull_request",
+ head_ref: str = "",
+ extract=None,
+) -> tuple[bool, str]:
+ if event != "pull_request":
+ return True, f"{event} runs the suite"
+ if head_ref.startswith("release-please--"):
+ return True, "release PR runs the suite"
+ if not changes:
+ return True, "no changed files listed, failing closed"
+ pages: list[Change] = []
+ for change in changes:
+ touched = [change.path] + ([change.old_path] if change.old_path else [])
+ for path in touched:
+ if is_input(path):
+ return True, f"{path} is an input of the suite"
+ if any(is_page(p) for p in touched):
+ pages.append(change)
+ if pages:
+ try:
+ extract = extract or _extract()
+ for change in pages:
+ why = page_effect(change, read, extract)
+ if why:
+ return True, why
+ except Exception as exc: # noqa: BLE001 - any doubt runs the suite
+ return True, f"cannot compare docs blocks ({exc}), failing closed"
+ return False, f"{len(pages)} docs page(s) changed prose only; no tagged block changed"
+ return False, "no changed path is an input of the suite"
+
+
+def _git(repo: Path, *args: str) -> bytes:
+ done = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, check=False)
+ if done.returncode != 0:
+ raise Unreadable(f"git {' '.join(args)} failed: {done.stderr.decode(errors='replace').strip()}")
+ return done.stdout
+
+
+def parse_name_status(raw: bytes) -> list[Change]:
+ """`git diff --name-status -z -M` output."""
+ parts = raw.decode("utf-8").split("\0")
+ if parts and parts[-1] == "":
+ parts.pop()
+ changes, i = [], 0
+ while i < len(parts):
+ status = parts[i][:1]
+ if status in ("R", "C"):
+ changes.append(Change(status, parts[i + 2], parts[i + 1]))
+ i += 3
+ else:
+ changes.append(Change(status, parts[i + 1]))
+ i += 2
+ return changes
+
+
+def git_changes(repo: Path, base: str, head: str) -> list[Change]:
+ return parse_name_status(_git(repo, "diff", "--name-status", "-z", "-M", base, head))
+
+
+def git_reader(repo: Path, base: str, head: str) -> Reader:
+ def read(side: str, path: str) -> Optional[str]:
+ try:
+ return _git(repo, "show", f"{base if side == 'base' else head}:{path}").decode("utf-8")
+ except (Unreadable, UnicodeDecodeError):
+ return None
+
+ return read
+
+
+def main(argv: Sequence[str]) -> int:
+ import argparse
+
+ ap = argparse.ArgumentParser(description=(__doc__ or "").split("\n")[0])
+ ap.add_argument("--repo", type=Path, default=Path.cwd())
+ ap.add_argument("--base", default="HEAD^1", help="default: the merge commit's first parent")
+ ap.add_argument("--head", default="HEAD")
+ args = ap.parse_args(argv)
+ event = os.environ.get("EVENT", "pull_request")
+ head_ref = os.environ.get("HEAD_REF", "")
+ try:
+ if event != "pull_request":
+ run, why = True, f"{event} runs the suite"
+ else:
+ run, why = decide(
+ git_changes(args.repo, args.base, args.head),
+ git_reader(args.repo, args.base, args.head),
+ event,
+ head_ref,
+ )
+ except Exception as exc: # noqa: BLE001 - any doubt runs the suite
+ run, why = True, f"cannot list the changed files ({exc}), failing closed"
+ out = {"run": str(run).lower(), "reason": why}
+ for key, value in out.items():
+ print(f"{key}={value}")
+ target = os.environ.get("GITHUB_OUTPUT")
+ if target:
+ with open(target, "a", encoding="utf-8") as fh:
+ fh.writelines(f"{k}={v}\n" for k, v in out.items())
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/.github/scripts/tests/test_e2e_cua_sdk_scope.py b/.github/scripts/tests/test_e2e_cua_sdk_scope.py
new file mode 100644
index 0000000000..90ec5288da
--- /dev/null
+++ b/.github/scripts/tests/test_e2e_cua_sdk_scope.py
@@ -0,0 +1,526 @@
+"""Docs-only pull requests skip `E2E: cua SDK` (e2e_cua_sdk_scope.py).
+
+The suite reads the docs only through fenced code blocks. These fixtures pin
+what runs it, what skips it, that every doubt runs it, that the workflow's
+`paths:` filter and the script agree, and that `ci-gate` counts a skipped run
+as passed.
+"""
+
+import glob
+import importlib.util
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).resolve().parents[3]
+MODULE_PATH = ROOT / ".github/scripts/e2e_cua_sdk_scope.py"
+SPEC = importlib.util.spec_from_file_location("e2e_cua_sdk_scope", MODULE_PATH)
+assert SPEC is not None and SPEC.loader is not None
+scope = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = scope
+SPEC.loader.exec_module(scope)
+
+WORKFLOW = yaml.safe_load((ROOT / ".github/workflows/e2e-cua-sdk.yml").read_text())
+GATE = yaml.safe_load((ROOT / ".github/workflows/ci-gate.yml").read_text())
+
+TAGGED = "```python test=\"docs\" id=\"demo\"\nprint(1)\n```"
+TAGGED_EDITED = "```python test=\"docs\" id=\"demo\"\nprint(2)\n```"
+PLAIN = "```bash\nnpm install\n```"
+PLAIN_EDITED = "```bash\nnpm install --save\n```"
+GUIDE = "docs/content/docs/cua-sdk/guides/images.mdx"
+OTHER = "docs/content/docs/spaces/guides/plans.mdx"
+
+
+def page(fence: str, prose: str = "Intro.") -> str:
+ return f"# Title\n\n{prose}\n\n{fence}\n\nAfter.\n"
+
+
+def decide(changes, base=None, head=None, **kwargs):
+ files = {"base": base or {}, "head": head or {}}
+ run, why = scope.decide(changes, lambda side, path: files[side].get(path), **kwargs)
+ return run, why
+
+
+def modified(path, before, after, **kwargs):
+ return decide([scope.Change("M", path)], {path: before}, {path: after}, **kwargs)
+
+
+# --- docs pages: only a change to a fence can change a result -------------------
+
+
+def test_prose_edit_on_a_tagged_page_skips():
+ run, why = modified(GUIDE, page(TAGGED), page(TAGGED, prose="A new sentence."))
+ assert not run, why
+
+
+def test_prose_edit_on_an_untagged_page_skips():
+ assert not modified(OTHER, page(PLAIN), page(PLAIN, prose="New."))[0]
+
+
+def test_edited_untagged_block_on_an_untagged_page_skips():
+ assert not modified(OTHER, page(PLAIN), page(PLAIN_EDITED))[0]
+
+
+def test_edited_tagged_block_runs():
+ assert modified(GUIDE, page(TAGGED), page(TAGGED_EDITED))[0]
+
+
+def test_changed_tag_runs():
+ retagged = page(TAGGED.replace('id="demo"', 'id="other"'))
+ assert modified(GUIDE, page(TAGGED), retagged)[0]
+
+
+def test_gaining_a_tag_runs():
+ assert modified(OTHER, page(PLAIN), page('```bash test="docs" id="x"\nnpm install\n```'))[0]
+
+
+def test_losing_every_tag_runs():
+ assert modified(GUIDE, page(TAGGED), page(PLAIN))[0]
+
+
+def test_untagged_block_edit_beside_tagged_blocks_runs():
+ # Conservative: it can shift the index of a tagged block that has no id.
+ both = TAGGED + "\n\n" + PLAIN
+ edited = TAGGED + "\n\n" + PLAIN_EDITED
+ assert modified(GUIDE, page(both), page(edited))[0]
+
+
+def test_generated_banner_on_a_tagged_page_runs():
+ banner = "{/* AUTO-GENERATED */}\n"
+ assert modified(GUIDE, page(TAGGED), banner + page(TAGGED))[0]
+
+
[email protected]("suffix", [".md", ".mdx"])
+def test_both_page_suffixes_are_compared(suffix):
+ path = "docs/content/docs/cua-sdk/guides/x" + suffix
+ assert modified(path, page(TAGGED), page(TAGGED_EDITED))[0]
+ assert not modified(path, page(TAGGED), page(TAGGED, prose="New."))[0]
+
+
+def test_added_tagged_page_runs():
+ assert decide([scope.Change("A", GUIDE)], head={GUIDE: page(TAGGED)})[0]
+
+
+def test_added_untagged_page_skips():
+ assert not decide([scope.Change("A", OTHER)], head={OTHER: page(PLAIN)})[0]
+
+
+def test_deleted_tagged_page_runs():
+ assert decide([scope.Change("D", GUIDE)], base={GUIDE: page(TAGGED)})[0]
+
+
+def test_deleted_untagged_page_skips():
+ assert not decide([scope.Change("D", OTHER)], base={OTHER: page(PLAIN)})[0]
+
+
+def test_renamed_tagged_page_runs():
+ new = "docs/content/docs/cua-sdk/guides/images-2.mdx"
+ assert decide([scope.Change("R", new, GUIDE)], {GUIDE: page(TAGGED)}, {new: page(TAGGED)})[0]
+
+
+def test_renamed_untagged_page_skips():
+ new = "docs/content/docs/spaces/guides/plans-2.mdx"
+ assert not decide([scope.Change("R", new, OTHER)], {OTHER: page(PLAIN)}, {new: page(PLAIN)})[0]
+
+
+def test_one_tagged_change_among_prose_edits_runs():
+ changes = [scope.Change("M", OTHER), scope.Change("M", GUIDE)]
+ base = {OTHER: page(PLAIN), GUIDE: page(TAGGED)}
+ head = {OTHER: page(PLAIN, prose="New."), GUIDE: page(TAGGED_EDITED)}
+ assert decide(changes, base, head)[0]
+
+
+ "path",
+ [
+ "docs/content/docs/spaces/meta.json",
+ "docs/content/docs/redirects.json",
+ "docs/content/docs/spaces/img/shot.png",
+ ],
+)
+def test_docs_files_that_are_not_pages_skip(path):
+ assert not decide([scope.Change("M", path)])[0]
+
+
+# --- every other input of the suite runs it -----------------------------------
+
+
+ "path",
+ [
+ "libs/cua/crates/cua-sdk/src/lib.rs",
+ "libs/cua/Cargo.lock",
+ "libs/cua/rust-toolchain.toml",
+ "libs/cua/typescript/package.json",
+ "libs/cua-spacesd/crates/cua-spacesd-server/src/lib.rs",
+ "libs/cua-spacesd/Cargo.lock",
+ "libs/images/linux/Dockerfile",
+ "libs/python/cua-sandbox/cua_sandbox/__init__.py",
+ "libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs",
+ "libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs",
+ "libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml",
+ "libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs",
+ "libs/cua-driver/rust/crates/platform-macos/Cargo.toml",
+ "libs/cua-driver/rust/crates/platform-windows/Cargo.toml",
+ "libs/cua-driver/rust/Cargo.toml",
+ "libs/cua-driver/rust/Skills/cua-driver/SKILL.md",
+ "libs/cua-driver/rust/include/cua_driver_abi.h",
+ "libs/cua-driver/wayland-helper/winrects@cua/extension.js",
+ "tests/e2e/cua-sdk/run.py",
+ "tests/e2e/cua-sdk/rust/Cargo.lock",
+ "tests/e2e/browse/server.py",
+ "docs/code-block-policy.json",
+ "scripts/images/install-gvisor.sh",
+ ".github/actions/linux-rust-prep/action.yml",
+ ".github/actions/setup-protoc/action.yml",
+ ".github/actions/rust-cache/action.yml",
+ ".github/scripts/e2e_cua_sdk_scope.py",
+ ".github/workflows/e2e-cua-sdk.yml",
+ ],
+)
+def test_suite_inputs_run(path):
+ assert decide([scope.Change("M", path)])[0]
+ # Beside a docs prose edit too.
+ changes = [scope.Change("M", OTHER), scope.Change("M", path)]
+ assert decide(changes, {OTHER: page(PLAIN)}, {OTHER: page(PLAIN, prose="New.")})[0]
+
+
+def test_input_renamed_out_of_the_suite_runs():
+ assert decide([scope.Change("R", "libs/misc/a.rs", "libs/cua/crates/a.rs")])[0]
+
+
[email protected]("path", ["README.md", "apps/cua-spaces/src/main.rs", "docs/src/app/page.tsx"])
+def test_unrelated_files_beside_docs_prose_skip(path):
+ changes = [scope.Change("M", OTHER), scope.Change("M", path)]
+ run, why = decide(changes, {OTHER: page(PLAIN)}, {OTHER: page(PLAIN, prose="New.")})
+ assert not run, why
+
+
+def test_docs_prose_beside_a_driver_dependency_runs():
+ # Before the docs filter was narrowed, the docs page alone started the whole
+ # suite for this pull request. The driver crate is an input in its own right,
+ # so the mix must not skip it.
+ changes = [
+ scope.Change("M", OTHER),
+ scope.Change("M", "libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs"),
+ ]
+ run, why = decide(changes, {OTHER: page(PLAIN)}, {OTHER: page(PLAIN, prose="New.")})
+ assert run and "cua-driver-core" in why
+
+
+ "path",
+ [
+ # Driver code the static cua-spacesd build does not compile.
+ "libs/cua-driver/rust/crates/cua-driver/src/main.rs",
+ "libs/cua-driver/rust/crates/platform-macos/src/lib.rs",
+ "libs/cua-driver/rust/crates/platform-windows/src/lib.rs",
+ "libs/cua-driver/rust/crates/cua-perception/src/lib.rs",
+ "libs/cua-driver/rust/Cargo.lock",
+ "libs/cua-driver/typescript/package.json",
+ ],
+)
+def test_driver_code_outside_the_closure_beside_docs_prose_skips(path):
+ changes = [scope.Change("M", OTHER), scope.Change("M", path)]
+ run, why = decide(changes, {OTHER: page(PLAIN)}, {OTHER: page(PLAIN, prose="New.")})
+ assert not run, why
+
+
+def load_toml(path):
+ try:
+ import tomllib
+
+ return tomllib.loads(path.read_text(encoding="utf-8"))
+ except ModuleNotFoundError:
+ return pytest.importorskip("toml").loads(path.read_text(encoding="utf-8"))
+
+
+def spacesd_path_dependencies():
+ """Every crate directory the libs/cua-spacesd workspace reaches through
+ `path = ...` dependencies, on every platform."""
+ seen = set()
+
+ def walk(directory):
+ directory = os.path.normpath(directory)
+ if directory in seen:
+ return
+ seen.add(directory)
+ doc = load_toml(Path(directory) / "Cargo.toml")
+ tables = [doc.get(k, {}) for k in ("dependencies", "dev-dependencies", "build-dependencies")]
+ tables.append(doc.get("workspace", {}).get("dependencies", {}))
+ for target in doc.get("target", {}).values():
+ tables += [target.get(k, {}) for k in ("dependencies", "dev-dependencies", "build-dependencies")]
+ for table in tables:
+ for spec in table.values():
+ if isinstance(spec, dict) and "path" in spec:
+ walk(os.path.join(directory, spec["path"]))
+ for member in doc.get("workspace", {}).get("members", []):
+ for found in glob.glob(os.path.join(directory, member)):
+ if (Path(found) / "Cargo.toml").exists():
+ walk(found)
+
+ walk(ROOT / "libs" / "cua-spacesd")
+ return {os.path.relpath(d, ROOT) for d in seen}
+
+
+# The cargo lockfile covers these, but a Linux build does not compile them.
+NOT_COMPILED_ON_LINUX = {"platform-macos", "platform-windows"}
+
+
+def test_driver_closure_is_listed():
+ crates = {
+ d.rsplit("/", 1)[1] for d in spacesd_path_dependencies() if d.startswith("libs/cua-driver/rust/crates/")
+ }
+ assert {"cua-driver-core", "platform-linux"} <= crates, "the walk found no driver crates"
+ for crate in sorted(crates):
+ base = f"libs/cua-driver/rust/crates/{crate}"
+ assert scope.is_input(f"{base}/Cargo.toml"), crate
+ if crate not in NOT_COMPILED_ON_LINUX:
+ assert scope.is_input(f"{base}/src/lib.rs"), f"{crate} is built into cua-spacesd but is not an input"
+
+
+ "directory",
+ [
+ "libs/cua-driver/rust/Skills/cua-driver",
+ "libs/cua-driver/rust/include",
+ "libs/cua-driver/wayland-helper/winrects@cua",
+ ],
+)
+def test_compile_time_includes_exist(directory):
+ # The directories behind the include_str! inputs: a rename must update PATHS.
+ assert (ROOT / directory).is_dir()
+
+
+# --- doubt runs the suite ------------------------------------------------------
+
+
[email protected]("event", ["workflow_dispatch", "schedule", "push"])
+def test_other_events_run(event):
+ assert modified(GUIDE, page(TAGGED), page(TAGGED, prose="New."), event=event)[0]
+
+
+def test_release_branch_runs():
+ ref = "release-please--branches--main"
+ assert modified(GUIDE, page(TAGGED), page(TAGGED, prose="New."), head_ref=ref)[0]
+
+
+def test_empty_change_list_runs():
+ assert decide([])[0]
+
+
+def test_unreadable_page_runs():
+ assert decide([scope.Change("M", GUIDE)], {GUIDE: page(TAGGED)}, {})[0]
+ assert decide([scope.Change("M", GUIDE)], {}, {GUIDE: page(TAGGED)})[0]
+
+
+def test_unknown_status_runs():
+ assert decide([scope.Change("U", GUIDE)], {GUIDE: page(TAGGED)}, {GUIDE: page(TAGGED)})[0]
+
+
+def test_broken_extractor_runs():
+ class Broken:
+ @staticmethod
+ def fences(*_):
+ raise RuntimeError("boom")
+
+ run, why = decide([scope.Change("M", GUIDE)], {GUIDE: page(TAGGED)}, {GUIDE: page(TAGGED)}, extract=Broken)
+ assert run and "failing closed" in why
+
+
+# --- the script and the workflow agree ----------------------------------------
+
+
+def test_script_paths_match_the_workflow_filter():
+ filter_paths = WORKFLOW[True]["pull_request"]["paths"]
+ assert sorted(filter_paths) == sorted([*scope.PATHS, scope.DOCS_GLOB])
+
+
+def test_every_path_matches_itself_and_nothing_wider():
+ for pattern in scope.PATHS:
+ sample = pattern.replace("**", "a/b.txt")
+ assert scope.is_input(sample), pattern
+ assert not scope.is_input("libs/cua-driver/rust/crates/cua-driver/src/main.rs")
+ assert not scope.is_input("libs/cua-driver/rust/crates/platform-macos/src/lib.rs")
+ assert not scope.is_input("libs/cua-driver/rust/crates/cua-driver-core-extras/a.rs")
+ assert not scope.is_input("libs/cuax/a.rs")
+ assert not scope.is_input("tests/e2e/cua-sdk-other/a.py")
+
+
+def test_workflow_wiring():
+ jobs = WORKFLOW["jobs"]
+ changes, local, live = jobs["changes"], jobs["local"], jobs["live"]
+ assert local["needs"] == "changes"
+ # Only an explicit `false` skips the suite.
+ assert "needs.changes.outputs.run != 'false'" in local["if"]
+ assert changes["outputs"] == {"run": "${{ steps.scope.outputs.run }}"}
+ checkout = changes["steps"][0]
+ assert checkout["with"]["fetch-depth"] == 2
+ assert changes["steps"][1]["env"]["EVENT"] == "${{ github.event_name }}"
+ # The nightly lane is not behind the scope job.
+ assert "needs" not in live
+ assert live["if"] == "github.event_name == 'schedule'"
+ assert set(WORKFLOW[True]) == {"pull_request", "schedule", "workflow_dispatch"}
+
+
+# --- git: the real change list --------------------------------------------------
+
+
+def git(repo, *args):
+ env = {
+ **os.environ,
+ "GIT_AUTHOR_NAME": "t",
+ "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "t",
+ "GIT_COMMITTER_EMAIL": "[email protected]",
+ }
+ subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, env=env)
+
+
+def write(repo, rel, text):
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+def scoped(repo, capsys, monkeypatch, event="pull_request"):
+ monkeypatch.setenv("EVENT", event)
+ monkeypatch.delenv("HEAD_REF", raising=False)
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+ assert scope.main(["--repo", str(repo)]) == 0
+ return dict(line.split("=", 1) for line in capsys.readouterr().out.splitlines())
+
+
+def repo(tmp_path):
+ git(tmp_path, "init", "-q")
+ write(tmp_path, GUIDE, page(TAGGED))
+ write(tmp_path, OTHER, page(PLAIN))
+ write(tmp_path, "README.md", "readme\n")
+ git(tmp_path, "add", "-A")
+ git(tmp_path, "commit", "-q", "-m", "base")
+ return tmp_path
+
+
+def commit(repo):
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "-m", "head")
+
+
+def test_git_prose_edit_skips(repo, capsys, monkeypatch):
+ write(repo, GUIDE, page(TAGGED, prose="Rewritten."))
+ write(repo, "README.md", "changed\n")
+ commit(repo)
+ out = scoped(repo, capsys, monkeypatch)
+ assert out["run"] == "false", out
+
+
+def test_git_block_edit_runs(repo, capsys, monkeypatch):
+ write(repo, GUIDE, page(TAGGED_EDITED))
+ commit(repo)
+ assert scoped(repo, capsys, monkeypatch)["run"] == "true"
+
+
+def test_git_sdk_change_runs(repo, capsys, monkeypatch):
+ write(repo, "libs/cua/crates/cua-sdk/src/lib.rs", "// x\n")
+ commit(repo)
+ assert scoped(repo, capsys, monkeypatch)["run"] == "true"
+
+
+def test_git_rename_of_a_tagged_page_runs(repo, capsys, monkeypatch):
+ git(repo, "mv", GUIDE, GUIDE.replace("images", "pictures"))
+ commit(repo)
+ assert scoped(repo, capsys, monkeypatch)["run"] == "true"
+
+
+def test_git_untagged_page_deletion_skips(repo, capsys, monkeypatch):
+ git(repo, "rm", "-q", OTHER)
+ commit(repo)
+ assert scoped(repo, capsys, monkeypatch)["run"] == "false"
+
+
+def test_git_dispatch_runs(repo, capsys, monkeypatch):
+ write(repo, GUIDE, page(TAGGED, prose="Rewritten."))
+ commit(repo)
+ assert scoped(repo, capsys, monkeypatch, event="workflow_dispatch")["run"] == "true"
+
+
+def test_git_failure_runs(tmp_path, capsys, monkeypatch):
+ # Not a repository: no change list, so the suite runs.
+ out = scoped(tmp_path, capsys, monkeypatch)
+ assert out["run"] == "true" and "failing closed" in out["reason"]
+
+
+def test_git_writes_github_output(repo, monkeypatch, tmp_path):
+ write(repo, GUIDE, page(TAGGED, prose="Rewritten."))
+ commit(repo)
+ target = tmp_path / "out.txt"
+ monkeypatch.setenv("EVENT", "pull_request")
+ monkeypatch.setenv("GITHUB_OUTPUT", str(target))
+ assert scope.main(["--repo", str(repo)]) == 0
+ assert "run=false\n" in target.read_text()
+
+
+# --- ci-gate counts a skipped run as passed ------------------------------------
+
+GATE_SCRIPT = GATE["jobs"]["ci-gate"]["steps"][0]["run"]
+
+
+def run_gate(rows, jobs):
+ mock = """
+set -uo pipefail
+api() {
+ case "$*" in
+ *'/jobs?'*) printf '%s' "$JOBS" ;;
+ *'head_sha='*) printf '%s' "$ROWS" ;;
+ *) printf '999' ;;
+ esac
+}
+sleeps=0
+sleep() { sleeps=$((sleeps + 1)); if (( sleeps > 4 )); then exit 124; fi; }
+"""
+ return subprocess.run(
+ ["bash", "-c", mock + GATE_SCRIPT[GATE_SCRIPT.index("sha=$PR_SHA") :]],
+ env={
+ **os.environ,
+ "PR_SHA": "abc",
+ "QUEUE_REF": "",
+ "GITHUB_REPOSITORY": "test/repo",
+ "GITHUB_RUN_ID": "99",
+ "ROWS": rows,
+ "JOBS": jobs,
+ },
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+
+
+ ("conclusion", "jobs", "verdict"),
+ [
+ # `local` skipped, `changes` ran: the run succeeded.
+ ("success", "E2E: cua SDK / changes\tsuccess", "pass"),
+ # Every job skipped (the jq filter drops them): not missing, not a failure.
+ ("success", "", "skipped"),
+ ("skipped", "", "skipped"),
+ # The suite ran and failed: still a failure.
+ ("failure", "hermetic + container\tfailure", "fail"),
+ ],
+)
+def test_gate_treats_a_skipped_suite_as_passed(conclusion, jobs, verdict):
+ rows = f"7\t70\tE2E: cua SDK\t{conclusion}\tcompleted"
+ done = run_gate(rows, jobs)
+ assert done.returncode == (1 if verdict == "fail" else 0), done.stderr
+ assert f"E2E: cua SDK: {verdict}" in done.stdout
+
+
+def test_gate_does_not_wait_for_a_workflow_that_never_started():
+ # A paths filter that does not match creates no run at all.
+ done = run_gate("1\t11\tbuild\tsuccess\tcompleted", "test\tsuccess")
+ assert done.returncode == 0
+ assert "E2E: cua SDK" not in done.stdout
diff --git a/.github/workflows/e2e-cua-sdk.yml b/.github/workflows/e2e-cua-sdk.yml
index 141a743a09..ba2d583c4e 100644
--- a/.github/workflows/e2e-cua-sdk.yml
+++ b/.github/workflows/e2e-cua-sdk.yml
@@ -4,7 +4,9 @@ name: "E2E: cua SDK"
# tests/e2e/cua-sdk (see its scenarios.json for the guide x lane registry).
#
# pull_request hermetic (fixtures, daemon) + container (docker + gVisor on
-# the locally built reference images) + docs blocks.
+# the locally built reference images) + docs blocks. A docs
+# edit that leaves every fenced code block as it was skips the
+# suite (the `changes` job, .github/scripts/e2e_cua_sdk_scope.py).
# nightly cua-sandbox and local QEMU (KVM) on the reference disk.
# Cua Cloud has ended, so there is no live Fleet lane.
# dispatch any lane set.
@@ -15,16 +17,43 @@ name: "E2E: cua SDK"
on:
pull_request:
paths:
+ # Keep in step with PATHS in .github/scripts/e2e_cua_sdk_scope.py (a test
+ # pins the two lists together).
- "libs/cua/**"
- "libs/cua-spacesd/**"
- "libs/images/**"
+ # The docs lane installs cua-sandbox from the tree.
+ - "libs/python/cua-sandbox/**"
+ # The cua-driver crates the static cua-spacesd build compiles (the closure
+ # `cargo metadata` reports from libs/cua-spacesd) and what they include.
+ - "libs/cua-driver/rust/crates/cua-cursor-motion/**"
+ - "libs/cua-driver/rust/crates/cua-driver-contract/**"
+ - "libs/cua-driver/rust/crates/cua-driver-core/**"
+ - "libs/cua-driver/rust/crates/cua-driver-sdk/**"
+ - "libs/cua-driver/rust/crates/cursor-overlay/**"
+ - "libs/cua-driver/rust/crates/pip-preview/**"
+ - "libs/cua-driver/rust/crates/platform-linux/**"
+ # Not compiled on this runner, but the lockfile (--locked) covers them.
+ - "libs/cua-driver/rust/crates/platform-macos/Cargo.toml"
+ - "libs/cua-driver/rust/crates/platform-windows/Cargo.toml"
+ - "libs/cua-driver/rust/Cargo.toml"
+ - "libs/cua-driver/rust/Skills/**"
+ - "libs/cua-driver/rust/include/**"
+ - "libs/cua-driver/wayland-helper/**"
- "tests/e2e/cua-sdk/**"
# The browse-the-web scenario's MCP client session.
- "tests/e2e/browse/**"
# Every docs page: tagged blocks run in the docs lane, and any page
# (reference/**, cua-sdk/index.mdx, how-to-guides/spaces/**, ...) can gain one.
+ # The `changes` job lets through only a change to a fenced code block.
- "docs/content/docs/**"
- "docs/code-block-policy.json"
+ # gVisor, the toolchain and cache steps, and the scope script the job runs.
+ - "scripts/images/install-gvisor.sh"
+ - ".github/actions/linux-rust-prep/**"
+ - ".github/actions/setup-protoc/**"
+ - ".github/actions/rust-cache/**"
+ - ".github/scripts/e2e_cua_sdk_scope.py"
- ".github/workflows/e2e-cua-sdk.yml"
schedule:
- cron: "23 7 * * *"
@@ -56,9 +85,37 @@ env:
CUA_E2E_RUN: gh${{ github.run_id }}-${{ github.run_attempt }}
jobs:
+ # Pull requests: the paths filter above starts this workflow for any docs
+ # page. The suite reads a page only through its fenced code blocks, so this
+ # job runs the suite when a block changed (or a tagged page came or went) and
+ # skips it for prose. Every other trigger, and any doubt, runs it. When it is
+ # skipped, the run still exists and succeeds, so `ci-gate` counts it as passed.
+ changes:
+ name: "E2E: cua SDK / changes"
+ if: ${{ !startsWith(github.head_ref, 'release-please--branches--') && (github.event_name != 'schedule') }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ outputs:
+ run: ${{ steps.scope.outputs.run }}
+ steps:
+ # The merge commit's first parent is the base, so two commits of history
+ # are enough to list exactly what the pull request changes.
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ fetch-depth: 2
+ persist-credentials: false
+ - id: scope
+ env:
+ EVENT: ${{ github.event_name }}
+ HEAD_REF: ${{ github.head_ref }}
+ run: python3 .github/scripts/e2e_cua_sdk_scope.py | tee -a "$GITHUB_STEP_SUMMARY"
+
local:
name: hermetic + container (${{ github.event_name == 'workflow_dispatch' && inputs.lanes || 'hermetic,container' }})
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') && (github.event_name != 'schedule') }}
+ needs: changes
+ if: ${{ !startsWith(github.head_ref, 'release-please--branches--') && (github.event_name != 'schedule') && needs.changes.outputs.run != 'false' }}
runs-on: ubuntu-24.04
# Run 37562962482 exhausted 180 minutes during cold browser compilation,
# before image preparation or the suite. Allow the hosted runner's full