Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions desktop/src/testing/nativeReviewSemanticProbe.test.mjs
Original file line number Diff line number Diff line change
@@ -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,
);
});
38 changes: 28 additions & 10 deletions desktop/src/testing/nativeReviewSemanticProbe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>(
Expand Down Expand Up @@ -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 } : {}),
Expand All @@ -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;
Expand Down
55 changes: 45 additions & 10 deletions scripts/start-isolated-test-relay.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
#
# 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
# 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

Expand Down Expand Up @@ -69,12 +74,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
Expand All @@ -86,13 +100,29 @@ 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
# 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
Expand Down Expand Up @@ -141,8 +171,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} \
Expand All @@ -163,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
Expand Down
62 changes: 62 additions & 0 deletions tools/native-review/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,68 @@ 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 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
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. 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 (`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 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.

`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

```bash
Expand Down
74 changes: 74 additions & 0 deletions tools/native-review/bin/answer-first-run-prompts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#!/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.
#
# 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
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

# 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="" failed=""
for _ in $(seq 1 20); do
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] while triggering $label, answered: $reply"
break
elif grep -Eq '"skipped" ?: ?\[ ?"' <<<"$reply"; then
skipped="$reply"
fi
sleep 0.5
done
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
}

answer "Local Network" dns-sd dns-sd -B _services._dns-sd._udp local.
if command -v ffmpeg >/dev/null 2>&1; then
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"
fi
45 changes: 45 additions & 0 deletions tools/native-review/bin/check-harness-database
Original file line number Diff line number Diff line change
@@ -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)"
Loading