feat(util): move screenshot pixel work into a Rust addon, off the JavaScript thread (ENG-1543)

KD
9h ago
+25934-642

[!IMPORTANT]
Before the first release that includes this PR: a maintainer publishes the nine new packages once by hand, @e2e-dev/util and @e2e-dev/util-<platform> for eight platforms, and connects each one to release.yml through npm Trusted Publishing (CONTRIBUTING.md, "npm Trusted Publishing"). A hand-run canary (pnpm run canary and canary:publish) publishes all nine. Until then, the publish step of the nightly fails.

What

@e2e-dev/core and @e2e-dev/mobile no longer process screenshot pixels on the JavaScript thread. A new package, @e2e-dev/util, does the work in Rust on a native thread pool: PNG decode and encode, box resampling, crop, box painting, and a pixelmatch 8 port. Every call returns a Promise. Output is byte for byte what @napi-rs/image and pixelmatch gave before, so stored screenshots do not change. The pixelmatch counts match pixelmatch on Node 24 and later bit for bit; on Node 22 a pixel pair at the threshold can count differently (step 2). @napi-rs/image and pixelmatch are no longer runtime dependencies.

npm installs the addon with @e2e-dev/util from one platform package for each of eight platforms: macOS 13 or later on arm64 and x64, Linux x64 and arm64 with glibc 2.28 or later (the oldest Node 22 and 24 run on) or with musl, and Windows x64 and arm64. @napi-rs/image also had builds for FreeBSD x64, 32-bit Arm Linux, 32-bit Windows, and Android arm64; this has none. On any other platform, toHaveScreenshot, locator.screenshot(), and an agent screenshot that the runner has to resize fail with IMAGE_CODEC_UNAVAILABLE, and the message names the platforms that have a build. A plain app.screenshot() still works there. A config that uses @e2e-dev/mobile fails to load, because that engine loads the addon when it loads. Every pull request builds, checks, and loads all eight on runners of those platforms, and release.yml publishes them.

Why

ENG-1543 (the RFC): every pixel step in e2e blocks the event loop, in a runner worker and in processes e2e does not own (openHost, e2e mcp, @e2e-dev/core launch). Before this change, a 2560x1440 model downscale held the JavaScript thread for about 20 ms, a toHaveScreenshot capture for about 20 ms, and a masked phone screenshot for about 28 ms. With this change, each holds it for under 1 ms. On Linux x64, npm install e2e also shrinks from 61.2 MiB to 40.6 MiB. The numbers are under ## Verified.

How it works

flowchart LR
  JS["@e2e-dev/core / @e2e-dev/mobile"] -->|"Promise"| U["@e2e-dev/util (loader, TS API)"]
  U -->|"first call loads"| N["e2e-util-napi (.node)"]
  N -->|"tokio blocking thread, one per core"| R["e2e-util (pure Rust)"]
  N -->|"NativeImage + adjust_external_memory"| V8[V8 heap accounting]
  1. Two crates join the root Cargo workspace beside e2e-desktop-napi, on its one Cargo.lock and its rust-toolchain.toml (1.100.0). crates/e2e-util is plain Rust with no binding dependency (crates/e2e-util/src/image/). The root Cargo.toml gets [workspace.package] and workspace lints, which the two util crates opt into. The desktop crate keeps its own fields and opts out of the lints with an empty [lints] table.

  2. JavaScript number semantics are kept where the old code depended on them. Math.round breaks a tie toward +∞ (crates/e2e-util/src/image/js.rs:6), and a Uint8Array store truncates and wraps. Math.cbrt is a port of V8's fdlibm version (FreeBSD's s_cbrt.c, whose notice the source and every package NOTICE carry), and a test checks a hash of its output against Node. pixelmatch's sRGB table is the one V8 computes in Node 24 and 26 (lin_table.rs), because V8's ** and the platform pow can differ in the last bit. Node 22's V8 rounds 32 of the 256 entries one bit the other way, so pixelmatch on Node 22 can count a pixel pair whose distance is within that rounding of the threshold differently from the port. No single table matches both, and the crate docs, README, and AGENTS.md say so. The pixelmatch port (compare.rs) does the floating-point steps in pixelmatch's order and reads both images through a view of their bytes (compare.rs:110), not a copy.

  3. Every image the crate makes is checked against MAX_IMAGE_BYTES (512 MiB, the image crate's default limit) before its buffer is allocated: the decode frame and RGBA buffers from the PNG header, the resample target, and the copy that NativeImage.fromRgba makes (Rgba::copy_of, crates/e2e-util/src/image/mod.rs:35). Rgba's fields are private, so Rgba::new and Rgba::copy_of, which check that the pixels fill the size, are the only way to make one outside the crate. A failed allocation would abort the host process, where @napi-rs/image and a JavaScript Uint8Array threw. The binding reads sizes as numbers and refuses anything that is not whole pixels from 1 to u32::MAX.

  4. PNG encoding uses the png crate with its zlib-rs feature at Balanced with an adaptive filter (codec.rs). This gives the same bytes as @napi-rs/image. With the default deflate backend, encoding at that level took twice as long.

  5. crates/e2e-util-napi/src/lib.rs is the NAPI-RS binding.

    • Input bytes are copied on the JavaScript thread, so the caller may reuse its buffer while the work runs.
    • Each call waits for a semaphore permit (one per core), runs on a tokio spawn_blocking thread, and resolves a Promise (blocking).
    • init_runtime (lib.rs:19) gives NAPI-RS a tokio runtime with one scheduler thread, so loading the addon adds one thread, not one per core. NAPI-RS takes that runtime once per process: a worker_threads worker that loads the addon after the first environment has gone gets NAPI-RS's default runtime. That costs idle threads only, and the runner's workers are child processes, so this stays as it is.
    • A decoded image stays native as NativeImage. It reports its size to V8 when created (adopt) and removes it in custom_finalize. The TypeScript wrapper references its images after each await, so a wrapper is not collected while a call still reads its pixels (packages/util/src/index.ts).
    • processPng decodes, resizes, crops, and paints in one call, so no pixels cross into JavaScript between the steps (process).
  6. packages/util loads the addon on the first call, not on import (binding(), packages/util/src/native.ts:137). It tries the checkout build util.<platform>.node first, then @e2e-dev/util-<platform>.

    • On Linux it tells glibc from musl with process.report, with excludeNetwork set for the call (native.ts:109). Without it, the report looks up every open socket: 63 s with 50 sockets open in Docker, 2 ms with the flag.
    • When nothing loads, NativeUtilUnavailableError keeps the most telling failure as its cause (native.ts:161): a build that was there and failed to load, then a platform package that is there without its .node, then a package that is not there. notInstalled is true only in the last case, and only then does the message tell you to install the package.
    • pnpm --filter @e2e-dev/util build:native builds the addon through the shared native scripts: scripts/native/addons.ts has a util entry with the eight NAPI-RS targets the loader names, and build-native.ts names a Linux host by its libc (linux-x64-gnu), as the loader does, where it used linux-x64. The entry has no types file: packages/util/src/native.ts types the loader by hand, so types and typeImports are optional in AddonSpec, and build-native.ts util --types fails before cargo runs.
  7. packages/core/src/internal/image.ts is now a thin async layer. Native work cannot be stopped once it starts, so every async call takes the signal that ends the wait for it as a required argument and races the native call with it (native, image.ts:32). A caller that leaves the signal out is a type error, and one with nothing to stop it passes NEVER_ABORTS by name. The layer also turns NativeUtilUnavailableError into IMAGE_CODEC_UNAVAILABLE (codecError, image.ts:50), with the install advice from before, now naming @e2e-dev/util's package, when the package is not installed, and the load failure otherwise. The callers become async:

    • the model downscale is one processPng call (agent/pixels.ts:49), so pixelsForModel and its callers in observation-feed.ts and invocation.ts await it. pixelsForModel passes the step's signal (agent/observation.ts:386). A judgment's recordPixels adds a timer for its deadline's remaining time to that signal and fails with STEP_TIMEOUT when the timer fires first (agent/invocation.ts:283);
    • a toHaveScreenshot capture reads the size from the PNG header, works out the crop, reads the masks, then makes one processPng call (packages/e2e/src/expect/screenshot-capture.ts:89). When the locator is outside the screenshot, it decodes the PNG first, so a cut-off file fails as unreadable, as before. The stored image, every poll's comparison, and the diff picture stay native (screenshot.ts). Each of these calls ends with the attempt's cancellation or with an enclosing expect.poll read's;
    • locator.screenshot() reads the size from the header, then crops and encodes in one call. When the box rounds to no pixels it decodes the bytes first (element-screenshot.ts:81), so a file that is only a valid header fails as UNSUPPORTED_CAPABILITY, as before, and not as LOCATOR_NOT_FOUND (locator/element-screenshot.ts).
    • Before, these steps ran synchronously, so a cancelled attempt could not get between the pixel work and the file write. Now the attempt's signal ends the wait (element-screenshot.ts:86, screenshot.ts:190 and :280), so a cancelled locator.screenshot() or toHaveScreenshot writes no file. A caller that turns a failed decode into its own error passes any E2EError on, so a cancellation is never reported as a bad PNG.
  8. @e2e-dev/mobile's maskPng rounds each rectangle outward and paints it through processPng (packages/mobile/src/png.ts:22). The engine races the mask with the operation's cancellation only, not its device input budget (raceAbort at surface.ts:2109 and :2141), so a cancelled screenshot keeps no file. The addon still loads when the engine loads, as @napi-rs/image did, so masking cannot fail later than import.

  9. CI and release prep:

    • pnpm build runs cargo build first. The CI images have rustup, which installs the pinned toolchain. CONTRIBUTING.md and AGENTS.md say the build needs rustup and build util before core in the focused commands.
    • spec.yml's check job runs clippy -D warnings and cargo test for the two util crates on Linux. The macOS native job checks the whole workspace, and its desktop loader step builds util's types before core.
    • The Bun job builds the addon and runs a PNG round trip and a comparison through it on each Bun version (packages/util/tests/runtime-smoke.mjs).
    • The microbenchmark worktrees build @e2e-dev/util's types before core.
    • filters.yml lists util's two crates, the shared Rust inputs, and .cargo/config.toml, but not the desktop crate, which no benchmark builds. actionlint.yaml lists the new runner labels.
    • The package NOTICE and crates/e2e-util/LICENSE-pixelmatch carry pixelmatch's ISC notice.
    • The Electron jobs, which main added after this branch began, build util's addon and util before core.
  10. Platform packages, the same pattern as @e2e-dev/desktop-darwin-*:

    • packages/util/npm/<platform> holds one package for each util target in scripts/native/addons.ts. Each is an optional dependency of @e2e-dev/util, with os, cpu, and (on Linux) libc set. All nine packages are in one changesets fixed group.
    • Each package ships THIRD_PARTY_LICENSES.md (pnpm --filter @e2e-dev/util licenses:native, which the check job compares with Cargo.lock; napi's license is vendored under crates/e2e-util-napi/licenses). Its prepublishOnly (check-native.ts) refuses to publish without an addon stamped with its version.
    • @e2e-dev/util's tarball no longer ships a checkout build. packages/util/tests/platforms.test.ts checks that the loader's platform list, the npm/ directories, the optional dependencies, and each manifest's os/cpu/libc agree. It also checks the error on a platform with no build. The three loader*.test.ts files check which failure the error reports.
    • .cargo/config.toml makes the musl builds link the musl that their Node runs on: with a static C runtime, rustc drops a cdylib. It makes the MSVC builds link the C runtime statically, so Windows needs no Visual C++ Redistributable.
  11. .github/workflows/util-native.yml builds the eight addons, each on a runner of its own platform:

    • glibc builds in a digest-pinned manylinux_2_28 container (AlmaLinux 8, glibc 2.28) on an x64 runner and an arm64 runner (.github/scripts/build-glibc.sh), which also loads each build there. check-build.ts refuses a build that needs glibc newer than 2.28. Built on Ubuntu 22.04, the addon needed GLIBC_2.34, which Debian 11, Ubuntu 20.04, and RHEL 8 do not have;
    • musl builds in a digest-pinned node:26-alpine container on an x64 runner and an arm64 runner (.github/scripts/build-musl.sh);
    • Windows builds on GitHub-hosted windows-latest and windows-11-arm;
    • macOS builds on the Blacksmith Mac, with the Intel build loaded under Rosetta (load-x64-addon now takes a probe script).

    scripts/native/check-build.ts reads each file's format, architecture, and C library, and its newest glibc symbol version. scripts/native/probe-util.ts then round-trips a pixel through the addon in that platform's Node. .github/actions/rust-toolchain now pins rustup-init by SHA-256 for Linux and Windows too.

  12. The callers of that workflow:

    • spec.yml, as util-native, which spec gate needs. It is skipped on agent-device compatibility runs, where examples.yml would upload the same artifact names into the same run.
    • release.yml. The release and nightly jobs need it and put the builds in the platform packages with place-native.ts util, after the version step and before publishing. place-native.ts also finds builds one directory down, where gh run download leaves them, leaves an addon in place when it is pointed at the platform packages' own directory, and with --dry-run it only checks that all eight are there.
    • examples.yml. It packs the eight platform packages, and example-packages serves each one by override. npm skips the packages for other platforms by os and cpu.
    • install-smoke.ts, which packs this machine's platform package from a copy, with the addon that pnpm run build built, then loads it through e2e and core in the installed project, importing it by file URL.
    • pnpm run canary, which takes the eight builds from a CI run's util-native-* artifacts (UTIL_NATIVE_DIR), because a Mac cannot build all of them. It stops before versioning if one is missing.

Not in this PR:

  • @e2e-dev/decision's zoom (nearest-neighbor sampling, which needs new crate functions);
  • @e2e-dev/web's readPngSize, and @e2e-dev/desktop.

Issue

ENG-1543

Verified

Ran it locally: yes, on macOS arm64, and the glibc builds in Docker. The Windows, musl, and Rosetta builds run only in this PR's CI (util-native / <platform>). On 7fefac78e, all eight built, passed check-build.ts, and loaded there, and install (11), install (12), bun (1.4.3), and bun (latest) passed.

glibc floor. build-glibc.sh in the pinned manylinux_2_28 images built both glibc addons, check-build.ts passed them, and probe-util.ts round-tripped a pixel in the container's glibc 2.28 (x64 under emulation). Then each build loaded in node:22-bullseye (Debian 11):

node:22-bullseye, glibc 2.31built on Ubuntu 22.04 (CI, 7fefac78e)built in manylinux_2_28 (this PR)
newest glibc symbol version2.342.28
arm64version 'GLIBC_2.33' not foundloads and round-trips a pixel
x64not runloads and round-trips a pixel

Packaging, as a user installs it. An npm scratch project installed this head's packed e2e, @e2e-dev/core, @e2e-dev/web, and @e2e-dev/util, with all eight platform packages served by override (--legacy-peer-deps, because main's @e2e-dev/web asks for an e2e newer than the unreleased 0.25.0). npm installed only @e2e-dev/util-darwin-arm64, and the @e2e-dev/util tarball holds no .node. A web test there ran toHaveScreenshot through the installed CLI:

run 1: ASSERTION_FAILED  no stored screenshot at tests/shot.e2e.ts-snapshots/box-web-darwin.png; wrote this run's there. Look at it, commit it, and run again
run 2: ✓ |web| tests/shot.e2e.ts > stores and compares a screenshot 468ms

With node_modules/@e2e-dev/util-darwin-arm64 removed, the same test fails with the documented advice:

IMAGE_CODEC_UNAVAILABLE: e2e reads and writes screenshots with @e2e-dev/util, and its native build for darwin-arm64 (@e2e-dev/util-darwin-arm64) is not installed. npm skips it with --omit=optional, ...

Checks. Every pnpm check step passed: lint, fallow, typecheck, error codes, peer ranges, changeset bumps, examples, benchmark coverage, install scripts, plugins, MCP server, and docs. Also passed: pnpm test:scripts (280), the util tests (29), the core tests (137), the e2e unit tests (5179), the mobile unit tests (717, the masking tests among them), the e2e screenshot and vision integration tests (58), cargo fmt, clippy -D warnings, and cargo test for the workspace, and native-licenses.ts util --check and desktop --check. The ten cancellation and deadline tests mock @e2e-dev/util under internal/image.ts. They cover every wait in toHaveScreenshot (stored decode, capture resample, compare, encode), the element crop, the model downscale, and a judgment's deadline through agent.assert. With the race removed from native, all ten fail. With readStored rethrowing only codec errors, the stored-decode case fails as INVALID_ARGUMENT.

Equivalence. packages/util/tests/equivalence.test.ts runs the old JavaScript (tests/reference.ts) next to the addon. Every test requires identical bytes. The inputs:

  • the 79 tracked PNGs;
  • more than 200 generated PNGs covering every color type, bit depth, palette, transparent color, and Adam7 interlacing;
  • headless Chromium screenshots (1280x720 at 1x and 2x, 1170x2532 at 3x) and changed versions of them: one word changed, a block moved 1 px, a translucent overlay.

The checks are decode, resample, crop and fill at fractional, negative, outside, and NaN coordinates, encode (through NativeImage.encode() and through processPng's PNG output after a resize and after a crop with a fill), and pixelmatch counts and diff pictures at 6 thresholds. The anti-aliasing path is asserted to run. tests/limits.test.ts checks the size refusals. packages/mobile/tests/unit/png-equivalence.test.ts holds masking to the previous code in 120 random cases.

Pixel work, old vs new (pnpm --filter @e2e-dev/util bench, M5 Pro, Node 26.13.1, 30 runs, each side in its own process, load average 9 on 18 cores; times in ms; "JS thread" is event-loop busy time per call, GC included; "burst" is 8 calls started at once). The old mask is mobile's previous code, copied into packages/util/tests/mobile-mask-before.ts:

Workoldnewold JS threadnew JS threadold burst of 8new burst of 8
decode 2560x14408.997.199.371.0675.013.5
encode 2560x144024.922.625.40.6019226.2
model downscale 2560x1440 to 768x43219.512.420.30.4716716.4
toHaveScreenshot capture 2560x1440 to 1280x720, 3 masks18.710.320.50.5315615.9
compare 1280x720, identical0.640.170.980.183.920.26
compare 1280x720, one word changed1.830.611.950.2013.41.09
diff picture 1280x720 and encode10.96.5210.90.5271.98.91
mask a 1170x2532 phone screenshot27.426.027.90.6921232.8

The longest event-loop stall per case went from 2.7 to 31.9 ms to 1.6 to 3.8 ms. Peak RSS for 120 model downscales in a row was 3,529 MB before and 221 MB after when the old calls do not yield between them, and 351 MB before and 220 MB after when they do.

Install size on Linux x64 (glibc). Both sides install e2e@0.25.0 from npm with npm install --os=linux --cpu=x64 --libc=glibc. "After" overrides @e2e-dev/core with this head's packed core, and the platform package carries the addon that CI built for 7fefac78e on Ubuntu 22.04 (util-native / linux-x64-gnu, 1,062,936 bytes). The manylinux_2_28 build of this head is 1,063,360 bytes, 424 more. Main's core has the same dependencies as the published 0.25.0. Sizes are the bytes of the files in node_modules:

before (main)after (this PR)change
Image packages on disk22,840,167 B (21.78 MiB)1,229,999 B (1.17 MiB)-94.6%
Image packages as downloaded (.tgz)8,860,064 B549,061 B-93.8%
Whole node_modules for npm install e2e64,128,206 B (61.16 MiB), 47 packages42,577,476 B (40.61 MiB), 45 packages-20.55 MiB (-33.6%)

The image packages are, before: @napi-rs/image 78,092 B, @napi-rs/image-linux-x64-gnu 22,075,179 B, pixelmatch 36,795 B, and pngjs 650,101 B. After: @e2e-dev/util 33,284 B and @e2e-dev/util-linux-x64-gnu 1,196,715 B (the addon, its notices, and its license). @e2e-dev/mobile also used to depend on @napi-rs/image, so a project that installs it saves the same amount. On macOS arm64, the addon is 947 KB, where @napi-rs/image's binding is 15 MiB.

End to end, the testbed's screenshot suites, main vs this PR:

bench-ab: aaf92318 (merge base with origin/main) vs 7fefac78

apps/testbed: e2e run --workers 1 tests/visual.e2e.ts tests/screenshot.e2e.ts. 8 pairs in random order, resolved after 8 pairs. Threshold ±3% and 10 ms. darwin arm64, Apple M5 Pro x18, Node 26.13.1, load 10.1.

Behavior

Every test ran the same steps with the same outcome on every run of both builds.

Timings

Metricbase median (IQR)head median (IQR)change (95% CI)verdict
wall (process)9.72 s (9.57 s-10.00 s)9.68 s (9.41 s-10.22 s)-1.3% (-2.6% to +1.9%)same
suite (sum of attempts)8.86 s (8.73 s-9.15 s)8.89 s (8.69 s-9.33 s)-1.2% (-2.9% to +2.5%)same
action (events)390 ms (377 ms-407 ms)397 ms (380 ms-434 ms)+0.9% (-3.6% to +5.8%)same, under the floor
step app.screenshot1.82 s (1.75 s-1.95 s)1.78 s (1.74 s-1.85 s)-2.6% (-7.1% to +4.0%)unresolved
step browser.goto875 ms (839 ms-940 ms)910 ms (838 ms-941 ms)+0.5% (-3.3% to +6.5%)same, under the floor
step expect.toHaveScreenshot839 ms (813 ms-944 ms)835 ms (787 ms-887 ms)-5.7% (-9.5% to +1.9%)unresolved
step app.open316 ms (307 ms-336 ms)337 ms (322 ms-390 ms)+1.7% (-3.0% to +26.7%)same, under the floor
step locator.screenshot182 ms (178 ms-212 ms)182 ms (179 ms-201 ms)+0.6% (-8.2% to +7.2%)same, under the floor
step expect.not.toHaveScreenshot82 ms (81 ms-85 ms)80 ms (79 ms-88 ms)-0.6% (-9.1% to +21.3%)same, under the floor
step browser.evaluate80 ms (71 ms-85 ms)69 ms (65 ms-71 ms)-15.8% (-24.7% to -2.8%)unresolved
step locator.pressSequentially67 ms (63 ms-69 ms)72 ms (67 ms-75 ms)+9.9% (-10.1% to +23.4%)same, under the floor
step expect.toBeVisible56 ms (54 ms-59 ms)58 ms (55 ms-61 ms)+2.4% (-3.4% to +11.1%)same, under the floor
step locator.focus44 ms (43 ms-47 ms)49 ms (44 ms-49 ms)+3.4% (-4.7% to +8.9%)same, under the floor
step expect.toBeAttached10 ms (9 ms-12 ms)10 ms (9 ms-11 ms)0.0% (-18.2% to +25.0%)same
step browser.setViewport2 ms (0 ms-3 ms)1 ms (1 ms-2 ms)-50.0% (-75.0% to 0.0%)same, under the floor
step browser.route1 ms (1 ms-1 ms)1 ms (1 ms-1 ms)0.0% (0.0% to +100.0%)same

Counters

Every counter matched on every run of both builds.

The suite time does not change here (-1.2%, 95% CI -2.9% to +2.5%; the load average was 10 on 18 cores, so the step timings are noisy): the testbed's screenshots are 1280x720 at 1x, and poll intervals take most of the time. The gain is JavaScript-thread time, which a large capture, parallel workers, or a host process (openHost, e2e mcp) turns into wall time.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added native image processing for PNG decoding, encoding, resizing, cropping, masking, screenshot comparison, and diff generation.
    • Added native utility support for macOS, Linux, and Windows across supported architectures.
  • Bug Fixes
    • Improved handling of invalid or truncated PNGs, oversized images, and unavailable image support.
    • Image processing now supports cancellation and respects operation deadlines.
  • Documentation
    • Added setup, platform support, and licensing information for the utility package.