From 162d047c3d85b1456c45ceee8a11a5b790a7515f Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 14:04:48 -0800 Subject: [PATCH 01/11] native-review: run the desktop journey on a headless macOS VM Make tools/native-review work on a Docker-less, headless macOS workstation and script the hand fixes that were needed to get there. - bin/setup-macos-vm: idempotent setup of native Postgres, Redis and MinIO on the harness ports (MinIO built with go install, bucket created with a SigV4 curl), a prefetched sherpa-onnx archive, the isolated relay, and the Local Network prompt. - scripts/start-isolated-test-relay.sh: BUZZ_HARNESS_NATIVE_SERVICES=1 runs the relay against those services instead of docker compose. - review_native.py: SHERPA_ONNX_ARCHIVE_DIR / SHERPA_ONNX_LIB_DIR reach host builds (never the reviewed app); doctor requires ffmpeg; the review window is moved onto the main display and the run waits for WebKit's accessibility tree before the first locator. - ios_review.py: PUB_HOSTED_URL passes through the env allowlist. - Swift driver: place_window and web_ready commands, press-system-alert-button, and answering first-run macOS privacy prompts (decline microphone/camera, allow Local Network) when the app cannot take focus. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jude Edwards --- scripts/start-isolated-test-relay.sh | 32 ++- tools/native-review/README.md | 37 ++++ .../bin/allow-local-network-prompt | 26 +++ tools/native-review/bin/setup-macos-vm | 182 ++++++++++++++++++ tools/native-review/ios_review.py | 2 + tools/native-review/review_native.py | 38 +++- .../swift/Sources/BuzzNativeDriver/main.swift | 97 +++++++++- .../DriverSupport.swift | 33 ++++ .../DriverSupportTests.swift | 53 +++++ tools/native-review/tests/test_ios_review.py | 7 + .../native-review/tests/test_review_native.py | 101 +++++++++- 11 files changed, 596 insertions(+), 12 deletions(-) create mode 100755 tools/native-review/bin/allow-local-network-prompt create mode 100755 tools/native-review/bin/setup-macos-vm diff --git a/scripts/start-isolated-test-relay.sh b/scripts/start-isolated-test-relay.sh index b737a73ea9c..7febc390ecd 100755 --- a/scripts/start-isolated-test-relay.sh +++ b/scripts/start-isolated-test-relay.sh @@ -22,6 +22,10 @@ # # Teardown (safe — scoped to our project only): # docker compose -p buzz-harness -f docker-compose.harness.yml down -v +# +# Hosts without Docker (e.g. a managed macOS VM): set BUZZ_HARNESS_NATIVE_SERVICES=1 +# after starting Postgres/Redis/MinIO yourself on the ports above and creating the +# media bucket; tools/native-review/bin/setup-macos-vm does all of that. # ============================================================================= set -euo pipefail @@ -69,12 +73,21 @@ ok() { echo -e "${GREEN}[isolated-relay]${NC} $*"; } err() { echo -e "${RED}[isolated-relay]${NC} $*" >&2; } # ── Backing services (scoped to buzz-harness only) ─────────────────────────── -log "Bringing up backing services (project=${PROJECT})..." -docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" up -d +NATIVE_SERVICES="${BUZZ_HARNESS_NATIVE_SERVICES:-0}" +if [[ "${NATIVE_SERVICES}" == "1" ]]; then + log "Using natively-run backing services on :${PG_PORT}/:${REDIS_PORT}/:${MINIO_PORT} (no Docker)..." +else + log "Bringing up backing services (project=${PROJECT})..." + docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" up -d +fi wait_pg() { for _ in $(seq 1 60); do - if docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ + if [[ "${NATIVE_SERVICES}" == "1" ]]; then + if pg_isready -h localhost -p "${PG_PORT}" -U buzz >/dev/null 2>&1; then + ok "Postgres ready"; return 0 + fi + elif docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ pg_isready -U buzz >/dev/null 2>&1; then ok "Postgres ready"; return 0 fi @@ -86,8 +99,14 @@ wait_pg # ── Schema + partitions ────────────────────────────────────────────────────── export PGPASSWORD=buzz_dev -psql_h() { docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ - psql -U buzz -d buzz -v ON_ERROR_STOP=1 "$@"; } +psql_h() { + if [[ "${NATIVE_SERVICES}" == "1" ]]; then + psql -h localhost -p "${PG_PORT}" -U buzz -d buzz -v ON_ERROR_STOP=1 "$@" + else + docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ + psql -U buzz -d buzz -v ON_ERROR_STOP=1 "$@" + fi +} log "Resetting isolated database and applying schema..." # This database belongs only to the buzz-harness Compose project. Reset it on @@ -141,8 +160,9 @@ if command -v lsof >/dev/null 2>&1 && lsof -nP -iTCP:"${RELAY_MAIN}" -sTCP:LISTE exit 1 fi log "Starting relay in tmux session '${TMUX_SESSION}' on :${RELAY_MAIN} (health :${RELAY_HEALTH}, metrics :${RELAY_METRICS})..." +RELAY_DATABASE_URL="postgres://buzz:buzz_dev@localhost:${PG_PORT}/buzz" # sadscan:disable np.postgres.1 -- public dev fixture from docker-compose.harness.yml tmux new-session -d -s "${TMUX_SESSION}" "cd '${REPO_ROOT}' && env \ - DATABASE_URL=postgres://buzz:buzz_dev@localhost:${PG_PORT}/buzz \ + DATABASE_URL=${RELAY_DATABASE_URL} \ REDIS_URL=redis://localhost:${REDIS_PORT} \ RELAY_URL=ws://localhost:${RELAY_MAIN} \ BUZZ_BIND_ADDR=0.0.0.0:${RELAY_MAIN} \ diff --git a/tools/native-review/README.md b/tools/native-review/README.md index 9b1ba136cdf..fd44567348f 100644 --- a/tools/native-review/README.md +++ b/tools/native-review/README.md @@ -65,6 +65,43 @@ or VM for untrusted changes. xcrun simctl list devices available ``` +### Headless macOS VM without Docker + +A cloud or CI Mac usually has a GUI session (Accessibility and Screen Recording +work) but no Docker, so `scripts/start-isolated-test-relay.sh` cannot start its +Compose stack. `tools/native-review/bin/setup-macos-vm` is the idempotent +one-shot for that machine: + +```bash +tools/native-review/bin/setup-macos-vm # services, relay, prefetch, prompt +. ~/.buzz-native-review/env.sh # PATH + SHERPA_ONNX_ARCHIVE_DIR +just native-review-desktop tools/native-review/desktop/composer-keyboard.yaml +``` + +It installs `postgresql@17`, `redis`, `ffmpeg` and `tmux` with Homebrew; builds a +pinned MinIO with `go install` (release binaries may be unreachable); runs +Postgres/Redis/MinIO natively on the harness ports (5471/6471/9471) under +`~/.buzz-native-review`; creates the `buzz-media` bucket with a SigV4 `curl`; +starts the isolated relay with `BUZZ_HARNESS_NATIVE_SERVICES=1`; prefetches the +`sherpa-onnx` archive (a TLS-intercepting proxy breaks that crate's rustls +downloader with `UnknownIssuer`, so the build reads `SHERPA_ONNX_ARCHIVE_DIR` +instead); and presses Allow on the one-time macOS "Local Network" prompt +through the same Accessibility-trusted driver (`bin/allow-local-network-prompt`). + +What it does not do: grant Accessibility or Screen Recording (the invoking +process needs them; `review-native doctor --require-permissions` checks), install +Homebrew, Go or Xcode, or set up iOS (CocoaPods mirrors, simulators). If your +network cannot reach pub.dev, export `PUB_HOSTED_URL` before running the setup +script and `review-ios`; the iOS runner passes it through. + +The driver moves the review window onto the main display and waits for WebKit's +accessibility tree before the first locator. A VM with a second display otherwise +opens the app there, where the web view exposes no accessibility children. +If the app cannot take focus because a first-run macOS privacy prompt is up, the +driver answers it before activating the window: it declines microphone and +camera access (a review never needs them) and allows Local Network. Other +alerts are never touched. + ## Run existing journeys ```bash diff --git a/tools/native-review/bin/allow-local-network-prompt b/tools/native-review/bin/allow-local-network-prompt new file mode 100755 index 00000000000..75a63d6027d --- /dev/null +++ b/tools/native-review/bin/allow-local-network-prompt @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Answer the one-time macOS "Local Network" prompt ("Allow to find devices +# on local networks?") that a fresh VM shows the first time any app on it touches +# the network, and which otherwise covers the reviewed window. Best effort: +# triggers the prompt with a Bonjour browse, then presses Allow through the same +# Accessibility-trusted native driver the harness uses. Exits 0 if the prompt was +# answered or never appeared; nonzero only if the driver could not run. +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +DRIVER="${BUZZ_NATIVE_REVIEW_DRIVER:-$SCRIPT_DIR/swift/.build/release/buzz-native-driver}" +if [[ ! -x "$DRIVER" ]]; then + swift build -c release --package-path "$SCRIPT_DIR/swift" >/dev/null +fi + +dns-sd -B _services._dns-sd._udp local. >/dev/null 2>&1 & +browse=$! +trap 'kill "$browse" 2>/dev/null || true' EXIT +for _ in $(seq 1 20); do + if "$DRIVER" press-system-alert-button --button Allow --contains "local network" | grep -Eq '"pressed" ?: ?true'; then + echo "[allow-local-network-prompt] pressed Allow" + exit 0 + fi + sleep 0.5 +done +echo "[allow-local-network-prompt] no Local Network prompt appeared (already answered, or not needed)" diff --git a/tools/native-review/bin/setup-macos-vm b/tools/native-review/bin/setup-macos-vm new file mode 100755 index 00000000000..d6cc1a2a1ae --- /dev/null +++ b/tools/native-review/bin/setup-macos-vm @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# One-time (idempotent) setup so `review-native run` works on a macOS VM +# (a headless cloud Mac). +# +# What that machine lacks, and what this script does about it: +# * No Docker (a VM without nested virtualization): runs the +# isolated relay's Postgres, Redis and MinIO natively on the harness ports +# (5471 / 6471 / 9471) and creates the media bucket. +# * No ffmpeg: installs it (video-share.mp4 finalization needs it). +# * A TLS-intercepting proxy that sherpa-onnx-sys's build script (rustls with +# bundled roots) rejects with `UnknownIssuer`: prefetches the archive with +# curl and exports SHERPA_ONNX_ARCHIVE_DIR. +# * pub.dev blocked (iOS/Flutter only): when PUB_HOSTED_URL is set in the +# environment running this script, it is recorded in env.sh so a later +# review-ios run receives the mirror. No mirror URL is hard-coded here. +# * A one-time macOS "Local Network" prompt for the process that launches the run: triggers it +# and clicks Allow through System Events (best effort, see README). +# +# Nothing here copies, creates or prints a secret. The Postgres/MinIO +# credentials are the public dev constants already hard-coded in +# docker-compose.harness.yml and review_native.fixture_environment. +# +# Usage: +# tools/native-review/bin/setup-macos-vm [--state-dir DIR] [--no-relay] +# [--skip-local-network] +# . "$STATE_DIR/env.sh" # then: tools/native-review/bin/review-native run ... +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" + +STATE_DIR="${BUZZ_NATIVE_REVIEW_STATE_DIR:-$HOME/.buzz-native-review}" +START_RELAY=1 +LOCAL_NETWORK=1 +while [[ $# -gt 0 ]]; do + case "$1" in + --state-dir) STATE_DIR="$2"; shift 2 ;; + --no-relay) START_RELAY=0; shift ;; + --skip-local-network) LOCAL_NETWORK=0; shift ;; + -h|--help) sed -n '2,/^set -euo/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac +done + +# Harness constants (docker-compose.harness.yml, start-isolated-test-relay.sh). +PG_PORT=5471 +REDIS_PORT=6471 +MINIO_PORT=9471 +MINIO_CONSOLE_PORT=9472 +DEV_USER=buzz_dev +DEV_SECRET=buzz_dev_secret +DB_USER=buzz +DB_PASS=buzz_dev +DB_NAME=buzz +BUCKET=buzz-media +# dl.min.io is may be unreachable from a locked-down VM; build a pinned upstream commit instead. +MINIO_REF="${MINIO_REF:-7aac2a2c5b7c}" + +log() { printf '[setup-macos-vm] %s\n' "$*"; } +die() { printf '[setup-macos-vm] ERROR: %s\n' "$*" >&2; exit 1; } + +[[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]] || die "this script is for Apple-silicon macOS" +command -v brew >/dev/null || die "Homebrew is required" +command -v go >/dev/null || die "Go is required to build MinIO (brew install go)" +mkdir -p "$STATE_DIR"/{logs,sherpa} "$HOME/.local/bin" +BREW_PREFIX="$(brew --prefix)" + +port_open() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +wait_port() { + local name="$1" port="$2" + for _ in $(seq 1 60); do port_open "$port" && return 0; sleep 1; done + die "$name did not open :$port (see $STATE_DIR/logs)" +} + +# -- 1. brew packages ------------------------------------------------------- +need=() +for formula in postgresql@17 redis ffmpeg tmux; do + brew list --formula "$formula" >/dev/null 2>&1 || need+=("$formula") +done +if ((${#need[@]})); then + log "brew install ${need[*]}" + HOMEBREW_NO_AUTO_UPDATE=1 brew install "${need[@]}" +fi +PG_BIN="$BREW_PREFIX/opt/postgresql@17/bin" +REDIS_SERVER="$BREW_PREFIX/opt/redis/bin/redis-server" +export PATH="$PG_BIN:$HOME/.local/bin:$PATH" + +# -- 2. MinIO --------------------------------------------------------------- +MINIO_BIN="$HOME/.local/bin/minio" +if [[ ! -x "$MINIO_BIN" ]]; then + log "go install github.com/minio/minio@$MINIO_REF" + GOBIN="$HOME/.local/bin" go install "github.com/minio/minio@$MINIO_REF" +fi + +# -- 3. Postgres on :5471 --------------------------------------------------- +PGDATA="$STATE_DIR/postgres" +if [[ ! -f "$PGDATA/PG_VERSION" ]]; then + log "initdb $PGDATA" + pwfile="$(mktemp)"; printf '%s\n' "$DB_PASS" > "$pwfile" + "$PG_BIN/initdb" -D "$PGDATA" -U "$DB_USER" --auth=scram-sha-256 --pwfile="$pwfile" -E UTF8 >/dev/null + rm -f "$pwfile" +fi +if ! port_open "$PG_PORT"; then + log "starting postgres on :$PG_PORT" + "$PG_BIN/pg_ctl" -D "$PGDATA" -l "$STATE_DIR/logs/postgres.log" \ + -o "-p $PG_PORT -c listen_addresses=127.0.0.1 -c unix_socket_directories=$STATE_DIR" -w start >/dev/null +fi +export PGPASSWORD="$DB_PASS" +if ! psql -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" -d postgres -qtAc \ + "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q 1; then + log "createdb $DB_NAME" + createdb -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" "$DB_NAME" +fi + +# -- 4. Redis on :6471 ------------------------------------------------------ +if ! port_open "$REDIS_PORT"; then + log "starting redis on :$REDIS_PORT" + mkdir -p "$STATE_DIR/redis" + "$REDIS_SERVER" --port "$REDIS_PORT" --bind 127.0.0.1 --dir "$STATE_DIR/redis" \ + --save "" --daemonize yes --logfile "$STATE_DIR/logs/redis.log" >/dev/null + wait_port redis "$REDIS_PORT" +fi + +# -- 5. MinIO on :9471 + bucket --------------------------------------------- +if ! port_open "$MINIO_PORT"; then + log "starting minio on :$MINIO_PORT" + mkdir -p "$STATE_DIR/minio" + MINIO_ROOT_USER="$DEV_USER" MINIO_ROOT_PASSWORD="$DEV_SECRET" \ + nohup "$MINIO_BIN" server "$STATE_DIR/minio" --address "127.0.0.1:$MINIO_PORT" \ + --console-address "127.0.0.1:$MINIO_CONSOLE_PORT" \ + > "$STATE_DIR/logs/minio.log" 2>&1 < /dev/null & + wait_port minio "$MINIO_PORT" +fi +# Create the media bucket with a SigV4-signed PUT (no `mc` needed). 200 = created, +# 409 = already ours. +empty_sha="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" +status="$(curl -s -o /dev/null -w '%{http_code}' -X PUT \ + --aws-sigv4 "aws:amz:us-east-1:s3" --user "$DEV_USER:$DEV_SECRET" \ + -H "x-amz-content-sha256: $empty_sha" "http://127.0.0.1:$MINIO_PORT/$BUCKET")" +case "$status" in 200|409) log "bucket $BUCKET ready (HTTP $status)" ;; *) die "bucket create failed (HTTP $status)" ;; esac + +# -- 6. sherpa-onnx archive (rustls cannot verify a TLS-intercepting proxy) -------- +sherpa_version="$(awk '/^name = "sherpa-onnx-sys"$/ {getline; gsub(/[^0-9.]/, "", $0); print; exit}' "$REPO_ROOT/Cargo.lock")" +[[ -n "$sherpa_version" ]] || die "could not read sherpa-onnx-sys version from Cargo.lock" +sherpa_archive="sherpa-onnx-v${sherpa_version}-osx-arm64-static-lib.tar.bz2" +if [[ ! -s "$STATE_DIR/sherpa/$sherpa_archive" ]] || ! bzip2 -t "$STATE_DIR/sherpa/$sherpa_archive" 2>/dev/null; then + log "downloading $sherpa_archive" + curl -fsSL --retry 3 -o "$STATE_DIR/sherpa/$sherpa_archive.part" \ + "https://github.com/k2-fsa/sherpa-onnx/releases/download/v${sherpa_version}/${sherpa_archive}" + bzip2 -t "$STATE_DIR/sherpa/$sherpa_archive.part" || die "sherpa archive is not valid bzip2" + mv "$STATE_DIR/sherpa/$sherpa_archive.part" "$STATE_DIR/sherpa/$sherpa_archive" +fi + +# -- 7. environment file ---------------------------------------------------- +cat > "$STATE_DIR/env.sh" <> "$STATE_DIR/env.sh" +fi + +# -- 8. isolated relay (native services, no Docker) ------------------------- +if ((START_RELAY)); then + if port_open 3030; then + log "relay already listening on :3030" + else + log "starting isolated relay (first build takes several minutes)" + # shellcheck disable=SC1091 + ( cd "$REPO_ROOT" && . bin/activate-hermit >/dev/null \ + && BUZZ_HARNESS_NATIVE_SERVICES=1 RELAY_LOG="$STATE_DIR/logs/relay.log" \ + SHERPA_ONNX_ARCHIVE_DIR="$STATE_DIR/sherpa" ./scripts/start-isolated-test-relay.sh ) + fi +fi + +# -- 9. macOS "Local Network" prompt ---------------------------------------- +if ((LOCAL_NETWORK)); then + "$SCRIPT_DIR/allow-local-network-prompt" || log "Local Network prompt not dismissed automatically; see README" +fi + +log "done. Next: . \"$STATE_DIR/env.sh\" && tools/native-review/bin/review-native doctor --require-permissions" diff --git a/tools/native-review/ios_review.py b/tools/native-review/ios_review.py index 0f2c86c1302..2d09b6b65cf 100755 --- a/tools/native-review/ios_review.py +++ b/tools/native-review/ios_review.py @@ -37,6 +37,8 @@ SUBPROCESS_ENV_ALLOWLIST = { "PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "SHELL", "USER", "LOGNAME", "TERM", "__CF_USER_TEXT_ENCODING", "DEVELOPER_DIR", + # Package-mirror override for hosts that cannot reach pub.dev directly. + "PUB_HOSTED_URL", } diff --git a/tools/native-review/review_native.py b/tools/native-review/review_native.py index 2c6f70e22b4..e3efe2b6022 100755 --- a/tools/native-review/review_native.py +++ b/tools/native-review/review_native.py @@ -329,8 +329,17 @@ def provenance() -> dict[str, Any]: } +# Host-build settings the Rust build needs on machines behind a TLS-intercepting +# proxy (sherpa-onnx-sys's build script cannot verify it and reads a prefetched +# archive instead). They reach host tooling (include_home=True) but never the +# reviewed app, and secret-shaped names are still dropped. +HOST_BUILD_PASSTHROUGH = {"SHERPA_ONNX_ARCHIVE_DIR", "SHERPA_ONNX_LIB_DIR"} + + def scrubbed_environment(*, include_home: bool = False) -> dict[str, str]: keep = {"PATH", "TMPDIR", "LANG", "LC_ALL", "SHELL", "USER", "LOGNAME", "TERM", "__CF_USER_TEXT_ENCODING"} + if include_home: + keep |= HOST_BUILD_PASSTHROUGH env = {key: value for key, value in os.environ.items() if key in keep and not SECRET_NAME.search(key)} env["HOME"] = os.environ.get("HOME", "") if include_home else "" # isolated per run unless tooling needs host caches return env @@ -434,7 +443,7 @@ def close(self) -> None: def doctor(require_permissions: bool = False) -> dict[str, Any]: checks: list[dict[str, Any]] = [] checks.append({"name": "platform", "ok": sys.platform == "darwin", "detail": sys.platform}) - for command in ("swift", "xcrun", "git"): + for command in ("swift", "xcrun", "git", "ffmpeg"): path = shutil.which(command) checks.append({"name": command, "ok": path is not None, "detail": path or "not found"}) checks.append({"name": "repository", "ok": (ROOT / "desktop/src-tauri/tauri.conf.json").is_file(), "detail": str(ROOT)}) @@ -445,7 +454,7 @@ def doctor(require_permissions: bool = False) -> dict[str, Any]: checks.extend(native.get("checks", [])) except (HarnessError, subprocess.SubprocessError, json.JSONDecodeError) as exc: checks.append({"name": "native-driver", "ok": False, "detail": str(exc)}) - hard_names = {"platform", "swift", "xcrun", "git", "repository", "native-driver-build"} + hard_names = {"platform", "swift", "xcrun", "git", "ffmpeg", "repository", "native-driver-build"} failed = [c for c in checks if not c.get("ok") and (require_permissions or c.get("name") in hard_names)] result = {"ok": not failed, "checks": checks} print(json.dumps(result, indent=2)) @@ -672,6 +681,29 @@ def wait_for_visible_window(driver: Driver, process: subprocess.Popen[str], time raise HarnessError(f"timed out after {timeout_seconds:g}s waiting for visible native window: {detail}") +def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], + timeout_seconds: float = 30) -> dict[str, Any]: + """Show the window, move it onto the main display, and wait for WebKit's AX tree. + + A fresh macOS VM can open the app on a secondary display whose WKWebView exposes + no accessibility children, so locators would never match. Placement is idempotent + (a window already on the main display is left alone). + """ + status = wait_for_visible_window(driver, process, timeout_seconds) + placement = driver.request("place_window") + deadline = time.monotonic() + timeout_seconds + while not driver.request("web_ready").get("ready"): + if process.poll() is not None: + raise HarnessError("Tauri exited while waiting for web content accessibility") + if time.monotonic() >= deadline: + raise HarnessError( + f"timed out after {timeout_seconds:g}s waiting for web content accessibility " + f"(window status: {status})") + time.sleep(0.1) + placed = driver.request("window_status") + return {**placed, "moved": bool(placement.get("moved"))} + + def locate_required(driver: Driver, locators: list[dict[str, str]], timeout_ms: int) -> dict[str, Any]: """Wait for a semantic target to materialize, then return the locator used.""" deadline = time.monotonic() + timeout_ms / 1000 @@ -792,7 +824,7 @@ def run_journey(path: pathlib.Path, relay_url: str, output_root: pathlib.Path, driver = Driver(build_driver(), app_pid, run_dir / "state" / "semantic.json") sampler = ProcessSampler(app_pid) sampler.start() - receipt["provenance"]["initial_window"] = wait_for_visible_window(driver, process) + receipt["provenance"]["initial_window"] = wait_for_interactive_window(driver, process) if journey["record"]["video"] == "window": video = run_dir / "video.mp4" driver.request("record_start", path=str(video)) diff --git a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift index 6a4ae5ec837..bc49b9bde8c 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift @@ -286,6 +286,31 @@ func windowStatus(pid: pid_t) -> [String: Any] { } } +/// Move the app's window onto the main display when it opened elsewhere (a fresh +/// VM can have a second display left of the main one, where WKWebView exposes no +/// accessibility tree). Returns whether the window moved. +func placeWindowOnMainDisplay(app: AXUIElement) throws -> Bool { + guard let window = (attribute(app, kAXWindowsAttribute) as? [AXUIElement])?.first, + let current = frameAttribute(window) else { + throw DriverError.message("no accessibility window to place") + } + let frame = CGRect(x: current.x, y: current.y, width: current.width, height: current.height) + guard let target = placementOnMainDisplay(window: frame, mainDisplay: CGDisplayBounds(CGMainDisplayID())) else { + return false + } + var size = target.size + var origin = target.origin + guard let sizeValue = AXValueCreate(.cgSize, &size), let originValue = AXValueCreate(.cgPoint, &origin) else { + throw DriverError.message("could not encode window placement") + } + // Size first so the window cannot be clamped against the display it is leaving. + guard AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, sizeValue) == .success, + AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, originValue) == .success else { + throw DriverError.message("accessibility refused to move the window; grant Accessibility to the invoking process") + } + return true +} + func captureWindow(pid: pid_t, path: String) throws { let (windowID, bounds) = try windowInfo(pid: pid) guard let image = CGWindowListCreateImage(bounds, .optionIncludingWindow, windowID, [.boundsIgnoreFraming, .bestResolution]) else { @@ -497,6 +522,8 @@ func ensureTargetFrontmost(pid: pid_t) async throws { throw DriverError.message("target app is no longer running") } if NSWorkspace.shared.frontmostApplication?.processIdentifier != pid { + // A first-run macOS privacy prompt keeps focus until answered. + _ = answerPrivacyPrompt() running.activate(options: [.activateIgnoringOtherApps]) } let deadline = ContinuousClock.now.advanced(by: .seconds(2)) @@ -550,12 +577,68 @@ func postText(_ text: String, pid: pid_t) throws { } } +/// Press `button` in a system alert whose text contains `hint` (for example the +/// one-time macOS "Local Network" prompt, which blocks input to every app until +/// answered). Scans every on-screen window owner, never the reviewed app, and +/// presses only when the hint text is present so no unrelated "Allow" is clicked. +func pressSystemAlertButton(button: String, hint: String) -> Bool { + let owners = Set(((CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []) + .compactMap { $0[kCGWindowOwnerPID as String] as? Int32 }) + for pid in owners where pid != getpid() { + let app = AXUIElementCreateApplication(pid) + for window in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] { + var queue = [window] + var texts: [String] = [] + var target: AXUIElement? + var visited = 0 + while !queue.isEmpty && visited < 500 { + let current = queue.removeFirst() + visited += 1 + if let text = elementName(current) { texts.append(text) } + if normalizedRole(elementRole(current)) == "button", let name = elementName(current), normalizedButtonTitle(name) == normalizedButtonTitle(button) { target = current } + queue.append(contentsOf: children(current)) + } + if let target, texts.joined(separator: " ").lowercased().contains(hint.lowercased()) { + return AXUIElementPerformAction(target, kAXPressAction as CFString) == .success + } + } + } + return false +} + +/// Answer a pending first-run macOS privacy prompt (see `privacyPromptButton`). +/// Returns whether a button was pressed. +func answerPrivacyPrompt() -> Bool { + let owners = Set(((CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []) + .compactMap { $0[kCGWindowOwnerPID as String] as? Int32 }) + for pid in owners where pid != getpid() { + let app = AXUIElementCreateApplication(pid) + for window in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] { + var queue = [window] + var texts: [String] = [] + var buttons: [String: AXUIElement] = [:] + var visited = 0 + while !queue.isEmpty && visited < 500 { + let current = queue.removeFirst() + visited += 1 + if let text = elementName(current) { texts.append(text) } + if normalizedRole(elementRole(current)) == "button", let name = elementName(current) { buttons[normalizedButtonTitle(name)] = current } + queue.append(contentsOf: children(current)) + } + if let name = privacyPromptButton(forAlertText: texts.joined(separator: " ")), let button = buttons[normalizedButtonTitle(name)] { + return AXUIElementPerformAction(button, kAXPressAction as CFString) == .success + } + } + } + return false +} + @main struct BuzzNativeDriver { static func main() async { do { let arguments = Array(CommandLine.arguments.dropFirst()) - guard let command = arguments.first else { throw DriverError.message("usage: buzz-native-driver doctor | serve --pid PID") } + guard let command = arguments.first else { throw DriverError.message("usage: buzz-native-driver doctor | serve --pid PID | press-system-alert-button --button NAME --contains TEXT") } if command == "doctor" { let accessibility = AXIsProcessTrusted() let screen = CGPreflightScreenCaptureAccess() @@ -567,6 +650,14 @@ struct BuzzNativeDriver { ]]) return } + if command == "press-system-alert-button" { + guard arguments.count == 5, arguments[1] == "--button", arguments[3] == "--contains" else { + throw DriverError.message("usage: buzz-native-driver press-system-alert-button --button NAME --contains TEXT") + } + guard AXIsProcessTrusted() else { throw DriverError.message("Accessibility permission is not granted") } + response(["ok": true, "pressed": pressSystemAlertButton(button: arguments[2], hint: arguments[4])]) + return + } guard command == "serve", (arguments.count == 3 || arguments.count == 5), arguments[1] == "--pid", let pid = pid_t(arguments[2]) else { throw DriverError.message("usage: buzz-native-driver serve --pid PID [--semantic-snapshot PATH]") } @@ -696,6 +787,10 @@ struct BuzzNativeDriver { } else { throw DriverError.message("unsupported action: \(type)") } } response(["ok": true]) + case "place_window": + response(["ok": true, "moved": try placeWindowOnMainDisplay(app: app)]) + case "web_ready": + response(["ok": true, "ready": semanticContentBounds(pid: pid) != nil]) case "window_status": response(windowStatus(pid: pid)) case "snapshot": diff --git a/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift b/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift index 2697e678f11..217257365e7 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift @@ -41,3 +41,36 @@ public func makeScrollEvent(deltaY: Int32, targetFrame: CGRect) -> CGEvent? { event.location = CGPoint(x: targetFrame.midX, y: targetFrame.midY) return event } + +/// Where to put a window so it sits wholly on the main display, centered, below +/// the menu bar. Returns nil when it is already there. A window larger than the +/// usable area is shrunk to fit. +public func placementOnMainDisplay(window: CGRect, mainDisplay: CGRect, menuBarHeight: CGFloat = 30) -> CGRect? { + let usable = CGRect(x: mainDisplay.minX, y: mainDisplay.minY + menuBarHeight, + width: mainDisplay.width, height: mainDisplay.height - menuBarHeight) + if usable.contains(window) { return nil } + let size = CGSize(width: min(window.width, usable.width), height: min(window.height, usable.height)) + return CGRect(x: usable.midX - size.width / 2, y: usable.midY - size.height / 2, + width: size.width, height: size.height) +} + +/// Which button to press for a first-run macOS privacy prompt, judged by its text, +/// or nil when the text is not one of the known prompts. Microphone and camera +/// access are declined (a review never needs them); the Local Network prompt is +/// allowed. Anything else is never answered. +public func privacyPromptButton(forAlertText text: String) -> String? { + let lowered = text.lowercased() + if lowered.contains("would like to access the microphone") || lowered.contains("would like to access the camera") { + return "Don't Allow" + } + if lowered.contains("find devices on local networks") || lowered.contains("local network") { + return "Allow" + } + return nil +} + +/// A button title with typographic apostrophes folded to plain ones, so +/// "Don\u{2019}t Allow" (what macOS draws) matches "Don't Allow" (what people type). +public func normalizedButtonTitle(_ title: String) -> String { + title.replacingOccurrences(of: "\u{2019}", with: "'") +} diff --git a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift index b69700a19be..1e0dfda5d71 100644 --- a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift +++ b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift @@ -31,3 +31,56 @@ import Testing #expect(event.location == CGPoint(x: 100, y: 110)) } + +@Test func windowOnSecondaryDisplayMovesToCenterOfMainDisplay() throws { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + let window = CGRect(x: -1016, y: 36, width: 1008, height: 726) + + let target = try #require(placementOnMainDisplay(window: window, mainDisplay: main)) + + #expect(target.size == window.size) + #expect(main.contains(target)) + #expect(target.midX == main.midX) +} + +@Test func windowAlreadyOnMainDisplayIsLeftAlone() { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + + #expect(placementOnMainDisplay(window: CGRect(x: 100, y: 80, width: 1008, height: 726), mainDisplay: main) == nil) +} + +@Test func windowUnderTheMenuBarOrPartlyOffscreenIsMoved() { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + + #expect(placementOnMainDisplay(window: CGRect(x: 100, y: 0, width: 800, height: 600), mainDisplay: main) != nil) + #expect(placementOnMainDisplay(window: CGRect(x: 1000, y: 100, width: 800, height: 600), mainDisplay: main) != nil) +} + +@Test func oversizedWindowIsShrunkToFitMainDisplay() throws { + let main = CGRect(x: 0, y: 0, width: 1024, height: 768) + let window = CGRect(x: -2000, y: 0, width: 1800, height: 1200) + + let target = try #require(placementOnMainDisplay(window: window, mainDisplay: main)) + + #expect(main.contains(target)) + #expect(target.width <= main.width && target.height <= main.height) +} + +@Test func microphoneAndCameraPromptsAreDeclined() { + #expect(privacyPromptButton(forAlertText: "\"bloxlet\" would like to access the Microphone. Don't Allow Allow") == "Don't Allow") + #expect(privacyPromptButton(forAlertText: "\"Terminal\" would like to access the Camera.") == "Don't Allow") +} + +@Test func localNetworkPromptIsAllowed() { + #expect(privacyPromptButton(forAlertText: "Allow \"bloxlet\" to find devices on local networks?") == "Allow") +} + +@Test func unrelatedAlertsAreNeverAnswered() { + #expect(privacyPromptButton(forAlertText: "Do you want to save changes? Allow") == nil) + #expect(privacyPromptButton(forAlertText: "") == nil) +} + +@Test func buttonTitlesCompareIgnoringTypographicApostrophes() { + #expect(normalizedButtonTitle("Don\u{2019}t Allow") == normalizedButtonTitle("Don't Allow")) + #expect(normalizedButtonTitle("Allow") != normalizedButtonTitle("Don't Allow")) +} diff --git a/tools/native-review/tests/test_ios_review.py b/tools/native-review/tests/test_ios_review.py index c08f1b438e8..8f49fb49de2 100644 --- a/tools/native-review/tests/test_ios_review.py +++ b/tools/native-review/tests/test_ios_review.py @@ -102,6 +102,13 @@ def test_flutter_environment_scrubs_host_credentials(self): for name in sentinels: self.assertNotIn(name, environment) + def test_flutter_environment_keeps_pub_mirror_but_not_credentials(self): + host = {"PUB_HOSTED_URL": "https://pub.example.org/api", "PUB_TOKEN": "secret"} + with mock.patch.dict(ios_review.os.environ, host, clear=False): + environment = ios_review.flutter_environment() + self.assertEqual(environment["PUB_HOSTED_URL"], "https://pub.example.org/api") + self.assertNotIn("PUB_TOKEN", environment) + def test_flutter_environment_carries_private_proceed_url(self): environment = ios_review.flutter_environment("http://127.0.0.1:1/proceed/token") self.assertEqual(environment["BUZZ_NATIVE_REVIEW_PROCEED_URL"], "http://127.0.0.1:1/proceed/token") diff --git a/tools/native-review/tests/test_review_native.py b/tools/native-review/tests/test_review_native.py index 720628168e1..48929e8bb38 100644 --- a/tools/native-review/tests/test_review_native.py +++ b/tools/native-review/tests/test_review_native.py @@ -502,7 +502,7 @@ def test_journey_body_interruption_runs_all_cleanup(self): mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ mock.patch.object(review_native, "Driver", return_value=driver), \ mock.patch.object(review_native, "ProcessSampler", return_value=sampler), \ - mock.patch.object(review_native, "wait_for_visible_window", return_value={"visible": True}), \ + mock.patch.object(review_native, "wait_for_interactive_window", return_value={"visible": True}), \ mock.patch.object(review_native, "capture_step", return_value={}), \ mock.patch.object(review_native, "terminate_and_reap", return_value=[]) as reap, \ mock.patch.object(review_native, "cleanup_review_state") as cleanup: @@ -549,7 +549,7 @@ def test_journey_cleanup_survives_driver_interruption(self): mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ mock.patch.object(review_native, "Driver", return_value=driver), \ mock.patch.object(review_native, "ProcessSampler", return_value=sampler), \ - mock.patch.object(review_native, "wait_for_visible_window", return_value={"visible": True}), \ + mock.patch.object(review_native, "wait_for_interactive_window", return_value={"visible": True}), \ mock.patch.object(review_native, "wait_expectation"), \ mock.patch.object(review_native, "capture_step", return_value={}), \ mock.patch.object(review_native, "terminate_and_reap", return_value=[]) as reap, \ @@ -615,6 +615,103 @@ def test_visible_window_fails_if_app_exits(self): review_native.wait_for_visible_window(driver, process, timeout_seconds=1) driver.request.assert_not_called() + def test_host_toolchain_overrides_reach_builds_but_not_the_reviewed_app(self): + overrides = {"SHERPA_ONNX_ARCHIVE_DIR": "/opt/archives", "SHERPA_ONNX_LIB_DIR": "/opt/sherpa/lib"} + with mock.patch.dict(review_native.os.environ, overrides, clear=False): + build = review_native.scrubbed_environment(include_home=True) + app = review_native.scrubbed_environment() + for name, value in overrides.items(): + self.assertEqual(build[name], value) + self.assertNotIn(name, app) + + def test_secret_shaped_toolchain_names_are_still_dropped(self): + with mock.patch.dict(review_native.os.environ, {"SHERPA_ONNX_ARCHIVE_TOKEN": "x"}, clear=False): + self.assertNotIn("SHERPA_ONNX_ARCHIVE_TOKEN", + review_native.scrubbed_environment(include_home=True)) + + def test_interactive_window_is_placed_then_waits_for_web_accessibility(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "moved": True}, + {"ok": True, "ready": False}, + {"ok": True, "ready": True}, + {"ok": True, "visible": True, "window_id": 7, "bounds": {"x": 40, "y": 60}}, + ] + with mock.patch.object(review_native.time, "sleep"): + status = review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + self.assertEqual([call.args[0] for call in driver.request.call_args_list], + ["window_status", "place_window", "web_ready", "web_ready", "window_status"]) + self.assertTrue(status["moved"]) + self.assertEqual(status["bounds"]["x"], 40) + + def test_interactive_window_reports_missing_web_accessibility(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + + def respond(command, **_): + return {"ok": True, "visible": True, "ready": False, "moved": False} + + driver.request.side_effect = respond + with mock.patch.object(review_native.time, "sleep"): + with self.assertRaisesRegex(review_native.HarnessError, "web content accessibility"): + review_native.wait_for_interactive_window(driver, process, timeout_seconds=0.05) + + def test_journey_runs_after_the_window_is_interactive(self): + journey = { + "flow": "interactive_order", + "record": {"video": "off", "screenshots": False, "accessibility": False}, + "steps": [{"name": "wait", "act": {"type": "wait", "duration_ms": 0}, + "expect": {"focused": False}}], + "cleanup": {"terminate_app": True, "remove_state": True}, + } + events = [] + process = mock.Mock(pid=42) + driver = mock.Mock() + driver.request.side_effect = lambda command, **_: events.append(command) or {"ok": True} + sampler = mock.Mock() + sampler.finish.return_value = {"sample_count": 0} + with tempfile.TemporaryDirectory() as directory: + output_root = pathlib.Path(directory) / "output" + fixture = {"secret_path": str(pathlib.Path(directory) / "identity.key")} + app_binary = pathlib.Path(directory) / "buzz-desktop" + app_binary.write_bytes(b"binary") + journey_path = pathlib.Path(directory) / "journey.yaml" + journey_path.write_text("fixture") + with mock.patch.object(review_native, "load_journey", return_value=journey), \ + mock.patch.object(review_native, "provenance", return_value={"head_sha": "a" * 40}), \ + mock.patch.object(review_native, "machine_fingerprint", return_value={}), \ + mock.patch.object(review_native, "doctor", return_value={"ok": True}), \ + mock.patch.object(review_native, "prepare_fixture", return_value=fixture), \ + mock.patch.object(review_native, "semantic_probe_server", return_value=(mock.Mock(), "probe")), \ + mock.patch.object(review_native, "build_and_launch", return_value=(process, app_binary, 42)), \ + mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ + mock.patch.object(review_native, "Driver", return_value=driver), \ + mock.patch.object(review_native, "ProcessSampler", return_value=sampler), \ + mock.patch.object(review_native, "wait_for_interactive_window", + side_effect=lambda *a, **k: events.append("interactive") or {"visible": True}), \ + mock.patch.object(review_native, "wait_expectation"), \ + mock.patch.object(review_native, "capture_step", return_value={}), \ + mock.patch.object(review_native, "terminate_and_reap", return_value=[]), \ + mock.patch.object(review_native, "cleanup_review_state"): + review_native.run_journey(journey_path, "ws://127.0.0.1:3030", output_root) + self.assertEqual(events[0], "interactive") + self.assertLess(events.index("interactive"), events.index("act")) + + def test_doctor_requires_ffmpeg_for_shareable_evidence(self): + with mock.patch.object(review_native.shutil, "which", + side_effect=lambda name: None if name == "ffmpeg" else f"/usr/bin/{name}"), \ + mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ + mock.patch.object(review_native, "run", + return_value=mock.Mock(stdout='{"checks": []}', stderr="")), \ + mock.patch("builtins.print"): + result = review_native.doctor() + self.assertFalse(result["ok"]) + self.assertIn("ffmpeg", [c["name"] for c in result["checks"] if not c["ok"]]) + class PerformanceTests(unittest.TestCase): MACHINE = {"host_id_sha256": "f" * 64, "system": "Darwin", "release": "test", "machine": "arm64", "cpu": "test"} From e5f7f8162923019ca16e1f0093f24261a4ac4e3e Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 14:09:42 -0800 Subject: [PATCH 02/11] native-review: wait for the accessibility window before placing it The compositor can report the app window before its accessibility window exists, so place_window failed with "no accessibility window to place" on a fresh VM. Retry that one error until the window appears or the wait times out; every other placement error still fails the run at once. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jude Edwards --- tools/native-review/review_native.py | 14 ++++++++- .../native-review/tests/test_review_native.py | 31 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/tools/native-review/review_native.py b/tools/native-review/review_native.py index e3efe2b6022..1ad2c4e088b 100755 --- a/tools/native-review/review_native.py +++ b/tools/native-review/review_native.py @@ -690,8 +690,20 @@ def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], (a window already on the main display is left alone). """ status = wait_for_visible_window(driver, process, timeout_seconds) - placement = driver.request("place_window") deadline = time.monotonic() + timeout_seconds + while True: + # The accessibility window can lag the compositor's by a moment. + try: + placement = driver.request("place_window") + break + except HarnessError as error: + if "no accessibility window" not in str(error): + raise + if process.poll() is not None: + raise HarnessError("Tauri exited while waiting for its accessibility window") from error + if time.monotonic() >= deadline: + raise + time.sleep(0.1) while not driver.request("web_ready").get("ready"): if process.poll() is not None: raise HarnessError("Tauri exited while waiting for web content accessibility") diff --git a/tools/native-review/tests/test_review_native.py b/tools/native-review/tests/test_review_native.py index 48929e8bb38..b0e3cfee6fc 100644 --- a/tools/native-review/tests/test_review_native.py +++ b/tools/native-review/tests/test_review_native.py @@ -647,6 +647,37 @@ def test_interactive_window_is_placed_then_waits_for_web_accessibility(self): self.assertTrue(status["moved"]) self.assertEqual(status["bounds"]["x"], 40) + def test_interactive_window_waits_for_the_accessibility_window_to_exist(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + review_native.HarnessError("no accessibility window to place"), + review_native.HarnessError("no accessibility window to place"), + {"ok": True, "moved": False}, + {"ok": True, "ready": True}, + {"ok": True, "visible": True, "window_id": 7, "bounds": {"x": 40, "y": 60}}, + ] + with mock.patch.object(review_native.time, "sleep"): + status = review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + self.assertEqual([call.args[0] for call in driver.request.call_args_list], + ["window_status", "place_window", "place_window", "place_window", + "web_ready", "window_status"]) + self.assertFalse(status["moved"]) + + def test_interactive_window_does_not_hide_other_placement_errors(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + review_native.HarnessError("Accessibility permission is not granted"), + ] + with mock.patch.object(review_native.time, "sleep"): + with self.assertRaisesRegex(review_native.HarnessError, "Accessibility permission"): + review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + def test_interactive_window_reports_missing_web_accessibility(self): driver = mock.Mock() process = mock.Mock() From eb8a3c6af4d281f958bfb051ee878b04d01d29f6 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 14:20:51 -0800 Subject: [PATCH 03/11] native-review: let the page's beacon authenticate to the semantic probe The reviewed page publishes its semantic snapshot with navigator.sendBeacon, which cannot set request headers, but the probe server only accepted a token in an X-Buzz-Native-Review-Token header and never told the page the token. Every beacon got a 401, the harness saw no semantic nodes, and any step that located or asserted by id failed even though the UI had rendered. Put the ephemeral token in the probe URL's query (compared in constant time). The header is still accepted. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jude Edwards --- tools/native-review/review_native.py | 14 +++-- .../native-review/tests/test_review_native.py | 53 +++++++++++++++++++ 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/tools/native-review/review_native.py b/tools/native-review/review_native.py index 1ad2c4e088b..57669bc9ef1 100755 --- a/tools/native-review/review_native.py +++ b/tools/native-review/review_native.py @@ -6,6 +6,7 @@ import dataclasses import datetime as dt import hashlib +import hmac import http.server import json import math @@ -549,8 +550,14 @@ def do_OPTIONS(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API self.end_headers() def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API - if self.path != "/snapshot" or self.headers.get("X-Buzz-Native-Review-Token") != token: - self.send_response(404 if self.path != "/snapshot" else 401) + target = urllib.parse.urlsplit(self.path) + # The page publishes with navigator.sendBeacon, which cannot set request + # headers, so the token travels in the probe URL's query; the header is + # still accepted for other clients. + supplied = (urllib.parse.parse_qs(target.query).get("token") or + [self.headers.get("X-Buzz-Native-Review-Token") or ""])[0] + if target.path != "/snapshot" or not hmac.compare_digest(supplied.encode(), token.encode()): + self.send_response(404 if target.path != "/snapshot" else 401) self.end_headers() return raw_length = self.headers.get("Content-Length") @@ -581,7 +588,8 @@ def log_message(self, _format: str, *_args: Any) -> None: server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) server.daemon_threads = True threading.Thread(target=server.serve_forever, daemon=True).start() - return server, f"http://127.0.0.1:{server.server_port}/snapshot" + query = urllib.parse.urlencode({"token": token}) + return server, f"http://127.0.0.1:{server.server_port}/snapshot?{query}" def build_native_review_app(isolation: dict[str, str]) -> pathlib.Path: diff --git a/tools/native-review/tests/test_review_native.py b/tools/native-review/tests/test_review_native.py index b0e3cfee6fc..f37f120bb78 100644 --- a/tools/native-review/tests/test_review_native.py +++ b/tools/native-review/tests/test_review_native.py @@ -5,6 +5,8 @@ import re import tempfile import unittest +import urllib.error +import urllib.request from unittest import mock MODULE_PATH = pathlib.Path(__file__).parents[1] / "review_native.py" @@ -744,6 +746,57 @@ def test_doctor_requires_ffmpeg_for_shareable_evidence(self): self.assertIn("ffmpeg", [c["name"] for c in result["checks"] if not c["ok"]]) +class SemanticProbeServerTests(unittest.TestCase): + NODE = {"id": "message-composer", "role": "textbox", "name": "Message", "value": "", + "scrollY": 0, "enabled": True, "focused": False, + "frame": {"x": 1, "y": 2, "width": 3, "height": 4}, + "viewport": {"width": 100, "height": 100}} + + def post(self, url, body=None, headers=None): + # navigator.sendBeacon sends a plain POST and cannot add request headers. + request = urllib.request.Request( + url, data=json.dumps(body if body is not None else [self.NODE]).encode(), + headers={"Content-Type": "text/plain;charset=UTF-8", **(headers or {})}, method="POST") + try: + with urllib.request.urlopen(request, timeout=5) as response: + return response.status + except urllib.error.HTTPError as error: + error.close() + return error.code + + def serve(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + path = pathlib.Path(directory.name) / "semantic.json" + server, url = review_native.semantic_probe_server(path, "s3cret-token") + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + return path, url + + def test_probe_url_carries_the_token_so_a_beacon_is_accepted(self): + path, url = self.serve() + self.assertIn("token=s3cret-token", url) + self.assertEqual(self.post(url), 204) + self.assertEqual(json.loads(path.read_text())[0]["id"], "message-composer") + + def test_beacon_without_or_with_the_wrong_token_is_rejected(self): + path, url = self.serve() + base = url.split("?")[0] + self.assertEqual(self.post(base), 401) + self.assertEqual(self.post(base + "?token=nope"), 401) + self.assertFalse(path.exists()) + + def test_header_token_is_still_accepted(self): + path, url = self.serve() + base = url.split("?")[0] + self.assertEqual(self.post(base, headers={"X-Buzz-Native-Review-Token": "s3cret-token"}), 204) + self.assertTrue(path.exists()) + + def test_unknown_path_is_not_found(self): + _, url = self.serve() + self.assertEqual(self.post(url.replace("/snapshot", "/other")), 404) + + class PerformanceTests(unittest.TestCase): MACHINE = {"host_id_sha256": "f" * 64, "system": "Darwin", "release": "test", "machine": "arm64", "cpu": "test"} From 1221954ab61dc0b2953f7adba43145c33f33b6ff Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 14:26:06 -0800 Subject: [PATCH 04/11] native-review: clip semantic probe frames to the viewport The harness validates a semantic snapshot as a whole and rejects it if any node leaves the viewport. A single visually hidden 1px element at -1px (the sidebar has one) made every snapshot after the loading screen fail with a 400, so the harness kept seeing the stale loading gate and never reached the seeded channel. Clip each node's frame to the viewport and skip nodes with no visible part. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jude Edwards --- .../nativeReviewSemanticProbe.test.mjs | 33 ++++++++++++++++ .../src/testing/nativeReviewSemanticProbe.ts | 38 ++++++++++++++----- 2 files changed, 61 insertions(+), 10 deletions(-) create mode 100644 desktop/src/testing/nativeReviewSemanticProbe.test.mjs diff --git a/desktop/src/testing/nativeReviewSemanticProbe.test.mjs b/desktop/src/testing/nativeReviewSemanticProbe.test.mjs new file mode 100644 index 00000000000..ebcd22c1da0 --- /dev/null +++ b/desktop/src/testing/nativeReviewSemanticProbe.test.mjs @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { clipFrameToViewport } from "./nativeReviewSemanticProbe.ts"; + +const viewport = { width: 1440, height: 792 }; + +test("a frame wholly inside the viewport is unchanged", () => { + const frame = { x: 11, y: 297, width: 260, height: 32 }; + assert.deepEqual(clipFrameToViewport(frame, viewport), frame); +}); + +test("a frame that overflows the viewport is clipped to its visible part", () => { + assert.deepEqual( + clipFrameToViewport({ x: 1400, y: 700, width: 100, height: 200 }, viewport), + { x: 1400, y: 700, width: 40, height: 92 }, + ); + assert.deepEqual( + clipFrameToViewport({ x: -20, y: -10, width: 100, height: 50 }, viewport), + { x: 0, y: 0, width: 80, height: 40 }, + ); +}); + +test("a frame wholly outside the viewport has no visible part", () => { + // The visually hidden 1px elements UI libraries park at -1px. + assert.equal( + clipFrameToViewport({ x: -1, y: -1, width: 1, height: 1 }, viewport), + undefined, + ); + assert.equal( + clipFrameToViewport({ x: 0, y: 800, width: 10, height: 10 }, viewport), + undefined, + ); +}); diff --git a/desktop/src/testing/nativeReviewSemanticProbe.ts b/desktop/src/testing/nativeReviewSemanticProbe.ts index c264898fea7..665c5c4456b 100644 --- a/desktop/src/testing/nativeReviewSemanticProbe.ts +++ b/desktop/src/testing/nativeReviewSemanticProbe.ts @@ -35,6 +35,26 @@ function accessibleName(element: HTMLElement): string | undefined { ); } +type Frame = SemanticNode["frame"]; + +/** + * The part of `frame` inside the viewport, or undefined when none of it is + * visible. The harness rejects a whole snapshot if any node leaves the + * viewport, so a visually hidden 1px element at -1px, or a list that overflows + * the window, must be clipped or skipped here rather than poison every update. + */ +export function clipFrameToViewport( + frame: Frame, + viewport: { width: number; height: number }, +): Frame | undefined { + const left = Math.max(frame.x, 0); + const top = Math.max(frame.y, 0); + const right = Math.min(frame.x + frame.width, viewport.width); + const bottom = Math.min(frame.y + frame.height, viewport.height); + if (right <= left || bottom <= top) return undefined; + return { x: left, y: top, width: right - left, height: bottom - top }; +} + function snapshot(): SemanticNode[] { const nodes: SemanticNode[] = []; for (const candidate of document.querySelectorAll( @@ -62,6 +82,12 @@ function snapshot(): SemanticNode[] { ? candidate.innerText.replace(/\r\n?/g, "\n").replace(/\n$/, "") : undefined; if (!id && !role && !name) continue; + const viewport = { width: window.innerWidth, height: window.innerHeight }; + const frame = clipFrameToViewport( + { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, + viewport, + ); + if (!frame) continue; nodes.push({ ...(id ? { id } : {}), ...(role ? { role } : {}), @@ -72,16 +98,8 @@ function snapshot(): SemanticNode[] { !candidate.hasAttribute("disabled") && candidate.getAttribute("aria-disabled") !== "true", focused: candidate === document.activeElement, - frame: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - viewport: { - width: window.innerWidth, - height: window.innerHeight, - }, + frame, + viewport, }); } return nodes; From b2502947cdd0ebd09b0da0a71393bbaec990f008 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 14:30:21 -0800 Subject: [PATCH 05/11] native-review: answer first-run privacy prompts while the app starts On a fresh macOS VM the reviewed app triggers a microphone prompt at launch that freezes its web view until someone answers it, so the window stayed blank and the run timed out waiting for web content accessibility. Ask the driver to answer a pending privacy prompt (decline microphone/camera, allow Local Network) on every poll while the window comes up, and bound the web_ready accessibility query so a frozen app cannot stall the driver. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jude Edwards --- tools/native-review/review_native.py | 7 ++++++- .../swift/Sources/BuzzNativeDriver/main.swift | 14 +++++++++----- tools/native-review/tests/test_review_native.py | 17 ++++++++++++++--- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/tools/native-review/review_native.py b/tools/native-review/review_native.py index 57669bc9ef1..e5694fff7c1 100755 --- a/tools/native-review/review_native.py +++ b/tools/native-review/review_native.py @@ -700,6 +700,8 @@ def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], status = wait_for_visible_window(driver, process, timeout_seconds) deadline = time.monotonic() + timeout_seconds while True: + # A first-run macOS privacy prompt freezes the web view until answered. + driver.request("answer_privacy_prompt") # The accessibility window can lag the compositor's by a moment. try: placement = driver.request("place_window") @@ -712,7 +714,10 @@ def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], if time.monotonic() >= deadline: raise time.sleep(0.1) - while not driver.request("web_ready").get("ready"): + while True: + driver.request("answer_privacy_prompt") + if driver.request("web_ready").get("ready"): + break if process.poll() is not None: raise HarnessError("Tauri exited while waiting for web content accessibility") if time.monotonic() >= deadline: diff --git a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift index bc49b9bde8c..db6cd0c6463 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift @@ -192,8 +192,10 @@ func describe(_ element: AXUIElement, locator: Locator) -> ElementDescription { focused: boolAttribute(element, kAXFocusedAttribute), frame: frameAttribute(element)) } -func semanticContentBounds(pid: pid_t) -> CGRect? { +func semanticContentBounds(pid: pid_t, messagingTimeout: Float? = nil) -> CGRect? { let app = AXUIElementCreateApplication(pid) + // An app frozen behind a privacy prompt would otherwise stall every query. + if let messagingTimeout { AXUIElementSetMessagingTimeout(app, messagingTimeout) } enableWebViewAccessibility(app) let webArea = find(accessibilityRoots(app: app, pid: pid), locator: Locator(id: nil, role: "web-area", name: nil)) guard let frame = webArea.flatMap(frameAttribute) else { return nil } @@ -523,7 +525,7 @@ func ensureTargetFrontmost(pid: pid_t) async throws { } if NSWorkspace.shared.frontmostApplication?.processIdentifier != pid { // A first-run macOS privacy prompt keeps focus until answered. - _ = answerPrivacyPrompt() + _ = answerPrivacyPrompt(excluding: pid) running.activate(options: [.activateIgnoringOtherApps]) } let deadline = ContinuousClock.now.advanced(by: .seconds(2)) @@ -608,10 +610,10 @@ func pressSystemAlertButton(button: String, hint: String) -> Bool { /// Answer a pending first-run macOS privacy prompt (see `privacyPromptButton`). /// Returns whether a button was pressed. -func answerPrivacyPrompt() -> Bool { +func answerPrivacyPrompt(excluding target: pid_t? = nil) -> Bool { let owners = Set(((CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []) .compactMap { $0[kCGWindowOwnerPID as String] as? Int32 }) - for pid in owners where pid != getpid() { + for pid in owners where pid != getpid() && pid != target { let app = AXUIElementCreateApplication(pid) for window in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] { var queue = [window] @@ -789,8 +791,10 @@ struct BuzzNativeDriver { response(["ok": true]) case "place_window": response(["ok": true, "moved": try placeWindowOnMainDisplay(app: app)]) + case "answer_privacy_prompt": + response(["ok": true, "answered": answerPrivacyPrompt(excluding: pid)]) case "web_ready": - response(["ok": true, "ready": semanticContentBounds(pid: pid) != nil]) + response(["ok": true, "ready": semanticContentBounds(pid: pid, messagingTimeout: 1.5) != nil]) case "window_status": response(windowStatus(pid: pid)) case "snapshot": diff --git a/tools/native-review/tests/test_review_native.py b/tools/native-review/tests/test_review_native.py index f37f120bb78..a1424ebd139 100644 --- a/tools/native-review/tests/test_review_native.py +++ b/tools/native-review/tests/test_review_native.py @@ -637,15 +637,20 @@ def test_interactive_window_is_placed_then_waits_for_web_accessibility(self): process.poll.return_value = None driver.request.side_effect = [ {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, {"ok": True, "moved": True}, + {"ok": True, "answered": False}, {"ok": True, "ready": False}, + {"ok": True, "answered": True}, {"ok": True, "ready": True}, {"ok": True, "visible": True, "window_id": 7, "bounds": {"x": 40, "y": 60}}, ] with mock.patch.object(review_native.time, "sleep"): status = review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) self.assertEqual([call.args[0] for call in driver.request.call_args_list], - ["window_status", "place_window", "web_ready", "web_ready", "window_status"]) + ["window_status", "answer_privacy_prompt", "place_window", + "answer_privacy_prompt", "web_ready", + "answer_privacy_prompt", "web_ready", "window_status"]) self.assertTrue(status["moved"]) self.assertEqual(status["bounds"]["x"], 40) @@ -655,17 +660,22 @@ def test_interactive_window_waits_for_the_accessibility_window_to_exist(self): process.poll.return_value = None driver.request.side_effect = [ {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, review_native.HarnessError("no accessibility window to place"), + {"ok": True, "answered": False}, review_native.HarnessError("no accessibility window to place"), + {"ok": True, "answered": False}, {"ok": True, "moved": False}, + {"ok": True, "answered": False}, {"ok": True, "ready": True}, {"ok": True, "visible": True, "window_id": 7, "bounds": {"x": 40, "y": 60}}, ] with mock.patch.object(review_native.time, "sleep"): status = review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) self.assertEqual([call.args[0] for call in driver.request.call_args_list], - ["window_status", "place_window", "place_window", "place_window", - "web_ready", "window_status"]) + ["window_status", "answer_privacy_prompt", "place_window", + "answer_privacy_prompt", "place_window", "answer_privacy_prompt", + "place_window", "answer_privacy_prompt", "web_ready", "window_status"]) self.assertFalse(status["moved"]) def test_interactive_window_does_not_hide_other_placement_errors(self): @@ -674,6 +684,7 @@ def test_interactive_window_does_not_hide_other_placement_errors(self): process.poll.return_value = None driver.request.side_effect = [ {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, review_native.HarnessError("Accessibility permission is not granted"), ] with mock.patch.object(review_native.time, "sleep"): From d90ef40d93399ef787b43ca8d84600714b4636f4 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 14:33:31 -0800 Subject: [PATCH 06/11] native-review: pre-answer the microphone prompt in the VM setup script The reviewed app asks for the microphone at launch; on a fresh VM the prompt freezes its web view until answered, and a driver blocked on that frozen view cannot answer it in time. Have setup trigger the prompt with a one-second ffmpeg capture and decline it once, next to the Local Network prompt. The script is renamed answer-first-run-prompts and the flag is now --skip-prompts. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jude Edwards --- tools/native-review/README.md | 6 ++- .../bin/allow-local-network-prompt | 26 ---------- .../bin/answer-first-run-prompts | 49 +++++++++++++++++++ tools/native-review/bin/setup-macos-vm | 17 ++++--- 4 files changed, 62 insertions(+), 36 deletions(-) delete mode 100755 tools/native-review/bin/allow-local-network-prompt create mode 100755 tools/native-review/bin/answer-first-run-prompts diff --git a/tools/native-review/README.md b/tools/native-review/README.md index fd44567348f..53bb263881a 100644 --- a/tools/native-review/README.md +++ b/tools/native-review/README.md @@ -85,8 +85,10 @@ Postgres/Redis/MinIO natively on the harness ports (5471/6471/9471) under starts the isolated relay with `BUZZ_HARNESS_NATIVE_SERVICES=1`; prefetches the `sherpa-onnx` archive (a TLS-intercepting proxy breaks that crate's rustls downloader with `UnknownIssuer`, so the build reads `SHERPA_ONNX_ARCHIVE_DIR` -instead); and presses Allow on the one-time macOS "Local Network" prompt -through the same Accessibility-trusted driver (`bin/allow-local-network-prompt`). +instead); and answers the one-time macOS "Local Network" (Allow) and "Microphone" +(Don't Allow) prompts through the same Accessibility-trusted driver +(`bin/answer-first-run-prompts`). Unanswered, the microphone prompt freezes the +app's web view. What it does not do: grant Accessibility or Screen Recording (the invoking process needs them; `review-native doctor --require-permissions` checks), install diff --git a/tools/native-review/bin/allow-local-network-prompt b/tools/native-review/bin/allow-local-network-prompt deleted file mode 100755 index 75a63d6027d..00000000000 --- a/tools/native-review/bin/allow-local-network-prompt +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -# Answer the one-time macOS "Local Network" prompt ("Allow to find devices -# on local networks?") that a fresh VM shows the first time any app on it touches -# the network, and which otherwise covers the reviewed window. Best effort: -# triggers the prompt with a Bonjour browse, then presses Allow through the same -# Accessibility-trusted native driver the harness uses. Exits 0 if the prompt was -# answered or never appeared; nonzero only if the driver could not run. -set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" -DRIVER="${BUZZ_NATIVE_REVIEW_DRIVER:-$SCRIPT_DIR/swift/.build/release/buzz-native-driver}" -if [[ ! -x "$DRIVER" ]]; then - swift build -c release --package-path "$SCRIPT_DIR/swift" >/dev/null -fi - -dns-sd -B _services._dns-sd._udp local. >/dev/null 2>&1 & -browse=$! -trap 'kill "$browse" 2>/dev/null || true' EXIT -for _ in $(seq 1 20); do - if "$DRIVER" press-system-alert-button --button Allow --contains "local network" | grep -Eq '"pressed" ?: ?true'; then - echo "[allow-local-network-prompt] pressed Allow" - exit 0 - fi - sleep 0.5 -done -echo "[allow-local-network-prompt] no Local Network prompt appeared (already answered, or not needed)" diff --git a/tools/native-review/bin/answer-first-run-prompts b/tools/native-review/bin/answer-first-run-prompts new file mode 100755 index 00000000000..80eae6d5535 --- /dev/null +++ b/tools/native-review/bin/answer-first-run-prompts @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Answer the one-time macOS privacy prompts a fresh VM shows the first time the +# process that launches a review touches the local network or the microphone. +# Left unanswered they freeze the reviewed app's web view or steal focus from it. +# Best effort: each prompt is triggered by a tiny child process (a Bonjour browse, +# a one-second audio capture) and answered through the same Accessibility-trusted +# driver the harness uses. The answers are remembered per launching process, so +# this only has to succeed once. Exits 0 when a prompt was answered or never +# appeared; nonzero only if the driver could not run. +# +# Local Network -> Allow +# Microphone -> Don't Allow (a review never records audio) +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DRIVER="${BUZZ_NATIVE_REVIEW_DRIVER:-$SCRIPT_DIR/swift/.build/release/buzz-native-driver}" +if [[ ! -x "$DRIVER" ]]; then + swift build -c release --package-path "$SCRIPT_DIR/swift" >/dev/null +fi + +# answer LABEL BUTTON HINT COMMAND... +answer() { + local label="$1" button="$2" hint="$3" + shift 3 + "$@" >/dev/null 2>&1 & + local trigger=$! + local pressed=0 + for _ in $(seq 1 20); do + if "$DRIVER" press-system-alert-button --button "$button" --contains "$hint" | grep -Eq '"pressed" ?: ?true'; then + pressed=1 + break + fi + sleep 0.5 + done + kill "$trigger" 2>/dev/null || true + wait "$trigger" 2>/dev/null || true + if ((pressed)); then + echo "[answer-first-run-prompts] $label: pressed $button" + else + echo "[answer-first-run-prompts] $label: no prompt appeared (already answered, or not needed)" + fi +} + +answer "Local Network" "Allow" "local network" dns-sd -B _services._dns-sd._udp local. +if command -v ffmpeg >/dev/null 2>&1; then + answer "Microphone" "Don't Allow" "microphone" \ + ffmpeg -hide_banner -loglevel error -f avfoundation -i ":0" -t 1 -f null - +else + echo "[answer-first-run-prompts] Microphone: ffmpeg not installed, skipping" +fi diff --git a/tools/native-review/bin/setup-macos-vm b/tools/native-review/bin/setup-macos-vm index d6cc1a2a1ae..f5782772d2f 100755 --- a/tools/native-review/bin/setup-macos-vm +++ b/tools/native-review/bin/setup-macos-vm @@ -13,8 +13,9 @@ # * pub.dev blocked (iOS/Flutter only): when PUB_HOSTED_URL is set in the # environment running this script, it is recorded in env.sh so a later # review-ios run receives the mirror. No mirror URL is hard-coded here. -# * A one-time macOS "Local Network" prompt for the process that launches the run: triggers it -# and clicks Allow through System Events (best effort, see README). +# * One-time macOS "Local Network" and "Microphone" prompts for the process that launches +# the run: triggers each and answers it through the Accessibility-trusted native driver +# (best effort, see README). # # Nothing here copies, creates or prints a secret. The Postgres/MinIO # credentials are the public dev constants already hard-coded in @@ -22,7 +23,7 @@ # # Usage: # tools/native-review/bin/setup-macos-vm [--state-dir DIR] [--no-relay] -# [--skip-local-network] +# [--skip-prompts] # . "$STATE_DIR/env.sh" # then: tools/native-review/bin/review-native run ... set -euo pipefail @@ -31,12 +32,12 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" STATE_DIR="${BUZZ_NATIVE_REVIEW_STATE_DIR:-$HOME/.buzz-native-review}" START_RELAY=1 -LOCAL_NETWORK=1 +ANSWER_PROMPTS=1 while [[ $# -gt 0 ]]; do case "$1" in --state-dir) STATE_DIR="$2"; shift 2 ;; --no-relay) START_RELAY=0; shift ;; - --skip-local-network) LOCAL_NETWORK=0; shift ;; + --skip-prompts) ANSWER_PROMPTS=0; shift ;; -h|--help) sed -n '2,/^set -euo/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "unknown option: $1" >&2; exit 2 ;; esac @@ -174,9 +175,9 @@ if ((START_RELAY)); then fi fi -# -- 9. macOS "Local Network" prompt ---------------------------------------- -if ((LOCAL_NETWORK)); then - "$SCRIPT_DIR/allow-local-network-prompt" || log "Local Network prompt not dismissed automatically; see README" +# -- 9. macOS first-run privacy prompts -------------------------------------- +if ((ANSWER_PROMPTS)); then + "$SCRIPT_DIR/answer-first-run-prompts" || log "first-run prompts not answered automatically; see README" fi log "done. Next: . \"$STATE_DIR/env.sh\" && tools/native-review/bin/review-native doctor --require-permissions" From ba90e33d62e3d9b9d112168ba3ea76a678c4b5ca Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 15:56:50 -0800 Subject: [PATCH 07/11] fix(native-review): identify prompts, own services, verify window placement Review follow-ups for the headless macOS VM path. Prompt auto-answer: replace the substring match with answer-privacy-prompt. It acts only on a window owned by the macOS system prompt agent, that is a system alert (not a sheet or document window), whose text names the prompt kind and an app that is one of this run's own processes, with exactly one matching button. Anything else is left alone and the reason is logged. Setup script: refuse to run outside a VM unless --allow-non-vm; mark the state dir and the database as the harness's own; identify each service by pidfile and refuse to reuse an open port that is not ours. The relay script runs check-harness-database (data directory, marker file, database marker) before DROP SCHEMA in native-services mode. Window placement: move the accessibility window that matches the window the harness reports, read the frame back, fail the run if it is not wholly on the main display, and record before/after in the receipt. Also fix the stale relay-script comment and teardown message, and a typo. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jude Edwards --- scripts/start-isolated-test-relay.sh | 27 ++- tools/native-review/README.md | 31 ++- .../bin/answer-first-run-prompts | 26 ++- .../native-review/bin/check-harness-database | 45 ++++ tools/native-review/bin/setup-macos-vm | 58 ++++- tools/native-review/review_native.py | 6 +- .../swift/Sources/BuzzNativeDriver/main.swift | 219 ++++++++++++------ .../DriverSupport.swift | 119 +++++++++- .../DriverSupportTests.swift | 96 +++++++- .../tests/test_harness_guards.py | 178 ++++++++++++++ .../native-review/tests/test_review_native.py | 23 +- 11 files changed, 718 insertions(+), 110 deletions(-) create mode 100755 tools/native-review/bin/check-harness-database create mode 100644 tools/native-review/tests/test_harness_guards.py diff --git a/scripts/start-isolated-test-relay.sh b/scripts/start-isolated-test-relay.sh index 7febc390ecd..8d7a3b1ec5f 100755 --- a/scripts/start-isolated-test-relay.sh +++ b/scripts/start-isolated-test-relay.sh @@ -24,8 +24,9 @@ # docker compose -p buzz-harness -f docker-compose.harness.yml down -v # # Hosts without Docker (e.g. a managed macOS VM): set BUZZ_HARNESS_NATIVE_SERVICES=1 -# after starting Postgres/Redis/MinIO yourself on the ports above and creating the -# media bucket; tools/native-review/bin/setup-macos-vm does all of that. +# and BUZZ_HARNESS_STATE_DIR after Postgres/Redis/MinIO were started on the ports above +# by tools/native-review/bin/setup-macos-vm, which also creates the media bucket and +# marks the state dir and database so the schema reset below can be checked. # ============================================================================= set -euo pipefail @@ -109,9 +110,19 @@ psql_h() { } log "Resetting isolated database and applying schema..." -# This database belongs only to the buzz-harness Compose project. Reset it on -# every launch so stale partitions/events from an earlier proof cannot alter -# schema planning or test results. +# This database is the harness's own: the buzz-harness Compose project's, or, with +# BUZZ_HARNESS_NATIVE_SERVICES=1, the Postgres that setup-macos-vm started. Reset it +# on every launch so stale partitions/events from an earlier proof cannot alter +# schema planning or test results. Natively run, the port is not ours by +# construction, so refuse to drop anything unless the server is demonstrably the +# harness's (its data directory, a marker file and a marker on the database). +if [[ "${NATIVE_SERVICES}" == "1" ]]; then + [[ -n "${BUZZ_HARNESS_STATE_DIR:-}" ]] \ + || { err "BUZZ_HARNESS_NATIVE_SERVICES=1 needs BUZZ_HARNESS_STATE_DIR (set by setup-macos-vm); refusing to reset a database."; exit 1; } + "${REPO_ROOT}/tools/native-review/bin/check-harness-database" \ + --state-dir "${BUZZ_HARNESS_STATE_DIR}" --port "${PG_PORT}" --db buzz --user buzz \ + || { err "Postgres on :${PG_PORT} is not the harness database; refusing to reset it."; exit 1; } +fi psql_h -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" export PGSCHEMA_PLAN_HOST=localhost PGSCHEMA_PLAN_PORT=${PG_PORT} export PGSCHEMA_PLAN_DB=buzz PGSCHEMA_PLAN_USER=buzz PGSCHEMA_PLAN_PASSWORD=buzz_dev @@ -183,7 +194,11 @@ for _ in $(seq 1 30); do ok "Relay live — BUZZ_E2E_RELAY_URL=http://localhost:${RELAY_MAIN}" ok "Logs: ${RELAY_LOG} Attach: tmux attach -t ${TMUX_SESSION}" ok "Stop relay: tmux kill-session -t ${TMUX_SESSION}" - ok "Full teardown: docker compose -p ${PROJECT} -f ${COMPOSE_FILE} down -v" + if [[ "${NATIVE_SERVICES}" == "1" ]]; then + ok "Backing services run natively under ${BUZZ_HARNESS_STATE_DIR} (stop them with pg_ctl, redis-cli shutdown and the pid in minio.pid)" + else + ok "Full teardown: docker compose -p ${PROJECT} -f ${COMPOSE_FILE} down -v" + fi exit 0 fi sleep 1 diff --git a/tools/native-review/README.md b/tools/native-review/README.md index 53bb263881a..04d7c3cabf7 100644 --- a/tools/native-review/README.md +++ b/tools/native-review/README.md @@ -97,12 +97,33 @@ network cannot reach pub.dev, export `PUB_HOSTED_URL` before running the setup script and `review-ios`; the iOS runner passes it through. The driver moves the review window onto the main display and waits for WebKit's -accessibility tree before the first locator. A VM with a second display otherwise -opens the app there, where the web view exposes no accessibility children. +accessibility tree before the first locator. It moves the same window the harness +reports (matched by frame, never "the first window"), reads the frame back, fails +the run if the window is not wholly on the main display, and records the +before/after frames in the receipt (`provenance.initial_window.placement`). A VM +with a second display otherwise opens the app there, where the web view exposes no +accessibility children. + If the app cannot take focus because a first-run macOS privacy prompt is up, the -driver answers it before activating the window: it declines microphone and -camera access (a review never needs them) and allows Local Network. Other -alerts are never touched. +driver (`answer-privacy-prompt`) answers it, but only when it can positively +identify the prompt, and otherwise leaves it alone and says why. All of these must +hold: the window belongs to the macOS system prompt agent (bundle id +`com.apple.UserNotificationCenter`, executable under `/System/Library/CoreServices`); +it is a system alert (`AXWindow`/`AXSystemDialog`, not a sheet or a document +window); its text parses as a microphone, camera or Local Network prompt; the app +it names is one of this run's own processes (the driver's ancestry, the app under +review, or a trigger child passed with `--expect`); and exactly one button carries +the expected title. It declines microphone and camera access (a review never needs +them) and allows Local Network. A prompt from any other app, a sheet, or an alert +from another process is never touched. + +`setup-macos-vm` refuses to run outside a virtual machine +(`kern.hv_vmm_present` must be 1) unless `--allow-non-vm` is passed. It marks its +state directory and database as the harness's own, uses a pidfile for each service +it starts, and refuses to reuse a port that is open but not its own. The relay +script refuses to run `DROP SCHEMA` in native-services mode unless +`bin/check-harness-database` confirms the server runs from the harness data +directory and the database carries the harness marker. ## Run existing journeys diff --git a/tools/native-review/bin/answer-first-run-prompts b/tools/native-review/bin/answer-first-run-prompts index 80eae6d5535..65b7d3f87a2 100755 --- a/tools/native-review/bin/answer-first-run-prompts +++ b/tools/native-review/bin/answer-first-run-prompts @@ -8,6 +8,11 @@ # this only has to succeed once. Exits 0 when a prompt was answered or never # appeared; nonzero only if the driver could not run. # +# The driver presses a button only when it can positively identify the window as +# the system's own privacy alert (owned by the system prompt agent, a system +# dialog) that names a process of this run: this script's ancestry, the reviewed +# app, or the trigger it launched here. Anything else is left alone and logged. +# # Local Network -> Allow # Microphone -> Don't Allow (a review never records audio) set -euo pipefail @@ -17,32 +22,37 @@ if [[ ! -x "$DRIVER" ]]; then swift build -c release --package-path "$SCRIPT_DIR/swift" >/dev/null fi -# answer LABEL BUTTON HINT COMMAND... +# answer LABEL TRIGGER_NAME COMMAND... answer() { - local label="$1" button="$2" hint="$3" - shift 3 + local label="$1" trigger_name="$2" + shift 2 "$@" >/dev/null 2>&1 & local trigger=$! - local pressed=0 + local pressed=0 skipped="" for _ in $(seq 1 20); do - if "$DRIVER" press-system-alert-button --button "$button" --contains "$hint" | grep -Eq '"pressed" ?: ?true'; then + reply="$("$DRIVER" answer-privacy-prompt --expect "$trigger_name")" + if grep -Eq '"answered" ?: ?true' <<<"$reply"; then pressed=1 + echo "[answer-first-run-prompts] $label: $reply" break fi + grep -Eq '"skipped" ?: ?\[ ?"' <<<"$reply" && skipped="$reply" sleep 0.5 done kill "$trigger" 2>/dev/null || true wait "$trigger" 2>/dev/null || true if ((pressed)); then - echo "[answer-first-run-prompts] $label: pressed $button" + : + elif [[ -n "$skipped" ]]; then + echo "[answer-first-run-prompts] $label: a window was left alone because it could not be identified as this run's prompt: $skipped" else echo "[answer-first-run-prompts] $label: no prompt appeared (already answered, or not needed)" fi } -answer "Local Network" "Allow" "local network" dns-sd -B _services._dns-sd._udp local. +answer "Local Network" dns-sd dns-sd -B _services._dns-sd._udp local. if command -v ffmpeg >/dev/null 2>&1; then - answer "Microphone" "Don't Allow" "microphone" \ + answer "Microphone" ffmpeg \ ffmpeg -hide_banner -loglevel error -f avfoundation -i ":0" -t 1 -f null - else echo "[answer-first-run-prompts] Microphone: ffmpeg not installed, skipping" diff --git a/tools/native-review/bin/check-harness-database b/tools/native-review/bin/check-harness-database new file mode 100755 index 00000000000..da981e920de --- /dev/null +++ b/tools/native-review/bin/check-harness-database @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Exit 0 only when the Postgres on the harness port is demonstrably the one that +# setup-macos-vm created, so a schema reset can never land on a database that +# belongs to someone else. Checks, all of which must hold: +# * the server's data_directory is the state dir's own postgres directory; +# * the state dir carries the harness marker file; +# * the database carries the harness marker as its comment. +# Fails closed: if any of it cannot be read (wrong password, no server), it +# refuses. Used by setup-macos-vm and scripts/start-isolated-test-relay.sh. +# +# check-harness-database --state-dir DIR [--port 5471] [--db buzz] [--user buzz] +# PSQL overrides the psql binary; PGPASSWORD defaults to the public dev constant. +set -euo pipefail + +MARKER="buzz-native-review-harness" +MARKER_FILE=".buzz-native-review-harness" +STATE_DIR="" PORT=5471 DB=buzz USER_NAME=buzz +while [[ $# -gt 0 ]]; do + case "$1" in + --state-dir) STATE_DIR="$2"; shift 2 ;; + --port) PORT="$2"; shift 2 ;; + --db) DB="$2"; shift 2 ;; + --user) USER_NAME="$2"; shift 2 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac +done +refuse() { printf '[check-harness-database] REFUSING: %s\n' "$*" >&2; exit 1; } +[[ -n "$STATE_DIR" ]] || refuse "no --state-dir given" +[[ -d "$STATE_DIR/postgres" ]] || refuse "$STATE_DIR/postgres does not exist" +[[ -f "$STATE_DIR/$MARKER_FILE" ]] || refuse "$STATE_DIR is not a harness state dir (no $MARKER_FILE)" + +PSQL="${PSQL:-psql}" +export PGPASSWORD="${PGPASSWORD:-buzz_dev}" +query() { "$PSQL" -h 127.0.0.1 -p "$PORT" -U "$USER_NAME" -d postgres -qtAc "$1" 2>/dev/null; } + +data_dir="$(query 'SHOW data_directory')" || refuse "cannot read data_directory from the server on :$PORT" +[[ -n "$data_dir" && -d "$data_dir" ]] || refuse "server on :$PORT reports an unreadable data directory" +actual="$(cd "$data_dir" && pwd -P)" +expected="$(cd "$STATE_DIR/postgres" && pwd -P)" +[[ "$actual" == "$expected" ]] || refuse "server on :$PORT runs from $actual, not the harness data dir $expected" + +comment="$(query "SELECT shobj_description(oid, 'pg_database') FROM pg_database WHERE datname = '$DB'")" \ + || refuse "cannot read database $DB" +[[ "$comment" == "$MARKER" ]] || refuse "database $DB on :$PORT is not marked as the harness database" +echo "[check-harness-database] :$PORT database $DB is the harness database ($expected)" diff --git a/tools/native-review/bin/setup-macos-vm b/tools/native-review/bin/setup-macos-vm index f5782772d2f..6c97960b0b1 100755 --- a/tools/native-review/bin/setup-macos-vm +++ b/tools/native-review/bin/setup-macos-vm @@ -17,13 +17,20 @@ # the run: triggers each and answers it through the Accessibility-trusted native driver # (best effort, see README). # +# Safety: it refuses to run outside a virtual machine (kern.hv_vmm_present must be 1) +# unless --allow-non-vm is passed, because it starts services on fixed ports and the +# relay script resets the harness database. Every service it starts is identified by +# a pidfile under the state dir; a port that is already open but not ours is never +# reused, and the schema reset is refused unless Postgres is the one started here +# (see check-harness-database). +# # Nothing here copies, creates or prints a secret. The Postgres/MinIO # credentials are the public dev constants already hard-coded in # docker-compose.harness.yml and review_native.fixture_environment. # # Usage: # tools/native-review/bin/setup-macos-vm [--state-dir DIR] [--no-relay] -# [--skip-prompts] +# [--skip-prompts] [--allow-non-vm] # . "$STATE_DIR/env.sh" # then: tools/native-review/bin/review-native run ... set -euo pipefail @@ -33,11 +40,13 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" STATE_DIR="${BUZZ_NATIVE_REVIEW_STATE_DIR:-$HOME/.buzz-native-review}" START_RELAY=1 ANSWER_PROMPTS=1 +ALLOW_NON_VM=0 while [[ $# -gt 0 ]]; do case "$1" in --state-dir) STATE_DIR="$2"; shift 2 ;; --no-relay) START_RELAY=0; shift ;; --skip-prompts) ANSWER_PROMPTS=0; shift ;; + --allow-non-vm) ALLOW_NON_VM=1; shift ;; -h|--help) sed -n '2,/^set -euo/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "unknown option: $1" >&2; exit 2 ;; esac @@ -54,19 +63,39 @@ DB_USER=buzz DB_PASS=buzz_dev DB_NAME=buzz BUCKET=buzz-media -# dl.min.io is may be unreachable from a locked-down VM; build a pinned upstream commit instead. +# dl.min.io may be unreachable from a locked-down VM; build a pinned upstream commit instead. MINIO_REF="${MINIO_REF:-7aac2a2c5b7c}" log() { printf '[setup-macos-vm] %s\n' "$*"; } die() { printf '[setup-macos-vm] ERROR: %s\n' "$*" >&2; exit 1; } [[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]] || die "this script is for Apple-silicon macOS" +# Refuse outside a VM before touching anything. kern.hv_vmm_present is 1 under +# Apple's Virtualization framework (Tart, ec2-macos workstations); hw.model is +# VirtualMac2,1 there too. +vmm_present="$(sysctl -n kern.hv_vmm_present 2>/dev/null || echo 0)" +if [[ "$vmm_present" != "1" ]]; then + ((ALLOW_NON_VM)) || die "refusing to run: this does not look like a virtual machine (kern.hv_vmm_present=$vmm_present, hw.model=$(sysctl -n hw.model 2>/dev/null || echo unknown)). It starts services on fixed local ports and resets a database; pass --allow-non-vm if you really mean to run it here." + log "WARNING: not a VM (kern.hv_vmm_present=$vmm_present); continuing because --allow-non-vm was given" +fi command -v brew >/dev/null || die "Homebrew is required" command -v go >/dev/null || die "Go is required to build MinIO (brew install go)" mkdir -p "$STATE_DIR"/{logs,sherpa} "$HOME/.local/bin" +# Marks this directory (and everything under it) as the harness's own. +printf 'buzz-native-review-harness\n' > "$STATE_DIR/.buzz-native-review-harness" BREW_PREFIX="$(brew --prefix)" port_open() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +listener_pids() { lsof -nP -iTCP:"$1" -sTCP:LISTEN -t 2>/dev/null | sort -u | tr '\n' ' ' | sed 's/ $//'; } +# An open port is ours only when its sole listener is the pid recorded in the pidfile +# this script's own service wrote. Anything else is someone else's: never use it. +require_ours() { + local name="$1" port="$2" pidfile="$3" want + want="$(head -1 "$pidfile" 2>/dev/null || true)" + if [[ -z "$want" || "$(listener_pids "$port")" != "$want" ]]; then + die "$name port :$port is already in use by something this script did not start (listener pid: $(listener_pids "$port")); refusing to use it. Stop it or free the port." + fi +} wait_port() { local name="$1" port="$2" for _ in $(seq 1 60); do port_open "$port" && return 0; sleep 1; done @@ -101,7 +130,9 @@ if [[ ! -f "$PGDATA/PG_VERSION" ]]; then "$PG_BIN/initdb" -D "$PGDATA" -U "$DB_USER" --auth=scram-sha-256 --pwfile="$pwfile" -E UTF8 >/dev/null rm -f "$pwfile" fi -if ! port_open "$PG_PORT"; then +if port_open "$PG_PORT"; then + require_ours postgres "$PG_PORT" "$PGDATA/postmaster.pid" +else log "starting postgres on :$PG_PORT" "$PG_BIN/pg_ctl" -D "$PGDATA" -l "$STATE_DIR/logs/postgres.log" \ -o "-p $PG_PORT -c listen_addresses=127.0.0.1 -c unix_socket_directories=$STATE_DIR" -w start >/dev/null @@ -112,24 +143,36 @@ if ! psql -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" -d postgres -qtAc \ log "createdb $DB_NAME" createdb -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" "$DB_NAME" fi +# The cluster is the one initdb'd under the state dir above, so this database is ours: +# mark it, then prove it. The relay script runs the same check before it resets the schema. +psql -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" -d postgres -qc \ + "COMMENT ON DATABASE $DB_NAME IS 'buzz-native-review-harness'" +"$SCRIPT_DIR/check-harness-database" --state-dir "$STATE_DIR" --port "$PG_PORT" --db "$DB_NAME" --user "$DB_USER" \ + || die "Postgres on :$PG_PORT is not the harness database" # -- 4. Redis on :6471 ------------------------------------------------------ -if ! port_open "$REDIS_PORT"; then +if port_open "$REDIS_PORT"; then + require_ours redis "$REDIS_PORT" "$STATE_DIR/redis/redis.pid" +else log "starting redis on :$REDIS_PORT" mkdir -p "$STATE_DIR/redis" "$REDIS_SERVER" --port "$REDIS_PORT" --bind 127.0.0.1 --dir "$STATE_DIR/redis" \ + --pidfile "$STATE_DIR/redis/redis.pid" \ --save "" --daemonize yes --logfile "$STATE_DIR/logs/redis.log" >/dev/null wait_port redis "$REDIS_PORT" fi # -- 5. MinIO on :9471 + bucket --------------------------------------------- -if ! port_open "$MINIO_PORT"; then +if port_open "$MINIO_PORT"; then + require_ours minio "$MINIO_PORT" "$STATE_DIR/minio.pid" +else log "starting minio on :$MINIO_PORT" mkdir -p "$STATE_DIR/minio" MINIO_ROOT_USER="$DEV_USER" MINIO_ROOT_PASSWORD="$DEV_SECRET" \ nohup "$MINIO_BIN" server "$STATE_DIR/minio" --address "127.0.0.1:$MINIO_PORT" \ --console-address "127.0.0.1:$MINIO_CONSOLE_PORT" \ > "$STATE_DIR/logs/minio.log" 2>&1 < /dev/null & + echo $! > "$STATE_DIR/minio.pid" wait_port minio "$MINIO_PORT" fi # Create the media bucket with a SigV4-signed PUT (no `mc` needed). 200 = created, @@ -165,12 +208,15 @@ fi # -- 8. isolated relay (native services, no Docker) ------------------------- if ((START_RELAY)); then if port_open 3030; then + # Only the relay this script's relay script started (a tmux session of that name) is ours. + tmux has-session -t dawn-relay 2>/dev/null \ + || die "port :3030 is in use by something that is not the harness relay; refusing to use it" log "relay already listening on :3030" else log "starting isolated relay (first build takes several minutes)" # shellcheck disable=SC1091 ( cd "$REPO_ROOT" && . bin/activate-hermit >/dev/null \ - && BUZZ_HARNESS_NATIVE_SERVICES=1 RELAY_LOG="$STATE_DIR/logs/relay.log" \ + && BUZZ_HARNESS_NATIVE_SERVICES=1 BUZZ_HARNESS_STATE_DIR="$STATE_DIR" RELAY_LOG="$STATE_DIR/logs/relay.log" \ SHERPA_ONNX_ARCHIVE_DIR="$STATE_DIR/sherpa" ./scripts/start-isolated-test-relay.sh ) fi fi diff --git a/tools/native-review/review_native.py b/tools/native-review/review_native.py index e5694fff7c1..20e7d7246dc 100755 --- a/tools/native-review/review_native.py +++ b/tools/native-review/review_native.py @@ -705,6 +705,10 @@ def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], # The accessibility window can lag the compositor's by a moment. try: placement = driver.request("place_window") + if not placement.get("verified", True): + raise HarnessError( + f"window placement was not verified: before {placement.get('before')}, " + f"after {placement.get('after')}") break except HarnessError as error: if "no accessibility window" not in str(error): @@ -726,7 +730,7 @@ def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], f"(window status: {status})") time.sleep(0.1) placed = driver.request("window_status") - return {**placed, "moved": bool(placement.get("moved"))} + return {**placed, "moved": bool(placement.get("moved")), "placement": placement} def locate_required(driver: Driver, locators: list[dict[str, str]], timeout_ms: int) -> dict[str, Any]: diff --git a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift index db6cd0c6463..f69eceb21fd 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift @@ -3,6 +3,7 @@ import ApplicationServices import AVFoundation import CoreGraphics import Foundation +import Darwin import BuzzNativeDriverSupport struct Locator: Codable { @@ -288,29 +289,58 @@ func windowStatus(pid: pid_t) -> [String: Any] { } } -/// Move the app's window onto the main display when it opened elsewhere (a fresh -/// VM can have a second display left of the main one, where WKWebView exposes no -/// accessibility tree). Returns whether the window moved. -func placeWindowOnMainDisplay(app: AXUIElement) throws -> Bool { - guard let window = (attribute(app, kAXWindowsAttribute) as? [AXUIElement])?.first, - let current = frameAttribute(window) else { - throw DriverError.message("no accessibility window to place") +/// Move the window the harness reports (`windowInfo`, the largest on-screen one) +/// onto the main display when it opened elsewhere (a fresh VM can have a second +/// display left of the main one, where WKWebView exposes no accessibility tree). +/// The accessibility window moved is the one whose frame matches the reported +/// window, never "the first"; the result is read back from the window server and +/// the call fails unless the reported window ends up wholly on the main display. +func placeWindowOnMainDisplay(app: AXUIElement, pid: pid_t) throws -> [String: Any] { + let (windowID, reported) = try windowInfo(pid: pid) + let windows = (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] + let frames = windows.map { window -> CGRect in + guard let frame = frameAttribute(window) else { return .null } + return CGRect(x: frame.x, y: frame.y, width: frame.width, height: frame.height) + } + guard let index = matchingWindowIndex(frames: frames, reported: reported) else { + throw DriverError.message("no accessibility window to place matches the reported window \(windowID) at \(reported)") + } + let window = windows[index] + let mainDisplay = CGDisplayBounds(CGMainDisplayID()) + var moved = false + if let target = placementOnMainDisplay(window: reported, mainDisplay: mainDisplay) { + var size = target.size + var origin = target.origin + guard let sizeValue = AXValueCreate(.cgSize, &size), let originValue = AXValueCreate(.cgPoint, &origin) else { + throw DriverError.message("could not encode window placement") + } + // Size first so the window cannot be clamped against the display it is leaving. + guard AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, sizeValue) == .success, + AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, originValue) == .success else { + throw DriverError.message("accessibility refused to move the window; grant Accessibility to the invoking process") + } + moved = true } - let frame = CGRect(x: current.x, y: current.y, width: current.width, height: current.height) - guard let target = placementOnMainDisplay(window: frame, mainDisplay: CGDisplayBounds(CGMainDisplayID())) else { - return false + // Read it back from the window server, the same source the harness reports from. + var after = reported + var verified = false + for _ in 0..<20 { + if let (_, current) = try? windowInfo(pid: pid) { after = current } + verified = windowIsOnMainDisplay(after, mainDisplay: mainDisplay) + if verified { break } + Thread.sleep(forTimeInterval: 0.1) } - var size = target.size - var origin = target.origin - guard let sizeValue = AXValueCreate(.cgSize, &size), let originValue = AXValueCreate(.cgPoint, &origin) else { - throw DriverError.message("could not encode window placement") + guard verified else { + throw DriverError.message("window \(windowID) is at \(after) after placement, not wholly on the main display \(mainDisplay)") } - // Size first so the window cannot be clamped against the display it is leaving. - guard AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, sizeValue) == .success, - AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, originValue) == .success else { - throw DriverError.message("accessibility refused to move the window; grant Accessibility to the invoking process") + func rect(_ value: CGRect) -> [String: Double] { + ["x": value.minX, "y": value.minY, "width": value.width, "height": value.height] } - return true + return [ + "ok": true, "moved": moved, "verified": true, "window_id": windowID, + "before": rect(reported), "after": rect(after), "main_display": rect(mainDisplay), + "accessibility_windows": windows.count, + ] } func captureWindow(pid: pid_t, path: String) throws { @@ -525,7 +555,7 @@ func ensureTargetFrontmost(pid: pid_t) async throws { } if NSWorkspace.shared.frontmostApplication?.processIdentifier != pid { // A first-run macOS privacy prompt keeps focus until answered. - _ = answerPrivacyPrompt(excluding: pid) + _ = answerPrivacyPrompt(target: pid) running.activate(options: [.activateIgnoringOtherApps]) } let deadline = ContinuousClock.now.advanced(by: .seconds(2)) @@ -579,60 +609,111 @@ func postText(_ text: String, pid: pid_t) throws { } } -/// Press `button` in a system alert whose text contains `hint` (for example the -/// one-time macOS "Local Network" prompt, which blocks input to every app until -/// answered). Scans every on-screen window owner, never the reviewed app, and -/// presses only when the hint text is present so no unrelated "Allow" is clicked. -func pressSystemAlertButton(button: String, hint: String) -> Bool { - let owners = Set(((CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []) - .compactMap { $0[kCGWindowOwnerPID as String] as? Int32 }) - for pid in owners where pid != getpid() { - let app = AXUIElementCreateApplication(pid) - for window in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] { - var queue = [window] - var texts: [String] = [] - var target: AXUIElement? - var visited = 0 - while !queue.isEmpty && visited < 500 { - let current = queue.removeFirst() - visited += 1 - if let text = elementName(current) { texts.append(text) } - if normalizedRole(elementRole(current)) == "button", let name = elementName(current), normalizedButtonTitle(name) == normalizedButtonTitle(button) { target = current } - queue.append(contentsOf: children(current)) - } - if let target, texts.joined(separator: " ").lowercased().contains(hint.lowercased()) { - return AXUIElementPerformAction(target, kAXPressAction as CFString) == .success +/// Names a privacy prompt may legitimately use for this review: the processes in +/// the driver's own ancestry (macOS names the responsible process, such as the +/// agent that launched the run, or an interpreter), the reviewed app, and any +/// `extra` names the caller launched on purpose (a trigger child). +func reviewProcessNames(target: pid_t?, extra: [String]) -> [String] { + var names = Set(extra) + func add(pid: pid_t) { + var path = [CChar](repeating: 0, count: 4096) + if proc_pidpath(pid, &path, UInt32(path.count)) > 0 { + let url = URL(fileURLWithPath: String(cString: path)) + names.insert(url.lastPathComponent) + for component in url.pathComponents where component.hasSuffix(".app") { + names.insert(String(component.dropLast(4))) } } + var name = [CChar](repeating: 0, count: 256) + if proc_name(pid, &name, UInt32(name.count)) > 0 { names.insert(String(cString: name)) } + if let app = NSRunningApplication(processIdentifier: pid) { + if let localized = app.localizedName { names.insert(localized) } + } } - return false + var pid = getpid() + var hops = 0 + while pid > 1 && hops < 32 { + add(pid: pid) + var info = proc_bsdinfo() + guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, Int32(MemoryLayout.size)) > 0 else { break } + pid = pid_t(info.pbi_ppid) + hops += 1 + } + if let target { add(pid: target) } + names.remove("") + return Array(names) } -/// Answer a pending first-run macOS privacy prompt (see `privacyPromptButton`). -/// Returns whether a button was pressed. -func answerPrivacyPrompt(excluding target: pid_t? = nil) -> Bool { +/// Every on-screen window owned by the system prompt agent, as the decision +/// function sees it, with its accessibility element. Scans only that owner, never +/// the reviewed app or anyone else. +func systemPromptWindows() -> [(PromptWindow, AXUIElement)] { let owners = Set(((CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []) .compactMap { $0[kCGWindowOwnerPID as String] as? Int32 }) - for pid in owners where pid != getpid() && pid != target { + var windows: [(PromptWindow, AXUIElement)] = [] + for pid in owners where pid != getpid() { + guard let running = NSRunningApplication(processIdentifier: pid), + running.bundleIdentifier == systemPromptBundleID else { continue } let app = AXUIElementCreateApplication(pid) for window in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] { - var queue = [window] - var texts: [String] = [] - var buttons: [String: AXUIElement] = [:] + windows.append((promptWindow(window, owner: running), window)) + } + } + return windows +} + +func promptWindow(_ window: AXUIElement, owner: NSRunningApplication) -> PromptWindow { + var queue = [window] + var texts: [String] = [] + var buttons: [String] = [] + var visited = 0 + while !queue.isEmpty && visited < 200 { + let current = queue.removeFirst() + visited += 1 + if normalizedRole(elementRole(current)) == "button" { + if let name = elementName(current) { buttons.append(name) } + } else if let text = stringAttribute(current, [kAXValueAttribute]) { + texts.append(text) + } + queue.append(contentsOf: children(current)) + } + return PromptWindow( + ownerBundleID: owner.bundleIdentifier, + ownerExecutablePath: owner.executableURL?.path, + role: stringAttribute(window, [kAXRoleAttribute]), + subrole: stringAttribute(window, [kAXSubroleAttribute]), + texts: texts, + buttons: buttons) +} + +/// Answer a pending first-run macOS privacy prompt, but only one that is positively +/// the system's own alert naming a process of this review (see +/// `decidePrivacyPrompt`). Returns what was done; a skipped window is reported with +/// its reason and nothing is pressed. +func answerPrivacyPrompt(target: pid_t? = nil, extraNames: [String] = []) -> [String: Any] { + let expected = reviewProcessNames(target: target, extra: extraNames) + var skipped: [String] = [] + for (candidate, element) in systemPromptWindows() { + switch decidePrivacyPrompt(candidate, expectedApps: expected) { + case .skip(let reason): + skipped.append(reason) + case .press(let title): + var queue = [element] var visited = 0 - while !queue.isEmpty && visited < 500 { + while !queue.isEmpty && visited < 200 { let current = queue.removeFirst() visited += 1 - if let text = elementName(current) { texts.append(text) } - if normalizedRole(elementRole(current)) == "button", let name = elementName(current) { buttons[normalizedButtonTitle(name)] = current } + if normalizedRole(elementRole(current)) == "button", let name = elementName(current), + normalizedButtonTitle(name) == normalizedButtonTitle(title) { + let pressed = AXUIElementPerformAction(current, kAXPressAction as CFString) == .success + return ["ok": true, "answered": pressed, "button": title, "prompt": candidate.texts.first ?? ""] + } queue.append(contentsOf: children(current)) } - if let name = privacyPromptButton(forAlertText: texts.joined(separator: " ")), let button = buttons[normalizedButtonTitle(name)] { - return AXUIElementPerformAction(button, kAXPressAction as CFString) == .success - } + skipped.append("could not find the \(title) button to press") } } - return false + return ["ok": true, "answered": false, "skipped": skipped] } @main @@ -640,7 +721,7 @@ struct BuzzNativeDriver { static func main() async { do { let arguments = Array(CommandLine.arguments.dropFirst()) - guard let command = arguments.first else { throw DriverError.message("usage: buzz-native-driver doctor | serve --pid PID | press-system-alert-button --button NAME --contains TEXT") } + guard let command = arguments.first else { throw DriverError.message("usage: buzz-native-driver doctor | serve --pid PID | answer-privacy-prompt [--expect NAME]...") } if command == "doctor" { let accessibility = AXIsProcessTrusted() let screen = CGPreflightScreenCaptureAccess() @@ -652,12 +733,20 @@ struct BuzzNativeDriver { ]]) return } - if command == "press-system-alert-button" { - guard arguments.count == 5, arguments[1] == "--button", arguments[3] == "--contains" else { - throw DriverError.message("usage: buzz-native-driver press-system-alert-button --button NAME --contains TEXT") + if command == "answer-privacy-prompt" { + // answer-privacy-prompt [--expect NAME]...: NAME is a process the caller launched + // on purpose to raise the prompt (for example dns-sd or ffmpeg). + var extra: [String] = [] + var rest = Array(arguments.dropFirst()) + while !rest.isEmpty { + guard rest.count >= 2, rest[0] == "--expect" else { + throw DriverError.message("usage: buzz-native-driver answer-privacy-prompt [--expect NAME]...") + } + extra.append(rest[1]) + rest.removeFirst(2) } guard AXIsProcessTrusted() else { throw DriverError.message("Accessibility permission is not granted") } - response(["ok": true, "pressed": pressSystemAlertButton(button: arguments[2], hint: arguments[4])]) + response(answerPrivacyPrompt(extraNames: extra)) return } guard command == "serve", (arguments.count == 3 || arguments.count == 5), arguments[1] == "--pid", let pid = pid_t(arguments[2]) else { @@ -790,9 +879,9 @@ struct BuzzNativeDriver { } response(["ok": true]) case "place_window": - response(["ok": true, "moved": try placeWindowOnMainDisplay(app: app)]) + response(try placeWindowOnMainDisplay(app: app, pid: pid)) case "answer_privacy_prompt": - response(["ok": true, "answered": answerPrivacyPrompt(excluding: pid)]) + response(answerPrivacyPrompt(target: pid)) case "web_ready": response(["ok": true, "ready": semanticContentBounds(pid: pid, messagingTimeout: 1.5) != nil]) case "window_status": diff --git a/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift b/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift index 217257365e7..b820cb906e8 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift @@ -54,19 +54,118 @@ public func placementOnMainDisplay(window: CGRect, mainDisplay: CGRect, menuBarH width: size.width, height: size.height) } -/// Which button to press for a first-run macOS privacy prompt, judged by its text, -/// or nil when the text is not one of the known prompts. Microphone and camera -/// access are declined (a review never needs them); the Local Network prompt is -/// allowed. Anything else is never answered. -public func privacyPromptButton(forAlertText text: String) -> String? { +public enum PrivacyPromptKind: Equatable, Sendable { case microphone, camera, localNetwork } + +public struct PrivacyPrompt: Equatable, Sendable { + public var kind: PrivacyPromptKind + public var appName: String + public init(kind: PrivacyPromptKind, appName: String) { + self.kind = kind + self.appName = appName + } +} + +/// What the driver can see of a candidate prompt window: who owns it, what kind +/// of accessibility window it is, and the text and buttons inside it. +public struct PromptWindow: Equatable, Sendable { + public var ownerBundleID: String? + public var ownerExecutablePath: String? + public var role: String? + public var subrole: String? + public var texts: [String] + public var buttons: [String] + public init(ownerBundleID: String?, ownerExecutablePath: String?, role: String?, + subrole: String?, texts: [String], buttons: [String]) { + self.ownerBundleID = ownerBundleID + self.ownerExecutablePath = ownerExecutablePath + self.role = role + self.subrole = subrole + self.texts = texts + self.buttons = buttons + } +} + +public enum PromptDecision: Equatable, Sendable { + case press(String) + case skip(String) +} + +/// The process macOS draws its privacy (TCC) prompts with. Observed on a macOS 26 +/// VM: the alert is an `AXWindow` with subrole `AXSystemDialog`, owned by this +/// bundle, running from the sealed system volume. +public let systemPromptBundleID = "com.apple.UserNotificationCenter" +public let systemPromptExecutablePrefix = "/System/Library/CoreServices/UserNotificationCenter.app/" + +/// Read the kind of prompt and the app it names (the first quoted name) from the +/// alert's text. nil when the text is not a known privacy prompt. +public func parsePrivacyPrompt(texts: [String]) -> PrivacyPrompt? { + let text = texts.joined(separator: " ") let lowered = text.lowercased() - if lowered.contains("would like to access the microphone") || lowered.contains("would like to access the camera") { - return "Don't Allow" + let kind: PrivacyPromptKind + if lowered.contains("would like to access the microphone") { + kind = .microphone + } else if lowered.contains("would like to access the camera") { + kind = .camera + } else if lowered.contains("to find devices on local networks") { + kind = .localNetwork + } else { + return nil + } + let quotes: Set = ["\u{201C}", "\u{201D}", "\""] + let characters = Array(text) + guard let open = characters.firstIndex(where: { quotes.contains($0) }), + let close = characters[(open + 1)...].firstIndex(where: { quotes.contains($0) }) else { return nil } + let name = String(characters[(open + 1).. PromptDecision { + guard window.ownerBundleID == systemPromptBundleID else { + return .skip("window is not owned by the system prompt agent (owner: \(window.ownerBundleID ?? "unknown"))") + } + guard let executable = window.ownerExecutablePath, + URL(fileURLWithPath: executable).standardizedFileURL.path.hasPrefix(systemPromptExecutablePrefix) else { + return .skip("window owner does not run from the system prompt agent's path") + } + guard window.role == "AXWindow", window.subrole == "AXSystemDialog" else { + return .skip("window is not a system dialog (role: \(window.role ?? "none"), subrole: \(window.subrole ?? "none"))") + } + guard let prompt = parsePrivacyPrompt(texts: window.texts) else { + return .skip("window text is not a known privacy prompt") + } + let names = Set(expectedApps.map { $0.lowercased() }) + guard names.contains(prompt.appName.lowercased()) else { + return .skip("prompt names \"\(prompt.appName)\", which is not a process of this review") } - if lowered.contains("find devices on local networks") || lowered.contains("local network") { - return "Allow" + let wanted = prompt.kind == .localNetwork ? "Allow" : "Don't Allow" + let matching = window.buttons.filter { normalizedButtonTitle($0) == normalizedButtonTitle(wanted) } + guard matching.count == 1 else { + return .skip("expected exactly one \"\(wanted)\" button, found \(matching.count)") } - return nil + return .press(wanted) +} + +/// The index of the accessibility window whose frame is the window the harness +/// reports (within `tolerance` points), or nil. Never falls back to another window. +public func matchingWindowIndex(frames: [CGRect], reported: CGRect, tolerance: CGFloat = 2) -> Int? { + frames.firstIndex { frame in + abs(frame.minX - reported.minX) <= tolerance && abs(frame.minY - reported.minY) <= tolerance + && abs(frame.width - reported.width) <= tolerance && abs(frame.height - reported.height) <= tolerance + } +} + +/// True when the window sits wholly on the main display below the menu bar. +public func windowIsOnMainDisplay(_ window: CGRect, mainDisplay: CGRect) -> Bool { + placementOnMainDisplay(window: window, mainDisplay: mainDisplay) == nil } /// A button title with typographic apostrophes folded to plain ones, so diff --git a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift index 1e0dfda5d71..64d9cce027d 100644 --- a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift +++ b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift @@ -66,18 +66,98 @@ import Testing #expect(target.width <= main.width && target.height <= main.height) } -@Test func microphoneAndCameraPromptsAreDeclined() { - #expect(privacyPromptButton(forAlertText: "\"bloxlet\" would like to access the Microphone. Don't Allow Allow") == "Don't Allow") - #expect(privacyPromptButton(forAlertText: "\"Terminal\" would like to access the Camera.") == "Don't Allow") +// The real prompt, as the VM's accessibility tree shows it. +private func systemPrompt( + text: String = "\u{201C}bloxlet\u{201D} would like to access the Microphone.", + buttons: [String] = ["Help", "Don\u{2019}t Allow", "Allow"], + bundleID: String? = "com.apple.UserNotificationCenter", + executable: String? = "/System/Library/CoreServices/UserNotificationCenter.app/Contents/MacOS/UserNotificationCenter", + role: String? = "AXWindow", + subrole: String? = "AXSystemDialog" +) -> PromptWindow { + PromptWindow(ownerBundleID: bundleID, ownerExecutablePath: executable, role: role, + subrole: subrole, texts: [text, ""], buttons: buttons) } -@Test func localNetworkPromptIsAllowed() { - #expect(privacyPromptButton(forAlertText: "Allow \"bloxlet\" to find devices on local networks?") == "Allow") +@Test func promptTextNamesTheKindAndTheApp() { + #expect(parsePrivacyPrompt(texts: ["\u{201C}bloxlet\u{201D} would like to access the Microphone."]) + == PrivacyPrompt(kind: .microphone, appName: "bloxlet")) + #expect(parsePrivacyPrompt(texts: ["\"Terminal\" would like to access the Camera."]) + == PrivacyPrompt(kind: .camera, appName: "Terminal")) + #expect(parsePrivacyPrompt(texts: ["Allow \u{201C}Python\u{201D} to find devices on local networks?", "This will allow the app to discover"]) + == PrivacyPrompt(kind: .localNetwork, appName: "Python")) + #expect(parsePrivacyPrompt(texts: ["Do you want to save changes? Allow"]) == nil) + #expect(parsePrivacyPrompt(texts: ["would like to access the Microphone."]) == nil) } -@Test func unrelatedAlertsAreNeverAnswered() { - #expect(privacyPromptButton(forAlertText: "Do you want to save changes? Allow") == nil) - #expect(privacyPromptButton(forAlertText: "") == nil) +@Test func theRealMicrophonePromptIsDeclinedWhenItNamesAProcessOfTheReview() { + #expect(decidePrivacyPrompt(systemPrompt(), expectedApps: ["bloxlet", "Buzz Native Review"]) == .press("Don't Allow")) +} + +@Test func theRealLocalNetworkPromptIsAllowedWhenItNamesAProcessOfTheReview() { + let prompt = systemPrompt(text: "Allow \u{201C}Python\u{201D} to find devices on local networks?", + buttons: ["Don\u{2019}t Allow", "Allow"]) + #expect(decidePrivacyPrompt(prompt, expectedApps: ["python"]) == .press("Allow")) +} + +@Test func aPromptNamingAnotherAppIsNeverAnswered() { + guard case .skip(let reason) = decidePrivacyPrompt(systemPrompt(text: "\u{201C}Zoom\u{201D} would like to access the Microphone."), + expectedApps: ["bloxlet", "Buzz Native Review"]) else { + Issue.record("answered a prompt for another app"); return + } + #expect(reason.contains("Zoom")) +} + +@Test func aWindowNotOwnedBySystemPromptAgentIsNeverAnswered() { + // Same words, same buttons, wrong owner: a web page or app drawing a lookalike. + for impostor in [ + systemPrompt(bundleID: "com.apple.Safari"), + systemPrompt(bundleID: nil), + systemPrompt(executable: "/Users/someone/UserNotificationCenter.app/Contents/MacOS/UserNotificationCenter"), + systemPrompt(executable: nil), + systemPrompt(executable: "/System/Library/CoreServices/../../../tmp/evil"), + ] { + guard case .skip = decidePrivacyPrompt(impostor, expectedApps: ["bloxlet"]) else { + Issue.record("answered a window the system prompt agent does not own: \(impostor)"); continue + } + } +} + +@Test func aWindowThatIsNotASystemAlertIsNeverAnswered() { + for other in [systemPrompt(role: "AXSheet"), systemPrompt(subrole: "AXStandardWindow"), systemPrompt(subrole: nil), systemPrompt(role: nil)] { + guard case .skip = decidePrivacyPrompt(other, expectedApps: ["bloxlet"]) else { + Issue.record("answered a window that is not a system dialog: \(other)"); continue + } + } +} + +@Test func aPromptWithoutTheExpectedButtonOrWithDuplicatesIsNotAnswered() { + guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Help", "Allow"]), expectedApps: ["bloxlet"]) else { + Issue.record("pressed a missing button"); return + } + guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Don\u{2019}t Allow", "Don't Allow"]), expectedApps: ["bloxlet"]) else { + Issue.record("pressed an ambiguous button"); return + } +} + +@Test func anEmptyExpectedSetNeverMatches() { + guard case .skip = decidePrivacyPrompt(systemPrompt(), expectedApps: []) else { + Issue.record("answered with nothing to identify the app by"); return + } +} + +@Test func theReportedWindowIsTheOneThatMoves() { + let reported = CGRect(x: -1016, y: 36, width: 1008, height: 726) + let others = [CGRect(x: 40, y: 40, width: 300, height: 200), CGRect(x: -1015, y: 36, width: 1008, height: 726)] + #expect(matchingWindowIndex(frames: others, reported: reported) == 1) + #expect(matchingWindowIndex(frames: [CGRect(x: 40, y: 40, width: 300, height: 200)], reported: reported) == nil) + #expect(matchingWindowIndex(frames: [], reported: reported) == nil) +} + +@Test func aMovedWindowIsVerifiedOnlyWhenItIsWhollyOnTheMainDisplay() { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + #expect(windowIsOnMainDisplay(CGRect(x: 100, y: 80, width: 1008, height: 726), mainDisplay: main)) + #expect(!windowIsOnMainDisplay(CGRect(x: -1016, y: 36, width: 1008, height: 726), mainDisplay: main)) } @Test func buttonTitlesCompareIgnoringTypographicApostrophes() { diff --git a/tools/native-review/tests/test_harness_guards.py b/tools/native-review/tests/test_harness_guards.py new file mode 100644 index 00000000000..b21825008b5 --- /dev/null +++ b/tools/native-review/tests/test_harness_guards.py @@ -0,0 +1,178 @@ +"""The setup and relay scripts must never act on a machine, port or database that +is not the harness's own. These run the real shell scripts against stub binaries.""" +import os +import pathlib +import stat +import subprocess +import tempfile +import unittest + +TOOL = pathlib.Path(__file__).parents[1] +REPO = TOOL.parents[1] +CHECK = TOOL / "bin/check-harness-database" +SETUP = TOOL / "bin/setup-macos-vm" +RELAY = REPO / "scripts/start-isolated-test-relay.sh" + +# A psql that answers from environment variables and records every statement. +STUB_PSQL = """#!/bin/bash +sql="" +while [[ $# -gt 0 ]]; do + case "$1" in -c|-qtAc|-qc) sql="$2"; shift 2 ;; *) shift ;; esac +done +echo "$sql" >> "$STUB_LOG" +case "$sql" in + # Stop the relay script right after the reset: nothing after it may run in a test. + *"DROP SCHEMA"*) exit 3 ;; + "SHOW data_directory") [[ -n "${STUB_DATA_DIR:-}" ]] && echo "$STUB_DATA_DIR" || exit 2 ;; + *shobj_description*) [[ -n "${STUB_COMMENT+x}" ]] && echo "$STUB_COMMENT" ;; +esac +exit 0 +""" + + +def write_exe(path: pathlib.Path, body: str) -> None: + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IXUSR) + + +class Sandbox(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + root = pathlib.Path(self.tmp.name).resolve() + self.stubs = root / "stubs" + self.stubs.mkdir() + self.state = root / "state" + (self.state / "postgres").mkdir(parents=True) + self.foreign = root / "foreign-postgres" + self.foreign.mkdir() + self.log = root / "psql.log" + self.log.write_text("") + write_exe(self.stubs / "psql", STUB_PSQL) + + def mark_state(self): + (self.state / ".buzz-native-review-harness").write_text("buzz-native-review-harness\n") + + def env(self, **extra): + env = { + "PATH": f"{self.stubs}:/usr/bin:/bin", + "HOME": self.tmp.name, + "STUB_LOG": str(self.log), + } + env.update(extra) + return env + + def run_script(self, args, **extra): + return subprocess.run(args, env=self.env(**extra), capture_output=True, text=True, timeout=60) + + def statements(self): + return self.log.read_text() + + +class CheckHarnessDatabaseTests(Sandbox): + def check(self, **extra): + return self.run_script([str(CHECK), "--state-dir", str(self.state)], **extra) + + def test_accepts_the_harness_database(self): + self.mark_state() + result = self.check(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT="buzz-native-review-harness") + self.assertEqual(result.returncode, 0, result.stderr) + + def test_refuses_a_server_running_from_another_data_directory(self): + self.mark_state() + result = self.check(STUB_DATA_DIR=str(self.foreign), STUB_COMMENT="buzz-native-review-harness") + self.assertEqual(result.returncode, 1) + self.assertIn("not the harness data dir", result.stderr) + + def test_refuses_an_unmarked_database(self): + self.mark_state() + for comment in ("", "someone else's database"): + result = self.check(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT=comment) + self.assertEqual(result.returncode, 1, comment) + self.assertIn("not marked", result.stderr) + + def test_refuses_without_the_state_dir_marker_file(self): + result = self.check(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT="buzz-native-review-harness") + self.assertEqual(result.returncode, 1) + self.assertIn("not a harness state dir", result.stderr) + + def test_refuses_when_the_server_cannot_be_read(self): + self.mark_state() + result = self.check(STUB_COMMENT="buzz-native-review-harness") # no data dir: psql fails + self.assertEqual(result.returncode, 1) + self.assertIn("cannot read data_directory", result.stderr) + + def test_refuses_without_a_state_dir(self): + result = self.run_script([str(CHECK)]) + self.assertEqual(result.returncode, 1) + + +class SetupVmGuardTests(Sandbox): + def setUp(self): + super().setUp() + write_exe(self.stubs / "uname", '#!/bin/bash\n[[ "$1" == "-m" ]] && echo arm64 || echo Darwin\n') + + def sysctl(self, vmm: str): + write_exe(self.stubs / "sysctl", f'#!/bin/bash\n[[ "$2" == "kern.hv_vmm_present" ]] && echo {vmm} || echo Mac15,9\n') + + def setup(self, *flags): + return self.run_script([str(SETUP), "--state-dir", str(self.state), *flags]) + + def test_refuses_outside_a_vm_before_touching_anything(self): + self.sysctl("0") + result = self.setup() + self.assertEqual(result.returncode, 1) + self.assertIn("does not look like a virtual machine", result.stderr) + self.assertFalse((self.state / ".buzz-native-review-harness").exists()) + + def test_allow_non_vm_is_an_explicit_opt_in(self): + self.sysctl("0") + result = self.setup("--allow-non-vm") + self.assertIn("continuing because --allow-non-vm", result.stdout) + self.assertNotIn("does not look like a virtual machine", result.stderr) + self.assertIn("Homebrew is required", result.stderr) # got past the guard, stopped at the stubbed PATH + + def test_a_vm_passes_the_guard(self): + self.sysctl("1") + result = self.setup() + self.assertNotIn("virtual machine", result.stderr) + self.assertIn("Homebrew is required", result.stderr) + + +class RelayResetGuardTests(Sandbox): + def relay(self, **extra): + write_exe(self.stubs / "pg_isready", "#!/bin/bash\nexit 0\n") + return self.run_script([str(RELAY)], BUZZ_HARNESS_NATIVE_SERVICES="1", **extra) + + def assertNoReset(self, result): + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("DROP SCHEMA", self.statements()) + + def test_native_mode_without_a_state_dir_never_drops(self): + result = self.relay(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT="buzz-native-review-harness") + self.assertNoReset(result) + self.assertIn("BUZZ_HARNESS_STATE_DIR", result.stderr) + + def test_native_mode_against_a_foreign_postgres_never_drops(self): + self.mark_state() + result = self.relay(BUZZ_HARNESS_STATE_DIR=str(self.state), STUB_DATA_DIR=str(self.foreign), + STUB_COMMENT="buzz-native-review-harness") + self.assertNoReset(result) + self.assertIn("refusing to reset", result.stderr) + + def test_native_mode_against_an_unmarked_database_never_drops(self): + self.mark_state() + result = self.relay(BUZZ_HARNESS_STATE_DIR=str(self.state), STUB_DATA_DIR=str(self.state / "postgres"), + STUB_COMMENT="") + self.assertNoReset(result) + + def test_the_harness_database_is_reset(self): + self.mark_state() + result = self.relay(BUZZ_HARNESS_STATE_DIR=str(self.state), STUB_DATA_DIR=str(self.state / "postgres"), + STUB_COMMENT="buzz-native-review-harness") + self.assertIn("DROP SCHEMA", self.statements()) + self.assertEqual(result.returncode, 3) # the stub aborts the script at the reset + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/native-review/tests/test_review_native.py b/tools/native-review/tests/test_review_native.py index a1424ebd139..a7cce4f3131 100644 --- a/tools/native-review/tests/test_review_native.py +++ b/tools/native-review/tests/test_review_native.py @@ -638,7 +638,9 @@ def test_interactive_window_is_placed_then_waits_for_web_accessibility(self): driver.request.side_effect = [ {"ok": True, "visible": True, "window_id": 7}, {"ok": True, "answered": False}, - {"ok": True, "moved": True}, + {"ok": True, "moved": True, "verified": True, "window_id": 7, + "before": {"x": -1016, "y": 36, "width": 1008, "height": 726}, + "after": {"x": 40, "y": 60, "width": 1008, "height": 726}}, {"ok": True, "answered": False}, {"ok": True, "ready": False}, {"ok": True, "answered": True}, @@ -653,6 +655,25 @@ def test_interactive_window_is_placed_then_waits_for_web_accessibility(self): "answer_privacy_prompt", "web_ready", "window_status"]) self.assertTrue(status["moved"]) self.assertEqual(status["bounds"]["x"], 40) + # The receipt records what was moved and where it ended up. + self.assertTrue(status["placement"]["verified"]) + self.assertEqual(status["placement"]["before"]["x"], -1016) + self.assertEqual(status["placement"]["after"]["x"], 40) + + def test_interactive_window_fails_when_placement_is_not_verified(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, + {"ok": True, "moved": True, "verified": False, + "before": {"x": -1016, "y": 36, "width": 1008, "height": 726}, + "after": {"x": -1016, "y": 36, "width": 1008, "height": 726}}, + ] + with mock.patch.object(review_native.time, "sleep"): + with self.assertRaisesRegex(review_native.HarnessError, "not verified"): + review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) def test_interactive_window_waits_for_the_accessibility_window_to_exist(self): driver = mock.Mock() From a207f23e46f53e074659c4abb9a24f5ae1b0b850 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 16:28:22 -0800 Subject: [PATCH 08/11] fix(native-review): do not hang on a trigger blocked by a privacy prompt A trigger child blocked on an unanswered privacy prompt can ignore SIGTERM, so answer-first-run-prompts waited on it forever. Escalate to SIGKILL, report a driver that could not run instead of exiting silently, and log the prompt text that was actually answered. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jude Edwards --- .../bin/answer-first-run-prompts | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/tools/native-review/bin/answer-first-run-prompts b/tools/native-review/bin/answer-first-run-prompts index 65b7d3f87a2..d6c58541752 100755 --- a/tools/native-review/bin/answer-first-run-prompts +++ b/tools/native-review/bin/answer-first-run-prompts @@ -22,29 +22,44 @@ if [[ ! -x "$DRIVER" ]]; then swift build -c release --package-path "$SCRIPT_DIR/swift" >/dev/null fi +# Stop a trigger child. A process blocked on an unanswered privacy prompt can ignore +# SIGTERM, so escalate rather than wait on it forever. +stop_trigger() { + kill "$1" 2>/dev/null || true + for _ in 1 2 3 4 5 6; do kill -0 "$1" 2>/dev/null || break; sleep 0.5; done + kill -9 "$1" 2>/dev/null || true + wait "$1" 2>/dev/null || true +} + # answer LABEL TRIGGER_NAME COMMAND... +# Starts the trigger, then answers whatever prompt the driver can positively identify +# as this run's own. The log line carries the prompt text that was actually answered, +# which may be an earlier trigger's prompt that was still on screen. answer() { local label="$1" trigger_name="$2" shift 2 "$@" >/dev/null 2>&1 & local trigger=$! - local pressed=0 skipped="" + local pressed=0 skipped="" failed="" for _ in $(seq 1 20); do - reply="$("$DRIVER" answer-privacy-prompt --expect "$trigger_name")" - if grep -Eq '"answered" ?: ?true' <<<"$reply"; then + if ! reply="$("$DRIVER" answer-privacy-prompt --expect "$trigger_name" 2>&1)"; then + failed="$reply" + elif grep -Eq '"answered" ?: ?true' <<<"$reply"; then pressed=1 - echo "[answer-first-run-prompts] $label: $reply" + echo "[answer-first-run-prompts] while triggering $label, answered: $reply" break + elif grep -Eq '"skipped" ?: ?\[ ?"' <<<"$reply"; then + skipped="$reply" fi - grep -Eq '"skipped" ?: ?\[ ?"' <<<"$reply" && skipped="$reply" sleep 0.5 done - kill "$trigger" 2>/dev/null || true - wait "$trigger" 2>/dev/null || true + stop_trigger "$trigger" if ((pressed)); then : elif [[ -n "$skipped" ]]; then echo "[answer-first-run-prompts] $label: a window was left alone because it could not be identified as this run's prompt: $skipped" + elif [[ -n "$failed" ]]; then + echo "[answer-first-run-prompts] $label: the driver could not run: $failed" else echo "[answer-first-run-prompts] $label: no prompt appeared (already answered, or not needed)" fi From 041c5ebffad90ef3026317ce698c450fef8d1f77 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 16:38:41 -0800 Subject: [PATCH 09/11] fix(native-review): recognise the responsible process of a detached review A privacy prompt names the process macOS holds responsible for the requester, not necessarily an ancestor. When a review is started detached (nohup, a remote exec that returns) the launcher is no longer in the parent chain, so the driver left the review's own microphone prompt alone and the app's web view froze. Count the driver's responsible process as one of the review's own. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jude Edwards --- tools/native-review/README.md | 6 ++++-- .../swift/Sources/BuzzNativeDriver/main.swift | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/tools/native-review/README.md b/tools/native-review/README.md index 04d7c3cabf7..0d1ab099f69 100644 --- a/tools/native-review/README.md +++ b/tools/native-review/README.md @@ -111,8 +111,10 @@ hold: the window belongs to the macOS system prompt agent (bundle id `com.apple.UserNotificationCenter`, executable under `/System/Library/CoreServices`); it is a system alert (`AXWindow`/`AXSystemDialog`, not a sheet or a document window); its text parses as a microphone, camera or Local Network prompt; the app -it names is one of this run's own processes (the driver's ancestry, the app under -review, or a trigger child passed with `--expect`); and exactly one button carries +it names is one of this run's own processes (the driver's ancestry, the process +macOS holds responsible for the driver, which is what a prompt names and which +survives a detached launch, the app under review, or a trigger child passed with +`--expect`); and exactly one button carries the expected title. It declines microphone and camera access (a review never needs them) and allows Local Network. A prompt from any other app, a sheet, or an alert from another process is never touched. diff --git a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift index f69eceb21fd..1ea11bc9d1b 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift @@ -613,6 +613,18 @@ func postText(_ text: String, pid: pid_t) throws { /// the driver's own ancestry (macOS names the responsible process, such as the /// agent that launched the run, or an interpreter), the reviewed app, and any /// `extra` names the caller launched on purpose (a trigger child). +/// The process macOS holds responsible for `pid`: the one a privacy prompt names. It is +/// fixed when the process is spawned, so unlike the parent chain it survives the +/// launcher exiting (a review started detached, for example under nohup). The symbol is +/// private to libSystem, so it is looked up at run time and its absence only narrows +/// what counts as this review's own process. +func responsiblePid(for pid: pid_t) -> pid_t? { + typealias Function = @convention(c) (pid_t) -> pid_t + guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "responsibility_get_pid_responsible_for_pid") else { return nil } + let responsible = unsafeBitCast(symbol, to: Function.self)(pid) + return responsible > 1 && responsible != pid ? responsible : nil +} + func reviewProcessNames(target: pid_t?, extra: [String]) -> [String] { var names = Set(extra) func add(pid: pid_t) { @@ -639,6 +651,7 @@ func reviewProcessNames(target: pid_t?, extra: [String]) -> [String] { pid = pid_t(info.pbi_ppid) hops += 1 } + if let responsible = responsiblePid(for: getpid()) { add(pid: responsible) } if let target { add(pid: target) } names.remove("") return Array(names) From 6c31ad99343faad06fe25d92d354a217e15cbff0 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Fri, 20 Nov 2026 16:48:50 -0800 Subject: [PATCH 10/11] test(native-review): use a neutral process name in prompt fixtures The fixtures named the launcher process of one particular workstation environment. Use a generic name; the tests only need some process that the review owns. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jude Edwards --- .../DriverSupportTests.swift | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift index 64d9cce027d..4743b6dcc68 100644 --- a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift +++ b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift @@ -68,7 +68,7 @@ import Testing // The real prompt, as the VM's accessibility tree shows it. private func systemPrompt( - text: String = "\u{201C}bloxlet\u{201D} would like to access the Microphone.", + text: String = "\u{201C}LauncherHost\u{201D} would like to access the Microphone.", buttons: [String] = ["Help", "Don\u{2019}t Allow", "Allow"], bundleID: String? = "com.apple.UserNotificationCenter", executable: String? = "/System/Library/CoreServices/UserNotificationCenter.app/Contents/MacOS/UserNotificationCenter", @@ -80,8 +80,8 @@ private func systemPrompt( } @Test func promptTextNamesTheKindAndTheApp() { - #expect(parsePrivacyPrompt(texts: ["\u{201C}bloxlet\u{201D} would like to access the Microphone."]) - == PrivacyPrompt(kind: .microphone, appName: "bloxlet")) + #expect(parsePrivacyPrompt(texts: ["\u{201C}LauncherHost\u{201D} would like to access the Microphone."]) + == PrivacyPrompt(kind: .microphone, appName: "LauncherHost")) #expect(parsePrivacyPrompt(texts: ["\"Terminal\" would like to access the Camera."]) == PrivacyPrompt(kind: .camera, appName: "Terminal")) #expect(parsePrivacyPrompt(texts: ["Allow \u{201C}Python\u{201D} to find devices on local networks?", "This will allow the app to discover"]) @@ -91,7 +91,7 @@ private func systemPrompt( } @Test func theRealMicrophonePromptIsDeclinedWhenItNamesAProcessOfTheReview() { - #expect(decidePrivacyPrompt(systemPrompt(), expectedApps: ["bloxlet", "Buzz Native Review"]) == .press("Don't Allow")) + #expect(decidePrivacyPrompt(systemPrompt(), expectedApps: ["LauncherHost", "Buzz Native Review"]) == .press("Don't Allow")) } @Test func theRealLocalNetworkPromptIsAllowedWhenItNamesAProcessOfTheReview() { @@ -102,7 +102,7 @@ private func systemPrompt( @Test func aPromptNamingAnotherAppIsNeverAnswered() { guard case .skip(let reason) = decidePrivacyPrompt(systemPrompt(text: "\u{201C}Zoom\u{201D} would like to access the Microphone."), - expectedApps: ["bloxlet", "Buzz Native Review"]) else { + expectedApps: ["LauncherHost", "Buzz Native Review"]) else { Issue.record("answered a prompt for another app"); return } #expect(reason.contains("Zoom")) @@ -117,7 +117,7 @@ private func systemPrompt( systemPrompt(executable: nil), systemPrompt(executable: "/System/Library/CoreServices/../../../tmp/evil"), ] { - guard case .skip = decidePrivacyPrompt(impostor, expectedApps: ["bloxlet"]) else { + guard case .skip = decidePrivacyPrompt(impostor, expectedApps: ["LauncherHost"]) else { Issue.record("answered a window the system prompt agent does not own: \(impostor)"); continue } } @@ -125,17 +125,17 @@ private func systemPrompt( @Test func aWindowThatIsNotASystemAlertIsNeverAnswered() { for other in [systemPrompt(role: "AXSheet"), systemPrompt(subrole: "AXStandardWindow"), systemPrompt(subrole: nil), systemPrompt(role: nil)] { - guard case .skip = decidePrivacyPrompt(other, expectedApps: ["bloxlet"]) else { + guard case .skip = decidePrivacyPrompt(other, expectedApps: ["LauncherHost"]) else { Issue.record("answered a window that is not a system dialog: \(other)"); continue } } } @Test func aPromptWithoutTheExpectedButtonOrWithDuplicatesIsNotAnswered() { - guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Help", "Allow"]), expectedApps: ["bloxlet"]) else { + guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Help", "Allow"]), expectedApps: ["LauncherHost"]) else { Issue.record("pressed a missing button"); return } - guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Don\u{2019}t Allow", "Don't Allow"]), expectedApps: ["bloxlet"]) else { + guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Don\u{2019}t Allow", "Don't Allow"]), expectedApps: ["LauncherHost"]) else { Issue.record("pressed an ambiguous button"); return } } From d3906362b25e70bba5cca547a6faa3ea94a07e15 Mon Sep 17 00:00:00 2001 From: Jude Edwards Date: Mon, 23 Nov 2026 11:44:52 -0800 Subject: [PATCH 11/11] feat(native-review): allow a caching mirror for the sherpa archive setup-macos-vm downloads the sherpa-onnx archive from GitHub releases by default. SHERPA_ONNX_DOWNLOAD_BASE now points the same path layout at a caching mirror, and the script logs the curl line, HTTP status and size. The bzip2 validation and SHERPA_ONNX_ARCHIVE_DIR are unchanged. Co-authored-by: Orbit Helper <9743d67196e296c93cc2958036615907e2e0b39128484b59b392cbb380edbb8b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jude Edwards --- tools/native-review/bin/setup-macos-vm | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tools/native-review/bin/setup-macos-vm b/tools/native-review/bin/setup-macos-vm index 6c97960b0b1..b34e509bfbb 100755 --- a/tools/native-review/bin/setup-macos-vm +++ b/tools/native-review/bin/setup-macos-vm @@ -9,7 +9,9 @@ # * No ffmpeg: installs it (video-share.mp4 finalization needs it). # * A TLS-intercepting proxy that sherpa-onnx-sys's build script (rustls with # bundled roots) rejects with `UnknownIssuer`: prefetches the archive with -# curl and exports SHERPA_ONNX_ARCHIVE_DIR. +# curl and exports SHERPA_ONNX_ARCHIVE_DIR. The download base defaults to the +# project's GitHub releases; set SHERPA_ONNX_DOWNLOAD_BASE to fetch the same +# path layout through a caching mirror instead. # * pub.dev blocked (iOS/Flutter only): when PUB_HOSTED_URL is set in the # environment running this script, it is recorded in env.sh so a later # review-ios run receives the mirror. No mirror URL is hard-coded here. @@ -189,8 +191,11 @@ sherpa_version="$(awk '/^name = "sherpa-onnx-sys"$/ {getline; gsub(/[^0-9.]/, "" sherpa_archive="sherpa-onnx-v${sherpa_version}-osx-arm64-static-lib.tar.bz2" if [[ ! -s "$STATE_DIR/sherpa/$sherpa_archive" ]] || ! bzip2 -t "$STATE_DIR/sherpa/$sherpa_archive" 2>/dev/null; then log "downloading $sherpa_archive" - curl -fsSL --retry 3 -o "$STATE_DIR/sherpa/$sherpa_archive.part" \ - "https://github.com/k2-fsa/sherpa-onnx/releases/download/v${sherpa_version}/${sherpa_archive}" + sherpa_url="${SHERPA_ONNX_DOWNLOAD_BASE:-https://github.com/k2-fsa/sherpa-onnx/releases/download}/v${sherpa_version}/${sherpa_archive}" + log "curl -fsSL --retry 3 $sherpa_url" + sherpa_status="$(curl -fsSL --retry 3 -o "$STATE_DIR/sherpa/$sherpa_archive.part" -w '%{http_code}' "$sherpa_url")" \ + || die "could not download $sherpa_url" + log "HTTP $sherpa_status, $(wc -c < "$STATE_DIR/sherpa/$sherpa_archive.part" | tr -d ' ') bytes" bzip2 -t "$STATE_DIR/sherpa/$sherpa_archive.part" || die "sherpa archive is not valid bzip2" mv "$STATE_DIR/sherpa/$sherpa_archive.part" "$STATE_DIR/sherpa/$sherpa_archive" fi