feat(util): move screenshot pixel work into a Rust addon, off the JavaScript thread (ENG-1543)
[!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]
-
Two crates join the root Cargo workspace beside
e2e-desktop-napi, on its oneCargo.lockand itsrust-toolchain.toml(1.100.0).crates/e2e-utilis plain Rust with no binding dependency (crates/e2e-util/src/image/). The rootCargo.tomlgets[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. -
JavaScript number semantics are kept where the old code depended on them.
Math.roundbreaks a tie toward +∞ (crates/e2e-util/src/image/js.rs:6), and aUint8Arraystore truncates and wraps.Math.cbrtis a port of V8's fdlibm version (FreeBSD'ss_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 platformpowcan 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. -
Every image the crate makes is checked against
MAX_IMAGE_BYTES(512 MiB, theimagecrate's default limit) before its buffer is allocated: the decode frame and RGBA buffers from the PNG header, the resample target, and the copy thatNativeImage.fromRgbamakes (Rgba::copy_of,crates/e2e-util/src/image/mod.rs:35).Rgba's fields are private, soRgba::newandRgba::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/imageand a JavaScriptUint8Arraythrew. The binding reads sizes as numbers and refuses anything that is not whole pixels from 1 tou32::MAX. -
PNG encoding uses the
pngcrate with itszlib-rsfeature atBalancedwith 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. -
crates/e2e-util-napi/src/lib.rsis 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_blockingthread, 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: aworker_threadsworker 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 incustom_finalize. The TypeScript wrapper references its images after eachawait, so a wrapper is not collected while a call still reads its pixels (packages/util/src/index.ts). processPngdecodes, resizes, crops, and paints in one call, so no pixels cross into JavaScript between the steps (process).
-
packages/utilloads the addon on the first call, not on import (binding(),packages/util/src/native.ts:137). It tries the checkout buildutil.<platform>.nodefirst, then@e2e-dev/util-<platform>.- On Linux it tells glibc from musl with
process.report, withexcludeNetworkset 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,
NativeUtilUnavailableErrorkeeps 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.notInstalledis true only in the last case, and only then does the message tell you to install the package. pnpm --filter @e2e-dev/util build:nativebuilds the addon through the shared native scripts:scripts/native/addons.tshas autilentry with the eight NAPI-RS targets the loader names, andbuild-native.tsnames a Linux host by its libc (linux-x64-gnu), as the loader does, where it usedlinux-x64. The entry has notypesfile:packages/util/src/native.tstypes the loader by hand, sotypesandtypeImportsare optional inAddonSpec, andbuild-native.ts util --typesfails before cargo runs.
- On Linux it tells glibc from musl with
-
packages/core/src/internal/image.tsis 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 passesNEVER_ABORTSby name. The layer also turnsNativeUtilUnavailableErrorintoIMAGE_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
processPngcall (agent/pixels.ts:49), sopixelsForModeland its callers inobservation-feed.tsandinvocation.tsawait it.pixelsForModelpasses the step's signal (agent/observation.ts:386). A judgment'srecordPixelsadds a timer for its deadline's remaining time to that signal and fails withSTEP_TIMEOUTwhen the timer fires first (agent/invocation.ts:283); - a
toHaveScreenshotcapture reads the size from the PNG header, works out the crop, reads the masks, then makes oneprocessPngcall (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 enclosingexpect.pollread'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 asUNSUPPORTED_CAPABILITY, as before, and not asLOCATOR_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:190and:280), so a cancelledlocator.screenshot()ortoHaveScreenshotwrites no file. A caller that turns a failed decode into its own error passes anyE2EErroron, so a cancellation is never reported as a bad PNG.
- the model downscale is one
-
@e2e-dev/mobile'smaskPngrounds each rectangle outward and paints it throughprocessPng(packages/mobile/src/png.ts:22). The engine races the mask with the operation's cancellation only, not its device input budget (raceAbortatsurface.ts:2109and:2141), so a cancelled screenshot keeps no file. The addon still loads when the engine loads, as@napi-rs/imagedid, so masking cannot fail later than import. -
CI and release prep:
pnpm buildrunscargo buildfirst. 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 runsclippy -D warningsandcargo testfor the two util crates on Linux. The macOSnativejob 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.ymllists util's two crates, the shared Rust inputs, and.cargo/config.toml, but not the desktop crate, which no benchmark builds.actionlint.yamllists the new runner labels.- The package NOTICE and
crates/e2e-util/LICENSE-pixelmatchcarry pixelmatch's ISC notice. - The Electron jobs, which main added after this branch began, build util's addon and util before core.
-
Platform packages, the same pattern as
@e2e-dev/desktop-darwin-*:packages/util/npm/<platform>holds one package for eachutiltarget inscripts/native/addons.ts. Each is an optional dependency of@e2e-dev/util, withos,cpu, and (on Linux)libcset. All nine packages are in one changesetsfixedgroup.- Each package ships
THIRD_PARTY_LICENSES.md(pnpm --filter @e2e-dev/util licenses:native, which the check job compares withCargo.lock; napi's license is vendored undercrates/e2e-util-napi/licenses). ItsprepublishOnly(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.tschecks that the loader's platform list, thenpm/directories, the optional dependencies, and each manifest'sos/cpu/libcagree. It also checks the error on a platform with no build. The threeloader*.test.tsfiles check which failure the error reports..cargo/config.tomlmakes 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.
-
.github/workflows/util-native.ymlbuilds the eight addons, each on a runner of its own platform:- glibc builds in a digest-pinned
manylinux_2_28container (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.tsrefuses a build that needs glibc newer than 2.28. Built on Ubuntu 22.04, the addon neededGLIBC_2.34, which Debian 11, Ubuntu 20.04, and RHEL 8 do not have; - musl builds in a digest-pinned
node:26-alpinecontainer on an x64 runner and an arm64 runner (.github/scripts/build-musl.sh); - Windows builds on GitHub-hosted
windows-latestandwindows-11-arm; - macOS builds on the Blacksmith Mac, with the Intel build loaded under Rosetta (
load-x64-addonnow takes a probe script).
scripts/native/check-build.tsreads each file's format, architecture, and C library, and its newest glibc symbol version.scripts/native/probe-util.tsthen round-trips a pixel through the addon in that platform's Node..github/actions/rust-toolchainnow pins rustup-init by SHA-256 for Linux and Windows too. - glibc builds in a digest-pinned
-
The callers of that workflow:
spec.yml, asutil-native, whichspec gateneeds. It is skipped on agent-device compatibility runs, whereexamples.ymlwould 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 withplace-native.ts util, after the version step and before publishing.place-native.tsalso finds builds one directory down, wheregh run downloadleaves them, leaves an addon in place when it is pointed at the platform packages' own directory, and with--dry-runit only checks that all eight are there.examples.yml. It packs the eight platform packages, andexample-packagesserves each one by override. npm skips the packages for other platforms byosandcpu.install-smoke.ts, which packs this machine's platform package from a copy, with the addon thatpnpm run buildbuilt, 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'sutil-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'sreadPngSize, 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.31 | built on Ubuntu 22.04 (CI, 7fefac78e) | built in manylinux_2_28 (this PR) |
|---|---|---|
| newest glibc symbol version | 2.34 | 2.28 |
| arm64 | version 'GLIBC_2.33' not found | loads and round-trips a pixel |
| x64 | not run | loads 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 (5154), the mobile unit tests (712, 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 seven cancellation and deadline tests mock @e2e-dev/util under internal/image.ts; with the race removed from native, all seven fail.
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:
| Work | old | new | old JS thread | new JS thread | old burst of 8 | new burst of 8 |
|---|---|---|---|---|---|---|
| decode 2560x1440 | 8.99 | 7.19 | 9.37 | 1.06 | 75.0 | 13.5 |
| encode 2560x1440 | 24.9 | 22.6 | 25.4 | 0.60 | 192 | 26.2 |
| model downscale 2560x1440 to 768x432 | 19.5 | 12.4 | 20.3 | 0.47 | 167 | 16.4 |
toHaveScreenshot capture 2560x1440 to 1280x720, 3 masks | 18.7 | 10.3 | 20.5 | 0.53 | 156 | 15.9 |
| compare 1280x720, identical | 0.64 | 0.17 | 0.98 | 0.18 | 3.92 | 0.26 |
| compare 1280x720, one word changed | 1.83 | 0.61 | 1.95 | 0.20 | 13.4 | 1.09 |
| diff picture 1280x720 and encode | 10.9 | 6.52 | 10.9 | 0.52 | 71.9 | 8.91 |
| mask a 1170x2532 phone screenshot | 27.4 | 26.0 | 27.9 | 0.69 | 212 | 32.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 disk | 22,840,167 B (21.78 MiB) | 1,229,999 B (1.17 MiB) | -94.6% |
Image packages as downloaded (.tgz) | 8,860,064 B | 549,061 B | -93.8% |
Whole node_modules for npm install e2e | 64,128,206 B (61.16 MiB), 47 packages | 42,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
| Metric | base 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.screenshot | 1.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.goto | 875 ms (839 ms-940 ms) | 910 ms (838 ms-941 ms) | +0.5% (-3.3% to +6.5%) | same, under the floor |
| step expect.toHaveScreenshot | 839 ms (813 ms-944 ms) | 835 ms (787 ms-887 ms) | -5.7% (-9.5% to +1.9%) | unresolved |
| step app.open | 316 ms (307 ms-336 ms) | 337 ms (322 ms-390 ms) | +1.7% (-3.0% to +26.7%) | same, under the floor |
| step locator.screenshot | 182 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.toHaveScreenshot | 82 ms (81 ms-85 ms) | 80 ms (79 ms-88 ms) | -0.6% (-9.1% to +21.3%) | same, under the floor |
| step browser.evaluate | 80 ms (71 ms-85 ms) | 69 ms (65 ms-71 ms) | -15.8% (-24.7% to -2.8%) | unresolved |
| step locator.pressSequentially | 67 ms (63 ms-69 ms) | 72 ms (67 ms-75 ms) | +9.9% (-10.1% to +23.4%) | same, under the floor |
| step expect.toBeVisible | 56 ms (54 ms-59 ms) | 58 ms (55 ms-61 ms) | +2.4% (-3.4% to +11.1%) | same, under the floor |
| step locator.focus | 44 ms (43 ms-47 ms) | 49 ms (44 ms-49 ms) | +3.4% (-4.7% to +8.9%) | same, under the floor |
| step expect.toBeAttached | 10 ms (9 ms-12 ms) | 10 ms (9 ms-11 ms) | 0.0% (-18.2% to +25.0%) | same |
| step browser.setViewport | 2 ms (0 ms-3 ms) | 1 ms (1 ms-2 ms) | -50.0% (-75.0% to 0.0%) | same, under the floor |
| step browser.route | 1 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.