Compare commits

...
Author SHA1 Message Date
feder-crandClaude Sonnet 5.5 c8842355fb e2e: the dot() reads a zero's sign as the GPU does (zeros of both signs in the vectors, the comparison keeps the sign)
The comparison treated -0 and +0 as equal, which hid a fma whose product and sum are both -0 coming back +0. The model's fma now gives IEEE's sign of a zero result, with a unit test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:20:40 +01:00
feder-crandClaude Sonnet 5.5 e9c888d8e8 e2e: a WebGL dot() gives the bits of the GPU family the persona declares (from firefox-60)
tests/test_webgl_dot_has_the_declared_gpu_s_bits_e2e.py reads back dot() of two, three and
four components through a float-bits shader and compares the bytes with the NVIDIA fma
chain computed in exact arithmetic, for alu_class 1 and 2; class 0 is the control. The model
runs as a unit test everywhere; the browser tests are Windows only and guarded by
engine_at_least("firefox-60"). The engine's gate lists it by name.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:05:35 +01:00
Federico EliaandClaude Sonnet 5.5 c7c7285557 e2e: tagged images read back on a canvas as retail Windows Firefox reads them (from firefox-60) (#425)
* tests: the canvas ICC readback reference (retail Firefox 159.0 on Windows, default prefs)

refs.json holds the SHA-256 of the 72 probes of tests/data/canvas_icc_ref/index.html as
retail Firefox 159.0 (build 20261022150525) gave them on a PC whose monitor profile is the
stock "sRGB Color Space Profile.icm": ten generated tagged images drawn four ways, 22 fill
colours, the canvas colorSpace probe, nine environment values. 27 probes depend on the
profile (qcms converts tagged images to it); for those the hash without the conversion
(force_srgb=true, same machine) is kept too. gen_images.py writes the images and ICC
profiles with the standard library, byte for byte what the measurement used, so the
repository holds no binary file. scripts/build_canvas_icc_refs.py rebuilds refs.json from
the run files; the unit test checks the structure, the 72 probes and the 27 profile
dependent ones.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* e2e: tagged images read back on a canvas as retail Windows Firefox reads them (from firefox-60)

The test builds the ten tagged test images with gen_images.py, serves them with the probe
page on localhost, runs the 72 probes on the engine and compares the SHA-256 of each
getImageData read with refs.json (retail Firefox 159.0 on Windows, default prefs, monitor
profile "sRGB Color Space Profile.icm"). Every differing probe is listed with the expected
and the obtained hash, and marked when the engine gave the value without the conversion.
On an engine that skips the conversion (firefox-58, firefox-59) 27 probes differ.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:15:14 +01:00
Federico EliaandClaude Haiku 5.5 da503f254a tests: webgl getParameter flake reports the reason (gl null, context lost, drift) (#424)
The test returned a bare false, so a CI failure could not tell a null
getContext('webgl') from a parameter that changed between reads. The
page now returns the reason: gl null (with webgl2 availability), context
lost, or drift with the round, parameter, and first differing vs
reference values.

Co-authored-by: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-09 12:45:33 +01:00
Federico EliaandClaude Sonnet 5 43a3197d89 e2e: WebCodecs software decode ignores a page's hardwareAcceleration request (#423)
* e2e: WebCodecs software decode ignores a page's hardwareAcceleration request

Firefox-60 checklist goal 6b. REA (invisible_WebCodecs/notes/
nv12-rgb-conversion.md) found the D3D11/DXVA hardware path doing its
NV12->RGB conversion in the GPU (ID3D11VideoContext::VideoProcessorBlt),
a host dependency. Companion to the engine fix
(ShouldPreferSoftwareDecoder in dom/media/webcodecs/DecoderTemplate.cpp,
branch media-webcodecs-software-only): with the engine on, decode must
stay on the software path (libyuv) no matter what the page asks for.

Same 96-frame 1080p B-frame clip and access-unit split as
test_webcodecs_h264_bframe_pts_order_e2e.py, but the page's VideoDecoder
config explicitly asks for hardwareAcceleration: "prefer-hardware", and
every output frame's copyTo({format: "RGBA"}) is hashed and compared
against the software reference (captures/h264-1080p-bframes/retail-win/
result.json - Firefox 159.0 retail Windows, headless, DXVA off per its
own meta.json), vendored at
tests/data/webcodecs_h264_1080p_bframes_rgba_sha256.json so the test does
not depend on the private study repo being checked out beside this one.

Needs no GPU to run: on a VM without one there is no hardware path to
force into software, so a pass only confirms libyuv has not drifted: the
guard is against a future regression that gives the engine a real
hardware path again while leaving the page's request wired straight
through.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Translate the Italian checklist quote in the e2e docstring to English

The pre-push hook's own English-only check refused on this (the goal
6b line, 'dalla, della'), which is why test_the_pre_push_hook_gates_release_tags
also failed: the hook's self-test run hit the refusal before the
gate-wiring assertion could see a clean pass. Not two separate bugs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 12:44:59 +01:00
Federico EliaandClaude Sonnet 5.5 ce79a51417 tests: the blending e2e runs on Linux only until ANGLE's translator does the blend (#422)
On Windows the blend is done by the host's Direct3D 11: a runner without a GPU uses WARP, which
rounds up to 2 off (4090 of 207956 results on the firefox-60 candidate). The Mesa patch that makes
blending exact fixes Linux only. The test skips on Windows with that reason and returns there when
the blending goes through the translator (objective 5).

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 11:26:08 +01:00
Federico EliaandClaude Sonnet 5 d9c21dd67b e2e: WebCodecs VideoFrame.timestamp order on a real H.264 B-frame stream (#421)
Companion to the engine fix in FFmpegVideoDecoder.cpp (branch
media-h264-bframe-pts, goal 6 of the firefox-60 checklist): ff_h264_decoder
doesn't set FF_CODEC_CAP_SETS_FRAME_PROPS, so without the engine's own
reorder buffer the pts ffmpeg attaches to each decoded frame is the most
recently sent packet's, not the one that produced it. A page reading
VideoFrame.timestamp from WebCodecs sees that reordering directly on any
B-frame stream.

Same schema as test_webcodecs_h264_without_host_libavcodec_linux_e2e.py:
decodes the vendored 96-frame 1080p clip (has_b_frames 2, same one measured
in invisible_WebCodecs) with the access units split client-side exactly like
the browser-side probe that produced the retail-win reference capture, and
checks the output order against that capture's own dense, strictly
increasing sequence.

Needs a firefox-60 (or later) build with the fix, which does not exist yet:
collects and skips cleanly today (no cached/pointed binary), same as the
fixture's documented contract.


(cherry picked from commit 2a025dc97f5d2f5ed9254395fc8facc8e411c59f)

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 11:24:26 +01:00
Federico Elia 64f76b2d94 e2e: the system fonts and colours are Windows retail's, and a missing declaration refuses the launch (from firefox-60) (#420)
* Add an e2e that compares the system fonts and colours with Windows retail

* Compare the system-ui family too

The e2e needs engine_at_least, so it is merged after PR #416.

* Add an e2e that a launch missing a system theme pref is refused

Needs engine_at_least, so it is merged after PR #416.
2026-11-09 11:16:09 +01:00
Federico EliaandClaude Sonnet 5.5 808c8f8c97 e2e: canvas 2D text equals retail Windows on every OS (from firefox-60) (#419)
* Test: canvas 2D text equals retail Windows on every OS

240 canvas text cases (five Windows fonts, six sizes, a transform, fill and stroke, synthetic
italic and bold) hashed from getImageData and compared with the hashes retail Firefox 159
gave. The run's hashes can be written out, and scripts/compare_canvas_text_runs.py names the
cases two runs (Debian 12 and Ubuntu 24.04) draw differently. Gated on firefox-61.

* Test: the canvas text reference is made with the bundled fonts, gated on firefox-60

refs.json carries the bundle file and sha256 of each font and the retail machine's
ClearType state; the test checks the engine's fonts against them and declares that
state as the persona.

* Test: the canvas text reference covers alpha false, COLR v0 emoji, large sizes and a variable face

refs.json now holds 330 cases in seven groups, merged by id from the two
measurements of retail Firefox 159.0 by scripts/build_canvas_text_refs.py;
the page draws them on getContext('2d', {alpha: false}) where the reference
did, frees each large canvas after its hash, and the test names the
differing cases group by group and checks the Twemoji Mozilla and
Bahnschrift font hashes too.

* Test: the canvas text reference covers Segoe UI Variable at three weights

Group 6 draws the bundled seguivar2_03.ttf (wght 300-700, opsz 5-36) through @font-face
font-weight 300 700 at weight 300, 400 and 700 and sizes 9, 12.5, 16 and 33: 12 cases, the
three weights hashing differently at every size. The hashes are retail Firefox 159.0's on
Windows (the official installer's firefox.exe, sha256 d8b5ed82...), measured by running this
page itself with the bundled font files; the same run redrew the 330 existing cases and
every width, height and hash equals the reference already in the repository, so the new
cases come from the same machine and the same code. refs.json keeps its existing cases and
field order and gains the 12 cases, the font entry and its load status.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 11:16:04 +01:00
Federico EliaandClaude Sonnet 5 a42d863e48 Add e2e: WebCodecs decodes H.264 without a host libavcodec/libavutil (#418)
Same schema as test_webgl2_exists_without_host_mesa_linux_e2e.py: the
engine ships its own ffvpx, so VideoDecoder must decode webcodecs/h264.annexb
(10 frames, 320x240, vendored from web-platform-tests) on a Linux host that
has no system libavcodec/libavutil to fall back on. Skips on firefox-59 and
earlier (engine_at_least("firefox-60")), on non-Linux, and on a host that
still has a libavcodec (the check proves nothing there).


(cherry picked from commit 47f26b376ba8c5e7de070c1ae6e2c3a5105fe3db)

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 07:08:33 +01:00
Federico EliaandClaude Sonnet 5.5 f62bf3f6dc e2e: WebGL blending rounds once and mediump runs at 32 bit (from firefox-60) (#417)
* e2e: no browser process reads the host's fontconfig (Linux)

The engine's gtest of the empty fontconfig configuration looks only at
the final state, so it would also pass if GTK, Pango or the first
FcInit() had loaded the host's configuration before the hook replaced
it. This test runs the browser under strace -f, through a tree of links
to the engine whose executable execs the real one, draws a page with
text and fails on any call, in the parent or a content process, that
names /etc/fonts, ~/.config/fontconfig, ~/.fonts.conf, /usr/share/fonts,
FONTCONFIG_FILE or FONTCONFIG_PATH.

Measured on ubuntu:24.04 under xvfb-run with invisible-core 58.56.0,
invisible-playwright 0.47.1 and firefox-58 (build 20261108115355): it
fails. The parent makes 1127 such calls over 503 paths, two content
processes 366 over 69, starting with access/openat of
/etc/fonts/fonts.conf and conf.d.

* e2e: Math.sin, Math.cos and Math.tan give ucrtbase's bytes in every JIT tier

Math.sin(Math.PI / 4) is 0.7071067811865476 on Windows Firefox (ucrtbase) and was
0.7071067811865475 on Linux (fdlibm, or glibc with the pref off). The test reads
the result bits of 4,516 hard inputs, every one where fdlibm or glibc 2.43 differ
from ucrtbase among 30,372 measured on Windows 11, plus every 8th of the others,
for twelve rounds in the same functions so the interpreter, the baseline JIT and
the optimizing JIT all answer. Fails on the Linux engine until it carries
libxul's own sin/cos/tan and Windows' value of
javascript.options.use_fdlibm_for_sin_cos_tan.

* e2e: the sin/cos/tan loop runs for a measured time, and the counts agree

No API a page can read tells which JIT tier ran a call, so the test no longer
claims every tier: each function now runs over its inputs for at least three
seconds and twelve rounds, and every round must equal ucrtbase. The docstring and
the data's header give the same counts, over the 30,372 distinct inputs: fdlibm
441, glibc 2.43 651 (653 counted duplicates), one or both 832, 4,516 lines kept.

* tests: engine_at_least skips a test on an engine older than the one that promises the property

* tests: calc() equals ucrtbase's text, and a screenshot of text returns

* tests: calc() cases read word-spacing, where a zero is 0px and not normal

* tests: engine_at_least compares the number only and fails on a seal with none

* tests: the fontconfig stand-in is killed as a group, the data checks are unit, the screenshot is wall-clock

* Test that WebGL blending is done unquantized and rounded once

On Windows the engine draws through ANGLE on Direct3D 11: the fragment
shader's float output goes into the blender as it is, the blend is
computed at float precision and the result is rounded once, to the
target's format. On Linux the engine's own llvmpipe quantized the shader
output to the target's 8 bits first and blended in 8-bit arithmetic, so
a page read back values up to one step off (two for SUBTRACT): SRC_ALPHA
/ ONE_MINUS_SRC_ALPHA over a destination of 100 with a source of 200 and
an alpha of 1/255 gave 101, where D3D11 gives round(100.392) = 100.

The test sweeps the source alpha over the common factor pairs and the
ADD, SUBTRACT, REVERSE_SUBTRACT, MIN and MAX equations, with straight,
premultiplied and non-8-bit-exact sources, onto RGBA8, RGB10_A2, RGBA4
and (with EXT_texture_norm16) RGBA16 and R16 targets, in one evaluate,
and compares every channel with the exact blend computed in double,
rounded half up (near-ties skipped). Maximum error must be 0. It runs on
every OS: it is the rule the Windows engine already follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that a mediump WebGL shader computes at 32 bit, as on Windows

On Windows the engine draws through ANGLE on Direct3D 11, which runs
mediump and lowp at full 32-bit precision. On Linux the engine's own
llvmpipe ran them as fp16, so an 8-bit texel read through a sampler of
default precision came back up to ~0.12 of a step off texel/255, and
arithmetic lost every bit past 11: 2049.0 + 1.0 gave 2048.

Three shaders with `precision mediump float;` write the bits of their
floats into an RGBA32UI target: texelFetch on an RGBA8 texture holding
all 256 byte values per channel (default sampler precision, and with
`precision mediump sampler2D;`), which must read back as float32(byte/
255) to one ulp, and single correctly rounded operations whose float32
result fp16 cannot hold (2049.0 + u, 0.1 * u, 1.0 + u * 2^-12, 32.0 + u
* 2^-10), which must be exact. Runs on every OS: the rule is the one the
Windows engine already follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: WebGL blending and mediump precision hold from firefox-60

Both read pixels a page reads back. firefox-59's llvmpipe still blends in 8
bits and runs mediump in fp16, so the two tests declare firefox-60 with
engine_at_least; older engines skip them with that reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that WebGL2 exists on a Linux host that has no Mesa

A page tells a host with no GL from one with a Mesa by getContext("webgl2")
returning null. On firefox-59 the host's glxtest blocked WebGL on a host with
GTK and no Mesa (FEATURE_FAILURE_WEBGL_EXHAUSTED_DRIVERS); the engine's WebGL
draws on the GL it ships, so the host must not decide. The test asks for WebGL2
and WebGL1 and reads a cleared pixel, from firefox-60 (engine_at_least), and
skips on a host that has a Mesa since it proves nothing there. The series gate
removes every Mesa library from its Linux legs and fails if one is left.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 00:18:27 +01:00
Federico Elia eadf95b90a e2e: engine-gated tests for the empty fontconfig, ucrt math, calc() and text screenshots (#416)
* e2e: no browser process reads the host's fontconfig (Linux)

The engine's gtest of the empty fontconfig configuration looks only at
the final state, so it would also pass if GTK, Pango or the first
FcInit() had loaded the host's configuration before the hook replaced
it. This test runs the browser under strace -f, through a tree of links
to the engine whose executable execs the real one, draws a page with
text and fails on any call, in the parent or a content process, that
names /etc/fonts, ~/.config/fontconfig, ~/.fonts.conf, /usr/share/fonts,
FONTCONFIG_FILE or FONTCONFIG_PATH.

Measured on ubuntu:24.04 under xvfb-run with invisible-core 58.56.0,
invisible-playwright 0.47.1 and firefox-58 (build 20261108115355): it
fails. The parent makes 1127 such calls over 503 paths, two content
processes 366 over 69, starting with access/openat of
/etc/fonts/fonts.conf and conf.d.

* e2e: Math.sin, Math.cos and Math.tan give ucrtbase's bytes in every JIT tier

Math.sin(Math.PI / 4) is 0.7071067811865476 on Windows Firefox (ucrtbase) and was
0.7071067811865475 on Linux (fdlibm, or glibc with the pref off). The test reads
the result bits of 4,516 hard inputs, every one where fdlibm or glibc 2.43 differ
from ucrtbase among 30,372 measured on Windows 11, plus every 8th of the others,
for twelve rounds in the same functions so the interpreter, the baseline JIT and
the optimizing JIT all answer. Fails on the Linux engine until it carries
libxul's own sin/cos/tan and Windows' value of
javascript.options.use_fdlibm_for_sin_cos_tan.

* e2e: the sin/cos/tan loop runs for a measured time, and the counts agree

No API a page can read tells which JIT tier ran a call, so the test no longer
claims every tier: each function now runs over its inputs for at least three
seconds and twelve rounds, and every round must equal ucrtbase. The docstring and
the data's header give the same counts, over the 30,372 distinct inputs: fdlibm
441, glibc 2.43 651 (653 counted duplicates), one or both 832, 4,516 lines kept.

* tests: engine_at_least skips a test on an engine older than the one that promises the property

* tests: calc() equals ucrtbase's text, and a screenshot of text returns

* tests: calc() cases read word-spacing, where a zero is 0px and not normal

* tests: engine_at_least compares the number only and fails on a seal with none

* tests: the fontconfig stand-in is killed as a group, the data checks are unit, the screenshot is wall-clock
2026-11-08 23:57:25 +01:00
Federico Elia b81f1561c5 Merge pull request #415 from feder-cr/clean-install-timeout
The tests that install from the index get their own deadline
2026-11-08 21:07:05 +01:00
Federico Elia 61d2ee29d5 Merge pull request #414 from feder-cr/gate-second-linux
Host gate: two Linux legs are held to each other; text.* narrowed to what is open
2026-11-08 21:07:02 +01:00
feder-crandClaude Opus 5.5 882c0f3a0e Host gate: the Linux GL defect is excused on both Linux legs
The Debian leg draws WebGL with the same Mesa delta 1 from Windows as the
Ubuntu one (and identical to it, same-OS comparison), and the exception
named only linux-x86_64: 12 failures on the re-gate of firefox-59. A test
holds every Linux-scoped known defect to all Linux legs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:22:00 +01:00
feder-crandClaude Opus 5.5 dde60415d7 The tests that install from the index get their own deadline
The module installs the README's block once, in the clean_venv fixture,
and pytest-timeout counts that setup in the first test that requests it.
With PyPI slow the install took 517 s, over run_e2e.py's 420 s per-test
deadline, and the guard killed the worker on a slow test, not a stuck one.
Each test that takes clean_venv now carries 900 s, under the block's own
1800 s cap; a test asserts it and fails without the marks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:01:18 +01:00
feder-crandClaude Opus 5.5 be60e4d7e4 Host gate: two Linux legs are held to each other, and text.* is narrowed to what is open
A known defect excused a key on every non-Windows leg, so a difference
between two Linux hosts passed unseen. compare() now holds the legs of one
OS to the first of them wherever the identity does not change the value,
known defects included: they excuse the difference from Windows only.
The text.* block becomes the surfaces that differ on the firefox-59 dumps
(glyph pixels, advances, ink extents, serif/monospace fallback widths);
text.adjust, text.fonts, text.rect, text.units and the vertical metrics
are now held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:55:31 +01:00
Federico Elia 8c2dcbf570 Merge pull request #412 from feder-cr/ledger/0.47.1
record 0.47.1 as published
2026-11-08 18:29:05 +01:00
feder-cr 4fddee2d46 record 0.47.1 as published 2026-11-08 17:12:11 +00:00
Federico Elia 87f48c9b8a Merge pull request #411 from feder-cr/release/0.47.1
0.47.1: pin invisible-core 58.56.0, the keyboards Windows installs with the language
2026-11-08 17:57:28 +01:00
feder-crandClaude Opus 5.5 7d702fb188 0.47.1: pin invisible-core 58.56.0, the keyboards Windows installs with the language
The keyboard pref carries Windows' own form (LANGID:KLID joined by
semicolons), declared by the core; the server's fallback, when a caller
wrote its prefs without it, uses the same form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:27:42 +01:00
Federico Elia 42cbc45da2 Merge pull request #410 from feder-cr/own-gl-e2e
e2e: on Linux WebGL draws on the engine's own GL, also under X11
2026-11-08 16:18:44 +01:00
Federico Elia 97faaa84f2 Merge pull request #409 from feder-cr/ledger/0.47.0
record 0.47.0 as published
2026-11-08 16:06:31 +01:00
feder-crandClaude Opus 5.5 e5cb8934a2 e2e: on Linux WebGL draws on the engine's own GL, also under X11, and every declared extension answers as on Windows
Skipped where the package has no llvmpipe/ (engines before firefox-59).
On candidate 42484125583 both fail: no WebGL under Xvfb, the surfaceless
display asked for with the X11 display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 15:51:56 +01:00
feder-cr 16abec2c09 record 0.47.0 as published 2026-11-08 14:49:58 +00:00
Federico Elia 742281ec3a Merge pull request #407 from feder-cr/engine/firefox-58
0.47.0: pin invisible-core 58.55.0, the firefox-58 engine (Firefox 159)
2026-11-08 15:36:08 +01:00
feder-cr c5e89a85d2 Merge remote-tracking branch 'origin/main' into engine/firefox-58 2026-11-08 14:51:13 +01:00
Federico Elia a8da4b117f Merge pull request #408 from feder-cr/ci-github-token
CI downloads the engine with the job token; the user path stays anonymous
2026-11-08 14:07:58 +01:00
feder-crandClaude Opus 5.5 4ba1cefcdd CI downloads the engine with the job token; the user path stays anonymous
On 2026-11-08 GitHub had timeouts for unauthenticated users and the gates failed
three times on the engine download, because the jobs called the release API
anonymously (also limited to 60 requests an hour per runner address). The core
uses GITHUB_TOKEN when it is set, so each workflow that runs tests declares it
once at the top. user-install.yml stays anonymous: it is the user's path.

Test: test_ci_downloads_are_authenticated fails on the old workflows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:32:50 +01:00
Federico Elia 3378b8f3e2 Merge pull request #406 from feder-cr/ledger/0.46.4
record 0.46.4 as published
2026-11-08 13:19:11 +01:00
feder-crandClaude Opus 5.5 07a03e41e9 Keyboard: the persona's keyboards are the core's declaration, read here
invisible-core 58.55.0 declares the keyboards with the language and
country (prefs._apply_locale) and owns the pref's name; the session no
longer writes a second copy, and the server imports the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:10:09 +01:00
feder-crandClaude Opus 5.5 22a098843a 0.47.0: pin invisible-core 58.55.0, the firefox-58 engine (Firefox 159)
The persona's keyboards (the language's and the second one Windows
installs with it, switched with left Alt + left Shift), the engine's own
scrollIntoViewIfNeeded (op_scroll_into_view hands a rect on), and the
engine's fixes for refused navigations, held requests and cookies.
test_frame_dispatch's hand-built InjectedScript gets the condition the
core's __init__ now makes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:03:53 +01:00
feder-crandClaude Opus 5.5 e76c63a6cb e2e: the switch to English is pressed, left Alt and left Shift, before KeyX
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:58:15 +01:00
feder-crandClaude Opus 5.5 caae1ea0aa Keyboard: the persona's keyboards, the language's and the second one Windows installs with it
The server-only keyboard pref carries layouts_for (KLIDs joined by
commas, the language's first), so a Russian or Greek persona types a
Latin letter on English (US) with its key events instead of answering
press("x") with "unknown key: 'x'". Needs the core with layouts_for.

The four keyboard e2e tests name the US keyboard (locale="en-US"): the
persona's keyboard follows the session's language, which the runner's
address decides, and run 42453174270 met a non-Latin one. New e2e: a
Russian persona presses x as KeyX, a Greek one types "cafe" with its
keys, a Nepali (India) one, whose Windows has no Latin keyboard, gets
the letter inserted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:58:15 +01:00
feder-cr acb073dda7 record 0.46.4 as published 2026-11-08 11:55:48 +00:00
Federico Elia 081b3a1aa0 Merge pull request #404 from feder-cr/release/0.46.4
0.46.4: pin invisible-core 57.54.0, release files through the API route first
2026-11-08 12:25:27 +01:00
feder-crandClaude Opus 5.5 9460e8eb86 0.46.4: pin invisible-core 57.54.0, release files through the API route first
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:57:06 +01:00
Federico Elia 3abd710393 Merge pull request #401 from feder-cr/counters-on-actions
Launch counter: the daily snapshot and the badges run on GitHub Actions
2026-11-08 10:17:04 +01:00
github-actions[bot]andfeder-cr 80034c9c84 record 0.46.3 as published (#403)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-08 09:52:15 +01:00
Federico Elia 820d88e8eb Merge pull request #402 from feder-cr/engine/firefox-57
0.46.3: pin invisible-core 57.53.0, the firefox-57 engine (Firefox 159)
2026-11-08 09:16:52 +01:00
feder-crandClaude Opus 5.5 558a402fa9 0.46.3: pin invisible-core 57.53.0, the firefox-57 engine (Firefox 159)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 08:59:58 +01:00
feder-crandClaude Opus 5.5 2b3cbe0795 Launch counter: the daily snapshot and the badges run on GitHub Actions
GitHub keeps only the running total of the counter asset, so a day's launches
exist only if the total is recorded that day. The snapshot ran from a scheduled
task on one PC with a token file beside it; when that task went, the badge
stopped on 2026-11-04 and the days after it were never recorded.

counters.yml runs every day at 00:10 UTC on the built-in token, appends the
counters to counters/history.csv on the badges branch, derives
counters/launches_daily.csv, and redraws launches.svg and stars.svg with the
same sum and the same bytes as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 07:03:26 +01:00
Federico Elia 3dd1424a0a Merge pull request #400 from feder-cr/host-gate-goto-timeout
Host gate: the navigation has the page's budget, not goto's default 30 s
2026-11-07 22:46:50 +01:00
feder-crandClaude Opus 5.5 5847dfe87a Host gate: the navigation has the page's budget, not goto's default 30 s
Candidate 42410156024 failed the Windows host gate on its first visit: the
page reached domcontentloaded but not load within goto's default 30 s on a
cold GitHub runner, while the wait right after it has 180 s. The same binary
passed 6/6 locally. goto now takes timeout_ms like the wait.

Test: test_the_navigation_has_the_page_s_budget_not_goto_s_default (fails on
the previous script).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 22:31:31 +01:00
Federico Elia 622b6e82a7 Merge pull request #399 from feder-cr/enumeration-test-inside-engine
e2e: the enumeration's host check reads the engine's log, not a clock beside a loaded runner
2026-11-07 21:33:00 +01:00
feder-crandClaude Opus 5.5 4355274838 e2e: the enumeration's host check reads the engine's log, not a clock beside a loaded runner
The upper bound ("nothing on top of the declared time") compared the page's
clock against a runner whose load delays the parent's main thread by 150-200
ms; it failed twice on 2026-11-07 (741 and 702 against 543 + 143), green on
rerun. The load-proof checks stay (the first call waits at least the declared
time, the second is fast). Whether the host's speakers were asked is now read
from inside the engine: with MOZ_LOG=StealthMediaEnumeration:4 the engine
logs the declared wait it dispatched and "host speakers asked: yes|no"
(firefox_antidetect_patch a00ba45). That test runs from firefox-57.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 21:17:49 +01:00
Federico Elia 97f8663ec6 Merge pull request #398 from feder-cr/ledger/0.46.2
record 0.46.2 as published
2026-11-07 20:49:11 +01:00
feder-cr ce68aea668 record 0.46.2 as published 2026-11-07 19:16:16 +00:00
Federico Elia dab71bd637 Merge pull request #397 from feder-cr/keyboard-country
0.46.2: the persona's keyboard from its language and country (core 56.53.0)
2026-11-07 20:01:47 +01:00
feder-crandClaude Opus 5.5 0c043d580e test: take the profile generator from the core's public API, not the _fpforge shim
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 19:46:23 +01:00
Federico Elia 0421f95adf Merge pull request #396 from feder-cr/ledger/0.46.1
record 0.46.1 as published
2026-11-07 19:40:21 +01:00
feder-cr 284a840ebe record 0.46.1 as published 2026-11-07 18:24:35 +00:00
feder-crandClaude Opus 5.5 eb8b415635 0.46.2: the persona's keyboard from its language and country (core 56.53.0)
The session decides the keyboard with the core (keyboard.layout_for on
SessionLocale.languages and .region) and hands it to the server in a
server-only pref (invisible.server.keyboard_layout), taken out before the
profile is written; without it the language alone decides. German in
Switzerland now types on the Swiss keyboard. Pins invisible-core 56.53.0.

Test: tests/test_the_keyboard_follows_the_session_language.py (KLIDs, and
the language-and-country case).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 19:14:21 +01:00
Federico Elia e508c10e9d Merge pull request #395 from feder-cr/fix-pyproject-driver-comment
0.46.1: pin core 56.52.0 (typing hand by key); pyproject comment names the real server
2026-11-07 19:08:09 +01:00
feder-crandClaude Opus 5.5 7a4e7c4d0a 0.46.1: pin invisible-core 56.52.0 (typing hand by key)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 18:40:29 +01:00
feder-crandClaude Opus 5.5 3824a2e03e pyproject: the dependency comment names the server that exists, not a Node driver
The comment said the Node driver lives in src/invisible_playwright/_driver/,
which does not exist; the server is _juggler/. Test: every src path the
pyproject names is a folder of this tree (fails on the previous comment).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 18:22:10 +01:00
Federico Elia fb5c3a403c Merge pull request #394 from feder-cr/ledger/0.46.0
record 0.46.0 as published
2026-11-07 14:13:08 +01:00
feder-cr eb2be0e88d record 0.46.0 as published 2026-11-07 12:56:39 +00:00
Federico Elia 621a396def Merge pull request #391 from feder-cr/remove-font-gate
0.46.0: dialogs answered after a reader's pause, the persona's keyboard, the WebGL test; the font gate removed
2026-11-07 13:42:30 +01:00
feder-crandClaude Fable 5.1 2afb1cc349 The dialog's answer always goes out: the seed is the browser's, and a failed plan is a warning
0.46.0's first CI run hung three e2e tests for 30 s: the pause read the
session seed from the transport (`self.server`) instead of the browser
(`self.browser.session_seed`), the AttributeError swallowed Page.handleDialog,
and the open dialog blocked every evaluate on the page. The unit test had
mirrored the wrong path; it now models the real one (server knows no seed,
the page reaches the browser through its context), fails on the previous
server, and a new case proves the answer goes out even when planning raises.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-07 13:12:57 +01:00
feder-crandClaude Fable 5.1 b0dc24031c 0.46.0: pin invisible-core 56.51.0, the firefox-56 engine (Firefox 159)
The engine carries the WebGL declared-extension hooks (a declared extension
can be called without killing the browser); this version adds the reader's
pause on dialogs, the persona's keyboard by language, and the WebGL e2e test.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-07 12:39:42 +01:00
feder-crandClaude Fable 5.1 d87cc4e3b6 The persona's keyboard follows the language the launcher decided
The server reads `intl.accept_languages` from the launch prefs and hands the
matching layout (invisible_core.juggler.keyboard.layout_for) to every page's
hands: an Italian persona types on an Italian keyboard. Until now every session
typed on one US table with Chromium's key codes. Pins invisible-core 55.51.0,
which carries the tables and the keyboard.

Test: tests/test_the_keyboard_follows_the_session_language.py.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-07 08:53:46 +01:00
feder-crandClaude Fable 5.1 8eb28c2ada Test: a WebGL extension the persona declares can be called without killing the browser
Read with symbols on 2026-11-07 (Linux, firefox-55): one provokingVertexWEBGL()
call on an extension the host had refused by policy hit MOZ_RELEASE_ASSERT and
took the main process down. The hooks ship in the engine (firefox_antidetect_patch
14feb6a, fingerprint/webgl/parameters); this test calls the six entry points on
both context kinds and asks the page a question after. Skipped on engines before
firefox-56, where it would not fail but kill the browser.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-07 08:33:02 +01:00
feder-crandClaude Fable 5.1 09eeb004d1 Answer a dialog after a reader's pause, not in the millisecond it opened
Page.handleDialog left as soon as Page.dialogOpened arrived, whoever
answered: the client's auto-dismiss or a handler's accept(). A page timing
alert()'s return saw single-digit milliseconds. The pause is drawn from the
session's seed and the dialog's text (reaction + per-word reading, clamped,
one draw per dialog); only the remainder is waited, in the worker; no seed
means no pause, as for every other rhythm.

Test fails on the previous server (two cases: the answer did not wait, and
two dialogs of a page took the same zero time) and passes on this one.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-07 07:58:03 +01:00
feder-crandClaude Opus 5.5 632490aa50 CI: remove the font gate, the host gate covers the font list
scripts/ci_font_gate.py asked one case (is the font list the persona's?) of
the host gate's question (is anything a page reads the host's?). It was kept
until the host gate ran green on a release: it did on firefox-55. The engine's
gate.yml no longer runs it (firefox_antidetect_patch 709404e).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:43:58 +01:00
Federico Elia 6c0cfdb610 Merge pull request #390 from feder-cr/drop-linux-arm64
Linux arm64 is no longer supported from firefox-56
2026-11-04 17:17:58 +01:00
feder-crandClaude Opus 5.5 9a98c0060b Linux arm64 is no longer supported from firefox-56
No engine is built for it from firefox-56 on; firefox-55 is the last one
with a Linux arm64 build. The README, the installation page, the arm64
guide, CONTRIBUTING and the release notes now name Linux x86_64 and Windows
x86_64 only, and the README says Linux arm64 is no longer supported. The
host gate drops its arm64-only known defects. The README check treats
linux-arm64 as retired, like macOS, and a new test fails on a page that
still lists it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:58:08 +01:00
Federico Elia 4b9e28a879 Merge pull request #389 from feder-cr/ledger/0.45.0
record 0.45.0 as published
2026-11-04 05:49:01 +01:00
feder-cr 6383f21dbb record 0.45.0 as published 2026-11-04 04:34:26 +00:00
Federico Elia 6080c06bd9 Merge pull request #388 from feder-cr/engine/firefox-55
0.45.0: invisible-core 55.50.0, the firefox-55 engine
2026-11-04 05:20:08 +01:00
feder-crandClaude Opus 5.5 ae947139d8 e2e: the tests that start the engine without the core bring the first-run declaration
Since firefox-55 the engine leaves Mozilla's first-run lines and the core declares
them. These two tests start the engine directly, so a second tab failed
Browser.newPage ("Unexpected number of tabs in the new window: 2"), run 41769630744.
The values come from the core, so they cannot drift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 05:04:24 +01:00
feder-crandClaude Opus 5.5 e1f1659776 0.45.0: pin invisible-core 55.50.0, the firefox-55 engine (Firefox 159)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 04:49:31 +01:00
feder-crandClaude Opus 5.5 02bd688896 Host gate: WebGPU's null on linux-arm64 is that leg's known defect
The leg ships without our Vulkan driver, so requestAdapter answers null there
by design, never the host's driver; arm64 is not a priority. Scoped to that
leg: on Windows and linux-x86_64 the adapter stays held to retail. Run
41402916724's dumps compare with 0 failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:46:48 +01:00
feder-crandClaude Opus 5.5 c6dca80401 Tests follow invisible-core's gfx contract: no webgl.force-enabled, gpu.device not pinnable
The core dropped webgl.force-enabled (the engine answers the blocklist from
zoom.stealth.gfx.feature_status, WEBGL2 = 1) and its GPU profile gained
`device`, the real GPU drawn from the renderer's bucket. The renderer is the
knob; the device follows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:39:54 +07:00
feder-crandClaude Opus 5.5 f03164e7e0 Drive gate: the first run is declared in the profile, as the core declares it
Since firefox-55 the engine leaves Mozilla's first-run lines and invisible-core
declares the state (terms of use accepted, pre-onboarding off). The drive gate
runs upstream Playwright only, whose defaults travel in Browser.enable, which
the engine refuses, so nothing declared it. Run 41388672849: Windows showed the
terms-of-use modal (no mouse event reached the page), Linux opened Mozilla's
privacy page in a second tab ("Unexpected number of tabs in the new window").

FIRST_RUN, a copy of the core's three prefs, goes into user.js and the gate
drives a persistent context, as the font gate does. On that run's packages:
Windows --click and --full OK, Linux --click and --full OK.
tests/test_ci_drive_gate_first_run.py ties the copy to the core (fails on the
previous gate).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:39:54 +07:00
feder-crandClaude Opus 5.5 0236afb11d Host gate: each visit pins its DPR in the persona
Every (dpr, seed) visit forced layout.css.devPixelsPerPx over whatever
persona the seed drew. A 100% persona at 1.5 read innerWidth 1920 inside an
outerWidth of 1291, and a 150% persona at 1.0 an outerWidth of 1942 on a
1280 screen (run 41325657085): identities no machine has. The DPR is now
pinned (screen.dpr), so the core declares a screen, work area and window
made at that scale; the engine refuses a scale that contradicts them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 01:01:54 +07:00
feder-crandClaude Opus 5.5 af932640b8 Host gate reference: retail 159 in fullscreen and back
state.normal, state.fullscreen and state.after_fullscreen measured on the
official Firefox 159 for Windows at DPR 1.0 and 1.5: headed, a profile past
the first-run onboarding (which otherwise keeps focus and input away from
the page), real OS-level input for the fullscreen gesture. Every invariant
of the gate holds on retail. Only state.* keys are added; no existing value
changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:11:47 +07:00
feder-crandClaude Opus 5.5 fd22249b65 Host gate: the window in fullscreen and back, held to invariants
A defect escaped every check: after requestFullscreen() the engine kept
declaring the maximized window (outer 1936x1048 under a 1920x1080 viewport,
screenX/Y -8/-8, mozInnerScreenY and every mouse event's screenY - clientY
at 85 instead of 0). No visit entered fullscreen, since it needs a user
gesture, and every value was checked alone against retail, never against
the others.

The dump now drives each visit through three states with real input
(drive_states): normal, fullscreen entered by a Playwright click on a page
button whose handler calls requestFullscreen(), and back through
exitFullscreen(). Each state records the window and screen geometry,
display-mode, fullscreenElement, window.fullScreen and the screen - client
offsets of real mouse events, under state.normal, state.fullscreen and
state.after_fullscreen. A transition that ends in a timeout or
fullscreenerror is recorded, never waited on.

compare() holds every leg and every visit to INVARIANTS, one table with
the reason of each: outer holds inner; in fullscreen outer == inner ==
screen, screenX/Y and mozInnerScreenX/Y at 0, display-mode and
fullscreenElement set; outside it neither; every event's screen - client
equals mozInnerScreenX/Y (exact, or within 1 px when mozInnerScreen is
fractional); the screen does not change; the return restores the normal
state. No exception and no reference applies to them.

The retail reference has no state.* yet: until it records them, those
values are held to host-independence and the invariants only, and compare
notes it. REFERENCE_PENDING says what the reference session must add.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:07:31 +07:00
feder-crandClaude Opus 5.5 c84c8c32a5 Host gate: the textarea is fixed, arm64-only differences are scoped to arm64
The textarea width at fractional DPRs now matches Windows on Linux (engine:
DirectWrite's average character width on FreeType), and the gate reported
the exception as no longer seen. The differences left on linux-arm64 only
(Skia's NEON composite, pattern and shadow; the offline audio FFT) are known
defects of that leg, which is not a priority. Run 41305135645's dumps
compare with 0 failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:42:58 +07:00
feder-crandClaude Opus 5.5 a5ad308e4a Host gate: the page tells why a host has no WebGL2 or MSAA, never compared
The Windows runner answers getContext('webgl2') with null and gives WebGL1
no multisampling; Linux does not. The page now records under diag.webgl,
for webgl and webgl2, with and without failIfMajorPerformanceCaveat:
whether getContext returned null, the statusMessage of every
webglcontextcreationerror (listener on a fresh canvas before getContext),
the context attributes, VENDOR/RENDERER/VERSION/SHADING_LANGUAGE_VERSION,
the unmasked pair when exposed, SAMPLES, SAMPLE_BUFFERS and MAX_SAMPLES.
The block runs last, and each context is lost once read.

diag. keys are information: the legs legitimately differ on them and the
retail reference does not record them. compare() skips the prefix by name
(documented in the module docstring); dump() prints the leg's diag values
into the job log (all on the first visit, then only what changed), so a
run says why without downloading its artifacts.

Tests: diag keys differing per leg and per seed and absent from retail do
not fail; a known defect matched only by a diag key is still reported as
no longer seen; only the exact prefix is skipped; a non-diag key missing
on one leg still fails host and retail; the dump's diag report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:56:42 +07:00
feder-crandClaude Opus 5.5 c30e07ee9f Merge host-gate: the host gate runs on the next engine's candidates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:04:13 +07:00
feder-crandClaude Opus 5.5 85cc5d10e6 Host gate: measured like the reference, compared leaf by leaf, identity declared
The dump visits the page the way retail's reference was taken: over
http://127.0.0.1, en-US, the zone the reference reported, the DPR through
layout.css.devPixelsPerPx, no drawn cursor. The reference is retail Firefox
159.0 for Windows at DPR 1 and 1.5 (gzipped, 1.2 MB).

Values are compared leaf by leaf, so a field the identity decides does not
hide a wrong field of the same object, and the values the identity decides
are declared: with a few seeds, 16 cores or a 1920x1080 screen repeat by
chance. exceptions.json: identity, measurement (focus on the hidden desktop
retail ran on) and the known defects with the work that closes each.

On the 0.44.1 dumps of Windows and Linux it fails exactly the defects the
next candidate fixes (invalid WebGL enums, stencil masks, MAX_VIEWS_OVR, the
WebGPU adapter and importExternalTexture from the host, -moz-dialog), and
nothing else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:04:06 +07:00
feder-crandClaude Opus 5.5 7c23e4377d The host gate: what a page reads depends on the identity and Firefox, never the host
One rule, two properties, checked on whole API dumps rather than a list of keys:
the same identity on different hosts gives the same bytes (each leg against
the Windows leg, the platform the identity claims), and a value that does not
depend on the identity equals retail Firefox for Windows at the same DPR.
Which values depend on the identity is measured, not listed: three seeds per
DPR, and a value that changes with the seed is held to host-independence only.

The exceptions are three kinds with a reason each (noise that differs between
two retail launches, network-derived values, known open defects), and the
known-defect list only shrinks: an entry that hides nothing any more fails.

The comparison is here with its tests (tests/test_ci_host_gate.py, 8 cases on
synthetic dumps). The page, the retail reference and the CI wiring follow; the
gate then replaces ci_font_gate.py, which checks one surface of the same rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:31:37 +07:00
feder-crandClaude Opus 5.5 0418f37dbb Pin invisible-core 54.50.0 for the next engine's candidates
The candidate of the engine that declares the WebGPU adapter is gated with
the core branch that declares it (fix/codec-follows-gpu, 54.50.0). Not for
release as is: the version and the CHANGELOG follow when the engine does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:02:59 +07:00
Federico Elia 0dc42b6380 Merge pull request #386 from feder-cr/ledger/0.44.1
record 0.44.1 as published
2026-10-31 10:21:03 +07:00
feder-cr f4381155bd record 0.44.1 as published 2026-10-31 03:17:49 +00:00
Federico Elia bec6e5f835 Merge pull request #385 from feder-cr/fix/core-54.49.0
Pin invisible-core 54.49.0: WebRTC decodingInfo no longer reads the host GPU (0.44.1)
2026-10-31 10:00:31 +07:00
feder-crandClaude Opus 5.5 d9dca5b498 Pin invisible-core 54.49.0: WebRTC decodingInfo no longer reads the host GPU
invisible-core 54.49.0 declares VP8, VP9 and AV1 for the WebRTC branch of
decodingInfo, so powerEfficient is Firefox 159 for Windows's answer instead of
the host's hardware decoding. Same engine, firefox-54. Version 0.44.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:41:57 +07:00
Federico Elia 469e1692a7 Merge pull request #384 from feder-cr/ledger/0.44.0
record 0.44.0 as published
2026-10-31 08:29:45 +07:00
feder-cr 44a3eed971 record 0.44.0 as published 2026-10-31 01:17:58 +00:00
Federico Elia 77b192eba5 Merge pull request #383 from feder-cr/engine/firefox-159
firefox-54: Firefox 159, downloads, set_offline, scroll only when needed
2026-10-31 06:28:42 +07:00
feder-crandClaude Opus 5.5 49e4e3a133 The scroll test asserts the core's if-needed scroll, not the old centring
Core 54.48.0 (3735356) leaves an element in full view where it is and
centres only one that is not, as Chromium's scrollIntoViewIfNeeded does: the
helper runs before every click, and a click on a visible button used to move
the page under it. This test still asserted the old always-centre behaviour,
so the e2e suite went red on the 54.48.0 pin.

It now checks both halves on a page where the two behaviours differ: an
element low in the viewport but in full view leaves scrollY at 0 (red on the
old helper, which centred it), and one cut by the bottom edge is scrolled to
the centre of the viewport.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 06:14:15 +07:00
feder-crandClaude Opus 5.5 4a0bd76768 Show the engine's Firefox 159.0 on the README badge
The seal pinned by invisible_core 54.48.0 is upstream 159.0; the badge
and its alt text still said 151.0, which test_readme_claims catches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:55:26 +07:00
feder-crandClaude Opus 5.5 6de45423d1 0.44.0: pin invisible-core 54.48.0, the firefox-54 engine (Firefox 159)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:52:21 +07:00
feder-crandClaude Opus 5.5 20f8a43693 Send download options and surface downloads (Artifact/Stream, download event)
The Python server never sent Browser.setDownloadOptions, so the engine's
download interceptor stayed off: no download event, no saved file, and a goto
or click that ended in a download waited out its timeout. Contexts now get
download options at creation (accept -> saveToDisk, deny -> cancel) into a
per-session temp dir removed at shutdown. Browser.downloadCreated/Finished
become a page 'download' event with Artifact and Stream channel objects
(pathAfterFinished, saveAs, saveAsStream, stream, failure, cancel, delete).
The engine ends a navigation that became a download with no event, so the
lifecycle is fed an abort "Download is starting", as upstream's server does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:33:26 +07:00
feder-crandClaude Opus 5.5 00d8154ef8 e2e: a download is reported, saved, and ends the navigation that led to it
The engine registered Juggler's download interceptor and never called it, so no
downloadCreated or downloadFinished reached Playwright and a goto that ended in
a download hung. Two cases: a clicked attachment reaches expect_download and is
saved with its bytes; a goto to an attachment reports the download and ends.
Red on the 157/159 engines before the interceptor is dispatched (both time
out), to go green with the engine fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:05:02 +07:00
feder-crandClaude Opus 5.5 12d1cc7308 e2e: a click on an element in full view does not scroll the page
The core's scroll_into_view centred every time, so every click moved the page.
Three cases from scrollY 1000: an element in full view and one inside a
same-origin iframe stay where they are (red on the previous core); one below
the fold is centred.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:36:39 +07:00
feder-crandClaude Opus 5.5 2e1b91b196 set_offline() sends Juggler's Browser.setOnlineOverride instead of refusing
The refusal said the engine had no offline command. It has one (new_context(offline=True) already sent it); what was missing was the engine honouring it: its HTTP channel asked a stub that always answered online. The engine now runs Mozilla's own code there (firefox_antidetect_patch 3087f02c56), so set_offline(True/False) maps to the override and leaves NO_ENGINE_COMMAND. tests/test_set_offline_e2e.py fails on an engine with the stub (the offline goto loads) and on a server that still refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:18:29 +07:00
feder-crandClaude Opus 5.5 c11c04b30e The page sends a commit's navigated from the lifecycle's announcement, not from its own listener
Sent from `_on_juggler_event`, the `navigated` of a commit raced the answer of a wait the same commit ended: the lifecycle, which runs first, had already woken it. With click() now waiting for the commit of the navigation it planned, `page.click("#next")` returned with `page.url` on the page it had left (tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py, red on the 07cbaa9cea engine before this). The commit now goes up from `_on_lifecycle`, as `sameDocument` already did, and not once the page is closed (what `_deliver` guaranteed before). The unit doubles reach it the way the page does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:05:21 +07:00
feder-crandClaude Opus 5.5 29a5c7a516 click and press wait for the navigation they set off unless no_wait_after, as Playwright's do
From Firefox 157 a form submission is a planned navigation (the retail's dom.forms.submit_async_navigation): page.click() on a submit button returned 7 ms before the POST was announced, so a script that clicked and read its requests or URL saw the page it had left; 151 and Microsoft's client both had it. FrameDispatcher._waiting_after runs Playwright's waitForSignalsCreatedBy around click and press (not dblclick, tap, hover or check, as there), on invisible_core's Lifecycle.wait_for_action_signals, which the engine's Page.linkClicked now feeds.

tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py fails on a 157 engine without it (the click returned before its form's request) and checks no_wait_after still returns at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:26:04 +07:00
Federico Elia 00ad6d702f Merge pull request #382 from feder-cr/ledger/0.43.0
record 0.43.0 as published
2026-10-25 06:40:12 +07:00
feder-cr 9fb0f20dbc record 0.43.0 as published 2026-10-24 23:18:49 +00:00
Federico Elia 254b2dce1d Merge pull request #381 from feder-cr/engine/firefox-53
firefox-53: the font gate checks the artifact's manifest, e2e for a page that changes process
2026-10-25 06:03:43 +07:00
feder-crandClaude Opus 5.5 2ee9f100bf 0.43.0: pin invisible-core 53.48.0, the firefox-53 engine
Locators keep working after a page that runs in a process of its own sends
itself to one that does not: the engine's context ids are unique for the
session. The exposed fonts are the set of a clean Windows (67 families).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 05:39:50 +07:00
feder-crandClaude Opus 5.5 d5a50275ea Test fixtures name the import error instead of a TypeError
With a core whose version the wrapper's pin did not name, the package was not
importable and firefox_binary answered "argument of type 'NoneType' is not
iterable" (measured 2026-10-25); sample_profile would have answered
"'NoneType' object is not callable". _require_package() exists for this and
neither fixture called it. Both do now, and a test drives both bodies with the
import missing: it fails on the old conftest and passes now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:30:25 +07:00
feder-crandClaude Opus 5.5 b02c79f279 e2e: reads on a page in a process of its own, then on the page it sends itself to
A page served with Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy
runs in a process of its own; one read there, and every locator on the page it
sent itself to failed for good with "Cannot find object with id" (measured
2026-10-24 on firefox-52 with 0.42.0, where this test fails). Each round checks
that the first page really was isolated, so it cannot pass for the wrong
reason. Fixed by firefox-53, whose context ids are unique for the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:30:25 +07:00
feder-crandClaude Opus 5.5 4a69d25254 Font gate: the binary declares exactly the clean Windows set, read from its own manifest
EXPECTED loses Leelawadee, Microsoft Uighur, Wingdings 2 and Wingdings 3, the
families the firefox-53 bundle drops because a clean Windows 11 has none of
them.

The gate now asks the allow-list question on the artifact itself: the engine
exposes exactly the families its manifest declares, and that manifest is
fonts/bundle-fonts.list beside the binary (Contents/Resources/fonts on macOS).
The families it declares must be EXPECTED and only those. The page probe can
only find names it asks about, so a family put back into the bundle was
invisible to it unless some list named it; now it is refused with no list
naming it.

Measured 2026-10-25 on real binaries: firefox-52 as published, where the
probe answers "detected 67 families (expected 67)", is refused with the four
families named; a copy carrying the firefox-53 font bundle passes the whole
gate. Unit tests cover exact, extra, missing, the macOS layout and no
manifest at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:30:24 +07:00
Federico Elia 7b783cf892 Merge pull request #380 from feder-cr/ledger/0.42.0
record 0.42.0 as published
2026-10-24 19:38:45 +07:00
feder-cr 455f0cf0e1 record 0.42.0 as published 2026-10-24 11:58:36 +00:00
Federico Elia 655d99020a Merge pull request #379 from feder-cr/canvas2d/read-as-drawn
0.42.0: pin invisible-core 52.48.0, a 2D canvas reads back as drawn
2026-10-24 18:41:37 +07:00
feder-cr 4b61bea3fa 0.42.0: pin invisible-core 52.48.0, a 2D canvas reads back as it was drawn 2026-10-24 18:13:30 +07:00
feder-crandClaude Opus 5.5 ffad787af9 A screenshot is measured in device pixels, at the persona's display scale
The core now draws 1920x1080 panels at 125% and 150% as often as the Windows
fleet does (invisible_core #170), and seed 4242 lands on 125%: the screenshot of
an 800x600 viewport is a 1000x750 image, exactly what a real Windows machine at
that scale gives. The tests asserted 1x sizes and pixel positions; they now read
window.devicePixelRatio and scale both, so they also prove the crop is right
when the scale is not 1. Passes at 1.25 (core main) and at 1 (0.41.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 15:52:43 +07:00
feder-crandClaude Opus 5.5 cc3bce2f58 A 2D canvas reads back as it was drawn, guarded at the e2e gate
The random-pixel test public fingerprinting pages run - 64 random opaque 1x1
fills read back - must come back byte for byte on a page canvas and on an
OffscreenCanvas 2D (invisible 0.41 changed 6 of 64, retail 151 changes 0); an
undrawn canvas reads zero; two seeds declaring the same display scale and
ClearType tuning draw the same text; and a toDataURL PNG on an http page carries
the 16-byte deBG chunk retail 151 writes after IDAT. Against the firefox-51
engine five of these fail, as they should; they pass from firefox-52 with the
core that turns baseline protection on (Linux and Windows, 2026-10-24).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 15:52:43 +07:00
Federico Elia 33940459f7 Merge pull request #377 from feder-cr/ci/publish-one-at-a-time
The publish workflow serialises per repository
2026-10-21 13:36:28 -07:00
feder-cr dc9ff53e78 The publish workflow serialises per repository, so a dispatch on a branch and a push of the tag wait for each other 2026-10-21 22:15:13 +02:00
Federico Elia 4ad30e5079 Merge pull request #376 from feder-cr/ci/publish-concurrency
The publish workflow runs one at a time per ref
2026-10-21 07:37:41 -07:00
feder-cr e94863c79d The publish workflow runs one at a time per ref, so two runs of one tag cannot both upload 2026-10-21 16:09:10 +02:00
Federico Elia 151c314c05 Merge pull request #375 from feder-cr/ledger/0.41.0
record 0.41.0 as published
2026-10-21 06:18:38 -07:00
feder-cr 8bbc41162b record 0.41.0 as published 2026-10-21 12:52:37 +00:00
Federico Elia 58fd0c8d93 Merge pull request #374 from feder-cr/feat/core-51.48.0-pin
0.41.0: pin invisible-core 51.48.0, document font.system_text_quality
2026-10-21 04:28:18 -07:00
feder-cr edaf224417 The voices test declares the session it measures
It asserts the voice list measured on retail Windows Firefox for an en-US
session, and it left the locale and the time zone to the egress IP: green on
US runners, red from anywhere else. From Italy the session came out it-IT and
the list began with Microsoft Cosimo, which is right for that session and not
the one measured ([B364]). The session now declares locale en-US and time zone
America/New_York; the expected list and the assertion are unchanged. Measured
from an Italian egress: green on firefox-50 and on the form B engine.
2026-10-21 12:59:29 +02:00
feder-cr 07a55bfc85 A flat WebGL clear reads back exactly, and a realistic render varies per seed
test_high_entropy_webgl_still_noised_per_seed drew 64 scissor-cleared stripes
and asserted their readback differs between two seeds. A clear has no device
variation: the value is the clear colour quantised to 8 bits, the same on
every GPU, so noise on it is a tell a page can read by comparing with what it
cleared. The engine of form B leaves it exact, and the test asserted the tell.

The file now asserts the two things that hold: a triangle with a gradient and
antialiased edges reads back differently for seeds 1 and 2, and a flat clear
in v/255 colours reads back exactly v (an integer v, so no driver rounds it
differently). Measured: retail Firefox 151 reads the stripes exact (0 of 4096
moved); the form B engine passes both; firefox-50 passes the first and fails
the second on every pixel, both seeds.
2026-10-21 12:59:29 +02:00
feder-cr 1bac4b6f8b The required-keys list asks for edge_tolerance, the canvas pref the firefox-51 engine reads, not the retired noise_skip_mask 2026-10-21 12:28:52 +02:00
feder-cr 47dabed289 0.41.0: pin invisible-core 51.48.0, document font.system_text_quality 2026-10-21 12:20:44 +02:00
feder-cr a1312941eb Pin invisible-core==51.48.0 for the firefox-51 coupled release 2026-10-20 13:39:45 +02:00
github-actions[bot] 5b762bab65 record 0.40.0 as published (#373)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-19 00:36:04 -07:00
Federico Elia 920292760a The version gate installs the build backend it builds with (#372)
`invisible_core.release check --verify-index` builds the package without
isolation to compare it with the ledger, and the gate job installs only the
dev extra, which carries `build` and not `hatchling`. On the first tag that
ran the step (invisible-playwright v0.40.0) it stopped with exit 2, "gate
broken: Backend 'hatchling.build' is not available", and the upload was
skipped. The step installs `build hatchling` first, as the record step does.
2026-10-18 23:50:03 -07:00
Federico Elia 0afe5737fa 0.40.0: pin invisible-core 50.48.0, expect through the injected script, goto on the base URL (#371)
0.40.0 moves the pin to invisible-core 50.48.0, on the same firefox-50 engine, and brings the fixes that waited for it.

expect() reads every condition through the injected script's own expect, as Playwright's server does, instead of a Python rewrite that covered two families; a failed expect now carries its call log and reports an object value as the object (this was #368, renumbered from 0.39.0). page.goto follows the context's base_url, resolved by the engine's URL parser. evaluate, evaluate_handle and wait_for_function run the caller's text as a script and call it when it is a function, with the argument as a protocol value. The vendored client's README says what actually differs from upstream.

The client side of core 50.48.0: user-install runs on the ledger pull request instead of release: published, which never fired, and CI checks that with invisible_core.install_job; the release tests keep out of their venvs every variable the core's library reads; publish.yml checks the version and the ledger against the index before it uploads.

Eight older tests were red on fakes that did not know about the base URL or the new evaluate road; they are updated to check the same contract on the new code, and the seal-floor stub now copies the core modules pin.py imports instead of a hand list. Default suite: 762 passed.
2026-10-18 23:06:24 -07:00
github-actions[bot] 9a1501af7a record 0.39.0 as published (#370)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-18 14:40:44 -07:00
Federico Elia fb56fde88d 0.39.0: pin invisible-core 50.47.0, the firefox-50 engine (#369)
The pin moves to invisible-core 50.47.0, on the firefox-50 engine. From firefox-50 every realm, worker and worklet takes the session's zone from the engine's own override, so the core no longer writes TZ into the browser's environment and drops the IANA-to-POSIX table.

This package stops importing IANA_TO_POSIX_TZ and tz_env and stops passing a zone to the launch environment. The tests of the table go with it, and so does the probe of the guarded import that took those names; a core of any other version is still refused by the pin check before anything is imported from it.
2026-10-18 11:56:14 -07:00
github-actions[bot] 88d3f7a513 record 0.38.0 as published (#367)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-17 20:20:45 -07:00
Federico Elia 1504d95ed3 0.38.0: pin invisible-core 49.46.0, uv as the way in (#366)
The pin moves to invisible-core 49.46.0. The desktop settings a page can read (scrollbars, text scale, drag threshold, double-click selection, the system colours in both schemes, the refresh rate, the form-control font) are now declared by the persona instead of read from the machine it runs on.

The way in is uv: the README has one complete install block per system, and CI refuses an install instruction that is not uv. A remedy the package prints (a broken pin, an old core) is now the command for the environment it runs in, so a uv venv, which has no pip, is told the uv command.

The guides and the issue template move to uv too, and the release e2e runs the README block as written in a clean home. The tests that build prefs outside a session now declare a timezone, which 49.46.0 asks for.
2026-10-17 13:39:46 -07:00
Federico Elia 9927c974da The firefox-N release body points at the README's install block instead of restating it (#365)
The body of every firefox-N release carried its own `pip install invisible-playwright`, a second copy of the README's install command that nothing kept in step with it. It now links to the README's Install section, so a release always teaches what the README teaches.

scripts/gen_release_notes.py is run by the engine's publish workflow; tests/test_release_notes_install.py checks the body restates no install command and the README has the section it links to. No package change, no version bump.
2026-10-17 16:34:04 +02:00
github-actions[bot]andfeder-cr 632f023b8c record 0.37.0 as published (#364)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-17 13:56:39 +02:00
Federico Elia 0dd99b7638 0.37.0: the pin moves to invisible-core 49.44.0, on the firefox-49 engine (#363)
The pin moves to invisible-core 49.44.0, on the firefox-49 engine.

With it: your code's evaluate runs in a world of its own; the favicon no longer reaches routes or events; route.abort() with no code fails like Playwright's; a route that sends a navigation elsewhere lands there; a held request released after interception went off no longer stalls the browser; request.post_data is the body without a route; and the response names its certificate and its service worker.

Measured on the firefox-49 candidate: the full e2e and Playwright's own suite against the recorded reference, no regression. tests/gates/upstream_baseline.json is recorded again with a cause per entry; one correction to its commit message: test_scroll is pinned failed because of a scroll position two worlds read differently after scrollTo, not because of test order.
2026-10-17 13:19:57 +02:00
github-actions[bot]andfeder-cr 0433b18aa7 record 0.36.2 as published (#362)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-17 02:28:33 +02:00
Federico Elia b40535b344 0.36.2: the tests that time themselves run alone, and security_details() hands on the certificate (#361)
* response.security_details() hands on the certificate the engine sent

op_security_details answered None for every response, HTTPS included,
which a script reads as "not over TLS". It was written against an engine
that sent securityDetails: null; the engine after firefox-48 reports the
certificate as upstream does, and the response now keeps what the
responseReceived event carried. An engine that still sends null answers
None, as before.

Measured with Playwright's own suite through this client: on firefox-48
with the engine change, test_response_security_details,
test_response_security_details_none_without_https and
test_should_report_if_response_was_from_service_worker pass; on the
published firefox-48 the answers are unchanged.

* The e2e tests that measure time run alone, after the parallel tests

Tests whose verdict is an upper bound on a wall-clock duration ("refused
at once", "returns before the page loads", the device enumeration's
declared time) carry the new wall_clock marker. From invisible-core
48.42.0 the e2e run gives them the machine alone, one browser, after the
last parallel test has ended: four browsers at once cross those bounds
with nothing wrong in the engine. The pin moves to invisible-core 48.42.0.

* The changelog dates 0.36.2 by the day it is uploaded, UTC
2026-10-17 01:47:55 +02:00
github-actions[bot]andfeder-cr 3986b4ccce record 0.36.1 as published (#360)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-16 13:23:31 -07:00
Federico Elia bc3d777f59 0.36.1: wait_for_function ends on an element, and evaluate_handle handles work (#359)
* wait_for_function ends when the predicate returns an element

The predicate ran by value and Python judged the serialized result, so a predicate that returns a node, the most common wait there is, never ended: a node serializes to nothing truthy. Each turn is now invisible-core's poll_in_main: one run by reference, judged with js_truthy, and a truthy value is the handle the wait returns. Needs invisible-core 48.42.0.

* A handle of a main-world value runs where the value lives

Every handle evaluate_handle returned was unusable on 0.36.0: text_content, evaluate and json_value failed with 'Cannot find object', because a main-world objectId was made into a utility-world handle and only json_value read the handle's world. FrameDispatcher._handle_from_main is now the one place such a handle is made: a node is adopted into the utility world and its main objectId released, as add_script_tag already did; any other value, primitives included, stays in the main world, where dispose, evaluate, get_property, get_property_list and json_value run. evaluate_handle and wait_for_function both go through it; evaluate_handle reads the whole RemoteObject (invisible-core's evaluate_in_main_remote) to tell a node from anything else. The poll test now pins one run of the caller's code per turn. Needs invisible-core 48.42.0.

* 0.36.1: the pin moves to invisible-core 48.42.0

The core brings js_truthy and poll_in_main, which wait_for_function now
uses, evaluate_in_main_remote, which evaluate_handle uses, and a GeoIP
cache that is never read half-written. The CHANGELOG lists the three under
0.36.1.
2026-10-16 12:54:03 -07:00
github-actions[bot]andfeder-cr 6dd3e5af82 record 0.36.0 as published (#358)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-16 10:57:08 -07:00
Federico Elia f7cd0cc378 0.36.0: the pin moves to invisible-core 48.41.0, on the firefox-48 engine (#357)
* A persistent profile stays the same machine across launches

The seed came from secrets.randbits whenever none was passed, so a
profile_dir reopened without seed= showed its cookies on another machine.
It now comes from invisible_core.resolve_session_seed, which reads the
seed the profile recorded, and record_session_seed records it where the
profile directory is created.

* docs: the branding pin, the voices by language and the persistent seed

pinning.md lists branding among the top-level keys and says the voices follow the session's first language; the CHANGELOG says all three under Unreleased.

* docs: the branding pin takes a zip archive, as the engine serves it
2026-10-16 10:09:41 -07:00
Federico Elia 36003250a4 0.35.11: a closed page says nothing, and a close waits for the event being handled (#355)
A page's close and the delivery of its session's events were not serialized, so a late Network.responseReceived could create a Response under a request the client had already dropped with the page, and new_page() or a response listener raised 'dict' object has no attribute '_object'. Every event of a page now goes through PageDispatcher._deliver, under the close's own lock.
2026-10-16 06:02:24 -07:00
Federico Elia 47ee59da22 The enumeration test bounds what the engine does, not how loaded the runner is (#354)
The first enumeration was held within the declared time plus 110 ms and the
second under 50 ms. A CI run with four browsers crossed each once in the
release of 0.35.10 (656 against 543 + 110, then exactly 50), both green again
on the same SHA, and the second one stopped the publish.

The bounds now come from the properties. The declared time is waited, which
load can only add to. The list is kept, so a second call is well under the
declared time that a fresh ask would wait again. And nothing is added on top:
the second call is the same round trip without the wait, so first - second is
the declared time plus whatever the host added, with the load both calls share
cancelled out; the margin is half the smallest time the host's audio stack
used to add (287 ms). Under four browsers at once on Windows, 12 launches out
of 12 hold all three, the difference 8-49 ms over the declared time.
2026-10-15 16:13:24 -07:00
github-actions[bot]andfeder-cr eaa044fef7 record 0.35.10 as published (#353)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-15 05:45:54 -07:00
Federico Elia 82565e0c98 0.35.10: the pin moves to invisible-core 47.41.0 (#352)
The engine can live on a read-only disk (INVISIBLE_PLAYWRIGHT_ENGINE_DIR), and
an "auto" timezone that cannot be resolved fails the launch without a proxy
too, instead of falling back to the host's zone in silence.
2026-10-15 05:04:40 -07:00
github-actions[bot]andfeder-cr 3dac7702ba record 0.35.9 as published (#350)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-14 18:41:45 -07:00
Federico Elia 48770e590e 0.35.9: the pin moves to invisible-core 47.40.0 (#349)
A connection releases each pipe end once: closing a browser twice no longer
closes the pipe of another browser in the same process.
2026-10-14 18:09:56 -07:00
Federico Elia c1835182ed record 0.35.8 as published (#348)
Records 0.35.8, uploaded by hand on 2026-10-14 at 22:49 UTC on the owner's order to release before the e2e of the merge had finished. A manual upload skips the release tool, so the entry is recorded from the same tag export that was uploaded.
2026-10-14 16:01:40 -07:00
Federico Elia bf9af85830 0.35.8: the pin moves to invisible-core 46.39.0 (firefox-46) (#347)
The pin moves to invisible-core 47.39.0, which seals the firefox-47 engine.

- **A page can no longer tell that the engine carries the automation protocol (invisible_playwright #336).** Every engine until firefox-47 registered the protocol as a chrome package named `juggler`, and a page tells a registered package from an absent one with `new Worker("chrome://juggler/...")`: it returned on our engine and throws on Firefox. Captcha vendors started probing it in October 2026, which is why a challenge solved by hand was still refused. firefox-47 loads the protocol from `resource://gre/modules/juggler/`; of 65 chrome packages and resource substitutions probed from a page, none answers differently from Firefox 151.

- **A goto the page stops on its way no longer answers OK on the old page, nor waits out its timeout.** document.open() and window.stop() in the page being left stop the navigation; the engine dropped every such stop of the main frame, so goto answered OK on the previous page (4 times in 4 on 0.35.7 with the page held 1.5 s) or waited for its timeout. It now raises NS_BINDING_ABORTED at once, as Playwright does on Firefox.
- **Every way a page or the caller can stop or replace a goto is tested**: document.open, window.stop, location.replace and assign, a form submit, an iframe navigating the top, history.back, pushState, a meta refresh, nothing, and a second goto, each in one process and across a process swap, back to back, checked against upstream Playwright 1.63's answers on its own Firefox.
- **goto refuses a success the engine made up**: a commit attributed to its navigation that is not where that navigation's request went raises instead of answering OK.
- A goto the caller's next goto stops is "interrupted by another navigation", as upstream; goto(until="load") counts only its own document's load; the timeout message no longer contradicts itself.
- The wheel is born before the page sees it, as keys and moves are since 0.35.7.

e2e on firefox-46 with core 46.39.0's source: Windows 389 passed, 5 skipped; Linux 390 passed, 4 skipped; no reruns.
2026-10-14 15:40:54 -07:00
github-actions[bot] a61169c830 record 0.35.7 as published (#346)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-13 13:31:36 -07:00
Federico 1839425da6 0.35.7: the pin moves to invisible-core 45.39.0 (firefox-45) (#345)
The pin moves to invisible-core 45.39.0, which seals the firefox-45 engine.

- **A key or a mouse move is born before the page sees it.** The engine stamped every input event at the instant it reached the page, so `event.timeStamp` equalled `performance.now()` in the handler, and a script that keeps only the events with `timeStamp < now` dropped most of our keys. Each event is now born a few milliseconds earlier, drawn per event from the session. The new e2e test checks every key and mouse move in the handler; measured on firefox-45, all of them arrive 4 to 22 ms after they were born, where retail Firefox with a real keyboard and mouse is at 3 to 18.
- **The first `enumerateDevices()` of a session takes the same time on Windows and on Linux**, a time the seed fixes between 240 and 640 ms, instead of the host's audio stack time (15 to 40 ms on Linux). The device list is unchanged. The new e2e test reads the declared time from the core's profile.

e2e on firefox-45 with core 45.39.0's source: Windows 378 passed, 5 skipped; Linux 379 passed, 4 skipped; no reruns.
2026-10-13 13:06:23 -07:00
github-actions[bot] 2aa4292458 record 0.35.6 as published (#344)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-13 10:48:18 -07:00
Federico 102913d5bf 0.35.6: the pin moves to invisible-core 44.39.0 (firefox-44) (#343)
The pin moves to invisible-core 44.39.0, which seals the firefox-44 engine.

- **Stopping a screencast no longer freezes the browser on Windows.** The engine stopped its window capture on the thread that owns the window while the capture was waiting for that thread to draw it. The new e2e test starts and stops a screencast fifty times at the rates the API is asked for; one browser froze at the ninth stop on firefox-43, and a probe of the same thing ran 1200 stops out of 1200 on firefox-44.
- **Text with a character the US layout has no key for is typed**: `page.type("#i", "café")`, `locator.type` and `keyboard.type` raised. The keys that exist are pressed and the character is inserted in its place, as Playwright does.
- **On Linux, the line endings a page reads are Windows'** (`Blob` / `File` with `endings: "native"`, and the text of a selection across two blocks).
- **`speechSynthesis.getVoices()` is Windows' list**, in its order, none of them the default.
- `scripts/run_e2e.py` is now the entry to the core's single e2e runner: a worker that dies at its deadline ends the run red, with the test's name and every thread's stack on the log, instead of waiting forever.

e2e on firefox-44 with core 44.39.0: Windows 376 passed, 5 skipped; Linux 377 passed, 4 skipped; no reruns.
2026-10-13 10:17:22 -07:00
github-actions[bot] 49e4d73de2 record 0.35.5 as published (#342)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-13 03:29:09 -07:00
Federico 857de63b48 0.35.5: firefox-43 (invisible-core 43.39.0) (#341)
The pin moves to invisible-core 43.39.0, which seals the firefox-43 engine.

- **A page's frames stay in `page.frames` after a few navigations in one tab.** The engine reported the iframes of the page being loaded as detached once the back-forward cache let an older page of the tab go, so `page.frames` missed them and a `frame_locator` into them waited until its timeout. The new e2e test (five pages in a row, then a page with nested frames) fails on firefox-42 with no child frames and passes on firefox-43 with all three.
- **On Linux, AAC is answered as on Windows** (the declaration is in the core): `canPlayType` and `MediaSource.isTypeSupported` for audio/mp4, audio/aac, audio/x-m4a and video/mp4 with mp4a.40.2 used to drop to "" after about 300 ms on a host without its own AAC decoder.

e2e on firefox-43 with core 43.39.0: Windows 373 passed, 5 skipped; Linux 374 passed, 4 skipped; no reruns.
2026-10-13 02:59:07 -07:00
github-actions[bot] 70285c5bc3 record 0.35.4 as published (#340)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-10-13 01:34:51 -07:00
Federico be0620f2ee 0.35.4: firefox-42 (invisible-core 42.39.0) (#339)
The pin moves to invisible-core 42.39.0, which seals the firefox-42 engine.

What users get from it:

- A page that navigates or reloads itself no longer loses its main world now and then (a read in the page's world used to wait 30 s and fail).
- A session keeps the focus when another one starts beside it. Two sessions on one hidden Windows desktop: the first lost the focus in 4 runs of 6 before, 0 of 6 now.
- In a visible session the real cursor moving over the window can no longer turn a click on a link into a native drag.
- `evaluate` of a function that rejects with a plain object or an Event raises instead of answering `None`.

On the firefox-42 build with this branch and core 42.39.0: e2e Windows 372 passed, 5 skipped, no reruns; Linux 373 passed, 4 skipped in four full runs of five, the fifth with one drag test that saw a native pointer move from the hidden display (it passed 16 times alone and is tracked on its own).
2026-10-13 01:07:01 -07:00
github-actions[bot]andfeder-cr 91ea73bb54 record 0.35.3 as published (#338)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-13 06:28:49 +02:00
Federico 7d86ba00bd 0.35.3: go_back and go_forward to a same-document entry answer None at once, and the test servers are threaded (#337)
go_back and go_forward to a same-document entry (a hash, a pushState) waited
for a navigation id that a same-document navigation never has, and raised
TimeoutError at the timeout. Measured on 0.35.2: 8.0 s for
go_back(timeout=8000). Playwright answers null at once. _history now takes
Lifecycle.mark before the command (invisible-core 41.39.0), which also counts
same-document navigations.

The e2e of tests/test_navigation_response.py had left this arm out on the
word of B185, which said the engine answered Page.goBack and then did nothing.
B185 was closed a month ago and the comment stayed. The arm is back, with
go_back and go_forward on a hash entry.

The core no longer gives a protocol command a 10 s bound of its own: inside an
action it waits for what is left of the action's timeout.

Tests: 35 single-threaded servers in 18 files are now tests/_servers.py's
LocalServer, threaded with daemon threads. A connection the browser opened and
left could hold a single-threaded server's only thread, and shutdown() with
it. That is a candidate for the Windows e2e worker that stopped for 420 s on
the screencast test.

The pin moves to invisible-core 41.39.0.

Two fixes to the test servers' conversion came after: the import of LocalServer in test_detectors_e2e.py had landed in its docstring, and LocalServer gives server_name and server_port as HTTPServer does.
2026-10-13 05:44:32 +02:00
github-actions[bot]andfeder-cr a279231512 record 0.35.2 as published (#335)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-13 00:37:29 +02:00
Federico 35951a1420 0.35.2: the caller's code runs once when its page navigates while it waits (#334)
* 0.35.2: the caller's code runs once when its page navigates while it waits

A script passed to page.evaluate, evaluate_handle or eval_on_selector_all
that was waiting on a promise when its page navigated was sent again into the
page that replaced it, and ran twice: Juggler sends a message still waiting
for its answer again to the new document, which refuses it in the same words
as a script that never ran, and from core 41.36.0 that refusal made the code
again. Core 41.38.0 sends the page world's code once; eval_on_selector_all
passes repeatable=False for the caller's function; wait_for_function goes on
polling through a world that went, as Playwright's does. The pin moves to
invisible-core 41.38.0.

* all_inner_texts and all_text_contents are the server's read, not the caller's $$eval

The fork's Locator asks readAll for them; upstream's client sends them
through evalOnSelectorAll with a fixed function, which the server cannot tell
from a caller's and now sends once (B285). readAll is the core's read_all,
made again on the page that replaced the one it went to (B282), which is what
the MCP's read_text reads right after a navigation. test_a_page_that_moves_on
reads both on every page, and evaluate there answers or raises Playwright's
navigation error.

* CHANGELOG: the library's reads keep answering with the new page

* page.evaluate_read: the door for a read its caller declares free of effects

Not in Playwright. page.evaluate sends the caller's code once and raises
Playwright's navigation error when the page moves under it (B285);
evaluate_read sends evaluateExpression with repeatable=True and is made again
on the page that replaced the one it went to. It exists for the MCP's snapshot
and read_html, fixed reads that inherited that robustness from core 41.36.0
through page.evaluate. Only a real True from the fork's client counts.

* CHANGELOG: page.evaluate_read
2026-10-13 00:10:28 +02:00
github-actions[bot]andfeder-cr e164432db0 record 0.35.1 as published (#333)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-12 22:02:37 +02:00
Federico 51b6602526 0.35.1: the pin moves to invisible-core 41.37.0 (#332)
A browser that closes or crashes now ends every wait on an event at once
with a closed-target error, including the waits a caller asked to have no
limit: the core's connection tells its close listeners, and the lifecycle's
waits listen.
2026-10-12 21:34:46 +02:00
github-actions[bot]andfeder-cr e93d16fd4b record 0.35.0 as published (#331)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-12 07:00:53 +02:00
Federico b03fa50a1a 0.35.0: invisible-core 41.36.0, pages that move on, goto that answers, reads that wait, expect that works (#330)
The pin moves to invisible-core 41.36.0.

- A page that replaces itself right after it loads no longer breaks the next call: a read right after `goto` failed with "Failed to find execution context", and `goto(..., "networkidle")` timed out.
- A `goto` the browser abandons for the previous page's own redirect raises at once with Playwright's "is interrupted by another navigation to" instead of waiting for its timeout.
- `page.frames` lists the frames the page has; it used to grow by a stale iframe and a repeated main frame at every cross-process navigation.
- Selector reads wait for the element as in Playwright, and find and read in one command.
- `expect(locator)` works: every `to_be_*` and `to_have_count` used to fail with an empty AssertionError.

`tests/test_a_page_that_moves_on_e2e.py` runs pages that redirect from the `<head>` and 0, 50 and 300 ms after `load`, same site and cross site, five rounds each, on a real engine.
2026-10-12 06:36:55 +02:00
github-actions[bot]andfeder-cr 93acb6cb13 record 0.34.0 as published (#328)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-12 00:35:42 +02:00
Federico 65dfbd5957 0.34.0: invisible-core 41.35.0, bypass_csp reaches the page, and a launch has one deadline (#327)
* A launch has one deadline, and a timeout reaches the caller as TimeoutError

On the firefox-41 gate, Linux under load, launch() failed with "the engine
refused the proxy, so the browser was closed": the proxy command had 10 s of
its own, went unanswered for 10 s, and the caller's 60 s still had time.

The core's launch now sets the proxy and keeps one deadline for the startup;
this side passes the caller's timeout (0 is no limit, as in Playwright, where
it used to become 60 s) and the proxy, sends Browser.enable through
startup_send, and closes the browser if building its object fails.

Every TimeoutError goes out named TimeoutError, whatever its subclass, because
the client picks its class by that name: a click on an element that never
became actionable (the core's ElementNotActionable) and a wait_for_function
that never became true reached the caller as a plain Error, so except
TimeoutError caught neither. Both checked on the firefox-41 binary.

Commands Playwright gives no timeout lose the bounds of their own (#321 did
newPage): context creation and its options, cookies, permissions and the
other context calls, Page.close, removeBrowserContext, the file chooser
subscription, Heap.collectGarbage, and the page commands, where screenshot
takes the caller's timeout.

Tests: tests/test_a_launch_has_one_deadline.py, six mutants each killed; the
fakes that stand for a connection gain startup_send. Proxy and bypass_csp e2e
pass on firefox-41 on Windows and Linux, and a 1 ms launch raises
TimeoutError and leaves no browser process.

* timeout=0 is no limit, read in one place (B278)

The server read a timeout as params.get("timeout") or 30000 in four places,
so the 0 the Playwright client sends for timeout=0 became 30 s for an action,
a wait or a navigation. _caller_timeout reads it once (0 is None, absent is
the operation's default) for actions, goto, history and launch, and
wait_for_function waits on the core's Deadline.

Tests: tests/test_timeout_zero_is_no_limit.py; the two tests that move the
actions' clock now move the deadline's too. On the firefox-41 binary,
click(timeout=0) on a button a page adds after 32 s clicks it at 32.5 s.

* The first-launch test runs the engine from a path of its own

The launcher state is per executable path, and the e2e workers all launch the
binary under test from the same path. This test deleted that path's values and
launched, while a neighbour's launch could find a Launcher timestamp without a
Browser one, read it as a crashed launcher and turn the launcher off for the
path: on firefox-41 under -n 4 the test failed once with no Launcher timestamp,
and 5 times in 8 with two other processes launching the same path (all 36 of
their launches succeeded, without the launcher).

The test now copies the engine tree, as hard links where the volume allows, to
a temporary path no Firefox has run from, which is the state it is about, and
removes that path's values afterwards. 8 in 8 under the same concurrent
launches.

* 0.34.0: invisible-core 41.35.0, bypass_csp reaches the page, and a launch has one deadline

The pin moves to invisible-core 41.35.0, which seals firefox-41: bypass_csp
lifts the page's header and meta policies (#295), a screencast keeps the rate
it was asked for, and on Linux a window covered by another one is not reported
as hidden. tests/test_bypass_csp_e2e.py checks both halves against the engine:
with the option inline script, eval and add_script_tag run; without it, in
several fresh contexts, they stay blocked.
2026-10-12 00:10:02 +02:00
Rayen Mlayeh 5925cecdf5 A launch that fails before the browser starts stops the hidden display (#326)
Composing the prefs, the proxy and the environment sat outside the try whose handler calls _teardown(), so a launch that failed there (a proxy the engine cannot express, a font manifest it does not carry) left the Xvfb or the hidden desktop running. They move inside it, in the same order. The version moves to 0.34.0 with its changelog entry.
2026-10-11 22:04:41 +02:00
github-actions[bot]andfeder-cr 06f06d5cec record 0.33.1 as published (#325)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-11 12:58:22 +02:00
ce97476fa8 A request's resource_type comes from Juggler's cause name (#305)
* fix(network): a request's resource_type comes from Juggler's cause name

Juggler sends `cause` and `internalCause` as nsIContentPolicy constant
names (TYPE_DOCUMENT, TYPE_XMLHTTPREQUEST, TYPE_FETCH). The table they were
looked up in was keyed by document / xmlhttprequest / fetch, so nothing
matched and every request's resource_type was "other": a page load, a
fetch and an XHR were indistinguishable on the request event.

Use the Playwright driver's own table (ffNetworkManager), internalCause
first for eventsource, so resource_type agrees with the driver transport.

* 0.27.1: a request's resource_type says what it is

* tests: each kind of request is named by the engine, end to end

The unit test proves the table maps the strings it is given; the defect lived
in which strings ARRIVE, so a real page now makes a document, stylesheet,
script, image, fetch and XHR request and the names come from the engine. Green
on firefox-40; red when the lookup goes back to lowercased keys.

---------

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-11 12:22:19 +02:00
Federico ac98613882 A new page waits for the engine's answer as long as the caller does (#324)
op_new_page gave Browser.newPage a fixed 30 s, a bound of its own on a call
Playwright gives none. The caller's bound is the one that means something (a
navigation that opens the page, an MCP tool call), and on a loaded host the
first page after a slow launch failed at 31 s while the navigation that asked
for it still had time: 5 such failures in 773 page calls of a real audit, each
loading normally when repeated.

The reply is now waited for without a bound: it ends when the engine answers,
or when the pipe closes and the connection raises TargetClosedError at once.
The adoption wait after the reply keeps its bound, which guards a protocol
contract (a reply with no attached target), not the engine's speed.
2026-10-11 11:53:56 +02:00
github-actions[bot]andfeder-cr b817217d2e record 0.33.0 as published (#323)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-11 11:09:55 +02:00
Federico 8c33d56c58 0.33.0: invisible-core 40.35.0, the shutdown pings leave by the session's proxy (#322)
0.33.0: invisible-core 40.35.0, the shutdown pings leave by the session's proxy
2026-10-11 10:22:15 +02:00
feder-cr 992ad3dff2 0.33.0: invisible-core 40.35.0, the shutdown pings leave by the session's proxy
The pin moves to invisible-core 40.35.0, which seals the firefox-40 engine: the
shutdown pings go through the engine's own background task by the session's
road instead of pingsender[.exe] from the machine's address, and the session's
last process is let finish them before the session's files are removed.
2026-10-11 10:06:51 +02:00
github-actions[bot]andfeder-cr 0819cd4e23 record 0.32.0 as published (#320)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-10 22:30:10 +02:00
Federico fa7ccba296 0.32.0: invisible-core 39.35.0, the session ends with its last process, and the hand presses Shift and waits before it clicks (#319)
0.32.0: invisible-core 39.35.0, the session ends with its last process, and the hand presses Shift and waits before it clicks
2026-10-10 21:57:25 +02:00
feder-cr 51fbe23431 tests: build Actions through its constructor, and pin the persona fields by count
With invisible-core 39.35.0 two tests broke on a property that still held.
test_drag_motion.py assembled an Actions with __new__ and set its fields by
hand, so the field the core added (pointer_persona, read before a press) raised
AttributeError on every drag; it is built through the constructor now, which
draws the motion from the same sub_seed(seed, "server:drag") stream. And
test_a_field_is_typed_after_a_pause.py pinned "all fields but the last", which
the Shift timing appended after the spread turned into a different set; it pins
the first ten, the ones 0.25.8 drew.
2026-10-10 21:20:57 +02:00
feder-cr a22d34b423 0.32.0: invisible-core 39.35.0, the session ends with its last process, and the hand presses Shift and waits before it clicks
The pin moves to invisible-core 39.35.0, which carries SessionFiles (used here
by the commit below), Shift around the characters that only exist with it, and
the pause between the pointer arriving and the press.
2026-10-10 20:59:45 +02:00
feder-cr 17baf3c6a8 A session's directories are the core's SessionFiles, removed after the session's last process
On Windows a session longer than a minute left its invisible_profile_* behind,
holding an empty saved-telemetry-pings; one machine had 6,091 of them. Two causes,
measured in that order:

- The profile removal was a shutdown hook registered after conn.close, and the
  hooks run in reverse, so it ran first, with the browser still up (the comment
  beside it said the opposite). The upload directory, created after the launch,
  went before the browser too, and a launch that failed or a proxy the engine
  refused returned before the removal was registered at all.
- With the order fixed the directory still stayed: at exit the browser starts
  pingsender.exe, a child that outlives it holding the ping file inside the
  profile, so the removal failed on that file and the child then deleted it.

The profile and the browser's temporary directory are the core's SessionFiles
now, made the moment the launch is asked for and handed to Server.after_shutdown,
which runs once every hook has: conn.close has waited for the browser, and
SessionFiles.remove ends whatever still carries the session's token before it
removes anything. The upload directory goes the same way. Nothing changes on
the network: the launcher's last step ended those processes anyway, a moment
later.

The browser's temporary directory (TMP, TEMP and TMPDIR, inside this process's)
is SessionFiles' too: Firefox's cleanup in the system one was cut off by short
sessions, and a 70 s session left two 4 MB Remote Settings bundles in %TEMP%.

Measured with this branch on firefox-39: two 70 s sessions, and the private TEMP
they ran with was empty afterwards.

- tests/test_juggler_transport.py: the profile is still there when the browser
  is closed and gone after, on the normal path, a failed launch and a refused
  proxy; the temporary directory lives and ends with the session. What
  SessionFiles.remove does about the children that outlive the browser is the
  core's to test.
2026-10-10 14:04:03 +02:00
github-actions[bot]andfeder-cr cbf061a28d record 0.31.0 as published (#318)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-10 05:35:28 +02:00
Federico 9d1635bdc5 0.31.0: firefox-39, a pointer call answers once the page has handled its event (#317)
With invisible-core 39.34.0 and the firefox-39 engine, page.mouse and every
element action return after the page's listeners have run, so the next call
cannot reach the page first; a right click no longer waits out an
acknowledgement that never came.

- tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py asks the
  contract deterministically (a handler that keeps the page busy for 300 ms):
  red on firefox-38, green on firefox-39; and a click that opens a dialog still
  answers.
- Two fakes follow the protocol: the landing comes back with the dispatch.
2026-10-10 05:12:55 +02:00
Federico 40dad414f1 tests: every Juggler protocol name the server writes is in the mirror (#314)
The core checks its client against the protocol mirror, and invisible-selenium
and invisible-puppeteer check their own code; the Playwright server, which writes
more protocol names than any of them, had no such test. It passes today; the
known-bad input is the command the engine dropped, written back into a send.
2026-10-09 20:04:30 +02:00
Federico 92184c6834 tests: the client's browser tests run in both pointer modes, the rest is the core's (#313)
test_juggler_actions.py keeps the tests that need the engine, and each now
runs twice: with the approach drawn by the client (this package's mode) and
by the engine (engine_approach=True, the mode invisible-selenium and
invisible-puppeteer use). Those two packages carried a copy of this file each
and drop it; the tests without a browser moved to invisible-core with the
client they test.
2026-10-09 19:08:06 +02:00
github-actions[bot]andfeder-cr fad3d56cba record 0.30.0 as published (#312)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-09 17:24:57 +02:00
Federico 0683e74e45 0.30.0: the Juggler client comes from invisible-core 38.34.0 (#311)
The pipe, the protocol mirror, the frame lifecycle, the injected script, the
input actions, the keyboard and the human rhythm leave this package for
invisible_core.juggler, the one copy invisible-selenium and
invisible-puppeteer now share too. _juggler/ keeps the Playwright server.

- Imports use the core's public names only (the package re-exports them);
  tests/test_juggler_lives_in_the_core.py refuses a core module copied back.
- user.js is written by invisible_core.launch.write_user_js, the one writer:
  a firefoxUserPrefs value Firefox has no pref type for is refused.
- The unit tests of the moved modules, and the injected-script page-surface
  gate, are the core's now; the browser tests stay here, where the e2e job
  has the engine (test_juggler_lifecycle_e2e.py brings back the lifecycle's).
- The e2e job checks the mirror against the engine with
  python -m invisible_core.juggler._gen_protocol --check.
2026-10-09 16:58:58 +02:00
github-actions[bot]andfeder-cr b02cde7ffb record 0.29.0 as published (#310)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-09 12:09:25 +02:00
Federico d4df15396d 0.29.0: the window Windows Firefox draws, firefox-38 (core 38.33.0) (#309)
- A maximized window answers screenX -8 and an outerWidth 16 wider than screen.availWidth at 100%, as Windows Firefox does, and its content starts where retail's does at every display scale (mozInnerScreenY 85.6 at 125%). A popup answers its own size, frame and position, and one opened without a position is placed where Windows Firefox places it. The frame is measured on Windows Firefox 151 at the four display scales the personas use.
- The default viewport and the tests follow the core's per-scale frame; docs/pinning.md drops the four window pins the core no longer accepts.
- The pins screen.chrome_w, screen.chrome_h, screen.window_x and screen.window_y are gone; screen.dpr takes 1, 1.25, 1.5 or 2.
2026-10-09 11:36:02 +02:00
Federico d606c4ee4b README: the animation reads at the size GitHub draws it, with a third version for narrow phones (#308)
GitHub draws the 1280px animation in an 838px column (0.655) and the 720px phone one 254-472px wide (0.35-0.66), so their smallest text reached a visitor at 9-11.8px. Every text is now at least 19px in the wide animation, 28px in the phone one, and 35px in a new one for phones up to 374px (banner-small-{light,dark}.gif); the scene titles are larger and the line under them semibold. Same scenes and timing.

Measured with Playwright on seventeen device profiles, from 320px phones to 1920px desktops, in light and dark, through a local copy of the README laid out with the column github.com gives each width: the smallest text is 12px or more on every one, and each loads the GIF of its own theme.
2026-10-09 03:24:35 +02:00
github-actions[bot]andfeder-cr b7458ba3e0 record 0.28.0 as published (#307)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-09 02:49:56 +02:00
FedericoandRichard Powell 0aed66de2f 0.28.0: firefox-37, service workers blocked in the engine, the screen in CSS pixels (core 37.33.0) (#306)
- `service_workers="block"` on `new_context()` and `launch_persistent_context()` turns service workers off for that context inside the engine (`Browser.setServiceWorkersBlocked`, firefox-37), before the context is handed out: no page script, no global preference, and `route()` still sees every page request. On a persistent profile the block removes the service workers that profile had saved. A context whose options fail is removed, and a persistent launch whose context fails closes the browser. Adopted from #299 by Richard Powell, without the engine probe: the pinned engine always has the command.
- The screen a page reads is in CSS pixels, and the default viewport with it, from the core's `context_geometry()` (a 1920x1080 panel at 125% reads 1536x864).
- On Linux the Xvfb display keeps X access control on, with a private cookie per session (core 37.33.0).
- An empty request header survives a route (firefox-37). New e2e tests read the raw HTTP/1.1 header block with and without a route, and check that a reloaded page is controlled by its service worker.
- A glide to where the pointer already is sends nothing instead of raising.
- `docs/differences-from-playwright.md` lists every place this package deliberately differs from Playwright.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-09 02:26:09 +02:00
Federico c279fb1632 README: the banner is an animation, as invisible_dots' is (#304)
It opens on the name and the logo, shows four scenes of what this package does, each taken from this README, and comes back to the logo, so the loop has no seam. A phone version, with nothing under 28px, takes over up to 1239px, where GitHub's README column is under 800px; both come in light and dark, on GitHub's own page colour, so no box shows around them.

The last scene is the five results of docs/screenshots/hero.gif. docs/banner-light.png and banner-dark.png stay: the README of the release on PyPI loads them from main.
2026-10-08 15:47:49 +02:00
Federico a310439f1f README: one banner for the four browser repositories, and a narrow one for phones (#302)
invisible_playwright, invisible_playwright_mcp, invisible_selenium and invisible_puppeteer now share one banner: the same title size (the one invisible_playwright's banner had), the same height, logos of the same weight and the same spacing, with only the width following the name.

On a phone the wide banner shrank to about 45px high and its title to body-text size. A narrow version, the logo above the title, now replaces it where github.com's README column is under about 520px: viewports up to 600px, and 768-880px, where the sidebar narrows the column. Every narrow banner is the same size, so the title is one size on a phone in all four.
2026-10-08 03:42:27 +02:00
github-actions[bot]andfeder-cr 9fc1d25b37 record 0.27.0 as published (#301)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-06 08:22:29 +02:00
Federico f6f4377685 0.27.0: the language of a session is the real Firefox of its egress country (core 36.33.0) (#300)
Requires invisible-core 36.33.0 (exact, as before).

- locale="auto" declares the real Firefox of the egress country, by share:
  each country carries the Firefox builds people there run and their share
  (Mozilla's Firefox Public Data Report), and the egress IP picks one. The
  same address always gets the same language. A country used to map to one
  country tag (de-DE) that no Firefox build has.
- An explicit locale is navigator.language: locale="en-AU" reports
  "en-AU, en-US, en" (it reported "en-US, en"). The test that pinned the old
  answer now pins the new one.
2026-10-06 07:55:44 +02:00
github-actions[bot]andfeder-cr 7c48af1fcf record 0.26.1 as published (#298)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-05 20:29:31 +02:00
FedericoandRichard Powell 4fa406fc45 0.26.1: add_script_tag and add_style_tag answer on the Frame channel (#297)
Lands #296.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-05 20:04:12 +02:00
github-actions[bot]andfeder-cr 0bacbdf066 record 0.26.0 as published (#294)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-05 18:49:04 +02:00
FedericoandRichard Powell 13766fe836 0.26.0: firefox-36, and the session language is the core's decision (#293)
Lands #277.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-05 03:48:49 +02:00
github-actions[bot]andfeder-cr 878794f099 record 0.25.13 as published (#292)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-04 15:43:30 +02:00
Federico b29531d643 A page's number in the session follows the call, not the engine (#291) 2026-10-04 14:47:08 +02:00
FedericoandRichard Powell b35a837c50 0.25.13: routes intercept, or refuse when they cannot (#290)
Lands #274.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-04 14:18:38 +02:00
github-actions[bot]andfeder-cr 30c0bf4044 record 0.25.12 as published (#289)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-04 13:29:44 +02:00
Federico 2c4913a122 0.25.12: no pause helper in the public API; set_input_files takes the pause itself (#288)
invisible_playwright.hesitation() was the one addition this package made to Playwright's public contract, and the package adds nothing to it. Its only use was the pause before answering a file chooser; set_input_files, and so FileChooser.set_files, now hands the files over after two of the session's hesitations (finding the file, confirming it), once per upload and bounded by the action's timeout, the way fill already pauses before its first key. With humanising off nothing changes. The helper is removed.
2026-10-04 13:08:10 +02:00
Federico 54dd95b151 The hidden-desktop e2e counts only its own session's windows (#286)
The hidden-desktop e2e counted every Mozilla window on the desktop, so any other Firefox open on the machine made a correct build fail with "a headless=True session put a window on the interactive desktop": 5 foreign windows, the same red on firefox-35 and on the build under test. A window now counts when its process carries the session's token, the stamp the reaper already reads, and the headed control arm still has to see its own window, so a headless window that lands on the visible desktop is still caught.
2026-10-04 04:51:44 +02:00
github-actions[bot]andfeder-cr 1d730d1275 record 0.25.11 as published (#285)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-04 04:15:19 +02:00
Federicoandpaulthesocket 91c1b3c92f 0.25.11: a page the site opens is a Page (#284)
Builds on #281 by @paulthesocket, whose commit is the base of this branch.

A page the site opens, with window.open or a target=_blank link after a real click, never became a Page: no page or popup event, and context.pages stayed at one. Pages are now adopted from attachedToTarget, the same single path every page takes, so all nine opening shapes tried (plain, with features, named, noopener, from a timer inside the click, target=_blank, rel=opener, a popup that closes itself, one closed by its opener) give one page event, one popup event and the right opener. On top of the original commit: the popup's own document now reaches context.on("request"/"response"), which matters for a PDF opened in a new tab; a page's end is cleaned up in one place instead of five; only targets of type page are adopted and a late target for a closed context is refused. Nothing the popup can read changed: opener, name, bars, size, focus, userActivation and webdriver are identical, and the popup blocker still blocks what retail Firefox blocks.

Co-authored-by: paulthesocket <paulthesocket@users.noreply.github.com>
2026-10-04 03:48:54 +02:00
github-actions[bot]andfeder-cr de4ed775bd record 0.25.10 as published (#283)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-04 02:31:46 +02:00
FedericoandRichard Powell 9da47ce395 networkidle is one load state, and every wait sees it (#282)
Builds on #280 by @richardpowellus, whose commit is the base of this branch.

After a goto, the old page's silence could satisfy wait_until="networkidle" before the new document had loaded (#280). Looking at it, networkidle had two definitions and the client never received the state at all: wait_for_load_state("networkidle"), wait_for_url and expect_navigation with networkidle always timed out. networkidle is now a load state like the others, born once in the lifecycle when the current document has loaded and the network has been quiet for half a second, reset with the next document, and sent to the client from that one place, so goto and every client wait read the same definition. A goto to a fragment of the same page now answers after its navigated event, as upstream does, so page.url already has the fragment.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-04 02:07:56 +02:00
Richard PowellandRichard Powell 27f7deb309 0.25.10: eval_on_selector and eval_on_selector_all pass arg (#278)
The argument was dropped, so an expression passed to eval_on_selector or eval_on_selector_all that read it failed with "a is undefined". The wrapper that turns the caller's expression into a call was written out by hand in four places, which is how two of them came to forget the argument; it is now built in one place (_marshal._invocation), and a test keeps it that way. The script that runs in the page is byte-for-byte the same.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-04 01:44:10 +02:00
github-actions[bot]andfeder-cr 460caeccae record 0.25.9 as published (#275)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-03 05:36:43 +02:00
Federico d94b0350de 0.25.9: the firefox-35 engine, with values committed through Firefox's own user paths (#273)
The wrapper speaks the firefox-35 engine and pins the core that seals it (invisible-core 35.32.0).

select_option, and fill on a field whose value is picked rather than typed (date, time, color, range), now let the engine commit the value through Firefox's own user path (Page.selectOptions, Page.setUserInput), so Firefox fires input and change itself with a user's flags, and nothing when a select did not change; a select or date field inside a shadow root can be set at all. On a page with a saved zoom a click lands where it was asked. On Linux behind a SOCKS proxy real sites see WebRTC working, and the check that used to skip that case now fails if the srflx is missing.

This version does not run on firefox-34, and earlier versions do not run on firefox-35. Verified on the published firefox-35: full e2e on Windows and Linux, transport parity with retail Firefox 151, and the canonical WebRTC/geo sites through a real proxy on both.
2026-10-03 05:13:29 +02:00
Federico ca4c55ac55 The two-tab rhythm e2e judges a timeline that load cannot rewrite (#272)
The e2e that checks two tabs of one session type with two rhythms failed on loaded CI runners with a correct build. It typed "hello", whose two plans differ by about 0.4 s over four intervals, while four browsers on four CPUs delay a single key by up to 480 ms: the tab with the faster plan then sat nearer the other one. Measured on Linux, no tab ever got the other tab's page number (0 of 440).\n\nIt now types "helloworld", whose plans differ by about 5 s, judges the pause and the intervals as one timeline with the median offset taken out, and requires the plans to differ by more than twice the worst delay measured. Under the same load: 12 of 12 green, and the defect it exists for (every page numbered from 0) caught 12 of 12.
2026-10-02 21:13:26 +02:00
github-actions[bot]andfeder-cr bb336142f2 record 0.25.8 as published (#271)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-10-02 19:05:58 +02:00
Federico 6288d90719 The pin moves to core 34.32.0: a Linux headless session starts on its own display (#270)
On Linux a headless session could land on another session's virtual display, or on an Xvfb that had died opening its sockets, because the display counted as ready as soon as its lockfile existed; the browser then failed with cannot open display. invisible-core 34.32.0 waits for Xvfb's own report and keeps the display off the network. Same engine (firefox-34).
2026-10-02 18:05:28 +02:00
Federico 6d9b01a0ce A typist's pause before the first key, a rhythm per tab, and delay on every key path (#269)
Three things a page can measure about how this package types, fixed where they happen.

fill and press_sequentially focused the field and pressed the first key a few milliseconds later, which no hand does, and a page that answers the focus a moment later wrote over the text that was arriving. With humanising on, the session's typist now pauses for one of its hesitations after the focus, starting again whenever the field changes, for no longer than the action's timeout. The spread of a hesitation is one field of the typing persona, and invisible_playwright.hesitation() exposes the pause for acts the package does not perform itself, so a caller no longer imports private names.

The counters behind the pause, the key intervals, the click hold and the drag lived on each page and started again on every new one, so with one seed the first field of every tab was typed the same way. They now belong to the session: page number plus a count per page, as the client cursor already did.

delay on page.type, locator.type, press_sequentially and press was accepted and dropped (locator.type("abcd", delay=150) went out 6, 10 and 22 ms apart); one reader now takes it off the wire for every key operation.

The keystroke timing guide said the rhythm is not seeded; it is, within one call, and the page now says so.
2026-10-02 16:07:22 +02:00
Richard PowellandRichard Powell c61e4d73a9 Nested frames, document navigations, fill('') and hidden inputs work (#263)
Four fixes that touch the same server code, landed together:

- Nested and cross-origin frames: inner_text, bounding_box, select_option, scroll_into_view and wait_for_selector read the frame the locator resolved to instead of the top one; parent_frame and frame_element() work. A humanized click inside a nested frame or a shadow root no longer lands on the exact centre every time: the landing point is checked in the element's own document, through one hit test.
- expect_navigation() and wait_for_url() no longer crash on a new document: the navigated event omits a request it does not have instead of sending null, and goto stops emitting a second navigated of its own. A same-document navigation (pushState, hash change) now reaches the client, so page.url follows it and wait_for_url wakes up.
- fill('') and clear() empty the field with a Delete keystroke, as upstream does, instead of selecting the text and leaving it there.
- set_input_files, focus, blur and dispatch_event act on an element with display:none instead of timing out on a missing box, and set_input_files uploads an in-memory payload instead of clearing the input.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-10-02 13:37:12 +02:00
github-actions[bot]andfeder-cr 321809009a record 0.25.7 as published (#261)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-25 15:41:50 +02:00
Federico f8b80c40b5 goto returns on pages that redirect themselves, and the browser's output is read for its whole life (#259)
goto on YouTube (`?themeRefresh=1`), on Reddit's JavaScript challenge, and on
any page that calls `location.replace` before `load` timed out after 45 s on a
page that was ready, while stock Playwright 1.61 answered in 2 to 4 s on the
same Firefox 151 and on Chromium. Such a page starts a new navigation after
ours has committed; our navigation never reaches `load`, and `wait_for_state`
accepted only the states of our own navigation id. The guard exists for a real
defect, the previous document's states being taken for ours (2026-08-27), but
that one is about navigations from BEFORE ours. The frame now numbers the
navigations it sees, and the wait accepts ours or one that came after it:
Reddit 5.8 s and YouTube 3.4 s on the fixed client. Two unit cases, one per
side of the line, and an e2e against a local page that replaces itself; three
mutations caught, and the old guard reproduces the YouTube message exactly.

The browser's stdout and stderr share one pipe, read only until the readiness
line. Once Firefox had written a pipe buffer's worth after startup, its next
write blocked and the browser stopped answering with no error: forced with
`devtools.console.stdout.content`, 2 KB still answered and 8 KB never did,
5085 bytes sitting unread. ProcessOutput is now the one reader, for the whole
life of the process, keeping the last 200 lines; readiness is a question asked
of it. When the pipe closes mid-session the error now carries the exit code
and those lines, not only "the pipe is closed". Unit tests on a real OS pipe
and an e2e writing 64 KB; the reader that stops at readiness makes both fail.

The pin moves to invisible-core 34.31.0 (GeoIP under a non-ASCII path, Windows
ARM64). Version 0.25.7. Full e2e: 231 passed, 3 skipped.
2026-09-25 15:15:51 +02:00
Federico b562cb8078 The README opens with what Playwright gets and what this one runs on, in two lines (#260)
The subtitle was two sentences of forty-four words that changed subject three
times. Now it says the thing the way the MCP server's README does: what happens
to Playwright, what this one is, and that existing Playwright code works. Free,
open source and the detection suites stay where the hero shows them.
2026-09-25 15:07:46 +02:00
github-actions[bot]andfeder-cr 7717bd6f3e record 0.25.6 as published (#258)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-25 10:48:45 +02:00
Federico bf77af0198 The engine starts under Claude Desktop: the pin moves to core 34.30.0 (#257)
Claude Desktop on Windows is an MSIX package, and so is the Microsoft Store
Python. Files written under AppData by a packaged app's processes really land
in the package's own LocalCache folder, and the engine downloaded there could
not be started from the AppData path: `[Errno 14001] ... side-by-side
configuration is incorrect`, because Windows looks for `mozglue.dll` where the
file really is. Every session of the MCP server under Claude Desktop failed at
its first `browser_open`. Reported in discussion #256; issue #22 was the same
failure under the Store Python.

The fix lives in invisible-core 34.30.0: `verify_engine`, which every launch
route in this package already goes through, hands back the path the file
system reports. Nothing in this package's code changes. The core's CI now
downloads and launches the engine inside a registered MSIX package on every
push.

Version 0.25.6.
2026-09-25 10:26:45 +02:00
github-actions[bot] 609c22fe8d record 0.25.5 as published (#255)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-09-23 20:48:18 +02:00
Federico a1f28bd774 The README is checked for promises no measurement supports, on every change (#254)
A sentence in this README promised to beat everything until 2026-09-22 ("it
passes every bot detection test"), and the check that found it ran by hand from
outside the repository, after the text was public. It is invisible_core.claims
since core 34.29.0, and a new `claims` job runs it with its selftest first, the
same shape as the language gate. `gate` waits for it and refuses on its failure.

What it reads is the README, which is also what PyPI shows; a circumvention claim
on its own stays allowed and is only reported. On this README today it reports
three and refuses none.

The pin moves to invisible-core 34.29.0 and the version to 0.25.5. No runtime
change in this package.
2026-09-23 20:29:03 +02:00
Federico 7529122385 The headline says what happens, and it no longer promises to beat everything (#253)
Two defects in one sentence, and the second is the serious one.

"it passes every bot detection test" is an absolute over an unbounded set. Nothing can pass every test, and this README already shows the measured figure two lines below, in the hero image whose alt text reads "5/5 detection suites passed". A claim the product cannot support is forbidden on grounds of truth rather than of rule, and a promise that big returns the traffic it attracts. The sentence points at that proof now instead of exceeding it, and the figure is not repeated in prose: the image is where it lives, and a number written twice goes stale in one of the two places.

Both halves were also noun piles with no verb, so a reader had to assemble the product from a list before learning that they write ordinary Playwright code and it runs somewhere undetectable. The action leads now.

Nothing about the circumvention claim changed: bypass, undetected and captcha are all still here, which is the owner's standing decision, and the account-wide scan reports the same pairing for this field as before. What changed is the absolute beside it.

Counted rather than judged: 0 fragments without a predicate where the old one had 1, and 15 of 15 keywords kept. Merged with all 14 checks green. The name scan and the disclosure scan were run by hand on the push range, because a pre-push from a worktree skips both.
2026-09-23 10:35:31 +02:00
github-actions[bot]andfeder-cr 9e9bda4e07 record 0.25.4 as published (#252)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-22 00:17:05 +02:00
Federico c937930b31 The pin moves to the core where the attempt count belongs to the caller (#251)
34.28.0 takes the retry out of the shared download primitive and makes it a
parameter: the engine download keeps its three attempts, and the geoip
refresh asks once when it has a cached mmdb to fall back on and three times
when the cache is cold. Without this the refresh inherited the engine's
policy and would have spent ten seconds of backoff at session start reaching
a fallback it was taking anyway. Nothing in this package changes beyond the
pin; same engine, firefox-34.
2026-09-21 23:58:05 +02:00
github-actions[bot] d187e3683f record 0.25.3 as published (#250) 2026-09-21 20:12:51 +02:00
Federico cb3ca7846c The pin moves to the core that asks again on a transient download failure (#249)
invisible-core 34.27.0 retries the failures that mean ask again when it
fetches the engine: nothing in the package had ever asked twice, so a 504 on
the 262 MB archive ended the install, on a runner and on the machine of
anyone whose first use landed on one. Nothing in this package changes beyond
the pin; same engine, firefox-34.
2026-09-21 19:57:15 +02:00
github-actions[bot] 850b4d63ea record 0.25.2 as published (#248) 2026-09-21 17:57:41 +02:00
Federico 3b6101ad37 build_env verifies the font manifest against the executable and delegates the rest to the core (#247)
It was a twin of the core's launch.build_launch_env: TZ, the WebRTC
declaration, the manifest variable and, since 0.25.0, the hidden surface's
launch_env() with its removals, all written twice. The only thing here that
needs the executable is the manifest check; everything else is composed by
the core (34.26.0), so there is one place that knows what the browser is
launched with. The three environment-variable constants that only this
function read are gone: the strings of the binary contract live in the
composer. Same environment on the wire, which the existing tests assert.
0.25.2, pinned to the core that carries display_env.
2026-09-21 17:33:22 +02:00
Federico f8661f0a8c The Linux e2e reads the environment of the browser it launched (#246)
The Linux e2e reads the environment of the browser it launched

The e2e that ran under xvfb-run was green over two real defects: a headed
session opened while an Xvfb session was alive was born on the Xvfb (B221),
and once that was fixed the hidden browser still carried WAYLAND_DISPLAY.
A page renders on any display, so opening one sees neither. This test reads
/proc/<pid>/environ of each Firefox it launches: a headed control on the
caller's DISPLAY, a hidden session on its own Xvfb with X11 pinned and the
Wayland variables absent while os.environ stays untouched, and a headed
session opened beside the hidden one still on the caller's DISPLAY. Measured
against the v0.25.0 tree it is red on the Wayland variable; on main it is
green. Tests only.

The Linux e2e finds its own browser by a mark, not by counting processes

In CI the e2e runs under xdist with four workers, each a process launching
Firefox at the same time, and the first cut of this test asked for the one
new Firefox and saw two. Counting was the wrong question. Each arm now sets
INVPW_TEST_MARK in this process before launching, the browser inherits it
the way every variable travels into its environment, and the assertion reads
the one Firefox carrying that mark. Green alone and under two workers with
other browser-launching files beside it.
2026-09-21 16:52:34 +02:00
github-actions[bot] 4cc4cc1979 record 0.25.1 as published (#245) 2026-09-21 16:08:29 +02:00
Federico 822bd50811 A launch environment the caller names is the whole environment (#244)
The in-process Juggler server added the named variables onto its own
process environment, so a variable build_env had removed came back from
os.environ: measured on 0.25.0 from the index, a headless=True session on
Linux was born with WAYLAND_DISPLAY still set (/proc/<pid>/environ), and
only GDK_BACKEND=x11 kept it off the real desktop. The server now hands the
engine exactly what was named; naming nothing (a bare launch) still
inherits, because a browser with no PATH and no SYSTEMROOT starts and then
cannot reach the network. Two tests: the composition with its known-bad
merge, and the handler handing that environment to the engine. 0.25.1.
2026-09-21 15:35:25 +02:00
github-actions[bot] a76e01fada record 0.25.0 as published (#243) 2026-09-21 15:25:23 +02:00
Federico ea8d049d6a build_env applies the None half of launch_env(), and the pin moves to 34.25.0 (#242)
On Linux the Xvfb display no longer travels through os.environ: the core's
launch_env() names the variables the browser must carry and, with None, the
five Wayland ones it must not. build_env sets the former and drops the latter
on the session's environment only, so a headed session opened while an Xvfb
session is alive in the same process is born where it was asked to be.
The known-bad input is the update() this replaces, which would hand the
subprocess a None value and keep WAYLAND_DISPLAY. 0.25.0, pinned to the core
that carries the contract, on the same engine (firefox-34).
2026-09-21 15:08:19 +02:00
github-actions[bot] 0f0d4ffcc2 record 0.24.0 as published (#241)
The changelog entry now carries the date the index served 0.24.0, 2026-09-21, which is what the release e2e compares it against.
2026-09-21 13:51:47 +02:00
Federico 47e71541a5 The pin moves to the core that seals firefox-34 (#240)
invisible-core 34.24.0 resolves the first engine whose window capturer reads
a hidden window from its own desktop, which is what the 0.24.0 screencast of a
headless=True session on Windows relies on. CHANGELOG 0.24.0 already names
that engine as a requirement; this is the pin that enforces it.
2026-09-21 08:10:14 +02:00
Federico a86ac08ca7 The environment block spells its NUL terminators with chr(0) (#239)
A control character inside a string literal is what the workbench's literal
gate hunts, because that is how a backslash escape corrupts a Windows path;
the two NULs of the CreateProcessW environment block are deliberate, so they
are spelled with chr() and a comment, which is the form that gate accepts.
Same bytes on the wire: the hidden-desktop and first-launch tests still pass.
2026-09-21 03:28:32 +02:00
Federico e151bb8a3e headless=True on Windows creates the browser on a hidden desktop (#238)
The Windows spawn names the hidden desktop the core created, and the cloak layer is gone

`headless=True` on Windows now creates the browser on the hidden Win32
desktop that `invisible_core` makes for the session. `_spawn_windows` is a
`CreateProcessW` in `ctypes` with `STARTUPINFOEXW`: `lpDesktop` is the one
field `subprocess.Popen` cannot set, so the call is ours, with the same
`PROC_THREAD_ATTRIBUTE_HANDLE_LIST` as before - exactly four handles are
inherited, the two Juggler pipe ends, the child's end of the stdout pipe
and a NUL for stdin - and `_WindowsProcess` gives `Connection` the four
verbs it asked of `Popen`. One spawner for both modes: with no desktop
named, `lpDesktop` stays NULL and the browser is born where the caller is.

`build_env` applies the session's `launch_env()` over a cleared slot, so a
headed session never inherits another session's desktop through
`os.environ`. `build_prefs` loses `headless=`: it selected the cloak layer
and selects nothing now; `virtual_display` is the fact that remains, and
with it the two sandbox keys measured in 2026-05 for exactly this desktop.

The screencast is refused, with the reason, on a hidden-desktop session:
from there the window capture starts and delivers no frame (measured 0 in
15 s against firefox-33, where the same window on the visible desktop gives
93 in 4 s), because the compositor only composes the active desktop. A
refusal that names the cause is the same choice the engine makes for true
headless; a silent black stream is not. `page.screenshot()` is unaffected
and `headless=False` keeps the screencast. Tracked as [B220] in the
workbench; the fix belongs in the engine's window capturer.

`tests/test_cloak.py` is replaced by `tests/test_hidden_desktop.py`, which
also carries the control arm the old guard lacked: a headed window is found
on the interactive desktop before a hidden one is asserted absent from it.
The two public docs pages that described the cloak describe the desktop.

0.24.0, pinned to invisible-core 33.24.0.

The screencast of a hidden session is the engine's to deliver, and the gate asks for it

The refusal of `screencast.start()` on a hidden-desktop session goes, and
so does the `hidden_desktop` flag it rested on: the frames were never the
wrapper's to withhold. They were missing because the engine's cropping
capturer cropped a visible window from the screen, which shows the input
desktop only, and moved the capture thread there for good; firefox-34
keeps a window that lives on another desktop on the window capturer,
whose `PrintWindow` reads it in full from its own desktop. Measured on the
fixed build with a seal of its own: both screencast tests green with
`headless=True`, where firefox-33 gave no frame in 15 s.

`tests/test_hidden_desktop.py` now asks for a frame from the hidden
session, so the engine's release gate proves the capability on every
Windows build. The two screencast tests are back to `headless=True` on
every platform. The CHANGELOG names the engine this release requires.

The std handles the spawner hands Firefox are shaped for its launcher

`tests/test_first_launch_from_a_new_path.py` went red on the ctypes spawn:
the launcher recorded a start and the browser never did. The tree showed
why - python -> browser, no launcher in between - and the Event Log said
where: the launcher's own `CreateProcessW` failed with
ERROR_INVALID_PARAMETER (`LauncherProcessWin.cpp:580`), so it disabled
itself for that path (`|Browser` = 0) and ran on as the browser.

The launcher builds a handle list from its stdin, stdout and stderr plus
the Juggler pipe (`ProcThreadAttributes.h`): it forwards only DISK and PIPE
handles, silently drops the rest while still naming them as std handles,
and never de-duplicates, and Windows refuses a handle list that holds the
same handle twice. The first draft passed a NUL device for stdin and one
handle for both stdout and stderr. `Popen` never tripped it: CPython
duplicates every std handle separately.

stdin is now the read end of a pipe whose write end is closed at once (EOF,
and a PIPE type), stderr its own duplicate of the stdout pipe: five
inherited handles, all distinct. Measured on the fixed build: first launch,
hidden desktop and both screencast tests green, and the launcher chain is
back, python -> launcher -> browser.
2026-09-21 00:55:46 +02:00
Federico aa8dca67c6 The release gate reads the e2e it never looked at (#237)
The gate that decides whether a release goes out runs `python -m pytest -q`,
which is the DEFAULT selection, and the default selection deselects `e2e`. So
the browser-driving suite has never been part of the decision: it runs on every
push and every pull request, and no gate reads it, so a red there stops neither
a merge nor a tag.

That is not hypothetical. 0.22.1 was tagged from a main whose e2e was red, and
nothing said so because nothing was looking. It is the same shape as the
`-m unit` false green the project forbids elsewhere, sitting inside the workflow
that publishes.

The new step ASKS rather than re-runs. The e2e has already run on that commit,
and running it again here would cost five minutes to learn what one API call
answers. What was missing was not a second measurement: it was somebody reading
the first one.

Three verdicts, and the middle one is the one that gets written wrong. A
check-run that concluded badly refuses, naming it. A leg still running waits,
then refuses on the deadline rather than assuming. And NO e2e check-run for that
commit refuses too: an empty list reads the same whether the job was renamed,
never started, or was never configured, and mapping it to a pass turns the gate
into decoration exactly when it matters. A gate that cannot read the checks at
all, for a missing token or an API error, refuses for the same reason.

The verdict is a pure function of the check-runs, so its ten known-bad cases
need no token, no repository and no network, and the workflow runs them before
trusting it. Measured against four real commits as well: a green one passes, a
red one refuses naming the leg, the repository's first commit refuses as absent,
and no token refuses.

Why now and not earlier: this was deliberately left open while the e2e was
intermittently red for a real reason, because a gate that says no at random
teaches people to go around it. That reason was the pointer teleporting under
load, and it shipped fixed in 0.23.0.
2026-09-20 03:24:14 +02:00
github-actions[bot] 3c44f046f4 record 0.23.0 as published (#236)
The upload succeeded and the ledger could not be pushed to main directly: branch protection declines this token, which has no bypass. Merging this keeps the next release from being refused over a missing entry.
2026-09-20 02:55:38 +02:00
Federico 2992056827 A pointer action that did not reach its element says so (#235)
A pointer action that did not reach its element used to return as if it had. The hit target is checked before the action and, on purpose, the geometry is never re-read after it, so a target that moved in between produced no error, no event on the element, and a caller told "done". On a moving target that was hover 2 silent misses out of 8 and click 8 out of 8.

Now the engine records where each event landed, at dispatch, and the driver asks after every commit: a miss raises ActionMissed and is not retried, because a press cannot be taken back. The question carries the id of the last event sent and the engine waits for the renderer's ack of it, since a mousemove is coalesced and dispatched at the next refresh tick, after a question sent right behind it. The e2e job also checks the protocol mirror against the pinned engine now; it had drifted four commands behind with the count test green.

Pins invisible_core 33.23.0 (engine firefox-33), which this change requires. Supersedes #233: that pin, firefox-32, delivered the drag but under load failed clicks more often than the engine before it, measured on the same runners the same day. Also carries the fix to the hover assertion that depended on where the pointer already was.
2026-09-20 02:24:28 +02:00
github-actions[bot]andfeder-cr 93d243c8e9 record 0.22.2 as published (#231)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-09-18 21:29:26 +02:00
313 changed files with 57845 additions and 24426 deletions

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ body:
id: install_cmd
attributes:
label: How you installed
placeholder: pip install invisible_playwright
placeholder: uv add invisible-playwright
validations:
required: true
+76
View File
@@ -0,0 +1,76 @@
# ─────────────────────────────────────────────────────────────────────────────
# counters.yml - the daily snapshot of the launch counter, and the README badges.
#
# GitHub keeps only the running total of a release asset's downloads, so the
# launches of a day exist only if someone records the total every day. This is
# that someone: no machine and no personal token, just the scheduler and the
# built-in GITHUB_TOKEN. A run that fails sends GitHub's failure mail, and the
# run's log warns when a day between two snapshots is missing.
#
# Everything it writes lives on the `badges` branch, which is not protected:
# counters/history.csv date,key,value - every counter, once a day
# counters/launches_daily.csv day_utc,launches - one row per measured day
# docs/badges/launches.svg, docs/badges/stars.svg
#
# 00:10 UTC, so the snapshot dated D closes calendar day D-1.
name: counters
on:
schedule:
- cron: "10 0 * * *"
workflow_dispatch: {}
permissions:
contents: write
concurrency:
group: counters
cancel-in-progress: false
jobs:
snapshot:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out the script (main)
uses: actions/checkout@v4
with:
path: main
- name: Check out the badges branch
uses: actions/checkout@v4
with:
ref: badges
path: badges
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Self-test
run: python main/scripts/launch_counters.py --selftest
- name: Record today's counters and redraw the badges
env:
GITHUB_TOKEN: ${{ github.token }}
run: >
python main/scripts/launch_counters.py
--history badges/counters/history.csv
--daily badges/counters/launches_daily.csv
--badges badges/docs/badges
- name: Commit to the badges branch
working-directory: badges
run: |
set -euo pipefail
git config user.name "feder-cr"
git config user.email "85809106+feder-cr@users.noreply.github.com"
git add counters docs/badges
if git diff --cached --quiet; then
echo "nothing changed"
exit 0
fi
total=$(awk -F, '$2=="launches_total"{v=$3} END{print v}' counters/history.csv)
git commit -q -m "counters: $(date -u +%F), browser launches at ${total}"
git push origin HEAD:badges
+8
View File
@@ -50,6 +50,14 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: hunt (${{ inputs.os }})
+18
View File
@@ -47,6 +47,14 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# The install below resolves `invisible-core==N.M.0` from the package index,
# and the core is published BEFORE this package. This gate answers whether it
@@ -90,6 +98,16 @@ jobs:
sudo "$(which python)" -m playwright install-deps firefox
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The protocol mirror agrees with the engine it is pinned to
# `invisible_core.juggler.protocol` is generated from the Protocol.js INSIDE the
# shipped binary, and nothing used to tie the two together after a pin
# bump: the mirror sat at 71 commands while the pinned engine declared
# 75, with the unit test that fixes the count green the whole time,
# because a count checks the mirror against itself. This is the only
# job that has the binary, so this is where the comparison belongs.
# The generator moved into the core with the module it writes (0.30.0),
# so the check runs against the core this package installs.
run: python -m invisible_core.juggler._gen_protocol --check --binary "$(dirname "$FF")"
- name: Run the full e2e suite under a virtual display
# PYTHONUNBUFFERED, and it is not a nicety. Without it Python block-buffers
# stdout when it is a pipe, and this step printed NOTHING for 39 minutes
@@ -28,6 +28,14 @@ on:
permissions:
contents: read
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# `pip install .` below resolves `invisible-core==N.M.0` from the package
# index, and the core is published BEFORE this package. This gate answers
+61
View File
@@ -30,6 +30,26 @@ on:
permissions:
contents: read
# One publish at a time per repository, whatever started it and on whatever
# ref. Two runs of one tag (a delayed delivery, or a dispatch plus the push)
# would both pass the already-published check before either had uploaded, and
# both would upload. Keyed on the ref, a dispatch on a branch and a push of the
# tag would not wait for each other, so the group is the workflow alone.
# Serialised, the second run waits for the first and then finds the version on
# the index, so it ends as a no-op. Never cancelled in progress: an upload that
# has started must be allowed to finish.
concurrency:
group: publish
cancel-in-progress: false
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# Asked of the INDEX, first, because a tag can legitimately name a version that
# is already published: a tag backfilled for a hand-published release, a tag
@@ -62,6 +82,11 @@ jobs:
needs: already-published
if: needs.already-published.outputs.present != 'yes'
runs-on: ubuntu-latest
# `checks: read` for the step below, which asks what the e2e concluded on
# this commit. Job level rather than workflow level: no other job needs it.
permissions:
contents: read
checks: read
steps:
- uses: actions/checkout@v4
with:
@@ -84,6 +109,29 @@ jobs:
exit 1
fi
- name: the e2e is GREEN on the commit being tagged
# ⛔ THE SUITE BELOW IS THE DEFAULT SELECTION, WHICH DESELECTS `e2e`. So
# until this step existed, the job that decides whether a release goes
# out had never looked at the suite that drives a browser: a red there
# stopped neither a merge nor a tag. 0.22.1 was tagged from a main whose
# e2e was red, and nothing said so because nothing was looking.
#
# It ASKS rather than re-runs. The e2e has already run on this commit;
# running it again here would cost five minutes to learn what one API
# call answers. What was missing was not a second measurement, it was
# somebody reading the first one.
#
# The selftest runs first, because a gate that has only ever printed
# PASS is not a gate - and this one's verdict is a pure function, so its
# ten known-bad cases cost nothing and need no network.
if: github.event_name == 'push'
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
python scripts/e2e_is_green.py --selftest
python scripts/e2e_is_green.py --repo "$GITHUB_REPOSITORY" --sha "$GITHUB_SHA"
- name: the pinned invisible-core is ON THE INDEX
# THE ordering rule, as a gate instead of a sentence in a runbook. This
# package declares `invisible-core==X.Y.Z`, so pip resolves the PUBLISHED
@@ -125,6 +173,19 @@ jobs:
python -m pip install --upgrade pip
pip install -e ".[dev]"
- name: version gate
# The version and the ledger against what the index serves, as the
# pre-push hook checks them: in layers, not as alternatives, because the
# hook is per clone and can be missing or skipped, and this cannot
# ([B353]). Exit codes: 0 pass, 1 refused, 2 gate broken, 4 no usable
# ledger; only 0 continues. The check builds the package to compare
# it, without isolation, so the build backend is installed here: the
# dev extra carries `build` and not `hatchling`, and without it the
# check stopped as "gate broken" on the first tag (v0.40.0).
run: |
python -m pip install build hatchling
python -m invisible_core.release check --verify-index
- name: arm the pre-push gates
# The suite asserts core.hooksPath is set and a fresh checkout has none.
run: python scripts/install_hooks.py
+98 -1
View File
@@ -19,6 +19,14 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# The gate was written FOR this repository on 2026-08-27, after 549 lines of
# Italian shipped here in one subsystem and 852 more were found in 33 files
@@ -60,6 +68,83 @@ jobs:
python -m invisible_core.english --selftest
python -m invisible_core.english
# A README that promises to beat everything was live here on 2026-09-22 ("it
# passes every bot detection test"), and the check that found it ran by hand,
# from outside the repository, after the text was public. The logic is
# `invisible_core.claims` since core 34.29.0, shared with the MCP server's
# repository; what this one reads is declared in `[tool.invisible.claims]`,
# and without a declaration it is the README, which is also what PyPI shows.
claims:
name: the README promises nothing it cannot support
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
run: |
python -m pip install --upgrade pip
pip install -e .
- name: check the claims
# --selftest first, for the same reason as the language gate: a check
# that has only ever printed "clean" may have gone blind.
run: |
python -m invisible_core.claims --selftest
python -m invisible_core.claims
# The way in is uv (the owner, 2026-09-06 and "uv everywhere" on 2026-10-17),
# and on that day this repository still taught pip in its README, its
# CONTRIBUTING, its docs and the messages its code prints, with nothing
# comparing any of them with the decision. `invisible_core.way_in` since core
# 49.45.0 refuses an install instruction that is not uv, in the tracked
# Markdown, the issue templates and the string literals of src/.
way-in:
name: every install instruction is uv
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
run: |
python -m pip install --upgrade pip
pip install -e .
- name: check the way in
# --selftest first: a check that has only ever printed "clean" may
# have gone blind.
run: |
python -m invisible_core.way_in --selftest
python -m invisible_core.way_in
# The user-install job installs what was published, as a user would. It ran
# on `release: published`, which never fires: the Release is created with
# GITHUB_TOKEN, and an event that token causes starts no other workflow
# ([B347], core 50.48.0). `invisible_core.install_job` judges this tree: the
# job runs on the ledger pull request, its wait for the index is scoped to it
# and bounded, and every test file it runs keeps out, in a `_LEAKS`, every
# variable the pinned core's library reads.
install-job:
name: the user-install job runs on the ledger pull request
needs: core-on-index
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install the pinned core, which carries the gate
run: |
python -m pip install --upgrade pip
pip install -e .
- name: check the install job
run: |
python -m invisible_core.install_job --selftest
python -m invisible_core.install_job
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
# package index. The core is published BEFORE this package, so between the
# first push of this repo and that upload there is a window in which no
@@ -240,7 +325,7 @@ jobs:
# exits 1 without saying which of five inputs went red is a gate somebody has
# to open five tabs to read.
gate:
needs: [core-on-index, unit, docs-api, english, version]
needs: [core-on-index, unit, docs-api, english, claims, version, way-in, install-job]
if: always()
runs-on: ubuntu-latest
steps:
@@ -250,7 +335,10 @@ jobs:
echo "unit: ${{ needs.unit.result }}"
echo "docs-api: ${{ needs.docs-api.result }}"
echo "english: ${{ needs.english.result }}"
echo "claims: ${{ needs.claims.result }}"
echo "way-in: ${{ needs.way-in.result }}"
echo "version: ${{ needs.version.result }}"
echo "install-job: ${{ needs.install-job.result }}"
case "${{ needs.unit.result }}" in
failure|cancelled) echo "the suite did not pass"; exit 1 ;;
esac
@@ -263,9 +351,18 @@ jobs:
case "${{ needs.english.result }}" in
failure|cancelled) echo "the repository is not English"; exit 1 ;;
esac
case "${{ needs.claims.result }}" in
failure|cancelled) echo "the README promises what no measurement supports"; exit 1 ;;
esac
case "${{ needs.way-in.result }}" in
failure|cancelled) echo "an install instruction is not uv"; exit 1 ;;
esac
case "${{ needs.version.result }}" in
failure|cancelled) echo "the version this change proposes is already taken"; exit 1 ;;
esac
case "${{ needs.install-job.result }}" in
failure|cancelled) echo "the user-install job would not run on a release, or leaks"; exit 1 ;;
esac
echo "ok"
# Measured 2026-09-04: 0.10.0 was on the index while main sat on 0.10.0 with
+25 -11
View File
@@ -15,12 +15,16 @@
# * installing a blessed `playwright==<pin>` afterwards REPAIRS the venv. If
# the declared range resolves to a client the shipped Juggler cannot speak,
# that manual line turns the job green while every fresh install is broken.
# What a user gets is what pip resolves from the declaration, and that is
# what has to be under test.
# What a user gets is what the installer resolves from the declaration,
# and that is what has to be under test.
#
# So this workflow installs nothing from the checkout except the test files. It
# takes `pip install invisible-playwright` from the index, in an empty venv, and
# runs it the way somebody's first script would.
# So this workflow installs nothing from the checkout except the test files.
# test_release_e2e.py runs the README's install block for the runner's system
# as written - uv from its own installer, `uv init`, `uv add
# invisible-playwright` from the index, `fetch` - and then drives the browser
# from the project it made, the way somebody's first script would.
# test_upgrade_e2e.py stays on pip on purpose: it is the path of the people who
# installed before the README said uv, and they are still there.
#
# WHY IT MUST NOT BE MADE TOLERANT.
# There is a real window in which this cannot pass: between publishing the core
@@ -54,8 +58,16 @@ on:
# here, so a run triggered only by pushes would never see them. Weekly is
# enough to catch that drift without adding a Windows job to the queue daily.
- cron: "17 6 * * 1"
release:
types: [published]
# ⛔ THE LEDGER PULL REQUEST, not `release: published` ([B347], core
# 50.48.0). The Release is created by the publish workflow with GITHUB_TOKEN,
# and an event that token causes starts no other workflow: on `release:` this
# job had never run at release time. The ledger PR exists only after the
# upload and `record`, and merging it waits for this run, so a release does
# not close before what it published installs. `python -m
# invisible_core.install_job` checks the wiring (tests.yml).
pull_request:
paths:
- PUBLISHED.json
permissions:
contents: read
@@ -88,7 +100,8 @@ jobs:
run: python -m pip install --upgrade pip pytest packaging
# PyPI does not serve a new version to pip the instant twine finishes, and
# this workflow runs on `release:` - which fires seconds after the upload.
# this workflow runs on the ledger pull request, which the publish run
# opens seconds after the upload (it ran on `release:`, just as soon).
# MEASURED 2026-07-28: invisible-firefox 0.2.6 was uploaded, the release was
# created about forty seconds later, and the pip install below still resolved
# 0.2.5. The job reported a forgotten publish that had happened two minutes
@@ -99,10 +112,11 @@ jobs:
# PER-VERSION endpoint is the authority; the aggregate `info.version` lags it
# by minutes and has its own trap, so this asks for the exact URL.
#
# Only on `release:`. A scheduled or dispatched run is not racing anything,
# and a wait there would hide a real absence behind five minutes of polling.
# Only on the ledger pull request. A scheduled or dispatched run is not
# racing anything, and a wait there would hide a real absence behind five
# minutes of polling.
- name: wait for the index to serve this version
if: github.event_name == 'release'
if: github.event_name == 'pull_request'
shell: bash
run: |
python - <<'PY'
+13 -3
View File
@@ -6,9 +6,11 @@ name: webrtc-e2e
# carries the WebRTC fixes (synthetic srflx in genuine nICEr form + the
# default-route fallback behind a proxy). Run it after publishing such a
# binary - it is the release gate for "WebRTC looks real behind a proxy".
# Until that binary ships, test_not_blocked_behind_tcp_only_socks is EXPECTED
# to fail (the old binary is fully blocked behind a SOCKS proxy), which is the
# whole point of the gate.
# On this Linux runner an engine older than firefox-35 never gets the synthetic
# srflx behind a SOCKS proxy (the wildcard default-route probe, fixed in
# firefox-35): test_not_blocked_behind_tcp_only_socks skips on it, naming that
# defect, and the floor below turns the skip red. From firefox-35 on, a
# missing srflx fails the test itself.
#
# No external proxy provider, no credentials: the "behind a proxy" condition is faked by an
# in-process TCP-only SOCKS5 server (refuses UDP ASSOCIATE) and the egress IP
@@ -20,6 +22,14 @@ on:
permissions:
contents: read
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
# unauthenticated users failed the gates three times). user-install.yml stays
# anonymous on purpose: it is the user's path.
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
# package index, and the core is published BEFORE this package. This gate
+1527
View File
File diff suppressed because it is too large. Load diff
+12 -12
View File
@@ -4,8 +4,7 @@ Thanks for your interest in improving this project. Contributions are welcome vi
## Quick links
- **Bug?** Open a [bug report](https://github.com/feder-cr/invisible_playwright/issues/new?template=bug_report.yml).
- **Idea?** Open a [feature request](https://github.com/feder-cr/invisible_playwright/issues/new?template=feature_request.yml).
- **Bug or idea?** Open an [issue](https://github.com/feder-cr/invisible_playwright/issues/new/choose).
- **Security issue?** Do **not** open a public issue - see [SECURITY.md](SECURITY.md).
- **The C++ patches** live in the companion repo [feder-cr/firefox_antidetect_patch](https://github.com/feder-cr/firefox_antidetect_patch) (branch `stealth/151`). Bugs in fingerprint spoofing usually belong there.
@@ -13,11 +12,12 @@ Thanks for your interest in improving this project. Contributions are welcome vi
This repository ships the **Python wrapper** (`invisible_playwright`) around a pre-built patched Firefox. In scope:
- The `InvisiblePlaywright` sync/async API and launcher
- The fingerprint sampler (`_fpforge`)
- Binary download/caching, CLI, proxy plumbing
- The `InvisiblePlaywright` sync and async API, and its Playwright compatibility layer
- The CLI (`invisible-playwright fetch`, `invisible-playwright version`)
- Tests, docs, examples, packaging
The fingerprint, the engine download and the browser protocol client are shared by every wrapper and live in [invisible_core](https://github.com/feder-cr/invisible_core).
Out of scope (belongs in `firefox_antidetect_patch`):
- Changes to the Firefox C++ source
@@ -26,19 +26,19 @@ Out of scope (belongs in `firefox_antidetect_patch`):
## Development setup
To *use* the package you do not need any of this: `pip install invisible-playwright`.
The steps below are for working on the code.
To *use* the package you do not need any of this: see [Install](README.md#install) in the README.
The steps below are for working on the code, with [uv](https://docs.astral.sh/uv/).
```bash
git clone https://github.com/feder-cr/invisible_playwright.git
cd invisible_playwright
python -m venv .venv
uv venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
python -m invisible_playwright fetch # download the patched Firefox binary
uv pip install -e ".[dev]"
invisible-playwright fetch # download the patched Firefox binary
```
Requires Python 3.11+ and one of: Windows x86_64, Linux x86_64.
One of: Windows x86_64, Linux x86_64.
## Running tests
@@ -72,7 +72,7 @@ Before opening, please:
Include:
- OS and version, Python version, `invisible_playwright` version (`invisible_playwright version`)
- OS and version, Python version, the output of `invisible-playwright version`
- A minimal reproduction
- Expected vs actual behavior
- Relevant logs / stack traces
+22256
View File
File diff suppressed because it is too large. Load diff
+31 -10
View File
@@ -1,10 +1,14 @@
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-dark.png">
<img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-light.png" alt="invisible_playwright" width="720">
<source media="(max-width: 374px) and (prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-small-dark.gif">
<source media="(max-width: 374px)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-small-light.gif">
<source media="(max-width: 1239px) and (prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-phone-dark.gif">
<source media="(max-width: 1239px)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-phone-light.gif">
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-dark.gif">
<img alt="invisible_playwright, Playwright on an anti-detect Firefox. An animation: the two-line switch from Playwright, the fingerprint set inside the engine, a mouse that moves like a hand, and the bot tests it passes." src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-light.gif" width="100%">
</picture>
<h3 align="center">Free antidetect browser stealth for Playwright: undetected Firefox fingerprint, headless or headed.<br>
Python web scraping and captcha bypass. Open source, and it passes every bot detection test.</h3>
<h3 align="center">Playwright gets caught by anti-bots and captchas.<br>
This one runs on an anti-detect Firefox with an undetected fingerprint, compatible with your existing Playwright code.</h3>
</div>
![invisible_playwright - 5/5 detection suites passed](https://raw.githubusercontent.com/feder-cr/invisible_playwright/7a8693c6b4386e9a84dd93bedc479ca8654482e1/docs/screenshots/hero.gif)
@@ -27,14 +31,31 @@ Anti-bots ask two questions, and reCAPTCHA, hCaptcha and Cloudflare Turnstile sc
## Install
```bash
pip install invisible-playwright
python -m invisible_playwright fetch # one-time download, sha256-verified: 240 MB (Windows) / 262 MB (Linux x86_64) / 253 MB (Linux arm64), about 550 MB unpacked
Windows, in PowerShell:
```powershell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
$env:Path = "$env:USERPROFILE\.local\bin;$env:Path"
uv init --python ">=3.11" my-project
cd my-project
uv add invisible-playwright
uv run invisible-playwright fetch # one-time download, sha256-verified: 240 MB, about 550 MB unpacked
```
Requires **Python 3.11 or newer**.
Linux:
Supported platforms: **Windows x86_64**, **Linux x86_64 / arm64**.
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
uv init --python ">=3.11" my-project
cd my-project
uv add invisible-playwright
uv run invisible-playwright fetch # one-time download, sha256-verified: 262 MB, about 550 MB unpacked
```
Supported platforms: **Windows x86_64**, **Linux x86_64**. Linux arm64 is no longer supported from firefox-56 (firefox-55 is the last engine built for it).
Then save one of the examples below as `main.py` in `my-project` and run it with `uv run main.py`.
---
@@ -301,7 +322,7 @@ This project is for educational purposes only. It is provided as-is, with no war
<a href="https://github.com/feder-cr/invisible_playwright/actions/workflows/tests.yml"><img src="https://github.com/feder-cr/invisible_playwright/actions/workflows/tests.yml/badge.svg" alt="tests"></a>
<a href="https://github.com/feder-cr/invisible_playwright/blob/main/LICENSE"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/license.svg" alt="License: MIT"></a>
<a href="https://www.python.org/downloads/"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/python.svg" alt="Python 3.11+"></a>
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/firefox.svg" alt="Firefox 151.0"></a>
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/firefox.svg" alt="Firefox 159.0"></a>
<img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/launches.svg" alt="browser launches">
<a href="https://github.com/feder-cr/invisible_playwright/stargazers"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/stars.svg" alt="GitHub stars"></a>
</p>
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="99" height="20" role="img" aria-label="Firefox: 151.0">
<title>Firefox: 151.0</title>
<svg xmlns="http://www.w3.org/2000/svg" width="99" height="20" role="img" aria-label="Firefox: 159.0">
<title>Firefox: 159.0</title>
<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
<clipPath id="r"><rect width="99" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
@@ -10,7 +10,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="28.0" y="15" fill="#010101" fill-opacity=".3">Firefox</text>
<text x="28.0" y="14">Firefox</text>
<text x="77.5" y="15" fill="#010101" fill-opacity=".3">151.0</text>
<text x="77.5" y="14">151.0</text>
<text x="77.5" y="15" fill="#010101" fill-opacity=".3">159.0</text>
<text x="77.5" y="14">159.0</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 855 B

After

Width:  |  Height:  |  Size: 855 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

@@ -119,7 +119,8 @@ step so the download never lands on a request path:
```dockerfile
FROM python:3.12-slim
RUN pip install invisible-playwright
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN uv pip install --system invisible-playwright
# Unpack the engine at BUILD time, not per request.
RUN python -m invisible_playwright fetch
# ... your worker entrypoint ...
+2 -1
View File
@@ -71,7 +71,8 @@ row is for a specific situation.
| Variable | When you need it |
|---|---|
| `INVISIBLE_PLAYWRIGHT_CACHE_DIR` | Put the cached engine somewhere else - another drive, a shared location, a path your CI already caches |
| `INVISIBLE_PLAYWRIGHT_CACHE_DIR` | Put the cache somewhere else - another drive, a shared location, a path your CI already caches. It holds the engine and this machine's state (the GeoIP database, the font manifest) |
| `INVISIBLE_PLAYWRIGHT_ENGINE_DIR` | Keep the engine apart from the state, for example on a read-only disk built once per release: `invisible-playwright fetch` with it set fills it, and a launch only reads it. The cache directory must still be writable |
| `INVPW_BINARY_PATH` | Point at a binary you already have, and skip the download |
| `STEALTHFOX_GITHUB_TOKEN` | A rate-limited or corporate network that refuses anonymous GitHub downloads |
| `INVISIBLE_PLAYWRIGHT_SKEW=allow` | Run a Playwright version outside the tested range anyway |
+58
View File
@@ -0,0 +1,58 @@
---
title: "Differences from Playwright"
description: "Where invisible-playwright deliberately behaves differently from upstream Playwright, what it refuses, and why each one is a choice rather than a gap."
parent: "Documentation"
nav_order: 6
---
# Differences from Playwright
invisible-playwright adds nothing to Playwright's API: every method, option and
argument is Playwright's own. Where it cannot do what Playwright does without leaving
something a page can see, or without claiming to have done something it did not, it
says so with an error instead of pretending. This page lists those places.
## Objects that are not implemented
These exist only so the object tree is well formed. Every call on them raises an error
that names the reason.
| Object | Why |
|---|---|
| `Tracing` | It records a session for the trace viewer and drives none of it. `tracing.stop()` is accepted and does nothing, so code that always stops a trace keeps working. |
| `APIRequestContext` (`context.request`, `playwright.request`) | It sends HTTP from outside the page, without the browser's fingerprint, which is the opposite of what this package is for. |
## Calls that are refused
| Call | What happens | Why |
|---|---|---|
| `set_input_files()` with a folder | Error | The engine takes files. Pass the files inside the folder. |
| `set_input_files()` with an in-memory payload | Works, but `mimeType` is ignored | The payload is written to a file and handed over the way a user's pick is, so Firefox derives the type from the file name, as it does for a real pick. |
| `drop()` with an explicit data payload | Error | The engine builds the `DataTransfer` from a real pointer drag. Use `drag_and_drop()`. |
| `route_web_socket()` | Error | The engine reports WebSocket frames but cannot hold or rewrite one, so a route would look like it worked and pass everything through. |
| Screencast to a video file | Error | The engine streams JPEG frames and has no encoder. Pass `on_frame=` to receive the frames. |
| `register_selector_engine()` or `set_test_id_attribute()` after a page exists | Error | Both are built into the page's injected script when it is created. Call them before the first page. |
| `expose_binding()`, `expose_function()` | Error, not implemented yet | The page-facing half is easy; the reply path into the page's promise is not wired, and a binding that never answers would hang the page. |
| `set_storage_state()` with per-origin `localStorage` | Error, not implemented yet | Restoring only the cookies would look like success and leave half the session missing. |
| `response.body()` on a very large or old response | Error | The engine keeps at most 100 MB of response bodies per tab and 10 MB per response. Read the body sooner. |
## Behaviour that differs on purpose
- **`service_workers="block"`** is honoured by the engine itself, per context, with
no page script: `register()` fails the way it fails when the worker's script is
unreachable, and `navigator.serviceWorker` stays native. Playwright does it with a
page script whose source names Playwright. On a persistent profile, turning the
block on removes the service workers the profile had saved for that context, and
they do not come back when the block is turned off.
- **Language.** `locale="auto"` (the default) declares the language of a Firefox
build people in the proxy's country actually run. An explicit `locale` is
`navigator.language`, followed by the fallbacks Firefox itself adds
(`en-AU, en-US, en`).
- **Human input.** With `humanize=True` (the default) the pointer moves along a paced
path, typing pauses before the first key, and a file chooser waits as a person
looking for the file does. Calls take longer than in Playwright, and the page sees a
person's timing.
- **The server speaks to this client only.** The bundled Playwright client and the
bundled server are versioned together; a stock Playwright client cannot drive the
server directly.
+1 -1
View File
@@ -141,7 +141,7 @@ Playwright method works unchanged because there is no wrapped subset to learn.
Install is the ordinary way, and the engine downloads itself on first use:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
That is the engine layer, in full, scriptable. What it does not print is a
+12
View File
@@ -81,6 +81,18 @@ All three are page-visible because they live in the document or the global scope
them is the control channel. Fixing them is a matter of not writing them into the page in
the first place, which is a design decision, not a runtime patch.
There is a fourth, and it is the one you control rather than one the browser decides:
**an init script of your own that throws reaches the page.** A script added with
`page.add_init_script()` runs in the page's own realm, so a callback it registers - an
event listener, a timer, a promise - throws into that realm like any other page code.
An uncaught one reaches the page's `window.onerror` with `"eval code"` as its source,
which is a string a document that never calls `eval` has no other way to produce. The
browser's own injection does not do this: measured on a page that installs `onerror`,
a capturing `error` listener and `unhandledrejection` before anything else, then reads
every surface this package spoofs, nothing surfaces across repeated loads, reloads and
an iframe. So keep your own init scripts inside `try { } catch { }`, especially the
callbacks they leave behind, and prefer feature checks over assuming a property exists.
## Chromium injects cdc_ into the document; Firefox through Juggler does not
Chromium-based tooling writes `cdc_`-prefixed properties into the page; Firefox driven
+1 -1
View File
@@ -112,7 +112,7 @@ The launch is the same two lines for both agents. The seed makes the identity
reproducible, so a failing run can be replayed rather than guessed at.
```bash
pip install invisible-playwright
uv add invisible-playwright
```
A DOM-reading agent reads structure and acts on a selector:
+3 -3
View File
@@ -223,9 +223,9 @@ deploy on. A blank or changing emoji is a failure, not a pass.
## Sources
- This project's font architecture and its cross-OS font gate, which runs the
browser on a Linux host with no Windows fonts and reads what it renders,
including colour emoji (decision log, 2026-06-20).
- This project's font architecture and its cross-OS host gate, which runs the
browser on a Linux host with no Windows fonts and compares what a page reads,
colour emoji included, with the Windows build (decision log, 2026-06-20).
- Firefox's use of a bundled colour-emoji font in place of the platform emoji
font, verified against a stock build on more than one operating system.
- [`HTMLCanvasElement.toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
+1 -1
View File
@@ -97,7 +97,7 @@ a Playwright page directly. Because invisible_playwright hands you a genuine
Playwright `Page`, the port attaches to it with no adapter:
```bash
pip install invisible-playwright python-ghost-cursor
uv add invisible-playwright python-ghost-cursor
```
```python
+1 -1
View File
@@ -44,7 +44,7 @@ override from the page, because the page is not where the tell originates.
- [Execution context was destroyed, and when it means detection](execution-context-destroyed.md) - Usually a race condition, but sometimes a redirect to a challenge; how to tell the two apart.
- [Why content_frame() returns None for a cross-origin iframe](cross-origin-iframe-unreachable.md) - One shared cause behind None, throws and timeouts: process isolation, not a permissions bug.
- [Running Playwright Firefox on ARM64 Linux](playwright-firefox-arm64-linux.md) - What ships per architecture on ARM64 Linux, the emulation trap, and the memory ceiling.
- [Running Playwright Firefox on ARM64 Linux](playwright-firefox-arm64-linux.md) - What ships per architecture on ARM64 Linux, the emulation trap, and the memory ceiling (this project no longer ships a Linux arm64 engine from firefox-56).
## Human-like input and interaction
+2 -1
View File
@@ -113,8 +113,9 @@ time, so point it at a persisted path:
```dockerfile
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN pip install invisible-playwright
RUN uv pip install --system invisible-playwright
# keep the cached engine on a mounted volume so it downloads once
ENV INVISIBLE_PLAYWRIGHT_CACHE_DIR=/engines
+39 -25
View File
@@ -70,15 +70,17 @@ what this project does when you ask for `headless=True`.
The browser is launched **headed** and the window is hidden, by a different mechanism on
each platform:
- **Windows.** The browser cloaks its own windows through the compositor, so they render
on the real GPU and never appear on screen, in the taskbar or in the switcher.
- **macOS.** The window is kept fully transparent with occlusion checks pinned, so the
system does not stop drawing it.
- **Windows.** A fresh desktop object is created for the session and the browser process
is created *on* it, so the whole tree - launcher, parent, GPU and content processes -
lives on a desktop nobody switches to. It renders on the real GPU and never appears on
screen, in the taskbar or in the switcher. The browser binary is not involved in the
hiding at all.
- **Linux.** A private virtual display is started for the session and the browser is
pointed at it, because X11 and Wayland have no per-window equivalent that keeps the
GPU rendering.
The point of all three is the same: stay on the code path a visible browser uses.
The point of both is the same: stay on the code path a visible browser uses, and hide
the screen rather than the window.
Being straight about the limits, because they matter:
@@ -108,27 +110,39 @@ same process level passed throughout, which is exactly why this went unnoticed:
thing validating the behaviour and the thing shipping it were not using the same
mechanism.
The fix is a compositor-level cloak, set on the window itself rather than on any
thread or process, which is also why it needs to live in the browser binary: only the
window's own owning process can set that attribute. Validated
afterward against a visible, headful window on the same machine: identical fingerprint
surface (no `visibilityState`, focus, canvas or WebGL tell), a real GPU-composited
screenshot, and a passing result on a commercial detector that specifically checks for
masked headless state. A per-platform automated check now asserts the underlying
window attribute directly - the cloak flag on Windows, the transparency and occlusion
state on macOS - rather than trusting a screenshot alone.
The first fix was a compositor-level cloak, set on the window itself from inside the
browser binary, because only the window's own owning process can set that attribute.
It worked, and it was validated against a visible, headful window on the same machine:
identical fingerprint surface, a real GPU-composited screenshot, a passing result on a
commercial detector that specifically checks for masked headless state.
**The same fix closed a second, unrelated-looking bug for free.** An earlier hiding
approach had put the browser's main process on one virtual desktop and left its
sandboxed content processes on a different one by default. Ordinary page loads never
noticed. A page that triggered a cross-process navigation - handing the active tab from
one content process to another mid-session - did notice: the window being reparented
expected both processes on the same desktop, found them split across two, and the tab
crashed. Because the compositor-level cloak keeps every process on the single real
desktop and hides at the window level instead, that split stopped existing as a
possibility, and the crash went away as a side effect of fixing something else
entirely. It's a reminder that "which mechanism hides the window" and "which processes
can actually talk to each other" are not as separate as they look.
It was replaced anyway, for a reason that has nothing to do with whether it worked: it
was a patch inside the browser on a surface that has nothing to do with fingerprinting,
and the fewer of those a modified browser carries, the less there is to diverge from
the original. The current mechanism puts the hiding back where the operating system
already offers it. A desktop object is created per session and the browser *process*
is created on it - the process, not the thread, which is exactly the scope the latent
bug above had got wrong. Every child inherits it. Nothing in the browser knows it is
hidden, because from where it stands it is not: it has a desktop, a compositor and a
GPU like any other window. Validated the same way, same seed hidden against headed:
focus, visibility, inner and outer size, screen position, screen geometry, pixel ratio
and the WebGL renderer string all identical, one window on the session's desktop and
none on the interactive one.
**Two things a separate desktop changes, and why they are handled rather than hoped
away.** A browser's process sandbox assumes its parent lives on the interactive
desktop. Its GPU process cannot parent the compositor window across desktops under the
default sandbox level, and its content processes above a certain level are placed on
the sandbox's own window station. Left alone, the first means a software renderer under
a hardware renderer string, and the second means a tab that dies on the first
cross-process navigation - handing the active tab from one content process to another
mid-session - because the window being reparented expects both processes on the same
desktop and finds them split across two. Both were measured, and both are closed by
two sandbox settings the session applies only when it actually created a desktop:
never from the platform name, always from the fact. An automated check asserts the
result directly - a headed window found on the interactive desktop as the control, then
a hidden one absent from it and present on its own, still rendering - rather than
trusting a screenshot alone.
## How to find out which one is your problem
+1 -1
View File
@@ -116,7 +116,7 @@ Switching from stock Playwright is the launch line; every method after it is sta
Playwright. Install it first:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
Then gather ICE candidates through the proxy and assert the positive form. The `seed`
@@ -95,7 +95,7 @@ Strip everything that is not part of the number, then parse the digits and separ
with the page's locale rather than guessing. Babel does the locale-aware step:
```bash
pip install babel
uv add babel
```
```python
@@ -127,7 +127,7 @@ Relative and localized dates need the page's language to read the words and the
timezone to anchor the arithmetic. `dateparser` takes both:
```bash
pip install dateparser
uv add dateparser
```
```python
@@ -93,7 +93,7 @@ the main content block and discard the rest. The `readability-lxml` package is
a direct port of the well-known algorithm and takes an HTML string:
```bash
pip install readability-lxml lxml
uv add readability-lxml lxml
```
```python
@@ -69,11 +69,12 @@ Chromium-specific plumbing you have to translate.
```dockerfile
FROM python:3.11-slim
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
RUN uv pip install --system --no-cache -r requirements.txt
# Bake the patched engine into the image at build time, not at container
# start. This is a one-time ~238 MB download (~544 MB unpacked), sha256-verified
@@ -92,7 +93,7 @@ invisible-playwright
That builds and runs. It also, by itself, still describes a machine with no GPU, a
tiny font set and no audio device, for the reason above: none of those come from
`pip install`, they come from the base image. The next two sections are what actually
the package install, they come from the base image. The next two sections are what actually
changes that.
## The part a Dockerfile cannot fix by itself
+9 -9
View File
@@ -55,15 +55,15 @@ with InvisiblePlaywright(seed=42, headless=True) as browser:
`browser` here is a real Playwright `Browser`, so every standard method works exactly
as documented upstream. What is different is what `headless=True` means underneath:
this engine renders on the code path a visible window uses, and hides the window
itself rather than switching to a stripped rendering mode. On Windows that is a
compositor-level cloak on the window; on Linux it is a private virtual display; on
macOS the window stays transparent with occlusion checks pinned. The point of all
three is the same, and it is worth being specific about it because the same product
did not always get this right: for several releases, `headless=True` on Windows
rendered the browser on the real desktop anyway, because the hiding mechanism moved
the launching *thread* to an invisible desktop while the browser's own child
processes inherited the *parent process's* desktop instead, and stayed visible
regardless. The fix had to move to the window itself, in the browser binary, because
itself rather than switching to a stripped rendering mode. On Windows the browser
process is created on a fresh desktop object nobody switches to; on Linux it is a
private virtual display. The point of both is the same, and it is worth being specific
about it because the same product did not always get this right: for several releases,
`headless=True` on Windows rendered the browser on the real desktop anyway, because
the hiding mechanism moved the launching *thread* to an invisible desktop while the
browser's own child processes inherited the *parent process's* desktop instead, and
stayed visible regardless. The fix is to name the desktop when the process is created,
so the whole tree is born there - the browser binary is not involved, because
only the window's own owning process can set that attribute. See
[headless vs headful](headless-vs-headful.md) for the full account and why it stayed
unnoticed for as long as it did.
@@ -51,7 +51,7 @@ The launch is stock Playwright. If you have driven Playwright before, the only c
the two lines that open the browser:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
```python
@@ -53,7 +53,7 @@ already in it. Wrap that string in `io.StringIO` (pandas asks for a file-like ob
literal HTML) and pass it in.
```bash
pip install invisible-playwright pandas lxml
uv add invisible-playwright pandas lxml
```
```python
@@ -259,7 +259,7 @@ port and that you confirm the exit inside the browser rather than assuming it. A
minimal install for the container it runs in:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
The engine downloads and caches itself on first use, so the first run in a fresh
@@ -165,7 +165,8 @@ scheduler calls it. A minimal container runs the job and exits:
```dockerfile
FROM python:3.12-slim
RUN pip install invisible-playwright
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN uv pip install --system invisible-playwright
COPY monitor.py .
CMD ["python", "monitor.py"]
```
@@ -10,8 +10,8 @@ nav_order: 7
# How to use invisible_playwright in Docker
To run `invisible_playwright` in Docker, start from a maintained Playwright
base image for the OS-level shared libraries, `pip install
invisible-playwright`, fetch the patched Firefox engine at build time, and
base image for the OS-level shared libraries, install
`invisible-playwright` with uv, fetch the patched Firefox engine at build time, and
run the container with `--shm-size=1gb`. The fingerprint itself needs
nothing container-specific: the same seed produces the same machine on a
desktop or inside a container.
@@ -39,6 +39,7 @@ packages that may not match your distro:
```dockerfile
FROM mcr.microsoft.com/playwright/python:v1.47.0-jammy
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
WORKDIR /app
```
@@ -50,17 +51,21 @@ libraries, not the browsers it ships alongside them.
## Installing invisible-playwright
Installing `invisible-playwright` in a container is the same two-step
install as on a desktop: `pip install invisible-playwright` for the
package, then a separate `fetch` step to download the patched engine. See
[installation](installation.md) for why the two steps are kept separate:
Installing `invisible-playwright` in a container takes the same two steps
as on a desktop: install the package with uv, then a separate `fetch` step
to download the patched engine. See [installation](installation.md) for why
the two steps are kept separate:
```dockerfile
RUN pip install --no-cache-dir invisible-playwright
RUN uv venv --python ">=3.11" /opt/venv
ENV VIRTUAL_ENV=/opt/venv PATH="/opt/venv/bin:$PATH"
RUN uv pip install --no-cache invisible-playwright
```
Nothing container-specific here yet. The wheel is small; the part that
needs a build-time decision is the next step.
The venv is not decoration: the Python in this base image is 3.10, older
than the 3.11 the package needs, so uv brings an interpreter that can run it.
The wheel is small; the part that needs a build-time decision is the next
step.
## Fetching the patched engine at build time
+1 -1
View File
@@ -93,7 +93,7 @@ a browser and read back what the server saw. A public HTTP/2 fingerprint endpoin
the frames it received as JSON.
```bash
pip install "httpx[http2]"
uv add "httpx[http2]"
```
```python
+13 -18
View File
@@ -1,6 +1,6 @@
---
title: "Installation"
description: "Install the wrapper from PyPI, then fetch the patched Firefox binary separately - a one-time, sha256-verified download. Supported on Windows, Linux and macOS."
description: "Install the wrapper with uv, then fetch the patched Firefox binary separately - a one-time, sha256-verified download. Supported on Windows and Linux."
parent: "Documentation"
nav_order: 1
---
@@ -8,31 +8,28 @@ nav_order: 1
# Installation
Install invisible-playwright in two steps: `pip install invisible-playwright` for
the Python wrapper, then `python -m invisible_playwright fetch` to download the
Install invisible-playwright in two steps: `uv add invisible-playwright` for
the Python wrapper, then `uv run invisible-playwright fetch` to download the
patched Firefox binary it drives. The steps are separate on purpose - the Python
package is small, the browser is not.
```bash
pip install invisible-playwright
python -m invisible_playwright fetch # one-time ~238 MB download (~544 MB unpacked), sha256-verified
uv add invisible-playwright
uv run invisible-playwright fetch # one-time ~238 MB download (~544 MB unpacked), sha256-verified
```
`pip install` gets you the wrapper and its API. `fetch` downloads the patched Firefox
If you do not have a uv project yet, [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
`uv add` gets you the wrapper and its API. `fetch` downloads the patched Firefox
binary itself, verifies it against a sha256 shipped inside `invisible-core`, and caches
it. You only pay that cost once per engine version - later runs use the cached copy
without a network call.
## Supported platforms
**Windows x86_64**, **Linux x86_64 / arm64**, **macOS arm64 / x86_64**.
On macOS the app is ad-hoc signed, not notarized. If Gatekeeper complains the first
time it runs, clear the quarantine flag once:
```bash
xattr -dr com.apple.quarantine /path/to/cached/Firefox.app
```
**Windows x86_64**, **Linux x86_64**. There is no macOS engine: its
build ended on 2026-08-26. Linux arm64 is no longer supported from firefox-56:
firefox-55 is the last engine built for it.
`invisible-playwright version` prints the cache location, and
`invisible-playwright fetch` prints the exact binary path as its last line.
@@ -66,7 +63,7 @@ the [CLI reference](cli-reference.md).
## Short answers to the questions that lead here
**Do I need to install Firefox myself?** No. `python -m invisible_playwright fetch`
**Do I need to install Firefox myself?** No. `uv run invisible-playwright fetch`
downloads the patched binary for you, verifies it, and caches it - there is nothing
to install separately.
@@ -83,9 +80,7 @@ Point `INVPW_BINARY_PATH` at a binary you already have to skip the download
entirely. [Configuration](configuration.md) lists the other environment variables,
including the ones for corporate networks and CI.
**Which platforms are supported?** Windows x86_64, Linux x86_64/arm64, and macOS
arm64/x86_64. macOS needs the quarantine flag cleared once if Gatekeeper complains
on first launch.
**Which platforms are supported?** Windows x86_64 and Linux x86_64. Linux arm64 is no longer supported from firefox-56.
**See also:** [Configuration](configuration.md) for proxy, timezone and environment
variables, [CLI reference](cli-reference.md) for what `fetch` and `version` do in
+5 -3
View File
@@ -25,11 +25,13 @@ The engine and the identity come from the Python package even though the tests a
JavaScript. Get them once:
```bash
pip install invisible-playwright
invisible-playwright fetch # downloads it if missing, prints the binary path as its last line
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
uv add invisible-playwright
uv run invisible-playwright fetch # downloads it if missing, prints the binary path as its last line
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
```
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
Regenerate `prefs.json` when you upgrade the package: the pref set moves with the
engine. Keep the seed written down next to it, because that number is the identity.
+5 -3
View File
@@ -27,11 +27,13 @@ The engine and the identity are produced by the Python package even though the
crawler is Node. Get them once, at install or deploy time:
```bash
pip install invisible-playwright
invisible-playwright fetch > .browser-path
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
uv add invisible-playwright
uv run invisible-playwright fetch > .browser-path
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
```
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
Yes, a Python dependency in a Node project. That is the real cost of this route,
and if it is unacceptable, the answer is a Chromium-based tool rather than a
workaround.
+1 -1
View File
@@ -20,7 +20,7 @@ check the signature before blaming the engine.
## What you need
```bash
pip install crawlee[playwright] invisible-playwright
uv add crawlee[playwright] invisible-playwright
```
The patched Firefox binary is downloaded on first launch and cached, so the first
+5 -3
View File
@@ -29,11 +29,13 @@ Verified 2026-07-27 by reading each binding's own launch options.
## Step one: get the two values
Run the commands below in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
The binary has a CLI:
```bash
pip install invisible-playwright
invisible-playwright fetch # downloads and caches it once, prints the absolute path
uv add invisible-playwright
uv run invisible-playwright fetch # downloads and caches it once, prints the absolute path
```
The preferences do not, and that is a real gap instead of an omission from this
@@ -41,7 +43,7 @@ page: there is no `prefs` subcommand today, so you generate them with a one-line
and keep the JSON.
```bash
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
```
Regenerate it when you upgrade the package, since the pref set moves with the engine.
+4 -2
View File
@@ -32,10 +32,12 @@ Written against `microsoft/playwright-mcp` as of 2026-07-27.
## The short version
```bash
pip install invisible-playwright
python -c "from invisible_playwright import ensure_binary; print(ensure_binary())"
uv add invisible-playwright
uv run python -c "from invisible_playwright import ensure_binary; print(ensure_binary())"
```
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
The second command downloads the patched Firefox on first run, caches it, and prints
the path. Give that path to the MCP server:
+4 -4
View File
@@ -31,10 +31,10 @@ The engine and the identity come from the Python package, which suits Robot Fram
since it is Python underneath anyway.
```bash
pip install robotframework-browser invisible-playwright
rfbrowser init
invisible-playwright fetch # downloads if needed, prints the path as its last line
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
uv add robotframework-browser invisible-playwright
uv run rfbrowser init
uv run invisible-playwright fetch # downloads if needed, prints the path as its last line
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
```
Regenerate `prefs.json` when you upgrade the package. Keep the seed written next to
+1 -1
View File
@@ -22,7 +22,7 @@ is the reference; this one explains which route to pick and what each one costs.
## Install
```bash
pip install "scrapy-playwright>=0.0.48" invisible-playwright
uv add "scrapy-playwright>=0.0.48" invisible-playwright
```
The patched Firefox is downloaded on first launch and cached. You do not need
+5 -3
View File
@@ -26,11 +26,13 @@ build's own defaults on every launch, which is a different product from
Get the two values first, the same way for all four:
```bash
pip install invisible-playwright
invisible-playwright fetch
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
uv add invisible-playwright
uv run invisible-playwright fetch
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
```
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
## Cypress
Cypress launches Firefox through geckodriver and builds a `moz:firefoxOptions` with
@@ -132,7 +132,7 @@ Do not assume, read it. The launch is a two-line change from stock Playwright, a
every method after it is standard Playwright. Install it first:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
Then ask an IP-echo endpoint, from inside the proxied browser, which address it saw,
+1 -1
View File
@@ -42,7 +42,7 @@ I/O-bound, so this rarely matters in practice, but it is not universally true.
**Distribution to non-technical end users.** A Python automation script needs
a Python environment, or a packaging step (PyInstaller and similar), to reach
someone who is not going to run `pip install`. If the deliverable is a
someone who is not going to run a package installer. If the deliverable is a
double-clickable app for someone else's machine, this is real friction that a
compiled or web-based alternative does not have.
+24 -13
View File
@@ -18,7 +18,8 @@ types at a fixed interval has a single spike. The spike is the signal.
This page is about the behavioural layer, not the fingerprint one. It answers the
question honestly: a real browser emitting real key events gets you past every check
that reads the *events*, and none of the checks that read the *rhythm*. The rhythm is
that reads the *events*, and a real event says nothing about the *rhythm*. Inside one
typing call the package keeps a rhythm of its own; between your calls the rhythm is
code you write, and this page is about writing it well.
## Yes, and it is a different question from your fingerprint
@@ -38,9 +39,12 @@ because the engine does not decide when your loop calls the next keypress. You d
invisible_playwright is built to answer the first question the way a real browser does.
It drives a genuine Firefox, patched at the C++ level, so the key events are real,
OS-level, trusted events rather than synthesized DOM dispatches. It does nothing about
the second question, and it cannot, which is the honest and slightly annoying core of
this whole topic.
OS-level, trusted events rather than synthesized DOM dispatches. It answers part of the
second question too: with `humanize` on, which is the default, `fill()`, `type()` and
`press_sequentially()` hold each key and wait between keys on a rhythm drawn from the
session's seed, and pause before the first key of a field. What it cannot pace is your
loop, the time between one call and the next, and that is the honest and slightly
annoying core of this whole topic.
## What a keystroke detector actually measures
@@ -150,10 +154,16 @@ stops to think, which a flat jitter never does. If you want dwell variance too,
some keys fractionally longer by pressing `down` and `up` separately with a short sleep
between them, rather than the atomic `press`.
The seed still does its job here. `seed=42` fixes the fingerprint so the *machine* is
reproducible; the typing rhythm is deliberately not seeded, because the point of a
rhythm is that it differs every time. If you need a failing run to be reproducible while
you debug, seed the `random` module too, and unseed it in production.
The seed does two jobs here. `seed=42` fixes the fingerprint, so the *machine* is
reproducible, and it fixes the package's own typist: how long each key is held, the gaps
inside a `type()` call made without a `delay`, and the pause before a field's first key
are all drawn from it. Measured on one machine, two sessions with seed 42 typing the same
text opened with gaps of 221, 111, 105, 162, 76 and 303 ms and of 209, 103, 99, 163, 77
and 303 ms, the same draw under a few milliseconds of latency, while seed 43 opened with
104, 89, 160, 59, 142 and 456. Inside one session nothing repeats: each field, each call
and each tab gets its own draw. The `random` calls in `human_type` above are yours, and
nothing seeds them. If you need a failing run of that loop to be reproducible while you
debug, seed the `random` module too, and unseed it in production.
## What invisible_playwright fixes here, and what it does not
@@ -167,9 +177,10 @@ from a physical keyboard. The fingerprint, the TLS handshake and the driver laye
read as a genuine Firefox, which is *why* the browser passes most detection: it is not
pretending to be real, it is real. That is the whole design.
What it does not fix, and cannot: the cadence. The browser cannot make your loop pause
like a person, because your loop is upstream of the browser. If you script a uniform
`delay`, you ship a uniform histogram, and a genuine browser emitting it does not make
What it does not fix, and cannot: the cadence of your loop. The package paces the keys
inside one typing call; it cannot make the time between your calls look like a person,
because your loop is upstream of the browser. If you script a uniform sleep between
presses, you ship a uniform histogram, and a genuine browser emitting it does not make
it look human. The same honesty applies to everything outside the browser process. A
real browser does not clean up a datacenter IP, reset a per-account quota, respect a
rate limit, or slow down a session that clicks faster than a person reads. Those are
@@ -202,8 +213,8 @@ identical gaps, which is the single strongest bot signal there is. Real events,
rhythm.
**Is the problem that the events are fake?** Not with invisible_playwright. The events
are real, trusted, OS-level key events. The problem is purely the timing, which you
control.
are real, trusted, OS-level key events. The problem is the timing: inside one typing
call the package draws it from the session's seed, and between your calls it is yours.
**What distribution should I use for the gaps?** A right-skewed one, centred around
100 to 130 ms with a long tail, plus an occasional longer stall. Not a flat uniform
+17 -16
View File
@@ -129,16 +129,14 @@ enough that there is no reason to open that window.
## What happens when the lookup fails
When resolution fails, the fallback depends on whether a proxy is in play, and the two
cases have opposite risks. Behind a proxy the wrapper fails early at launch rather than
ship a mismatch; without a proxy it falls back to the host timezone and the session
continues. The interesting part of any resolution step is what it does when it cannot
resolve, so both cases are set out below.
When resolution fails, the launch fails, with a proxy or without one. The interesting part
of any resolution step is what it does when it cannot resolve, so both cases are set out
below.
| Situation | On a failed resolution | Why |
|---|---|---|
| Proxy set | Fails early at launch | A foreign exit paired with the host timezone is a mismatch worth stopping for |
| No proxy | Falls back to the host timezone, continues | The host address is what the session presents, so the host timezone is correct |
| No proxy | Fails early at launch | The host's timezone can disagree with the host's own address, which is why it is resolved at all |
**With a proxy**, a failed resolution fails early. The reason is precise: if resolution
fell back to the host's own timezone while the traffic exits through a foreign proxy, the
@@ -147,14 +145,16 @@ to prevent, and it would do so silently. A foreign exit paired with the host tim
`timezone_mismatch` waiting to be scored, so the wrapper refuses rather than ship it. You
find out at launch, not from a block three requests later.
**Without a proxy**, there is no exit to disagree with. The session presents the host's own
address, so the host's own timezone is the correct answer, and a transient failure to read
it should never take the launch down. In that case resolution falls back to the host
timezone and the session proceeds.
**Without a proxy**, the session presents the host's own address, and the timezone is still
resolved from that address rather than read from the host. The reason is the case this
section used to wave through: a server kept in UTC whose public address is in another
country. Until invisible-core 47.41.0 a failed resolution here fell back to the host
timezone and the session went on, which handed exactly that server a timezone contradicting
its own IP, with nothing said. Now it fails at launch and names the cause. To launch with
no network at all, pass an explicit IANA zone, which asks the network nothing.
So the fallback is not a single policy applied everywhere. It is chosen so that the only
time resolution is allowed to fail loudly is the only time a quiet fallback would have been
a fingerprint bug. This matters most when you
So the rule is a single one: a resolution that cannot be honoured is an error, never a
quiet guess. This matters most when you
[rotate proxies across sessions](how-to-rotate-proxies-playwright.md) or run
[a different exit per browser context](playwright-proxy-per-context.md), because each new
exit is a fresh resolution, and each one either agrees with its browser or refuses to start.
@@ -220,9 +220,10 @@ explicit IANA identifier only when you want to override that.
once, over the proxy, and maps it against a local database. There is no per-launch call to a
geolocation service.
**Will my session break if the timezone lookup fails?** Behind a proxy it fails early, on
purpose, because a foreign exit with the host timezone is a mismatch worth stopping for.
Without a proxy it falls back to the host timezone and the session continues.
**Will my session break if the timezone lookup fails?** Yes, on purpose, with a proxy or
without one: a timezone that contradicts the exit is a mismatch worth stopping for, and the
host's own timezone can contradict the host's own address. Pass an explicit IANA zone to
launch without the lookup.
**How does the offline database stay current?** Each launch makes one cheap, unmetered check
against a permalink to the newest build and downloads only when the cache is behind. There is
+37 -8
View File
@@ -108,6 +108,7 @@ profile disagree with the browser, on about 12% of seeds.
| `screen.height` | int | `1440` |
| `screen.dpr` | float | `1.0`, `1.25`, `1.5`, `2.0` |
| `screen.color_depth` | int | `24` | `screen.colorDepth` and `screen.pixelDepth`. Declared rather than read off the panel: the engine only returned a fixed 24 when resistFingerprinting was on, which we do not turn on because it is itself a tell, so before this it reported the real display - 30 on a wide-gamut monitor, and a persona claiming an office laptop with a 30-bit panel is a contradiction a page can read. |
| `screen.refresh_hz` | int | `60`, `144` | The monitor's refresh rate, which is the cadence of `requestAnimationFrame`: a page reads it from the gap between two frame timestamps. Without it the engine follows the host's display, so one persona answered about 120 on one machine and 58 on another. Not sampled: 60 is what an office laptop or monitor runs at, and a 144 Hz persona is one pin away. |
### `hardware.*`
@@ -116,16 +117,15 @@ profile disagree with the browser, on about 12% of seeds.
| `hardware.concurrency` | int | `16` | [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency). |
| `hardware.storage_quota_mb` | int | `10_000` | `navigator.storage.estimate().quota / 1024**2`. |
| `hardware.max_touch_points` | int | `0` | `navigator.maxTouchPoints`. `0` is what a desktop without a touchscreen reports, which is what the personas claim; it was a constant compiled into the binary until 2026-08-08, correct but not inspectable and not overridable. |
| `hardware.voices` | str | *(five en-US voices)* | The speechSynthesis voice list, as the engine parses it: `name\|lang\|default\|localService`, comma separated. Always the English (United States) set today, whatever locale the session resolved to - a real Windows machine running in Italian reports Italian voices, so an it-IT session declaring only American ones contradicts itself. The per-locale tables have to be measured on a real install of each locale, not invented; this field is the level at which that becomes possible. |
| `hardware.voices` | str | *(the session language's voices)* | The speechSynthesis voice list, as the engine parses it: `name\|lang\|default\|localService`, comma separated. Unpinned, it follows the session's first language: English gives the English (United States) set, Italian the set of a Windows with English UI and Italian added, as measured on one; a language without a measured set keeps the English one, because a table has to be measured on a real install, not invented. A pin wins over the table. |
| `hardware.fake_media_devices` | bool | `True` | One fake audio input and one fake video input on every host, so `enumerateDevices` does not report the machine's real hardware. Measured in a secure context (about:blank is not one, and measuring there made the two hosts look like they agreed because both returned nothing): Linux enumerated 0 real devices and Windows 2. |
| `hardware.media_enumeration_ms` | int | `412` | How long the first `navigator.mediaDevices.enumerateDevices()` of a session takes, in ms. With `fake_media_devices` the engine no longer asks the host's audio stack for its speakers, whose time it was (15-40 ms on Linux, about 300 on Windows), and answers after this long on every host; later calls are fast, as in Firefox. Drawn from the seed between 240 and 640, the range retail Windows Firefox took on one machine in two states. Ignored with real devices. Needs firefox-45. |
| `hardware.storage_enabled` | bool | `True` | Whether cookies, localStorage, sessionStorage and indexedDB all work. One field for four booleans because Gecko exposes them through two levers, not four. They used to be true because nobody touched `network.cookie.cookieBehavior` or `dom.storage.enabled`, i.e. because the upstream defaults happened to be right. |
| `hardware.generics` | str | *(20 rows)* | The CSS generic families, as `generic\|lang\|family` records separated by newlines. It was ten rows compiled into gfxPlatformFontList.cpp; the `x-math` row is load-bearing and easy to lose, because without it every MathML glyph renders in Times New Roman on every host, which no cross-OS gate can see. |
| `hardware.accessibility_overrides` | bool | `False` | Reduced motion, reduced transparency and inverted colours. Content-exposed media features that read the HOST through different code on each platform. They agreed across our two builds when measured - by luck, both machines having no accessibility settings on - and nothing declared them. Costs nothing to close: Firefox reads these generic prefs before the native path. |
| `screen.taskbar_px` | int | `48` | How much shorter `availHeight` is than `height`. It was the literal 48 in three places - the generator, nsScreen.cpp and nsGlobalWindowOuter.cpp - kept in step by hand. |
| `screen.chrome_w` | int | `0` | `outerWidth - innerWidth`, i.e. how much wider the window is than the page. Zero, because a real Firefox has no horizontal chrome: measured against stock 151, it answers 0 and this wrapper answered 14 for months. It was a module constant in `launcher.py`, so nothing could pin it and nothing could compare it to anything. |
| `screen.chrome_h` | int | `85` | `outerHeight - innerHeight`: tab strip plus navigation toolbar. Also measured against stock 151, which answers 85 where we answered 91. Pin it if a persona needs a bookmarks toolbar or a different tab density. |
| `screen.window_x` | int | `0` | `window.screenX`, and with it `screenLeft` and `mozInnerScreenX`. `outerWidth` already claims a maximized window filling the screen, and a maximized window is at the origin - but the position was never declared, so it stayed whatever the OS gave the headless widget: `(4,4)` on Windows, which put the right edge of a 1920-wide window at 1924 on a 1920 screen. That is impossible on a real machine and takes one addition to spot. |
| `screen.window_y` | int | `0` | `window.screenY` / `screenTop`, and the base of `mozInnerScreenY` (`window_y + chrome_h`). Pin both this and `window_x` together with a smaller viewport if you want a window that is not maximized. |
The window around the page is not a pin: since 0.29.0 (core 38) it is a frame measured on Windows Firefox at each display scale, so `outerWidth`, `screenX` and `mozInnerScreenY` follow `screen.dpr`, which takes 1, 1.25, 1.5 or 2. A maximized window answers `screenX` -8 and is 16 wider than the work area at 100%, and a popup answers its own frame. The keys `screen.chrome_w`, `screen.chrome_h`, `screen.window_x` and `screen.window_y` are gone.
### `audio.*`
@@ -168,7 +168,8 @@ would be the signal. They are pinnable for A/B work, not for realism.
| Key | Type | Example | Notes |
|-----|------|---------|-------|
| `font.ui_family` | str | `"Segoe UI"` | Family behind `font: menu`, `font: caption`, and the `-moz-` widget fonts. |
| `font.ui_family` | str | `"Segoe UI"` | Family behind `font: menu` and `font: caption`. The form-control fonts take `font.dialog_family`. |
| `font.dialog_family` | str | `"MS Shell Dlg 2"` | The family of the form-control fonts, `-moz-button`, `-moz-field` and `-moz-list`, which is not the shell font: Windows Firefox builds them from the message font under the name "MS Shell Dlg 2", and a page reads it with one `getComputedStyle(input).fontFamily`. |
| `font.ui_size` | str | `"12"` | **A string, not an int.** Gecko reads this pref through `Preferences::GetFloat`, which parses the value from its text form; an int is not rejected, it is ignored, and the UI silently falls back to 16px. |
| `font.monospace_size` | int | `13` | Default monospace size. Firefox ships 13 on Windows and 12 in its Unix block, and the gap is directly readable as the width of the `monospace` generic at the default size. |
| `font.alpha_ladder` | tuple of int | `(0, 18, 35, ..., 255)` | The distinct alpha levels a Windows rasteriser leaves on an antialiased glyph edge, ascending, first `0` and last `255` so a fully transparent or fully opaque pixel never moves. Canvas readback snaps onto these. An empty tuple disables the snap, which is what you want when measuring what the unsnapped edge looks like. |
@@ -180,15 +181,43 @@ would be the signal. They are pinnable for A/B work, not for realism.
| `font.cleartype_rendering_mode` | int | `5` | DirectWrite rendering mode. |
| `font.freetype_gamma` | int | `220` | The FreeType equivalent of `cleartype_gamma`, x100. Declared so the Linux build rasterises with Windows' curve instead of Skia's linear default. |
| `font.freetype_contrast` | int | `100` | The FreeType equivalent of `cleartype_contrast`, x100. |
| `font.system_text_quality` | int | `5` | The text quality the engine would otherwise ask the host for: `0` none, `4` standard antialiasing, `5` ClearType. It decides whether the ClearType parameters above apply at all, so on a machine with ClearType off (an RDP session, a VM, a Server) the same binary would draw different text from the same declaration. Declared, never asked of the machine. Any other value is refused. |
### `desktop.*`
The Windows desktop settings a page can read, declared instead of asked of the
machine. Each one is a value whose engine default either reads the host or
differs between Windows and Linux, so without it the same persona answered
with the machine it ran on. The defaults are a Windows 11 desktop at its
defaults, and they are not sampled.
| Key | Type | Default | Notes |
|-----|------|---------|-------|
| `desktop.text_scale` | int | `100` | Windows' "Text size" slider, in percent. It multiplies the device pixel ratio, so `100` is the value that leaves `screen.dpr` the one number for it. |
| `desktop.overlay_scrollbars` | bool | `True` | Windows 11's "Automatically hide scroll bars": scrollbars draw over the content, so a scrolling box loses no width (`offsetWidth - clientWidth` is 0). Off, they take `desktop.scrollbar_size`. |
| `desktop.scrollbar_style` | int | `5` | How scrollbars are drawn: 5 Windows 11, 4 Windows 10, 2 GTK. |
| `desktop.scrollbar_size` | int | `17` | The width a scrollbar takes when it is not an overlay, at 96 dpi. |
| `desktop.drag_threshold` | int | `3` | How far the pointer moves before `dragstart`. |
| `desktop.scroll_to_click` | bool | `False` | A click in a scrollbar's track jumps there instead of paging. |
| `desktop.document_colors` | int | `0` | When the page's colours give way to the system's: `0`, the Windows default, only under a high-contrast theme. |
| `desktop.select_styling` | bool | `True` | A page may style a `<select>`'s popup, as on Windows. |
| `desktop.word_select_eats_space` | bool | `True` | A double click selects the word and the space after it, as on Windows; a page reads it with `getSelection()` after a real double click. |
| `desktop.srgb_output` | bool | `True` | Tagged images are converted to sRGB instead of the host monitor's colour profile, which a small canvas reads back. |
| `desktop.os_client_certs` | bool | `False` | Whether the operating system's personal certificates answer a server that asks for one. Off: the persona has none. |
| `desktop.theme_accent` | bool | `False` | Whether the page-visible `AccentColor` follows the desktop theme's accent; on Windows it does not. |
| `desktop.hour_cycle` | int | `0` | The clock format, `0` meaning the locale decides, as on Windows; otherwise the host's 12/24-hour setting changes every `toLocaleTimeString()`. |
| `desktop.select_on_focus` | bool | `True` | Tabbing into a pre-filled field selects all of it, as on Windows. |
| `desktop.palette` | str | *(the Windows palette)* | The system colours, light and dark, as `ui.<name>\|<light>\|<dark>` records, one per line, the dark part empty where the scheme does not move it. Every persona carries both schemes; `dark_theme` says which one it uses. |
### Top-level
| Key | Type | Example | Notes |
|-----|------|---------|-------|
| `dark_theme` | bool | `False` | [`prefers-color-scheme: dark`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme). Real traffic is ~85% light, 15% dark. |
| `branding` | str | `"official"`, `"unofficial"`, `"C:/brand/branding.zip"` | The branding a page can read at `chrome://branding/content/` and `resource://usercontext-content/branding/`: the about dialog's stylesheet, the wordmarks' boxes, the logos' sizes. `"official"` (the default) is the retail Firefox's files, `"unofficial"` those of a build without the trademark, and an absolute path is a zip archive of your own holding exactly the same 16 file names at its root; anything else raises when the profile is built. An archive and not a folder because the engine serves it the way Firefox serves its own branding, from inside an archive: served from a folder, a page could tell the difference. The engine keeps no copy of its own. Needs firefox-48. |
`dark_theme` is the ONLY top-level key. Anything else raises `ValueError: pin key
'...' is not valid`.
`dark_theme` and `branding` are the ONLY top-level keys. Anything else raises
`ValueError: pin key '...' is not valid`.
**`fonts` is not one of them, and no longer exists as an axis.** This table used
to list a per-profile font allowlist ("the sampler usually picks 14-24 system
+3 -3
View File
@@ -23,8 +23,8 @@ is the fastest way to tell the three apart.
## Cause 1: the browsers were never downloaded
The library and the binaries are decoupled on purpose, so `pip install playwright` or
`npm install playwright` alone leaves you with a client and no browser to drive:
The library and the binaries are decoupled on purpose, so installing the `playwright`
package from PyPI or npm alone leaves you with a client and no browser to drive:
```bash
playwright install # every browser Playwright supports
@@ -144,7 +144,7 @@ changing anything, since the fix for each is different and none of them is guess
a specific cache path and did not find a runnable one there. The message names the exact
path it checked.
**Does `npm install playwright` or `pip install playwright` include the browsers?**
**Does installing the `playwright` package from npm or PyPI include the browsers?**
No. The package is the client library; `playwright install` is a separate, required step
that downloads the actual browser binaries.
+7 -5
View File
@@ -43,9 +43,11 @@ Most current Debian and Ubuntu base images are published as multi-architecture m
```dockerfile
FROM --platform=linux/arm64 debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
python3 python3-pip ca-certificates
RUN pip install invisible-playwright
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates
RUN uv venv --python ">=3.11" /opt/venv
ENV VIRTUAL_ENV=/opt/venv PATH="/opt/venv/bin:$PATH"
RUN uv pip install --no-cache invisible-playwright
```
The `--platform` flag pins the build explicitly rather than relying on the Docker daemon's default, which matters if you build on one machine and deploy to another. For a real GPU, font set, or screen presented to the browser instead of a bare container's defaults, see [How to run Playwright in Docker without getting detected](how-to-run-playwright-docker-undetected.md); it applies the same way on arm64, only the base image and engine differ by architecture.
@@ -76,7 +78,7 @@ One caveat: Python's own `platform.machine()` inside your automation does not pr
## What this project ships, and does not
This project currently builds and publishes engines for Linux on both x86_64 and arm64, and for Windows on x86_64. There is no macOS build; macOS support was discontinued after the engine build for it ended, so a macOS host has no engine to download here regardless of its own CPU architecture.
This project builds and publishes engines for Linux x86_64 and Windows x86_64. Linux arm64 is no longer supported from firefox-56: firefox-55 is the last engine built for it. There is no macOS build; macOS support was discontinued after the engine build for it ended, so a macOS host has no engine to download here regardless of its own CPU architecture.
## Short answers to the questions that lead here
@@ -90,7 +92,7 @@ It usually starts under emulation, but runs slower and less predictably, which m
Run `file` on the resolved browser binary to see its real architecture, and compare it to the host's own `uname -m` or your cloud provider's listed instance type, rather than trusting the image tag alone.
**Does invisible_playwright support ARM64?**
Yes, on Linux: separate engine builds for x86_64 and arm64, alongside a Windows x86_64 build. There is currently no macOS build.
Not on Linux from firefox-56: firefox-55 is the last engine built for Linux arm64. The engines are Linux x86_64 and Windows x86_64. There is currently no macOS build.
**Is WebKit's ARM64 Linux support as mature as Chromium and Firefox?**
Playwright's own system requirements name Debian 12 and 13 and Ubuntu 22.04, 24.04 and 26.04 on "x86-64 or arm64" without splitting the list per browser, so confirm the browser you need actually downloads on your distribution before you build around it.
+2 -1
View File
@@ -34,6 +34,7 @@ Debian and Ubuntu-based images, which most Playwright containers are, ship almos
```dockerfile
FROM python:3.11-slim
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN apt-get update && apt-get install -y --no-install-recommends \
fonts-noto \
@@ -46,7 +47,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
RUN uv pip install --system --no-cache -r requirements.txt
RUN python -m invisible_playwright fetch
+1 -1
View File
@@ -108,7 +108,7 @@ anecdotal. Fix the seed, capture, and assert two things at once: the screenshot
is a sane size and it is a real image, not a wall of noise.
```bash
pip install invisible-playwright
uv add invisible-playwright
```
```python
@@ -132,10 +132,11 @@ to add, because the engine downloads itself on first use:
```dockerfile
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN apt-get update \
&& apt-get install -y --no-install-recommends xvfb \
&& rm -rf /var/lib/apt/lists/*
RUN pip install invisible-playwright
RUN uv pip install --system invisible-playwright
COPY scrape.py .
CMD ["python", "scrape.py"]
```
@@ -55,8 +55,9 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- uses: astral-sh/setup-uv@v6
- name: Install
run: pip install invisible-playwright
run: uv pip install --system invisible-playwright
- name: Run
run: python scrape.py
```
@@ -199,7 +199,8 @@ describe:
```dockerfile
FROM python:3.12-slim
RUN pip install invisible-playwright
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
RUN uv pip install --system invisible-playwright
ENV INVISIBLE_PLAYWRIGHT_CACHE_DIR=/engines
VOLUME /engines
COPY scrape_job.py /srv/scrape_job.py
@@ -93,6 +93,30 @@ This is the same shape as every other suppression in this subject: the value you
was less interesting than the absence you created. If you can leave them enabled, leave
them enabled, and handle the interception complexity rather than trading it for a signal.
### Engine-native blocking for request guards
`browser.new_context(service_workers="block")` and
`firefox.launch_persistent_context(..., service_workers="block")` are honoured by the
engine itself (`Browser.setServiceWorkersBlocked`, from firefox-37). The wrapper never
uses a page script or `dom.serviceWorkers.enabled=false`: the latter also disables
Firefox's request-interception hook, so `route()` refuses in that configuration.
Juggler cancels service-worker script downloads in the parent
process, scoped by `originAttributes.userContextId`. `register()` rejects with Firefox's
native network-failure exception; no request for the main script reaches the server.
The container and its prototype are unchanged, and `register.toString()` still reports
native code. This removes the page-script automation artefact, **not the observable
absence of a worker**.
Before acknowledging the option, Juggler shuts down and unregisters existing workers
for that context, including registrations saved in a persistent profile. That removal
is permanent; turning blocking off does not restore them. A registration listener also
removes later registrations. Requests in a blocked context are never handed to a
service-worker intercept controller, while normal page requests still reach `route()`.
Other contexts and ordinary workers (including their `importScripts()`) are unchanged.
Apply the option at context creation, before opening or navigating pages; it cannot
undo requests sent before the policy was applied.
## What a browser context does and does not separate
A browser context separates storage but nothing about the machine. Two contexts get
@@ -43,7 +43,7 @@ That directness is the whole reason the fixture pair works cleanly:
Install what you need first:
```bash
pip install invisible-playwright pytest pytest-asyncio
uv add invisible-playwright pytest pytest-asyncio
```
And turn on pytest-asyncio's auto mode so you do not decorate every test by hand. In
+2 -2
View File
@@ -102,8 +102,8 @@ How this project does it, because the details are the part that bites:
request per launch announcing that a new session started.
- The **same** lookup feeds the locale and the WebRTC public address, so those three
cannot drift apart. They come from one answer, not three.
- **On failure with a proxy configured, it fails the launch** instead of falling back
to the host timezone. That fallback is the exact mismatch you set out to avoid, and a
- **On failure it fails the launch**, with a proxy or without one, instead of falling
back to the host timezone. That fallback is the exact mismatch you set out to avoid, and a
silent fallback to it is worse than an error.
That last one is a small decision that took a while to get right. A fallback that
+1 -1
View File
@@ -146,7 +146,7 @@ with InvisiblePlaywright(seed=42, proxy=proxy) as browser:
```
```bash
pip install invisible-playwright
uv add invisible-playwright
```
If your project is committed to Chrome and to an async Python API of its own, and
+1 -1
View File
@@ -105,7 +105,7 @@ Switching from plain Playwright is the same two-line change it always is, and th
object is a real Playwright `Browser` with every method intact:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
```python
+1 -1
View File
@@ -191,7 +191,7 @@ authentication](playwright-socks5-proxy-authentication.md).
A minimal install to run the snippet:
```bash
pip install invisible-playwright
uv add invisible-playwright
```
## Conclusion
+11 -10
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.22.2"
version = "0.47.1"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
@@ -69,10 +69,10 @@ dependencies = [
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
# fails if one appears). What stays invisible to install-time machinery is the
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
"invisible_core==31.23.0",
"invisible_core==58.56.0",
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
# client lives in src/invisible_playwright/_pw/ and the Node driver in
# src/invisible_playwright/_driver/. Reintroducing it would not visibly
# client lives in src/invisible_playwright/_pw/ and its server in
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
# break anything - that is the problem - because the two packages coexist
# without colliding: one of them would simply never run, and whoever
# reads the pyproject would believe the opposite.
@@ -117,7 +117,7 @@ dependencies = [
]
[project.optional-dependencies]
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0"]
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41"]
[tool.pytest.ini_options]
markers = [
@@ -138,13 +138,15 @@ markers = [
# invisible_core's addopts said `not slow` while never declaring `slow`,
# so the exclusion matched nothing and the word meant nothing.
#
# The blocks are byte-identical on purpose, and
# The lists are identical on purpose, and
# invisible_core/tests/test_marker_vocabulary.py fails when they drift.
# (It compares the parsed lists, so this comment may differ per repo.)
"unit: pure logic - no I/O, no network, no subprocess, no browser",
"integration: several modules together, in process - no network, no browser",
"e2e: needs something outside this process - the network, the real patched binary, or a display",
"slow: builds a wheel or an sdist - opt-in only",
"linux_only: requires Linux",
"wall_clock: its verdict reads a wall-clock duration - the e2e run gives it the machine alone, after the parallel tests",
]
# Both exclusions in ONE addopts: declaring the key twice is a TOML error, not
# a merge, and pytest then sees neither value.
@@ -232,16 +234,15 @@ release_tags = ["v"]
# gained the `.js/.css/.html` coverage AIHawk's did.
#
# Vendored upstream Playwright is excluded as a FOLDER, but our own patches
# inside it are still read: they are found by the marker. `injected.js` is
# extracted from the upstream bundle. `test_fork.py` carries Italian ON
# inside it are still read: they are found by the marker. (`injected.js`,
# extracted from the upstream bundle, moved to invisible-core with the Juggler
# client in 0.30.0, and its exclusion with it.) `test_fork.py` carries Italian ON
# PURPOSE - its known-bad fixture reproduces a JavaScript comment whose defect
# IS the trailing apostrophe of an Italian word; translate it and the mutation
# stops reproducing the bug. Named file by file, never by folder: an
# exclusion that names nothing is refused by the gate.
[tool.invisible.english]
excluded = [
"src/invisible_playwright/_pw/",
"src/invisible_playwright/_juggler/injected.js",
"tests/test_fork.py",
]
marker = "MODIFIED by invisible_playwright"
+172
View File
@@ -0,0 +1,172 @@
"""Builds tests/data/canvas_icc_ref/refs.json, the reference of the canvas ICC readback test.
One measurement of retail Firefox 159.0 on Windows with the default prefs (the run
``a_win_default``: qcms converts a tagged image to the monitor profile, here the stock
"sRGB Color Space Profile.icm"), and one control run on the same machine with
gfx.color_management.force_srgb=true (``b_win_force_srgb``: the bytes without that
conversion), both made by index.html and the images of gen_images.py:
python -I scripts/build_canvas_icc_refs.py <a_win_default.json> <b_win_force_srgb.json> \
--repeat <a2_win_default_repeat.json> --host-profile <host_display_profile.json> \
--source <name of the capture> [--out tests/data/canvas_icc_ref/refs.json]
The script stops if the repeat run has other hashes than the reference run, if the runs
were not made on the same Firefox build, or if the prefs of the two runs are not the default
and force_srgb=true. The probes are the 72 of the page: for each of the 10 images drawImage,
drawImage at 32 px, createImageBitmap with the default colour space conversion and with
``none``; the 22 fill colours; the canvas colorSpace probe; the 9 environment values.
Standard library only: it does not import invisible_core, and the repository holds no PNG
and no run's pixel hex, only hashes and sizes.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import sys
from pathlib import Path
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_icc_ref" / "refs.json"
IMAGE_PROBES = ("drawImage", "drawImage_scaled32", "bitmap_default", "bitmap_none")
#: Value probes that are not colour management: the host's theme, which the retail machine
#: had dark; the test does not compare it (the persona's colour scheme is checked elsewhere).
NOT_COMPARED = ("env | prefers-color-scheme:dark",)
GEN_IMAGES = DEFAULT_OUT.parent / "gen_images.py"
def image_files():
"""{image id: {file, bytes, sha256}} of the ten images gen_images.py writes: the reference
names them, so a generator that drifts is seen before the engine is blamed."""
spec = importlib.util.spec_from_file_location("gen_images", GEN_IMAGES)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
imgs, _profiles = mod.build_images()
return {iid: {"file": "images/%s.%s" % (iid, ext), "bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest()}
for iid, ext, data, _what in imgs}
class RefError(ValueError):
"""The runs cannot be one reference."""
def env_sha256(value):
"""The hash of an environment value: SHA-256 of its compact JSON (as JSON.stringify)."""
return hashlib.sha256(json.dumps(value, separators=(",", ":")).encode()).hexdigest()
def probes(R):
"""{probe name: {kind, sha256, bytes (pixel probes), value (env)}} of a page result R
(``window.R`` of index.html). ``bytes`` is the RGBA length: 4 x width x height."""
out = {}
for iid, v in R["images"].items():
for k in IMAGE_PROBES:
e = v.get(k)
if not isinstance(e, dict) or "sha256" not in e:
raise RefError("image %s probe %s has no hash: %r" % (iid, k, e))
size = 32 if k == "drawImage_scaled32" else 16
out["%s | %s" % (iid, k)] = {"kind": "image", "sha256": e["sha256"],
"bytes": 4 * size * size}
for f, v in R["fills"].items():
if "sha256" not in v:
raise RefError("fill %s has no hash: %r" % (f, v))
out["fill | " + f] = {"kind": "fill", "sha256": v["sha256"], "bytes": 4 * 16 * 16}
p3 = R["canvas_colorspace"].get("p3_fill_p3_canvas") or {}
if "sha256" not in p3:
raise RefError("the canvas colorSpace probe has no hash")
out["canvas colorSpace p3 fill"] = {"kind": "colorspace", "sha256": p3["sha256"],
"bytes": 4 * 16 * 16}
for k, v in R["env"].items():
out["env | " + k] = {"kind": "env", "sha256": env_sha256(v), "value": v}
return out
def build(a, b, repeat, host_profile, source):
"""The reference from the default run ``a``, the control run ``b`` (force_srgb), the
repeat of ``a`` and the host profile description; all as loaded JSON."""
for key in ("buildid", "exe_sha256", "version", "os"):
if a["firefox"][key] != b["firefox"][key] or a["firefox"][key] != repeat["firefox"][key]:
raise RefError("the runs differ in the Firefox %s" % key)
pa, pb, pr = probes(a["R"]), probes(b["R"]), probes(repeat["R"])
if pa != pr:
bad = sorted(k for k in pa if pa[k] != pr.get(k))
raise RefError("the repeat run differs from the reference run on %d probes: %s"
% (len(bad), ", ".join(bad[:5])))
if set(pa) != set(pb):
raise RefError("the control run has other probes than the reference run")
prefs_a, prefs_b = a["prefs_read_back"], b["prefs_read_back"]
if prefs_a.get("gfx.color_management.display_profile") not in ("", None):
raise RefError("the reference run has a display_profile pref: it must read the host's")
if prefs_a.get("gfx.color_management.force_srgb") is not False:
raise RefError("the reference run is not made with the default force_srgb (false)")
if prefs_b.get("gfx.color_management.force_srgb") is not True:
raise RefError("the control run is not made with force_srgb=true")
for k, v in prefs_a.items():
if k != "gfx.color_management.force_srgb" and prefs_b.get(k) != v:
raise RefError("the control run differs in %s" % k)
out = {}
dependent = []
for name, p in pa.items():
e = dict(p)
if pb[name]["sha256"] != p["sha256"]:
e["without_conversion_sha256"] = pb[name]["sha256"]
dependent.append(name)
if name in NOT_COMPARED:
e["compared"] = False
out[name] = e
return {
"test_page": "index.html",
"image_generator": "gen_images.py",
"source": {
"capture": source,
"reference_run": "runs/a_win_default.json",
"repeat_run": "runs/a2_win_default_repeat.json (same hashes on all probes)",
"control_run": "runs/b_win_force_srgb.json (gfx.color_management.force_srgb=true)",
"date": "2026-11-09",
},
"firefox": {**a["firefox"], "prefs": prefs_a},
"display_profile": {"file": host_profile["file"], "size": host_profile["size"],
"sha256": host_profile["sha256"], "api": "GetICMProfileW"},
"images": image_files(),
"probe_count": len(out),
"profile_dependent_count": len(dependent),
"profile_dependent": sorted(dependent),
"probes": out,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("reference", help="run json of the retail default run (a_win_default)")
ap.add_argument("control", help="run json of the force_srgb run (b_win_force_srgb)")
ap.add_argument("--repeat", required=True, help="run json of the repeat of the default run")
ap.add_argument("--host-profile", required=True, help="host_display_profile.json")
ap.add_argument("--source", default="canvas-color/canvas-color-icc-readback",
help="name of the capture the runs come from")
ap.add_argument("--out", default=str(DEFAULT_OUT))
a = ap.parse_args(argv[1:])
def load(p):
return json.loads(Path(p).read_text(encoding="utf-8"))
try:
refs = build(load(a.reference), load(a.control), load(a.repeat),
load(a.host_profile), a.source)
except RefError as e:
print("error: %s" % e, file=sys.stderr)
return 1
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
print("%d probes (%d depend on the display profile) -> %s"
% (refs["probe_count"], refs["profile_dependent_count"], a.out))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+106
View File
@@ -0,0 +1,106 @@
"""Builds tests/data/canvas_text_ref/refs.json, the one reference of the canvas text test.
Two measurements of retail Firefox 159.0 on Windows, made with the same page code, the same
bundled font files and the same machine, are merged by case id:
python -I scripts/build_canvas_text_refs.py <canvas_ref_bundle/refs.json> \
<canvas_ref_ext/refs.json> [--out tests/data/canvas_text_ref/refs.json]
The bundle file has the base cases (no ``gruppo`` field: they become group ``0_base``), the
extension file has the cases of the other groups. A case id that is in both files is kept
once, with the extension's group; the script stops if the two hashes of such a case differ,
or if the two files were not measured on the same Firefox build, with the same ClearType
state and the same font files. Fields that name a file of the measuring machine (the PNG
paths) are dropped: the repository holds no PNG and no font.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
BASE_GROUP = "0_base"
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_text_ref" / "refs.json"
_DROP = ("png",)
class MergeError(ValueError):
"""The two measurements cannot be one reference."""
def _case(case, group):
out = {k: v for k, v in case.items() if k not in _DROP}
out.setdefault("alpha", True)
out.setdefault("stretch", "normal")
out.setdefault("text", "TEXT")
out["gruppo"] = group
return out
def merge(bundle, ext):
"""One reference from the bundle measurement and the extension measurement."""
for key in ("firefox", "canvas", "cleartype", "text"):
if bundle[key] != ext[key]:
raise MergeError("the two measurements differ in %r: %r vs %r"
% (key, bundle[key], ext[key]))
ext_fonts = {f["bundle_file"]: f for f in ext["fonts"]}
for f in bundle["fonts"]:
other = ext_fonts.get(f["bundle_file"])
if other is None or other["sha256"] != f["sha256"]:
raise MergeError("font %s is not the same file in the two measurements"
% f["bundle_file"])
cases = {}
for cid, c in bundle["cases"].items():
cases[cid] = _case(c, c.get("gruppo") or BASE_GROUP)
for cid, c in ext["cases"].items():
if not c.get("gruppo"):
raise MergeError("extension case %r has no group" % cid)
if cid in cases and cases[cid]["sha256"] != c["sha256"]:
raise MergeError("case %r has two different hashes: %s and %s"
% (cid, cases[cid]["sha256"], c["sha256"]))
cases[cid] = _case(c, c["gruppo"])
groups = {}
for c in cases.values():
groups[c["gruppo"]] = groups.get(c["gruppo"], 0) + 1
status = {**bundle.get("font_load_status", {}), **ext.get("font_load_status", {})}
return {
"test_page": "index.html",
"font_source": "bundle",
"text": bundle["text"],
"firefox": bundle["firefox"],
"canvas": bundle["canvas"],
"cleartype": bundle["cleartype"],
"fonts": ext["fonts"],
"font_load_status": status,
"case_count": len(cases),
"groups": dict(sorted(groups.items())),
"cases": cases,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("bundle", help="refs.json of the base measurement (canvas_ref_bundle)")
ap.add_argument("ext", help="refs.json of the extension measurement (canvas_ref_ext)")
ap.add_argument("--out", default=str(DEFAULT_OUT))
a = ap.parse_args(argv[1:])
load = lambda p: json.loads(Path(p).read_text(encoding="utf-8"))
try:
refs = merge(load(a.bundle), load(a.ext))
except MergeError as e:
print("error: %s" % e, file=sys.stderr)
return 1
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
print("%d cases -> %s" % (refs["case_count"], a.out))
for g, n in refs["groups"].items():
print(" %-30s %3d" % (g, n))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+33 -4
View File
@@ -60,9 +60,31 @@ Exit 0 + "DRIVE GATE OK ..." on success; non-zero with a reason on failure.
from __future__ import annotations
import http.server
import json
import shutil
import socketserver
import sys
import tempfile
import threading
from pathlib import Path
# ⛔ THE FIRST RUN IS DECLARED HERE, A COPY OF THE CORE'S, written into the
# profile's user.js. Since firefox-55 the engine leaves Mozilla's first-run
# lines and invisible_core declares the state (terms of use accepted long ago,
# pre-onboarding off). This job installs only Playwright, so nothing declared
# it: measured 2026-11-02 on run 41388672849, Windows showed the terms-of-use
# modal ("the page did not handle mouse event") and Linux opened
# https://www.mozilla.org/en-US/privacy/firefox/ in a second tab (the legacy
# data-reporting flow) ("Unexpected number of tabs in the new window: 2").
# Upstream Playwright sends its own defaults in Browser.enable, which this
# engine refuses, so a raw launch runs on Mozilla's lines alone. With these
# three in user.js, both legs drive. tests/test_ci_drive_gate_first_run.py
# ties the copy to the core.
FIRST_RUN = {
"browser.preonboarding.enabled": False,
"termsofuse.acceptedVersion": 4,
"termsofuse.acceptedDate": "1785573000000",
}
HTML = (
"<!doctype html><html><head><title>dt</title></head><body>"
@@ -135,10 +157,16 @@ def _drive(exe: str, url: str, level: str) -> str:
full = level == "full"
from playwright.sync_api import sync_playwright
# A user.js is read at startup, before the window that would carry the
# modal; a persistent context is the only way to hand Playwright a profile.
profile_dir = Path(tempfile.mkdtemp(prefix="ci-drive-gate-"))
(profile_dir / "user.js").write_bytes(
"".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
for k, v in sorted(FIRST_RUN.items())).encode("utf-8"))
with sync_playwright() as p:
browser = p.firefox.launch(executable_path=exe, headless=True)
ctx = p.firefox.launch_persistent_context(str(profile_dir), executable_path=exe, headless=True)
try:
page = browser.new_page()
page = ctx.new_page()
resp = page.goto(url, wait_until="load")
assert resp and resp.ok, f"navigation to {url} failed: {resp.status if resp else 'no response'}"
ua = page.evaluate("() => navigator.userAgent")
@@ -163,7 +191,8 @@ def _drive(exe: str, url: str, level: str) -> str:
inter["langs"] = page.evaluate("() => navigator.languages.length")
inter["plugins"] = page.evaluate("() => navigator.plugins instanceof PluginArray")
finally:
browser.close()
ctx.close()
shutil.rmtree(profile_dir, ignore_errors=True)
# SMOKE asserts (always).
assert "Firefox" in ua, f"unexpected UA (binary not driving correctly): {ua!r}"
@@ -171,7 +200,7 @@ def _drive(exe: str, url: str, level: str) -> str:
assert not webdriver, f"navigator.webdriver leaked True (stealth regression): {webdriver!r}"
if interacts:
assert inter["clicked"] == 1, "page.click() did not fire the click listener - mouse-event synthesis broken (firefox-2 class), or a chrome overlay is swallowing input (terms-of-use modal: see browser/app/profile/firefox.js, termsofuse.acceptedDate)"
assert inter["clicked"] == 1, "page.click() did not fire the click listener - mouse-event synthesis broken (firefox-2 class), or a chrome overlay is swallowing input (terms-of-use modal: see FIRST_RUN above)"
assert inter["moves"] >= 1, "page.mouse.move() produced no mousemove - jugglerSendMouseEvent regression, or a chrome overlay is swallowing input"
if full:
assert inter["typed"] == "ok", f"page.keyboard.type() failed: {inter['typed']!r}"
-417
View File
@@ -1,417 +0,0 @@
#!/usr/bin/env python3
"""CI font gate - assert the patched binary exposes exactly the Windows font
persona on EVERY host OS (Windows / Linux / macOS), with zero host-font leak.
The patched binary is bundle-only: at font-list construction it drops every host
system font and exposes only the bundled Windows-11 family set (the exposed set
IS the bundle). This gate launches the binary on its NATIVE runner - so
macOS/CoreText, Linux/fontconfig and Windows/DWrite are each tested for real -
enumerates the visible families with the same width-probe web detectors use, and
asserts three things:
1. the detected family set == the canonical Windows set (EXPECTED): the SAME
set on all three platforms. A leaked host font or a missing Windows one
fails here. This is the "identical on every OS" contract.
2. no known host family is visible (macOS: Helvetica Neue / Geneva / Menlo ...;
Linux: DejaVu / Ubuntu ...) - a POSITIVE proof that block-at-birth ran for
this platform's backend, not just "no obvious tell".
3. the CSS generics resolve to Windows fonts (serif=Times New Roman,
sans-serif=Arial, monospace=Consolas) and system-ui=Segoe UI.
This is the macOS validator the local Win/Linux gate cannot be - there is no
local Mac, so CoreText is only ever exercised here. Headless, no proxy, no
secrets, loopback-free (about:blank + arrow-function evaluate, which is not
eval and carries no CSP problem) -> safe in public CI.
Usage: python ci_font_gate.py <firefox-binary>
Exit 0 + "FONT GATE OK ..." on success; non-zero + the diff on failure.
"""
from __future__ import annotations
import json
import shutil
import sys
import tempfile
from pathlib import Path
# The canonical Windows-11 family set the bundle exposes. Verified byte-for-byte
# identical on Windows/DWrite and Linux/fontconfig; macOS/CoreText must match it
# too. These are the `F|` records that `invisible_core` declares.
#
# ⛔ THIS IS A LITERAL, and the reason is NOT laziness: verified 2026-08-17 by
# reading the workflow that runs it. The font gate runs inside `release.yml`
# of the SOURCE repo, in a job that checks out THIS repo but installs only
# `playwright==...` and nothing else. Deriving it from `invisible_core` is the
# form rule 16 asks for, was written and tried, works locally, and kills EVERY
# release with an ImportError.
#
# And there is a second reason, which survives even if that job someday
# installed the core: when the pipeline runs, the PUBLISHED core is still the
# one from the previous release, because the core is published AFTER the
# binary exists (17-release-seal-spec.md §9). Deriving from there would
# measure the new binary against the old declaration.
#
# What keeps the literal honest is not the attention of whoever edits it: it
# is `test_the_family_list_in_the_gate_matches_the_core_manifest`, in
# `tests/test_ci_font_gate_declaration.py` of this repo, where the core IS
# present. That test did not exist: it was DOCUMENTED as existing and nothing
# more, and that is exactly why the list was able to stay at 68 while the
# manifest moved to 71 (the two icon Segoes plus Twemoji Mozilla).
#
# ⛔ AND THE DRIFT DOES NOT GIVE A RED, IT GIVES A GREEN: measured 2026-08-17
# on the real binary. The probe queries `EXPECTED + HOST_MUST_BE_ABSENT` and
# nothing else, so a family removed from here also stops being LOOKED FOR:
# with the three missing, the gate printed `detected 68 families (expected
# 68)` and `FONT GATE OK`, exit 0, on a binary that exposes 71. A gate that
# agrees with itself cannot see its own drift.
EXPECTED = [
"Arial", "Bahnschrift", "Calibri", "Cambria", "Cambria Math", "Candara",
"Comic Sans MS", "Consolas", "Constantia", "Corbel", "Courier New",
"Ebrima", "Franklin Gothic", "Gabriola", "Gadugi", "Georgia", "Impact",
"Ink Free", "Javanese Text", "Leelawadee", "Leelawadee UI",
"Lucida Console", "Lucida Sans Unicode", "MS Gothic", "MS PGothic",
"MS UI Gothic", "MV Boli", "Malgun Gothic", "Marlett",
"Microsoft Himalaya", "Microsoft JhengHei", "Microsoft JhengHei UI",
"Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Sans Serif",
"Microsoft Tai Le", "Microsoft Uighur", "Microsoft YaHei",
"Microsoft YaHei UI", "Microsoft Yi Baiti", "MingLiU-ExtB",
"Mongolian Baiti", "Myanmar Text", "NSimSun", "Nirmala UI",
"PMingLiU-ExtB", "Palatino Linotype", "Segoe Fluent Icons",
"Segoe MDL2 Assets", "Segoe Print", "Segoe Script", "Segoe UI",
"Segoe UI Emoji", "Segoe UI Historic", "Segoe UI Symbol", "SimSun",
"SimSun-ExtB", "Sitka Small", "Sylfaen", "Symbol", "Tahoma",
"Times New Roman", "Trebuchet MS", "Twemoji Mozilla", "Verdana",
"Webdings", "Wingdings", "Wingdings 2", "Wingdings 3", "Yu Gothic",
"Yu Gothic UI",
]
# Host families that must NEVER be visible - one per backend. Their presence is a
# hard fail (block-at-birth did not run for this OS). These are decoys added to
# the probe list; they must all come back absent.
HOST_MUST_BE_ABSENT = [
# macOS / CoreText
"Helvetica Neue", "Geneva", "Menlo", "Monaco", "Avenir", "Lucida Grande",
"Apple SD Gothic Neo", "PingFang SC",
# Linux / fontconfig
"DejaVu Sans", "Liberation Sans", "Ubuntu", "Nimbus Sans", "Noto Sans",
# Office / non-standard families intentionally dropped from the bundle
"Century Gothic", "Agency FB", "Monotype Corsiva", "Pristina",
]
# CSS generic -> the Windows family it must resolve to under bundle-only.
GENERICS = {
"serif": "Times New Roman",
"sans-serif": "Arial",
"monospace": "Consolas",
"system-ui": "Segoe UI",
}
# Families that live inside a .ttc TrueType Collection (several faces packed in
# one file). Being *listed* is not enough: without a per-face index the table
# lookup reads the first font of the collection, so every other face silently
# falls back to a default one. That is invisible to the presence probe below
# (the family is registered either way) but wrecks the persona for CJK text.
# The FF150->151 rebase dropped exactly that fix and only 7 of these loaded.
#
# Calibrated on firefox-17, the known-good release: these are the families that
# demonstrably render the CJK sample with their own face there. Deliberately
# NOT listed: "SimSun-ExtB" (covers Unicode Ext-B, not the BMP characters in
# the sample, so it legitimately falls back) and the "... UI" variants of YaHei
# and JhengHei (they already fall back on firefox-17, so requiring them would
# fail the known-good build). Keep this list as a regression detector, not an
# aspiration: everything here loads on firefox-17 and must keep loading.
#: A fixed seed, because the declared metrics depend on the profile and a
#: gate that changes numbers on every run is not a gate.
_SEED = 970411
#: COPY of zoom.stealth.fonts.generics as invisible_core declares it.
#: Constant across seeds (verified on 5). Tied to the core by the test
#: test_ci_font_gate_generics_match_the_core, which turns red if they diverge.
GENERICS_DECL = (
"cursive||Comic Sans MS\n"
"serif|x-math|Cambria Math\n"
"sans-serif|ja|Yu Gothic UI\n"
"serif|ja|Yu Gothic UI\n"
"monospace|ja|Yu Gothic UI\n"
"sans-serif|ko|Malgun Gothic\n"
"serif|ko|Malgun Gothic\n"
"monospace|ko|Malgun Gothic\n"
"sans-serif|zh-CN|Microsoft YaHei UI\n"
"serif|zh-CN|Microsoft YaHei UI\n"
"monospace|zh-CN|Microsoft YaHei UI\n"
"sans-serif|zh-TW|Microsoft JhengHei UI\n"
"serif|zh-TW|Microsoft JhengHei UI\n"
"monospace|zh-TW|Microsoft JhengHei UI\n"
"sans-serif|zh-HK|Microsoft JhengHei UI\n"
"serif|zh-HK|Microsoft JhengHei UI\n"
"monospace|zh-HK|Microsoft JhengHei UI\n"
"serif||Times New Roman\n"
"sans-serif||Arial\n"
"monospace||Consolas"
)
TTC_FAMILIES = [
"Microsoft YaHei", "Microsoft YaHei UI",
"Microsoft JhengHei", "Microsoft JhengHei UI",
"MS Gothic", "MS PGothic", "MS UI Gothic",
"SimSun", "NSimSun",
"Yu Gothic", "Yu Gothic UI", "Malgun Gothic",
"MingLiU-ExtB", "PMingLiU-ExtB",
]
#: The families above grouped by FACE, measured from the ink box. This is the
#: invariant the check rests on, and it says two things at once: that every
#: face loads (a face that does not load falls into the fallback group, and
#: the grouping changes) and that the two platforms answer the same way (the
#: values are identical, not just the groups).
#:
#: The FALLBACK group contains YaHei because YaHei IS the CJK fallback face -
#: measured at the pixel level: asking for a nonexistent font produces exactly
#: its glyphs. MingLiU-ExtB and PMingLiU-ExtB sit there for a different and
#: equally correct reason: they are Extension-B fonts and their cmap does NOT
#: cover any of the probe's characters, so the fallback draws as it should.
#: The old check asked "does this family measure differently from NO font?"
#: and on these four it answered no, deducing that the face had not loaded:
#: the question was ill-posed, because the fallback face is itself one of the
#: bundled families.
EXPECTED_FACE_GROUPS = [
# The FALLBACK group. Contains YaHei because YaHei IS the CJK fallback
# face, measured at the pixel level: asking for a nonexistent font
# produces exactly its glyphs. MingLiU-ExtB and PMingLiU-ExtB sit here for
# a different and equally correct reason: they are Extension-B faces and
# their cmap does not cover ANY of the probe's characters (verified by
# reading the cmap of the bundled files), so the fallback draws as it
# should.
{"Microsoft YaHei", "Microsoft YaHei UI", "MingLiU-ExtB",
"PMingLiU-ExtB", "__NoSuchFontXYZ__"},
{"Microsoft JhengHei", "Microsoft JhengHei UI"},
{"SimSun", "NSimSun"},
{"MS Gothic"},
{"MS PGothic"},
{"MS UI Gothic"},
{"Yu Gothic"},
{"Yu Gothic UI"},
{"Malgun Gothic"},
]
# Width+height probe (the offsetWidth method real detectors use): a family is
# "present" if styling text in it renders at a different size than the three CSS
# base generics. For the generics, return the measured size of each generic and
# of its target Windows family so the caller can assert they coincide.
DETECT_JS = r"""(arg) => {
const bases = ['monospace', 'sans-serif', 'serif'];
const sample = 'mmmmmmmmmmlli WwQ 0123456789 gjpqy';
const sp = document.createElement('span');
sp.style.cssText =
'position:absolute;left:-9999px;font-size:72px;white-space:nowrap;';
sp.textContent = sample;
document.body.appendChild(sp);
const size = (ff) => { sp.style.fontFamily = ff; return sp.offsetWidth + 'x' + sp.offsetHeight; };
const bw = {};
for (const b of bases) bw[b] = size(b);
const present = {};
for (const f of arg.cands) {
present[f] = bases.some((b) => size("'" + f + "'," + b) !== bw[b]);
}
const gen = {};
for (const g of arg.generics) gen[g] = size(g);
const genref = {};
for (const w of arg.targets) genref[w] = size("'" + w + "'");
// The INK box of measureText for a CJK string, family by family. Not the
// pixels and not the line height, for two measured reasons:
// - line height is a value WE DECLARE, so different families can
// legitimately share it and the comparison stops distinguishing
// anything;
// - the pixels of a canvas with text are not readable on Linux (entry
// 2026-08-11 in 70-known-bugs.md).
// The ink box is geometry derived from the glyphs: measured 2026-08-11 it
// is identical to the third digit between Windows and Linux.
const c = document.createElement('canvas');
const cx = c.getContext('2d');
const inkbox = {};
for (const f of arg.ttc.concat(['__NoSuchFontXYZ__'])) {
cx.font = "56px '" + f + "', '__NoSuchFontXYZ__'";
const m = cx.measureText(arg.cjk);
inkbox[f] = [m.width, m.actualBoundingBoxAscent, m.actualBoundingBoxDescent,
m.actualBoundingBoxLeft, m.actualBoundingBoxRight]
.map((v) => Math.round(v * 1000) / 1000).join('|');
}
document.body.removeChild(sp);
return { present, gen, genref, inkbox };
}"""
# ⛔ FOUR PREFS THAT DISABLED THE NEWTAB USED TO SIT HERE, removed 2026-08-20
# with the newtab revert, for the same reason as `ci_drive_gate.py`: the
# product no longer ships them, and a bench that runs in a configuration
# different from what ships measures a different thing.
#
# The comment used to say "mirrors ci_drive_gate", and that was already false:
# it was FOUR here against SIX there, diverged who knows since when. This
# removal closes the defect at its root instead of realigning it: now there is
# no list to keep in sync, because there is no list at all.
#
# The race these prefs meant to avoid no longer exists anywhere: it was not
# Fission, it was the preallocated new-tab browser grabbing the page's
# channel, and it has been fixed in the engine since 2026-08-23
# (`20-our-patches.md` §5.2w). No gate waits on anything anymore.
_PREFS: dict = {}
# ── The structural limit of this gate, measured and not inferred ─────────
#
# A page cannot ENUMERATE the system fonts: it can only ask name by name. So
# the probe queries `EXPECTED + HOST_MUST_BE_ABSENT` and nothing else, and
# from that follows something that needs to be said rather than discovered:
# **a family removed from EXPECTED also stops being LOOKED FOR**, so the count
# comes out even and the gate passes. Verified 2026-08-11 as a mutation:
# deleting "Georgia" from the list, the gate answered "detected 67 families
# (expected 67)" and OK.
#
# It cannot be fixed from the inside: it is the reason the list exists. The
# practical consequence is that HOST_MUST_BE_ABSENT must stay GENEROUS,
# because it is the only place from which the discovery of an unexpected host
# font can arrive. A name that is in neither list is invisible to this gate
# by construction.
def main(exe: str) -> int:
cands = EXPECTED + HOST_MUST_BE_ABSENT
arg = {
"cands": cands,
"generics": list(GENERICS.keys()),
"targets": list(GENERICS.values()),
"ttc": TTC_FAMILIES,
"cjk": "中文字体測試あア漢字",
}
# RAW launch, and a hand-delivered declaration. The CI gate job installs
# only Playwright: invisible_core is not there and cannot be without
# changing the workflow, i.e. without rebuilding the five archives.
#
# The only thing missing from a rawly-launched engine is the generics map.
# Measured 2026-08-11 on the same binary: without it,
# serif/sans-serif/monospace/cursive/fantasy ALL collapse onto Arial on
# Linux (not on Windows, because there Gecko's defaults happen to coincide
# with the persona we declare); with it, they map onto Times New Roman,
# Arial, Consolas and Comic Sans on BOTH, with the same numbers.
#
# GENERICS_DECL below is a COPY of what invisible_core declares, and it is
# the only one in the project. It cannot diverge silently: it is tied by
# the test test_ci_font_gate_generics_match_the_core, which compares this
# string against the one the core produces and turns red if they part
# ways.
from playwright.sync_api import sync_playwright
prefs = dict(_PREFS)
prefs["zoom.stealth.fonts.generics"] = GENERICS_DECL
# ⛔ Prefs are written into the PROFILE, not sent over the protocol.
# Through firefox-20 this was `launch(firefox_user_prefs=prefs)`, which
# Playwright delivers to the browser inside `Browser.enable` - i.e. AFTER
# startup. From firefox-21 the engine REFUSES it instead of applying it
# late:
#
# Browser.enable no longer applies preferences. They are written into
# the profile before startup...
#
# and that is the right refusal. Applying them after startup means the
# first launch initializes gfx and fonts with the defaults and the second
# with the prefs active: two different paths, which are the cause of
# [B150]. And ignoring them would be worse - a browser without the prefs
# the caller believes it set, and no error.
#
# A `user.js` in the profile is read at STARTUP, so the generics map is
# already there when gfx initializes: a single path.
profile_dir = Path(tempfile.mkdtemp(prefix="ci-font-gate-"))
(profile_dir / "user.js").write_bytes(
("".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
for k, v in sorted(prefs.items()))).encode("utf-8"))
with sync_playwright() as p:
ctx = p.firefox.launch_persistent_context(
str(profile_dir), executable_path=exe, headless=True)
try:
page = ctx.new_page()
page.goto("about:blank")
r = page.evaluate(DETECT_JS, arg)
finally:
ctx.close()
shutil.rmtree(profile_dir, ignore_errors=True)
detected = {f for f, v in r["present"].items() if v}
expected = set(EXPECTED)
missing = sorted(expected - detected)
# Anything detected that isn't in EXPECTED (host leaks land here too).
extra = sorted(detected - expected)
leaked_host = [h for h in HOST_MUST_BE_ABSENT if r["present"].get(h)]
gen_bad = []
for g, want in GENERICS.items():
got, ref = r["gen"].get(g), r["genref"].get(want)
if got != ref:
gen_bad.append(f"{g} -> {got} (expected {want} = {ref})")
n = len(detected)
print(f"[font-gate] {exe}")
print(f"[font-gate] detected {n} families (expected {len(EXPECTED)})")
if missing:
print(f"[font-gate] MISSING (in bundle, not exposed): {missing}")
if extra:
print(f"[font-gate] UNEXPECTED (exposed, not in canonical set): {extra}")
if leaked_host:
print(f"[font-gate] HOST LEAK (block-at-birth did not run!): {leaked_host}")
if gen_bad:
print(f"[font-gate] GENERIC MISMATCH: {gen_bad}")
# The face groups, measured now, against the expected ones. A grouping
# that changes says a face fell into the fallback; a VALUE that changes
# says the declared metrics have shifted, or that the two platforms no
# longer answer the same way. These are two different defects and the
# message keeps them apart.
ink = r.get("inkbox", {})
seen = {}
for fam, box in ink.items():
seen.setdefault(box, []).append(fam)
# The STRUCTURE is compared - which families share a face - not the
# values. The values are identical between Windows and Linux only when the
# browser receives all its declarations, and this gate launches it raw
# because the CI job has no invisible_core: on a raw launch Linux returns
# integer bounds (FreeType's grid-fit) while Windows returns fractions.
# The structure coincides instead, and it is what answers the question
# "did this face load?" - a face that does not load FALLS into the
# fallback group and the grouping changes. Cross-OS parity of the values
# is a different check, one that has to be done under the wrapper where
# all the declarations are present.
measured = [set(f) for f in seen.values()]
face_bad = []
for expected_group in EXPECTED_FACE_GROUPS:
if expected_group not in measured:
nearest = max(measured, key=lambda g: len(g & expected_group), default=set())
face_bad.append(f"expected group {sorted(expected_group)} not found; "
f"the closest measured is {sorted(nearest)}")
for g in measured:
if g not in EXPECTED_FACE_GROUPS:
face_bad.append(f"unexpected group: {sorted(g)}")
if face_bad:
print("[font-gate] FACES: the grouping is not the expected one")
for line in face_bad:
print(f"[font-gate] {line}")
ok = (not missing and not extra and not leaked_host and not gen_bad
and not face_bad)
if ok:
print(f"FONT GATE OK - exactly the {n} Windows families, host-leak 0, "
f"generics map to Windows (serif/sans/mono/system-ui), "
f"{len(EXPECTED_FACE_GROUPS)} face groups over "
f"{len(TTC_FAMILIES)} CJK families (every declared face draws "
f"its own glyphs).")
return 0
print("FONT GATE FAILED - the exposed set does not match the Windows "
"persona on this OS (see the diff above).")
return 1
if __name__ == "__main__":
if len(sys.argv) < 2:
print("usage: python ci_font_gate.py <firefox-binary>", file=sys.stderr)
raise SystemExit(2)
raise SystemExit(main(sys.argv[1]))
+606
View File
@@ -0,0 +1,606 @@
#!/usr/bin/env python3
"""CI host gate: what a page reads is a function of the declared identity and of
Firefox's code, never of the machine the browser runs on.
Two properties follow, and they are checked for every value the page dumps
(whole APIs, not a hand-picked list), so the gate needs no knowledge of where
the next leak will be:
1. HOST-INDEPENDENCE. The same identity on different hosts (the Windows and
Linux x86_64 legs) gives the same bytes.
2. RETAIL EQUALITY. A value that does not depend on the identity equals what
retail Firefox for Windows answers on the same page, at the same device
pixel ratio.
Values are compared leaf by leaf: an object the page reads (navigator, screen)
mixes fields the identity decides with fields it does not, and each is held to
its own property.
Which values depend on the identity is measured AND declared. Each leg visits
the page with several seeds at a fixed DPR; a value that changes with the seed
depends on the identity and is held to property 1 only. A value the identity
decides can still come out the same for every seed (16 cores, a 1920x1080
screen), so those are declared as well.
The only exceptions live in host_gate/exceptions.json, each with its reason:
- identity: values the declared identity decides; exempt from property 2,
never from property 1;
- noise: values that differ between two launches of retail itself;
- network: values the identity takes from the network (language and zone
from the egress IP), which CI without a proxy cannot reproduce;
- measurement: values that record how the reference was taken rather than
what Firefox answers (focus, on the hidden desktop retail ran on);
- known_defects: open divergences with the work that closes them. This list
only shrinks: an entry that no longer matches a difference fails the gate,
so it is removed when its fix lands.
Values under the diag. prefix are not held to either property. They are
information the page records about the host (diag.webgl: whether WebGL2 and
multisampling exist there and, when not, the message Firefox gives): the legs
legitimately differ on them and the retail reference does not record them.
compare() skips them by name; dump() prints them into the job log, so a run
tells why without its artifacts being downloaded.
Values under the state. prefix are the window in the states a page can drive
it to: state.normal, state.fullscreen (entered through a real click, a user
gesture) and state.after_fullscreen. The dump measures them after the page is
done (drive_states). Besides the two properties they are held to INVARIANTS:
relations between values that hold on every host, for every identity and
whatever the reference says, because a window that breaks them cannot exist
(an outer window smaller than its viewport, a fullscreen window off the
screen's origin). Each value can look plausible on its own; only the relation
shows the defect, so these are checked even where nothing else is.
This replaces ci_font_gate.py, which checked one surface (the font list) of
the same rule.
python ci_host_gate.py dump <firefox> --leg linux-x86_64 --out dumps/
python ci_host_gate.py compare dumps/ (reference: host_gate/reference/firefox-159)
"""
from __future__ import annotations
import argparse
import base64
import fnmatch
import gzip
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Callable, NamedTuple
HERE = Path(__file__).resolve().parent / "host_gate"
PAGE = HERE / "host_gate_page.html"
EXCEPTIONS = HERE / "exceptions.json"
REFERENCE = HERE / "reference" / "firefox-159"
FORMAT = "host-gate/1"
#: DPRs the reference is recorded at, and the seeds visited at each. Three seeds
#: so that a value that depends on the identity is very unlikely to look
#: constant by chance.
DPRS = (1.0, 1.5)
SEEDS = (11, 12, 13)
#: The leg every other leg is compared with: the platform the identity claims.
ANCHOR = "win-x86_64"
#: Keys under this prefix are information, never compared (see the module docstring).
DIAG = "diag."
def is_diag(key: str) -> bool:
return key.startswith(DIAG)
def diag_lines(items: dict, before: dict | None = None) -> list:
"""The diag. leaves of one visit as 'key = value' lines; with before (an
earlier visit's diag leaves), only the keys whose value changed."""
now = {k: v for k, v in leaves(items).items() if is_diag(k)}
lines = [" %s = %s" % (k, json.dumps(v, sort_keys=True)) for k, v in now.items()
if before is None or before.get(k, "<missing>") != v]
return lines + [" %s = <missing>" % k for k in (before or {}) if k not in now]
def diag_report(visit: str, items: dict, first: dict | None) -> list:
"""What dump() prints for one visit: every diag. value on the leg's first
visit (first is None), then only what changed from it."""
if first is None:
return ["diag %s:" % visit] + (diag_lines(items) or [" (the page recorded no diag. keys)"])
changed = diag_lines(items, first)
return ["diag %s: %s" % (visit, "changed from the first visit:" if changed else "as the first visit")] + changed
# -
# States: the window driven to fullscreen and back with real input, and the
# relations its values must keep in every state.
STATE = "state."
#: The states drive_states measures, in the order it reaches them.
STATES = ("normal", "fullscreen", "after_fullscreen")
#: How long the page waits for fullscreenchange before recording 'timeout'.
STATE_TIMEOUT_MS = 5000
#: Retail equality for these namespaces waits for the reference to record them.
#: The firefox-159 reference was taken before the dump drove any state, so it has
#: no state.* key; until it has, a state.* value is held to host-independence and
#: to INVARIANTS only, and compare() notes it. The session that produces the
#: reference adds, to the items of each dpr<x>.json.gz, the three items
#: state.normal, state.fullscreen and state.after_fullscreen, shaped exactly as
#: drive_states returns them, by running drive_states on retail Firefox for
#: Windows on this page with evaluate = run the expression in the page, and move
#: and click = OS-level input at those viewport (CSS px) points, e.g. SendInput:
#: a click a script dispatches is not a user gesture and requestFullscreen
#: refuses it. From the first reference that has state.*, these values are
#: compared with retail like every other; the window geometry is declared
#: identity in exceptions.json, the rest (display-mode, fullscreenElement,
#: window.fullScreen, how the transition went) is held to retail.
REFERENCE_PENDING = (STATE,)
def drive_states(evaluate: Callable, move: Callable, click: Callable,
timeout_ms: int = STATE_TIMEOUT_MS) -> dict:
"""The page's window in each of STATES, as items {state.<name>: values}.
evaluate runs an expression in the page and returns its (awaited) value;
move and click are real input at a viewport point. In each state the mouse
moves twice and clicks on the middle of the viewport, so every value of the
state comes with the screen - client offsets of real mouse events.
Fullscreen is entered by clicking the page's button (its handler calls
requestFullscreen) and left with document.exitFullscreen(); each transition
records how it ended (fullscreenchange, fullscreenerror, timeout). Whatever
raises leaves {"error": ...} in the states not measured yet, which the
'measured' invariant reports.
"""
states = {}
def measure(name, transition=None):
evaluate("__hostGateStates.clear()")
w, h = evaluate("[innerWidth, innerHeight]")
x, y = w // 2, h // 2
move(x - 20, y)
move(x, y + 20)
click(x, y + 20)
values = evaluate("__hostGateStates.measure()")
if transition is not None:
values["transition"] = transition
states[name] = values
try:
button = evaluate("__hostGateStates.prepare()")
measure("normal")
evaluate("__hostGateStates.arm(%d)" % timeout_ms)
click(button["x"], button["y"])
measure("fullscreen", evaluate("__hostGateStates.wait()"))
evaluate("__hostGateStates.leave(%d)" % timeout_ms)
measure("after_fullscreen", evaluate("__hostGateStates.wait()"))
except Exception as e: # noqa: BLE001 - recorded, and failed by the 'measured' invariant
for name in STATES:
states.setdefault(name, {"error": "%s: %s" % (type(e).__name__, str(e)[:300])})
return {STATE + name: states[name] for name in STATES}
#: What a state is made of; the screen is {width, height, availWidth, availHeight}.
POSITION = ("innerWidth", "innerHeight", "outerWidth", "outerHeight", "screenX", "screenY",
"mozInnerScreenX", "mozInnerScreenY", "screen")
FIELDS = POSITION + ("display_mode_fullscreen", "fullscreen_element", "events")
def _measured(s, states):
if "error" in s:
return "not measured: %s" % s["error"]
missing = [f for f in FIELDS if f not in s]
missing += ["%s as a number" % f for f in POSITION[:-1]
if f in s and (isinstance(s[f], bool) or not isinstance(s[f], (int, float)))]
if not isinstance(s.get("screen"), dict) or not {"width", "height", "availWidth", "availHeight"} <= set(s["screen"]):
missing.append("screen.width/height/availWidth/availHeight")
if not isinstance(s.get("events"), dict):
missing.append("events as {type: [[dx, dy]]}")
return missing and "not measured: no %s" % ", ".join(missing)
def _transition(s, states):
t = s.get("transition")
if not isinstance(t, dict) or t.get("how") != "fullscreenchange" or not t.get("settled"):
return "the transition did not complete: %s" % json.dumps(t, sort_keys=True)
def _outer_holds_inner(s, states):
bad = ["outer%s %s < inner%s %s" % (d, s["outer" + d], d, s["inner" + d])
for d in ("Width", "Height") if s["outer" + d] < s["inner" + d]]
return "; ".join(bad)
def _is_the_screen(s, states):
w, h = s["screen"]["width"], s["screen"]["height"]
bad = ["%s %s" % (k, s[k]) for k, want in (("innerWidth", w), ("outerWidth", w),
("innerHeight", h), ("outerHeight", h)) if s[k] != want]
return bad and "%s, screen %sx%s (avail %sx%s)" % (", ".join(bad), w, h,
s["screen"]["availWidth"], s["screen"]["availHeight"])
def _at_origin(s, states):
bad = ["%s %s" % (k, s[k]) for k in ("screenX", "screenY", "mozInnerScreenX", "mozInnerScreenY") if s[k] != 0]
return ", ".join(bad)
def _declares(fullscreen):
def check(s, states):
bad = ["%s %s" % (k, json.dumps(s[k])) for k in ("display_mode_fullscreen", "fullscreen_element")
if s[k] is not fullscreen]
return ", ".join(bad)
return check
def _offset_matches(offset, inner_screen):
# MouseEvent.screenX and clientX are each rounded to a whole CSS px, while
# mozInnerScreenX is the viewport's exact offset, fractional when the DPR
# does not divide the window's device position (85.33 at 1.5): the
# difference of the two rounded values is then within 1 px of it. A whole
# offset has nothing to round and must match exactly.
if float(inner_screen).is_integer():
return offset == inner_screen
return abs(offset - inner_screen) <= 1
def _events_at_inner_screen(s, states):
if not any(s["events"].values()):
return "no mouse event was recorded"
inner = (s["mozInnerScreenX"], s["mozInnerScreenY"])
bad = ["%s (%s, %s)" % (typ, dx, dy) for typ, pairs in sorted(s["events"].items()) for dx, dy in pairs
if not (_offset_matches(dx, inner[0]) and _offset_matches(dy, inner[1]))]
return bad and "screen - client of %s, mozInnerScreen (%s, %s)" % (", ".join(bad), inner[0], inner[1])
def _screen_stays(s, states):
normal = states.get("normal")
if not isinstance(normal, dict) or not isinstance(normal.get("screen"), dict):
return None # the normal state's own 'measured' failure says why
bad = ["screen.%s %s (normal %s)" % (k, s["screen"][k], normal["screen"].get(k))
for k in ("width", "height") if s["screen"][k] != normal["screen"].get(k)]
return ", ".join(bad)
def _back_to_normal(s, states):
normal = states.get("normal")
if not isinstance(normal, dict) or _measured(normal, states):
return None # the normal state's own 'measured' failure says why
bad = ["%s %s (normal %s)" % (k, json.dumps(s[k]), json.dumps(normal[k])) for k in POSITION if s[k] != normal[k]]
return ", ".join(bad)
class Invariant(NamedTuple):
name: str
states: tuple
check: Callable # (state values, every state's values) -> failure message, or a false value
why: str
#: Every relation the states are held to, the only place they are declared.
#: 'measured' runs first: the others assume the state's fields are there.
INVARIANTS = (
Invariant("measured", STATES, _measured,
"a state the dump could not reach or read is a failure, never a silent pass"),
Invariant("transition", ("fullscreen", "after_fullscreen"), _transition,
"a real click is a user gesture, so retail enters and leaves fullscreen and the window then holds still; "
"a timeout or fullscreenerror means the window did not do what a user's does"),
Invariant("outer_holds_inner", STATES, _outer_holds_inner,
"the outer window contains the viewport: a smaller outer window cannot exist "
"(the defect it was written for: 1936x1048 outer under a 1920x1080 viewport in fullscreen)"),
Invariant("fullscreen_is_the_screen", ("fullscreen",), _is_the_screen,
"in fullscreen retail has no frame, toolbar or taskbar: viewport, window and screen are one rectangle "
"(a viewport at availHeight is a window that never really went fullscreen)"),
Invariant("fullscreen_at_origin", ("fullscreen",), _at_origin,
"a fullscreen window sits at the screen's origin and its viewport at the window's: "
"screenX/Y and mozInnerScreenX/Y are 0 (not a maximized window's -8/-8 and 85)"),
Invariant("fullscreen_declared", ("fullscreen",), _declares(True),
"the page entered fullscreen, so CSS (display-mode) and the DOM (fullscreenElement) say so"),
Invariant("not_fullscreen", ("normal", "after_fullscreen"), _declares(False),
"outside fullscreen neither CSS nor the DOM may claim it; it also keeps 'back_to_normal' "
"from passing with both states stuck in fullscreen"),
Invariant("events_at_inner_screen", STATES, _events_at_inner_screen,
"an event's screen point is its client point plus where the viewport sits on the screen, "
"which is mozInnerScreenX/Y: screen - client of every mouse event equals it"),
Invariant("screen_stays", ("fullscreen", "after_fullscreen"), _screen_stays,
"fullscreen changes the window, not the monitor: screen.width/height are the normal state's"),
Invariant("back_to_normal", ("after_fullscreen",), _back_to_normal,
"leaving fullscreen puts the window back as it was: every size and position is the normal state's"),
)
def check_invariants(states: dict) -> list:
"""Every broken invariant of one visit as (invariant, state, message).
states maps each of STATES to its values (None when the dump has none)."""
broken = []
for state in STATES:
s = states.get(state)
if not isinstance(s, dict):
s = {"error": "the dump has no %s%s" % (STATE, state)}
for inv in INVARIANTS:
if state not in inv.states:
continue
message = inv.check(s, states)
if message:
broken.append((inv, state, message))
if inv.name == "measured":
break
return broken
def visit_states(items: dict) -> dict:
return {name: items.get(STATE + name) for name in STATES}
def invariant_lines(visit: str, items: dict) -> list:
return ["invariant %s %s %s%s: %s (why: %s)" % (inv.name, visit, STATE, state, message, inv.why)
for inv, state, message in check_invariants(visit_states(items))]
# -
# Dump: one leg, every (dpr, seed) visit, the way the reference was measured:
# the page over http://127.0.0.1 (a secure context), en-US, the zone the retail
# reference reported (retail on Windows ignores TZ and answers the machine's),
# the device pixel ratio pinned in the persona, no drawn cursor.
class _Page(BaseHTTPRequestHandler):
def do_GET(self):
body = PAGE.read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(body)
def do_POST(self): # the page also posts its result; the dump reads it from the page
self.rfile.read(int(self.headers.get("Content-Length") or 0))
self.send_response(204)
self.end_headers()
def log_message(self, *args):
pass
def reference_items(reference: Path, dpr: float) -> dict | None:
"""Retail's items at one DPR, from dpr<x>.json.gz (or a plain dpr<x>.json)."""
for name in ("dpr%s.json.gz" % dpr, "dpr%s.json" % dpr):
path = reference / name
if path.is_file():
raw = path.read_bytes()
return json.loads(gzip.decompress(raw) if name.endswith(".gz") else raw)["items"]
return None
def reference_zone(reference: Path) -> str:
return reference_items(reference, 1.0)["surface.intl"]["DateTimeFormat"]["timeZone"]
def visit_options(firefox: str, seed: int, dpr: float, zone: str) -> dict:
"""The launch of one (dpr, seed) visit. The DPR is PINNED in the persona
(screen.dpr), so the core declares a screen, a work area and a window made
at that scale. It used to be forced through
extra_prefs={"layout.css.devPixelsPerPx": ...} on whatever persona the seed
drew: a 100% persona at 1.5 read innerWidth 1920 inside an outerWidth of
1291 (run 41325657085), an identity no machine has, which the engine now
refuses to start with."""
return {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
"locale": "en-US", "timezone": zone, "pin": {"screen.dpr": dpr}}
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000) -> int:
from invisible_playwright import InvisiblePlaywright
out.mkdir(parents=True, exist_ok=True)
server = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
threading.Thread(target=server.serve_forever, daemon=True).start()
zone = reference_zone(reference)
first_diag = None
try:
for dpr in DPRS:
for seed in SEEDS:
with InvisiblePlaywright(**visit_options(firefox, seed, dpr, zone)) as browser:
page = browser.new_context().new_page()
# The same budget as the wait below: a cold Windows runner took
# more than goto's default 30 s to reach `load` on the first
# visit (candidate 42410156024), and passed locally 6/6.
page.goto("http://127.0.0.1:%d/?dpr%s" % (server.server_address[1], dpr),
timeout=timeout_ms)
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
result = page.evaluate("window.__hostGate")
if result.get("format") == FORMAT:
result["items"].update(drive_states(page.evaluate, page.mouse.move, page.mouse.click))
if result.get("format") != FORMAT:
print("the page answered format %r, not %r" % (result.get("format"), FORMAT))
return 2
path = out / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))
path.write_text(json.dumps({"leg": leg, "dpr": dpr, "seed": seed, "result": result}),
encoding="utf-8")
print("dumped %s: %d items" % (path.name, len(result["items"])))
visit = "%s dpr %s seed %d" % (leg, dpr, seed)
for line in diag_report(visit, result["items"], first_diag):
print(line)
# told here too, so the job log says it without the compare step
for line in invariant_lines(visit, result["items"]):
print(line)
sys.stdout.flush()
if first_diag is None:
first_diag = {k: v for k, v in leaves(result["items"]).items() if is_diag(k)}
finally:
server.shutdown()
return 0
# -
# Compare: every leg, every visit, against each other and against retail.
KINDS = ("identity", "noise", "network", "measurement", "known_defects")
def load_exceptions(path: Path = EXCEPTIONS) -> dict:
data = json.loads(path.read_text(encoding="utf-8"))
unknown = set(data) - set(KINDS)
if unknown:
raise SystemExit("exceptions.json: unknown kinds %s" % sorted(unknown))
for kind in KINDS:
for entry in data.get(kind, []):
if not entry.get("keys") or not entry.get("why"):
raise SystemExit("exceptions.json: every %s entry needs keys and why" % kind)
return data
def matching(entries: list, key: str, leg: str | None = None) -> list:
return [e for e in entries
if any(fnmatch.fnmatchcase(key, p) for p in e["keys"])
and (leg is None or not e.get("legs") or leg in e["legs"])]
def is_image(value) -> bool:
return isinstance(value, dict) and "data" in value and "enc" in value
def leaves(items: dict) -> dict:
"""Every value as a leaf with a dotted key; an image stays one value."""
out = {}
def walk(key, value):
if isinstance(value, dict) and value and not is_image(value):
for k, v in value.items():
walk("%s.%s" % (key, k), v)
else:
out[key] = value
for key, value in items.items():
walk(key, value)
return out
def describe(a, b) -> str:
"""A short account of a difference; for images, how many bytes differ."""
if isinstance(a, dict) and isinstance(b, dict) and "data" in a and "data" in b:
x, y = base64.b64decode(a["data"]), base64.b64decode(b["data"])
if len(x) != len(y) or (a.get("w"), a.get("h")) != (b.get("w"), b.get("h")):
return "image %sx%s vs %sx%s" % (a.get("w"), a.get("h"), b.get("w"), b.get("h"))
diff = [abs(p - q) for p, q in zip(x, y) if p != q]
return "image: %d of %d bytes differ, max delta %d" % (len(diff), len(x), max(diff, default=0))
text = lambda v: json.dumps(v, sort_keys=True)[:120]
return "%s vs %s" % (text(a), text(b))
def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None = None) -> list:
"""Every failure as one line. Empty means the gate passes. notes, when
given, receives what was not checked and why (REFERENCE_PENDING)."""
visits = {} # (leg, dpr, seed) -> items
failures = []
for path in sorted(dumps.glob("*.json")):
d = json.loads(path.read_text(encoding="utf-8"))
items = d["result"]["items"]
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
# the invariants: every leg, every visit, every state; no exception and no reference applies
failures += invariant_lines("%s dpr %s seed %d" % (d["leg"], d["dpr"], d["seed"]), items)
if not visits:
return ["no dumps in %s" % dumps]
legs = sorted({k[0] for k in visits})
refs = {}
pending = {} # dpr -> the REFERENCE_PENDING namespaces the reference does not record yet
for dpr in DPRS:
items = reference_items(reference, dpr)
if items is None:
return ["no retail reference for dpr %s in %s" % (dpr, reference)]
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
pending[dpr] = tuple(p for p in REFERENCE_PENDING if not any(k.startswith(p) for k in refs[dpr]))
for p in pending[dpr]:
if notes is not None:
notes.append("the retail reference has no %s* at dpr %s: those values are held to "
"host-independence and the invariants, not to retail" % (p, dpr))
identity = exceptions.get("identity", [])
excusable = exceptions.get("noise", []) + exceptions.get("network", []) + exceptions.get("measurement", [])
known = exceptions.get("known_defects", [])
used = set()
def excused(key, leg):
if matching(excusable, key):
return True
hit = matching(known, key, leg)
for e in hit:
used.add(id(e))
return bool(hit)
for dpr in DPRS:
for leg in legs:
missing = [s for s in SEEDS if (leg, dpr, s) not in visits]
if missing:
failures.append("%s dpr %s: no dump for seeds %s" % (leg, dpr, missing))
present = [(leg, s) for leg in legs for s in SEEDS if (leg, dpr, s) in visits]
keys = sorted(set().union(*(visits[(l, dpr, s)].keys() for l, s in present)) | set(refs[dpr]))
for key in keys:
# 1. host-independence: for each seed, every leg gives the Windows
# leg's value. Windows is the anchor because it is the platform the
# identity claims: a leg that differs from it is the one that moved.
for seed in SEEDS:
values = {leg: visits[(leg, dpr, seed)].get(key, "<missing>")
for leg in legs if (leg, dpr, seed) in visits}
base = ANCHOR if ANCHOR in values else next(iter(values), None)
for leg, value in values.items():
if leg != base and value != values[base] and not excused(key, leg):
failures.append("host %s dpr %s seed %d: %s differs from %s: %s"
% (key, dpr, seed, leg, base, describe(value, values[base])))
# 1b. host-independence among the legs of one OS (two Linux
# distributions): a known defect excuses a difference from Windows,
# never one between two machines of the same system, whose libraries
# (FreeType, fontconfig, Mesa) are the host's and must not show.
for seed in SEEDS:
for family in sorted({l.split("-")[0] for l in legs}):
same_os = [l for l in legs if l.split("-")[0] == family and (l, dpr, seed) in visits]
for leg in same_os[1:]:
value = visits[(leg, dpr, seed)].get(key, "<missing>")
first = visits[(same_os[0], dpr, seed)].get(key, "<missing>")
if value != first and not matching(excusable, key):
failures.append("host %s dpr %s seed %d: %s differs from %s (same OS): %s"
% (key, dpr, seed, leg, same_os[0], describe(value, first)))
# 2. retail equality, for a value that is the same for every seed
if key.startswith(pending[dpr]):
continue
for leg in legs:
per_seed = [visits[(leg, dpr, s)].get(key, "<missing>")
for s in SEEDS if (leg, dpr, s) in visits]
if len({json.dumps(v, sort_keys=True) for v in per_seed}) != 1 or matching(identity, key):
continue # depends on the identity: property 1 only
retail = refs[dpr].get(key, "<missing>")
if per_seed[0] != retail and not excused(key, leg):
failures.append("retail %s dpr %s on %s: %s"
% (key, dpr, leg, describe(per_seed[0], retail)))
for e in known:
if id(e) not in used:
failures.append("known defect no longer seen, remove it from exceptions.json: %s (%s)"
% (e["keys"], e["why"]))
return failures
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
d = sub.add_parser("dump")
d.add_argument("firefox")
d.add_argument("--leg", required=True)
d.add_argument("--out", type=Path, required=True)
d.add_argument("--reference", type=Path, default=REFERENCE)
c = sub.add_parser("compare")
c.add_argument("dumps", type=Path)
c.add_argument("--reference", type=Path, default=REFERENCE)
args = ap.parse_args(argv)
if args.cmd == "dump":
return dump(args.firefox, args.leg, args.out, args.reference)
notes = []
failures = compare(args.dumps, args.reference, load_exceptions(), notes)
for n in notes:
print("NOTE " + n)
for f in failures:
print("FAIL " + f)
print("HOST GATE %s: %d failures" % ("OK" if not failures else "FAILED", len(failures)))
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())
+50
View File
@@ -0,0 +1,50 @@
"""Which canvas text cases two runs draw differently.
tests/test_canvas_text_is_windows_e2e.py writes canvas_text_<tag>.json (case id -> SHA-256
of the RGBA bytes) into INVISIBLE_CANVAS_TEXT_OUT. Run it on Debian 12 and on Ubuntu 24.04
(and the retail reference, tests/data/canvas_text_ref/refs.json, is accepted too), then:
python scripts/compare_canvas_text_runs.py debian.json ubuntu.json
The exit status is 0 when every case is equal on both sides and both draw the same set.
"""
from __future__ import annotations
import json
import sys
def load(path):
"""case id -> sha256, from a run file or from refs.json."""
data = json.loads(open(path, encoding="utf-8").read())
if "cases" in data:
return {k: v["sha256"] for k, v in data["cases"].items()}
return data
def compare(a, b):
"""(only in a, only in b, ids whose hash differs)."""
only_a = sorted(set(a) - set(b))
only_b = sorted(set(b) - set(a))
differ = sorted(k for k in set(a) & set(b) if a[k] != b[k])
return only_a, only_b, differ
def main(argv):
if len(argv) != 3:
print(__doc__)
return 2
a, b = load(argv[1]), load(argv[2])
only_a, only_b, differ = compare(a, b)
for label, ids in (("only in %s" % argv[1], only_a), ("only in %s" % argv[2], only_b),
("differ", differ)):
if ids:
print("%s (%d):" % (label, len(ids)))
for k in ids:
print(" " + k)
print("%d cases compared, %d differ" % (len(set(a) & set(b)), len(differ)))
return 1 if (only_a or only_b or differ) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python
"""Refuse a release when the browser-driving e2e is not green on the commit
being tagged.
python scripts/e2e_is_green.py --repo owner/name --sha <sha>
python scripts/e2e_is_green.py --selftest
⛔ WHY THIS EXISTS. `publish.yml`'s gate runs `python -m pytest -q`, which is the
DEFAULT selection, and the default selection deselects `e2e`. So the job that
decides whether a release goes out has never looked at the suite that drives a
browser. The e2e runs on every push and every pull request, and no gate reads
it: a red there stops neither a merge nor a tag.
It has already happened. 0.22.1 was tagged from a main whose e2e was red, and
nothing said so, because nothing was looking. That is the same shape as the
`-m unit` false green the project forbids elsewhere, sitting inside the workflow
that publishes.
⛔ AND IT ASKS RATHER THAN RE-RUNS. The e2e has already run on that commit, and
running it again here would cost five minutes to learn something the API can
answer in one call. What is missing is not a second measurement: it is somebody
reading the first one.
The three verdicts, and the middle one is the one that gets written wrong:
- a check-run concluded badly -> REFUSE, naming it
- NO e2e check-run exists for that commit -> REFUSE
- still running -> wait, then refuse on the deadline
⛔ ZERO CHECK-RUNS IS NOT A VERDICT. An empty list is indistinguishable from
"the workflow was renamed", "it never started" and "nobody configured one", and
mapping it to a pass turns this gate into decoration exactly when it is most
needed. Measured the hard way on a different gate: a poller read an empty result
as DONE and reported a conclusion that the next iteration contradicted.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
#: What counts as a conclusion that does not block. `skipped` and `neutral` are
#: here because a matrix leg can legitimately not run; `cancelled` is NOT, since
#: a cancelled run measured nothing and saying otherwise is the same lie as an
#: empty list.
FINE = ("success", "skipped", "neutral")
REFUSED_RED = 1
REFUSED_ABSENT = 2
REFUSED_TIMEOUT = 3
def verdict(runs, pattern):
"""(code, message) for the check-runs of one commit. Pure: no network.
Separated from the fetching so its known-bad cases can run without a token,
a repository or a network, which is what `--selftest` exercises.
"""
ours = [c for c in runs if str(c.get("name", "")).startswith(pattern)]
if not ours:
return REFUSED_ABSENT, (
"no check-run whose name starts with %r exists for this commit.\n"
"That is not a pass: an empty list reads the same whether the job\n"
"was renamed, never started, or was never configured. If the e2e\n"
"workflow no longer produces that name, fix the name here rather\n"
"than letting a release go out unmeasured." % pattern)
running = [c["name"] for c in ours if c.get("status") != "completed"]
if running:
return None, "still running: %s" % ", ".join(sorted(running))
bad = [(c["name"], c.get("conclusion")) for c in ours
if c.get("conclusion") not in FINE]
if bad:
return REFUSED_RED, (
"the e2e is not green on the commit being tagged:\n" +
"\n".join(" %s: %s" % (n, c) for n, c in sorted(bad)) +
"\nA release from here ships code the browser-driving suite\n"
"rejected. Fix it, or re-run the job and let it say so itself.")
return 0, "e2e green on this commit: %s" % ", ".join(
sorted(c["name"] for c in ours))
def fetch(repo, sha, token):
url = ("https://api.github.com/repos/%s/commits/%s/check-runs?per_page=100"
% (repo, sha))
req = urllib.request.Request(url, headers={
"Accept": "application/vnd.github+json",
"Authorization": "Bearer %s" % token,
"X-GitHub-Api-Version": "2022-11-28",
})
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r).get("check_runs", [])
SELFTEST = [
("a green leg passes", 0,
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "success"}]),
("a red leg refuses", REFUSED_RED,
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "failure"}]),
("a cancelled leg refuses, because it measured nothing", REFUSED_RED,
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "cancelled"}]),
("timed_out refuses", REFUSED_RED,
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "timed_out"}]),
("no check-run at all refuses", REFUSED_ABSENT, []),
("other jobs alone are not an e2e", REFUSED_ABSENT,
[{"name": "tests (3.12)", "status": "completed", "conclusion": "success"}]),
("one green leg does not excuse a red one", REFUSED_RED,
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "success"},
{"name": "e2e (macos)", "status": "completed", "conclusion": "failure"}]),
("a skipped leg is allowed", 0,
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "skipped"}]),
("still running is neither a pass nor a refusal", None,
[{"name": "e2e (linux, xvfb)", "status": "in_progress", "conclusion": None}]),
("running beside a red one waits rather than guessing", None,
[{"name": "e2e (a)", "status": "in_progress", "conclusion": None},
{"name": "e2e (b)", "status": "completed", "conclusion": "failure"}]),
]
def selftest():
bad = 0
for label, want, runs in SELFTEST:
got, _ = verdict(runs, "e2e")
ok = got == want
bad += not ok
print(" %-56s %s" % (label, "ok" if ok else
"WRONG (wanted %r, got %r)" % (want, got)))
print("%d/%d known-bad cases behave" % (len(SELFTEST) - bad, len(SELFTEST)))
return 1 if bad else 0
def main(argv=None):
ap = argparse.ArgumentParser(prog="e2e_is_green.py")
ap.add_argument("--repo", help="owner/name")
ap.add_argument("--sha", help="the commit being tagged")
ap.add_argument("--pattern", default="e2e",
help="check-run name prefix to look for (default: e2e)")
ap.add_argument("--wait-minutes", type=float, default=30.0,
help="how long to wait while a leg is still running")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args(argv)
if a.selftest:
return selftest()
if not (a.repo and a.sha):
ap.error("--repo and --sha are required without --selftest")
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if not token:
print("GITHUB_TOKEN is not set, so this gate cannot read the checks.\n"
"A gate that cannot run is a refusal, not a pass.", file=sys.stderr)
return REFUSED_ABSENT
deadline = time.time() + a.wait_minutes * 60
while True:
try:
runs = fetch(a.repo, a.sha, token)
except urllib.error.HTTPError as e:
print("the checks API answered %s: %s" % (e.code, e.reason),
file=sys.stderr)
return REFUSED_ABSENT
code, message = verdict(runs, a.pattern)
if code is not None:
print(message, file=sys.stderr if code else sys.stdout)
return code
if time.time() >= deadline:
print("%s\nstill not finished after %g minutes. Refusing rather "
"than assuming." % (message, a.wait_minutes), file=sys.stderr)
return REFUSED_TIMEOUT
print("%s - waiting" % message)
time.sleep(30)
if __name__ == "__main__":
sys.exit(main())
-149
View File
@@ -1,149 +0,0 @@
"""Extracts the injected script from the driver bundle into
`_juggler/injected.js`.
WHY WE EXTRACT AND DO NOT REWRITE. That JavaScript is the selector engines
(css, xpath, text, role, testid, label), actionability, the ARIA snapshot and
`expect`: thousands of lines of subtle DOM logic that **runs in the page**
and that no Python rewrite could replace, because Python is not in the page.
It is not work to redo: it is cargo to carry over.
⛔ BUT IT IS NOT VIRGIN UPSTREAM. It already carries our own fixes -
`markTargetElements` emptied out, `__pwClock` read via a descriptor,
`Symbol.hasInstance` captured, and since 2026-08-27 listener installs
guarded by `_isUtilityWorld`. Extracting it from a bundle other than THIS
one loses all of them, silently. See `31-client-fork.md` §3.
⛔ AND IT IS NOT YET TRIMMED. The chosen perimeter
(`32-stacco-da-playwright.md` §1) leaves out the ARIA snapshot,
`locatorGenerators`, `highlight` and `consoleApi`, that is **87,468 bytes
out of 311,365**. Here we extract the WHOLE thing: the trim is a step of
its own, and it has to be done on the real module boundaries, which in the
emitted bundle **are not boundaries** (§3.3).
python scripts/gen_injected_source.py (extracts)
python scripts/gen_injected_source.py --check (regenerates and compares)
"""
from __future__ import annotations
import argparse
import os
import pathlib
import sys
ANCHOR = "source4 = '"
def extract(bundle: str) -> str:
"""The value of the `source4` string, de-escaped.
⛔ It is a SINGLE-QUOTE string on ONE physical line of three hundred
thousand characters. It is scanned by hand respecting backslashes: a
greedy regex would grab all the way to the last quote in the FILE, and
a lazy one would stop at the first apostrophe inside a comment.
"""
i = bundle.index(ANCHOR) + len(ANCHOR)
bs = chr(92)
j = i
n = len(bundle)
while j < n:
if bundle[j] == bs:
j += 2
continue
if bundle[j] == "'":
break
j += 1
else:
raise SystemExit("the source4 string never closes: corrupted bundle?")
raw = bundle[i:j]
# De-escape: the string is JavaScript, but the escapes it uses are the
# ones `unicode_escape` understands. We go through latin-1 so as not to
# break the high bytes.
return raw.encode("latin-1", "backslashreplace").decode("unicode_escape")
def main() -> int:
here = pathlib.Path(__file__).resolve().parent.parent
ap = argparse.ArgumentParser()
ap.add_argument("--bundle", default=str(
here / "src" / "invisible_playwright" / "_driver" / "package" / "lib" / "coreBundle.js"))
ap.add_argument("--out", default=str(
here / "src" / "invisible_playwright" / "_juggler" / "injected.js"))
ap.add_argument("--check", action="store_true")
a = ap.parse_args()
# ⛔ A MISSING BUNDLE IS A STATE, NOT A CRASH. Since the Node driver was
# removed there may be no bundle in the tree at all, and the extracted
# `injected.js` is COMMITTED - it stays valid without one. What is gone is
# the ability to RE-DERIVE it, and letting that arrive as
# `FileNotFoundError` from a path deep in an argparse default sends the
# reader looking for a broken script instead of a deleted folder.
named = os.environ.get("INVPW_DRIVER_BUNDLE")
path = pathlib.Path(named) if named else pathlib.Path(a.bundle)
if not path.exists():
print("NOT COMPARABLE: no driver bundle at %s." % path)
print(" `injected.js` is committed and still valid - what is gone is "
"the ability to re-derive it.")
print(" To get one back: git worktree add <dir> <the last commit that "
"carried _driver/>, then")
print(" INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/"
"package/lib/coreBundle.js")
return 2
bundle = path.read_bytes().decode("utf-8", "replace")
source = extract(bundle)
# Proof that what we extracted is REALLY the injected script, not some
# random string that happens to start the same way. A check on what it
# MUST contain costs nothing and stops us from shipping the wrong blob.
EXPECTED = ("InjectedScript", "internal:role", "internal:testid",
"_setupHitTargetInterceptors", "createRoleEngine")
#
# ⛔ `_setupHitTargetInterceptors` IS STILL THE RIGHT FINGERPRINT even
# though the shipped `injected.js` no longer has it. This tuple describes the
# bundle we EXTRACT FROM, which is upstream's and still carries it; our
# removal happens after. Do not delete the name because a grep for removed
# symbols lands here.
#
# What catches a regeneration that quietly brings the mechanism back is
# `tests/test_injected_page_surface.py`: constructing the InjectedScript
# would touch the page's window again, and the gate goes red.
missing = [x for x in EXPECTED if x not in source]
if missing:
raise SystemExit("the extract does not look like the injected script: "
"missing %s" % ", ".join(missing))
# And that it carries OUR fixes: an upstream bundle would lose all of
# them without anything raising an error.
#
# NOTE: the marker below is a LITERAL, not prose. It has to match the
# actual bytes of the comments `injected.js` carries, so it is compared
# exactly and never reworded. It was `MODIFICATO da invisible_playwright`
# until 2026-08-27, when the whole repository moved to English.
if "MODIFIED by invisible_playwright" not in source:
raise SystemExit("the extract does NOT carry invisible_playwright's "
"changes: it is an upstream bundle, not ours")
print("extracted: %d bytes, %d lines" % (len(source.encode("utf-8")),
source.count(chr(10))))
print(" our changes marked: %d"
% source.count("MODIFIED by invisible_playwright"))
out = pathlib.Path(a.out)
new_bytes = source.encode("utf-8")
if a.check:
if not out.is_file():
print("MISSING: %s" % out)
return 1
if out.read_bytes() == new_bytes:
print("INJECTED SCRIPT ALIGNED")
return 0
print("DRIFT: the extract does not match the file in the tree")
return 1
out.parent.mkdir(parents=True, exist_ok=True)
out.write_bytes(new_bytes)
print("wrote %s" % out)
return 0
if __name__ == "__main__":
sys.exit(main())
-466
View File
@@ -1,466 +0,0 @@
"""Generates `_juggler/protocol.py` from Juggler's `Protocol.js`.
WHY IT IS GENERATED AND NOT HAND-WRITTEN. `Protocol.js` is the
machine-readable schema of the protocol, and the browser enforces it in a
CLOSED WORLD: an undeclared field is not ignored, it is REJECTED at
runtime, and the session dies at context creation with a green build. The
measured cost of that class of failure in this project is 97 tests out of
133. A hand-written table next to a file that already holds the truth is a
second source that drifts on its own.
⛔ IT READS THE **SHIPPED** PROTOCOL.JS, NOT THE ONE IN THE TREE. They are
two different files that happen to coincide today: generating from the
tree produces a client for a browser no user runs, and the way it fails is
the closed-world way. The default is therefore a binary, not a source
path.
⛔ AND JUGGLER LIVES IN TWO LAYOUTS: `omni.ja` (Windows) and the loose tree
`./chrome/juggler/` (Linux). Both are tried, and it says which one
answered.
⛔ THIS DOES NOT REPLACE `protocol_drift_check.py`. That gate compares
what a REAL client sends against our declaration, and remains the only
thing that knows how to answer that question. Generating both sides from
the same source does not make drift impossible: it makes it UNOBSERVABLE.
See `docs/firefox-stealth-architecture/32-stacco-da-playwright.md` §3.2.
python scripts/gen_juggler_protocol.py --binary <firefox folder>
python scripts/gen_juggler_protocol.py --check (regenerate and compare)
"""
from __future__ import annotations
import argparse
import pprint
import os
import pathlib
import re
import sys
import zipfile
JAR_MEMBER = "chrome/juggler/content/protocol/Protocol.js"
LOOSE_TREE = "chrome/juggler/content/protocol/Protocol.js"
# The combinators that `Protocol.js` actually uses. The vocabulary
# declared in PrimitiveTypes.js has 11; these 8 are the ones exercised. If
# another one shows up one day, the generator REJECTS instead of guessing.
COMBINATORS = {"String", "Number", "Boolean", "Any", "Enum",
"Nullable", "Optional", "Array"}
# ── reading ──────────────────────────────────────────────────────────────────
def protocol_source(binary: str) -> tuple[str, str]:
"""(label, text) of the SHIPPED Protocol.js. Tries both layouts."""
base = pathlib.Path(binary)
loose = base / LOOSE_TREE
if loose.is_file():
return ("loose tree: %s" % loose,
loose.read_bytes().decode("utf-8", "replace"))
for name in ("omni.ja", os.path.join("browser", "omni.ja")):
jar = base / name
if not jar.is_file():
continue
try:
with zipfile.ZipFile(jar) as z:
if JAR_MEMBER in z.namelist():
return ("%s!%s" % (jar, JAR_MEMBER),
z.read(JAR_MEMBER).decode("utf-8", "replace"))
except zipfile.BadZipFile:
# Firefox may package an optimized jar that zipfile cannot
# read. Not a case to swallow: say which file and why.
raise SystemExit(
"jar %s does not open with zipfile (optimized jar). "
"Extract it with 7z and pass --proto." % jar)
raise SystemExit(
"Protocol.js not found in %s: neither loose tree nor omni.ja"
% binary)
def strip_comments(s: str) -> str:
"""Removes // and /* */ without touching what is inside strings."""
out, i, n = [], 0, len(s)
while i < n:
c = s[i]
if c in ("'", '"', "`"):
j = i + 1
while j < n:
if s[j] == chr(92):
j += 2
continue
if s[j] == c:
break
j += 1
out.append(s[i:j + 1])
i = j + 1
elif s.startswith("//", i):
j = s.find(chr(10), i)
i = n if j < 0 else j
elif s.startswith("/*", i):
j = s.find("*/", i)
i = n if j < 0 else j + 2
else:
out.append(c)
i += 1
return "".join(out)
def block(s: str, start: int) -> str:
"""The balanced block from the first '{' at `start`, skipping strings."""
i = s.index("{", start)
d, j, n = 0, i, len(s)
while j < n:
c = s[j]
if c in ("'", '"', "`"):
k = j + 1
while k < n:
if s[k] == chr(92):
k += 2
continue
if s[k] == c:
break
k += 1
j = k + 1
continue
if c == "{":
d += 1
elif c == "}":
d -= 1
if d == 0:
return s[i:j + 1]
j += 1
raise SystemExit("unbalanced block starting at %d" % start)
def entries(body: str) -> list[tuple[str, str]]:
"""The TOP-level key/value pairs of a { ... } block."""
inner = body[1:-1]
out, i, n = [], 0, len(inner)
while i < n:
m = re.compile(r"\s*'?([A-Za-z_$][\w$]*)'?\s*:\s*").match(inner, i)
if not m:
i += 1
continue
key, i = m.group(1), m.end()
d, j, start = 0, i, i
while j < n:
c = inner[j]
if c in ("'", '"', "`"):
k = j + 1
while k < n:
if inner[k] == chr(92):
k += 2
continue
if inner[k] == c:
break
k += 1
j = k + 1
continue
if c in "{[(":
d += 1
elif c in "}])":
d -= 1
elif c == "," and d == 0:
break
j += 1
out.append((key, inner[start:j].strip()))
i = j + 1
return out
# ── types ────────────────────────────────────────────────────────────────────
def parse_type_expr(expr: str, tables: dict) -> dict:
"""A type expression -> a JSON-serializable structure."""
e = expr.strip()
if e.startswith("{"):
return {"k": "Object",
"fields": {c: parse_type_expr(v, tables)
for c, v in entries(block(e, 0))}}
m = re.match(r"t\.(\w+)\s*\((.*)\)\s*$", e, re.S)
if m:
name, inner = m.group(1), m.group(2)
if name not in COMBINATORS:
raise SystemExit("unexpected combinator: t.%s" % name)
if name == "Enum":
return {"k": "Enum", "values": re.findall(r"'([^']*)'", inner)}
return {"k": name, "of": parse_type_expr(inner, tables)}
m = re.match(r"t\.(\w+)\s*$", e)
if m:
if m.group(1) not in COMBINATORS:
raise SystemExit("unexpected combinator: t.%s" % m.group(1))
return {"k": m.group(1)}
m = re.match(r"(\w+)\.(\w+)\s*$", e)
if m and m.group(1) in tables and m.group(2) in tables[m.group(1)]:
return dict(tables[m.group(1)][m.group(2)], ref="%s.%s" % m.groups())
raise SystemExit("unparseable type expression: %r" % e[:90])
# ── parsing ──────────────────────────────────────────────────────────────────
def parse_type(text: str) -> dict:
s = strip_comments(text)
tables: dict = {}
for m in re.finditer(r"^const (\w+Types) = \{\};", s, re.M):
tables[m.group(1)] = {}
for name in list(tables):
for m in re.finditer(r"^%s\.(\w+) = " % re.escape(name), s, re.M):
tables[name][m.group(1)] = parse_type_expr(
block(s, m.end() - 1), tables)
domains: dict = {}
for m in re.finditer(r"^const ([A-Z]\w*) = \{", s, re.M):
domain = m.group(1)
body = block(s, m.end() - 1)
if "methods:" not in body and "events:" not in body:
continue
d = {"commands": {}, "events": {}}
for key, value in entries(body):
if key not in ("methods", "events"):
continue
where = "commands" if key == "methods" else "events"
for name, body2 in entries(value):
if where == "events":
d["events"][name] = parse_type_expr(body2, tables)
else:
parts = dict(entries(body2))
d["commands"][name] = {
"params": (
parse_type_expr(parts["params"], tables)
if "params" in parts else None),
"returns": (
parse_type_expr(parts["returns"], tables)
if "returns" in parts else None),
}
domains[domain] = d
return domains
# ── emission ─────────────────────────────────────────────────────────────────
HEADER = '''"""GENERATED by scripts/gen_juggler_protocol.py.
Do not edit by hand.
Source: %s
Commands: %d Events: %d
The browser enforces this schema in a CLOSED WORLD: an undeclared field is
REJECTED at runtime, not ignored. It therefore serves to verify what WE
SEND before it goes out, not to document.
⛔ Does not replace `protocol_drift_check.py` in the source repo: that
gate asks what a REAL client sends, and that is a question this file
cannot ask, because it is generated from the same source it should be
checking.
"""
from __future__ import annotations
'''
def stable_source(source: str) -> str:
"""The source line in the generated file must not contain an absolute
path: it would change from one machine to another and every
regeneration would look like a change. And Windows backslashes inside
a docstring are ESCAPES: `C:\\Users` raises `truncated \\UXXXXXXXX
escape` and the generated file does not import. It happened on
2026-08-27, and the way it was noticed was that the file did not
import, not that the generator failed."""
f = source.replace(chr(92), "/")
return (f.split("/")[-1] if "!" not in f
else "omni.ja!" + f.split("!", 1)[1])
def render(domains: dict, source: str) -> str:
source = stable_source(source)
n_cmd = sum(len(d["commands"]) for d in domains.values())
n_ev = sum(len(d["events"]) for d in domains.values())
commands, events = {}, {}
for domain, d in sorted(domains.items()):
for name, spec in sorted(d["commands"].items()):
commands["%s.%s" % (domain, name)] = spec
for name, spec in sorted(d["events"].items()):
events["%s.%s" % (domain, name)] = spec
# ⛔ pprint and not json.dumps: json emits `null`/`true`/`false`,
# which do not exist in Python, and the generated file does not
# IMPORT. The generator, though, still exits 0, so the failure only
# shows up when importing - which is why this generator's test
# imports the file instead of looking at its bytes.
body = HEADER % (source, n_cmd, n_ev)
body += "DOMAINS = %s\n\n" % pprint.pformat(sorted(domains), width=78)
body += "COMMANDS = %s\n\n" % pprint.pformat(commands, width=88,
sort_dicts=True)
body += "EVENTS = %s\n" % pprint.pformat(events, width=88,
sort_dicts=True)
return body
def _selftest(text: str) -> int:
"""Known-bad mutations on Protocol.js, without a browser and without a
network.
The question: if the SHIPPED Protocol.js changes, does `--check`
notice? The text is mutated in memory, regenerated, and compared
against the body produced from the intact text. A mutation that does
not move the body is a hole.
"""
base = render(parse_type(text), "base")
def body(t):
i = t.find("DOMAINS = ")
return t[i:] if i >= 0 else t
MUTATIONS = [
("a command REMOVED",
lambda s: s.replace(
" 'collectGarbage': {\n params: {},\n },\n",
"", 1)),
("a command ADDED",
lambda s: s.replace(
" 'collectGarbage': {",
" 'invented': {\n params: {},\n },\n"
" 'collectGarbage': {", 1)),
("a field removed from a command",
lambda s: s.replace(
" attachToDefaultContext: t.Boolean,\n", "", 1)),
("a type changed: String -> Number",
lambda s: s.replace(
" url: t.String,", " url: t.Number,", 1)),
("an Optional becomes required",
lambda s: s.replace(
" browserContextId: t.Optional(t.String),",
" browserContextId: t.String,", 1)),
("a value removed from an Enum",
lambda s: s.replace(
"t.Enum(['reduce', 'no-preference'])",
"t.Enum(['no-preference'])", 1)),
("an event RENAMED",
lambda s: s.replace(
" 'ready': {", " 'renamedReady': {", 1)),
("an event REMOVED",
lambda s: s.replace(
" 'crashed': {" + chr(10) + " }," + chr(10), "", 1)),
]
print("known-bad mutations on Protocol.js:")
survived = 0
for description, mutate in MUTATIONS:
mutated = mutate(text)
if mutated == text:
print(" INERT MUTATION %-42s (did not touch the text)"
% description)
survived += 1
continue
try:
different = body(render(parse_type(mutated), "base")) != body(base)
except SystemExit as e:
different, description = (
True, description + " -> the generator REJECTS: %s" % e)
if different:
print(" killed %s" % description[:70])
else:
print(" SURVIVED %s" % description)
survived += 1
print()
print("and the cases that must NOT trigger:")
false_positives = 0
if body(render(parse_type(text), "another source")) == body(base):
print(" PASSES same text, different source in the header")
else:
print(" WRONGLY REJECTED same text with another source")
false_positives += 1
# An extra space inside an empty block is a reformat, not a drift: if
# the gate tripped here it would be red on every touch-up of the
# source, and a gate that is always red teaches people to route
# around it.
reformatted = text.replace(" params: {},", " params: { },", 1)
if reformatted == text:
print(" WRONGLY REJECTED no empty block to reformat: "
"case not exercised")
false_positives += 1
elif body(render(parse_type(reformatted), "base")) == body(base):
print(" PASSES one extra space is not a drift")
else:
print(" WRONGLY REJECTED one extra space")
false_positives += 1
# And a new COMMENT is not a drift: the parser strips comments.
commented = text.replace(
"const Heap = {", "// a note\nconst Heap = {", 1)
if (commented != text
and body(render(parse_type(commented), "base")) == body(base)):
print(" PASSES a new comment is not a drift")
else:
print(" WRONGLY REJECTED a new comment")
false_positives += 1
print()
print("survived: %d of %d, wrongly rejected: %d"
% (survived, len(MUTATIONS), false_positives))
return 1 if (survived or false_positives) else 0
def main() -> int:
here = pathlib.Path(__file__).resolve().parent.parent
ap = argparse.ArgumentParser()
ap.add_argument("--binary", help="folder of the SHIPPED firefox")
ap.add_argument("--proto",
help="an already-extracted Protocol.js "
"(for a jar that will not open)")
ap.add_argument("--out", default=str(
here / "src" / "invisible_playwright" / "_juggler" / "protocol.py"))
ap.add_argument("--check", action="store_true",
help="regenerate and compare, without writing")
ap.add_argument("--selftest", action="store_true",
help="known-bad mutations on Protocol.js, "
"without a browser")
a = ap.parse_args()
if a.proto:
source, text = (
a.proto,
pathlib.Path(a.proto).read_bytes().decode("utf-8", "replace"))
elif a.binary:
source, text = protocol_source(a.binary)
else:
ap.error("need --binary (the shipped firefox) or --proto")
if a.selftest:
return _selftest(text)
domains = parse_type(text)
n_cmd = sum(len(d["commands"]) for d in domains.values())
n_ev = sum(len(d["events"]) for d in domains.values())
new = render(domains, source)
print("source: %s" % source)
for domain in sorted(domains):
print(" %-10s %3d commands %3d events"
% (domain, len(domains[domain]["commands"]),
len(domains[domain]["events"])))
print(" %-10s %3d commands %3d events" % ("TOTAL", n_cmd, n_ev))
out = pathlib.Path(a.out)
if a.check:
if not out.is_file():
print("MISSING: %s" % out)
return 1
old = out.read_bytes().decode("utf-8")
# compares the BODY, not the header: the source line carries a
# path that changes from one machine to another.
def body(t):
i = t.find("DOMAINS = ")
return t[i:] if i >= 0 else t
if body(old) == body(new):
print("PROTOCOL ALIGNED")
return 0
print("DRIFT: the generated file does not match the shipped "
"Protocol.js")
return 1
out.parent.mkdir(parents=True, exist_ok=True)
out.write_bytes(new.encode("utf-8"))
print("wrote %s (%d bytes)" % (out, len(new)))
return 0
if __name__ == "__main__":
sys.exit(main())
-317
View File
@@ -1,317 +0,0 @@
"""Extracts the US keyboard layout from the driver bundle into `_juggler/keylayout.py`.
⛔ NEVER HAND-EDIT THIS. `Page.dispatchKeyEvent` expects `key`, `code`,
`keyCode` and `location` together, and there are ~230 entries: a
hand-copied table has two ways to go wrong that no test catches. The
first is a wrong `keyCode`, which the page reads back in
`event.keyCode` without the action failing. The second, worse one, is
an INCOMPLETE table: a missing key raises no error, it produces
`keyCode: 0` for a key that on every real Firefox has a number, and
that is a tell that lives in a field nobody looks at.
It has the same shape as `gen_juggler_protocol.py` and
`gen_injected_source.py`: a single source, generated, never two
numbers for the same thing (rule 16).
python scripts/gen_key_layout.py # regenerates _juggler/keylayout.py
python scripts/gen_key_layout.py --check # 1 if the tree file is stale
python scripts/gen_key_layout.py --selftest # 6 mutations, plus 2 that must NOT trigger
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import re
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
BUNDLE = ROOT / "src/invisible_playwright/_driver/package/lib/coreBundle.js"
OUTPUT = ROOT / "src/invisible_playwright/_juggler/keylayout.py"
#: The literal starts here. ⛔ It anchors on the variable NAME, not on
#: a table entry: anchoring on `"KeyA"` would tie the extraction to a
#: key that could move to a different line someday.
START = re.compile(r"USKeyboardLayout\s*=\s*\{")
#: The escapes the bundle actually uses. Whatever is not here is
#: passed through as-is, which is the right behavior for `\'` and
#: `\"`: the escape disappears and the character remains.
#:
#: ⛔ SPELLED WITH `chr()`, and not because it reads better. A literal that
#: EVALUATES to a control character is the same defect class as a Windows path
#: written in a non-raw string: the bytes on disk look fine and the value the
#: program uses is a formfeed. `test_marker_vocabulary.py` reads the resolved
#: value with `ast` precisely to catch that, and it caught this table -
#: correctly, because nothing here distinguishes a deliberate 0x08 from an
#: accidental one except saying so.
ESCAPES = {"n": chr(10), "r": chr(13), "t": chr(9), "b": chr(8),
"f": chr(12), "0": chr(0), chr(92): chr(92)}
class ExtractionFailed(RuntimeError):
pass
def _literal(text: str) -> str:
"""The balanced `{...}` body that follows `USKeyboardLayout =`.
⛔ Counts braces instead of looking for the first `};`: the value
contains strings with braces inside (`"key": "{"` really exists,
it is BracketLeft with shift) and a naive search would cut the
table in half with no error.
"""
m = START.search(text)
if not m:
raise ExtractionFailed(
"`USKeyboardLayout = {` does not appear in the bundle. If "
"the bundler renamed the variable, the anchor should be "
"changed here, not worked around.")
i = m.end() - 1
depth, j, in_str, quote, escape = 0, i, False, "", False
while j < len(text):
c = text[j]
if in_str:
if escape:
escape = False
elif c == chr(92):
escape = True
elif c == quote:
in_str = False
elif c in "\"'":
in_str, quote = True, c
elif c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
return text[i:j + 1]
j += 1
raise ExtractionFailed("unbalanced braces starting at USKeyboardLayout")
def _to_json(literal: str) -> str:
"""From JS literal to JSON, in a single pass that SCANS.
Three things a regex cannot do well, and all three show up in the
real bundle:
1. ⛔ **Single quotes.** `"Quote": { "shiftKey": '"' }` is valid JS
and JSON does not accept it. They must be rewritten as JSON
strings, not substituted character by character: the content
can contain a double quote, which is exactly this case.
2. ⛔ **Comments.** Stripping them with `//[^\\n]*` also deletes a
`//` INSIDE a string. It does not happen here, but the failure
mode is silent - it shortens a value instead of raising an
error - and it is not worth keeping.
3. Trailing commas before a brace, which JS accepts and JSON does
not.
"""
out, i = [], 0
while i < len(literal):
c = literal[i]
if c == "/" and literal[i + 1:i + 2] == "/":
i = literal.find("\n", i)
if i < 0:
break
continue
if c in "\"'":
quote, j, inside = c, i + 1, []
while j < len(literal):
d = literal[j]
if d == chr(92):
# ⛔ It gets DECODED here instead of re-quoting the
# raw text. Re-quoting it would double an already
# escaped `\"`, and the character the bundle
# writes with a single quote is exactly the double
# quote.
seg = literal[j + 1:j + 2]
if seg == "u":
inside.append(chr(int(literal[j + 2:j + 6], 16)))
j += 6
else:
inside.append(ESCAPES.get(seg, seg))
j += 2
continue
if d == quote:
break
inside.append(d)
j += 1
out.append(json.dumps("".join(inside)))
i = j + 1
continue
out.append(c)
i += 1
return re.sub(r",(\s*[}\]])", r"\1", "".join(out))
def extract(text: str) -> dict:
data = json.loads(_to_json(_literal(text)))
if not isinstance(data, dict) or not data:
raise ExtractionFailed("the table is empty")
# ⛔ The SANITY check is here and not in the caller: a table that
# extracts but does not contain the keys every layout has is an
# extraction that got lucky with the braces.
missing = [k for k in ("KeyA", "Enter", "Backspace", "Digit0", "Space",
"ShiftLeft", "ArrowLeft", "Tab", "Escape")
if k not in data]
if missing:
raise ExtractionFailed(
"extracted but incomplete: missing %s. It is not the US "
"layout." % ", ".join(missing))
return data
def render(data: dict) -> str:
body = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
body = body.replace("true", "True").replace("false", "False") \
.replace(": null", ": None")
# ⛔ A control character in the DATA becomes `chr(n)`, never an escape.
# `NumpadDecimal` really carries a NUL as its `key` upstream, and written
# as an escape the generated file holds a literal that EVALUATES to 0x00 -
# the defect class `test_marker_vocabulary.py` exists to catch, and it
# cannot tell a deliberate NUL from a mangled Windows path. The pattern is
# built from `chr(92)` so this source has no backslash of its own.
body = re.sub(chr(92) + r'"' + chr(92) + chr(92) + r'u000([0-9a-fA-F])"',
lambda m: "chr(%d)" % int(m.group(1), 16), body)
return (
'"""The US keyboard layout, EXTRACTED from the driver bundle.\n'
"\n"
"GENERATED by `python scripts/gen_key_layout.py`. Do not\n"
"hand-edit: the `--check` gate rejects a tree where this file\n"
"and the bundle no longer agree, and a hand-fixed entry would\n"
"be undone on the next regenerate.\n"
"\n"
"Each entry is indexed by `code` (the PHYSICAL key) and\n"
"carries `keyCode`, the unshifted `key` and, where it exists,\n"
"`shiftKey`. That is what `Page.dispatchKeyEvent` expects:\n"
"four fields together, and a wrong one does not fail the\n"
"action - it just lies in `event.keyCode`.\n"
'"""\n'
"from __future__ import annotations\n"
"\n"
"#: %d entries, indexed by `code`.\n" % len(data) +
"LAYOUT = " + body + "\n"
"\n"
"#: unshifted `key` -> `code`. Used for `press(\"a\")` and for\n"
"#: typing: a character is looked up here first, then among\n"
"#: the shifted ones.\n"
"BY_KEY = {v[\"key\"]: k for k, v in LAYOUT.items() if \"key\" in v}\n"
"\n"
"#: `shiftKey` -> `code`. `A`, `!`, `{` live here and NOT in\n"
"#: BY_KEY.\n"
"BY_SHIFTED_KEY = {v[\"shiftKey\"]: k for k, v in LAYOUT.items()\n"
" if \"shiftKey\" in v}\n")
# ── the selftest ──────────────────────────────────────────────────────────
def selftest() -> int:
good = ('var x = 1;\n'
'USKeyboardLayout = {\n'
' // first line\n'
' "KeyA": { "keyCode": 65, "shiftKey": "A", "key": "a" },\n'
' "Digit0": { "keyCode": 48, "shiftKey": ")", "key": "0" },\n'
' "BracketLeft": { "keyCode": 219, "shiftKey": "{", "key": "[" },\n'
' "Enter": { "keyCode": 13, "key": "Enter", "text": "\\r" },\n'
' "Backspace": { "keyCode": 8, "key": "Backspace" },\n'
' "Space": { "keyCode": 32, "key": " " },\n'
' "ShiftLeft": { "keyCode": 16, "key": "Shift", "location": 1 },\n'
' "ArrowLeft": { "keyCode": 37, "key": "ArrowLeft" },\n'
' "Tab": { "keyCode": 9, "key": "Tab" },\n'
' "Escape": { "keyCode": 27, "key": "Escape" },\n'
'};\nvar after = 2;\n')
def try_case(name, text, should_raise=True):
try:
d = extract(text)
except Exception as e:
if should_raise:
print(" killed: %s (%s)" % (name, str(e).splitlines()[0][:60]))
return 0
print(" FALSE POSITIVE: %s -> %s" % (name, e))
return 1
if should_raise:
print(" SURVIVED: %s -> extracted %d entries" % (name, len(d)))
return 1
print(" silenced: %s (%d entries)" % (name, len(d)))
return 0
print("--- mutations that MUST trigger ---")
bad = 0
bad += try_case("the variable renamed by the bundler",
good.replace("USKeyboardLayout", "UsKbLayout"))
bad += try_case("the table truncated: keys every layout has are missing",
'USKeyboardLayout = {\n "KeyA": { "keyCode": 65, "key": "a" },\n};')
bad += try_case("unbalanced braces",
good.replace('"Escape": { "keyCode": 27, "key": "Escape" },\n};',
'"Escape": { "keyCode": 27, "key": "Escape" },\n'))
bad += try_case("the empty table",
good[:good.index("{", good.index("USKeyboardLayout")) + 1] + "};")
# ⛔ This is the mutation that justified counting braces: with a
# search for the first `};` the table gets cut at BracketLeft,
# which contains a brace INSIDE a string, and the extraction
# half-succeeds.
truncated = good.replace('"Enter": { "keyCode": 13, "key": "Enter", "text": "\\r" },\n', "")
bad += try_case("Enter removed: incomplete but syntactically valid", truncated)
bad += try_case("the literal replaced by an array",
good.replace("USKeyboardLayout = {", "USKeyboardLayout = ["))
print("--- cases that must NOT trigger ---")
bad += try_case("the good bundle", good, should_raise=False)
bad += try_case("a brace inside a string does not close the table",
good.replace('"shiftKey": "{"', '"shiftKey": "}"'),
should_raise=False)
print()
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--check", action="store_true")
p.add_argument("--selftest", action="store_true")
a = p.parse_args()
if a.selftest:
return selftest()
bundle = BUNDLE
named = os.environ.get("INVPW_DRIVER_BUNDLE")
if named:
bundle = pathlib.Path(named)
if not bundle.exists():
# ⛔ TWO IS NOT ENOUGH HERE: "cannot compare" and "stale" are
# different answers, and collapsing them makes a missing bundle look
# like a broken tree. The generated file is COMMITTED and stays valid
# without a bundle; what is lost is the ability to re-derive it, and
# that is what this says.
print("NOT COMPARABLE: no driver bundle at %s." % bundle)
print(" The generated file is committed and still valid - what is "
"gone is the ability to re-derive it.")
print(" To get one back: git worktree add <dir> <the last commit "
"that carried _driver/>, then")
print(" INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/"
"package/lib/coreBundle.js")
return 2
try:
data = extract(bundle.read_text(encoding="utf-8", errors="replace"))
except ExtractionFailed as failure:
print("extraction failed: %s" % failure)
return 2
text = render(data)
if a.check:
current = OUTPUT.read_bytes().decode("utf-8") if OUTPUT.exists() else ""
if current != text:
print("keylayout.py does not match the bundle (%d entries "
"extracted). `python scripts/gen_key_layout.py`" % len(data))
return 1
print("keylayout.py matches: %d entries" % len(data))
return 0
# ⛔ `write_bytes`: `write_text` on Windows would translate every newline.
OUTPUT.write_bytes(text.encode("utf-8"))
print("wrote %s: %d entries" % (OUTPUT.name, len(data)))
return 0
if __name__ == "__main__":
sys.exit(main())
+9 -4
View File
@@ -37,6 +37,13 @@ import urllib.error
# Conventional-commit prefixes that never belong in user-facing release notes.
_SKIP = re.compile(r"^(docs|chore|ci|test|style|build)(\(|:)", re.I)
#: Where the install commands live. ⛔ NOT RESTATED HERE: the body used to carry
#: its own `pip install invisible-playwright`, a second copy of the README's
#: install block that nothing kept in step with it. A command written in two
#: places is two commands the day one of them changes; the release points at the
#: one the README keeps.
INSTALL_DOC = "https://github.com/feder-cr/invisible_playwright#install"
def _api(url: str, token: str | None) -> dict:
headers = {"Accept": "application/vnd.github+json",
@@ -102,12 +109,10 @@ def build_body(tag: str, current_sha: str, bullets: list[str],
parts += [f"- {b}" for b in bullets]
parts.append("")
parts += [
"Builds: Linux x86_64, Linux arm64, Windows x86_64.",
"Builds: Linux x86_64, Windows x86_64.",
"",
"Most people won't grab these by hand. The wrapper fetches the right one for "
"your platform on first run:",
"",
" pip install invisible-playwright",
"your platform on first run; how to install it is in " + INSTALL_DOC + ".",
"",
"If you do download manually, `checksums.txt` has the SHA256s.",
]
+37
View File
@@ -0,0 +1,37 @@
{
"identity": [
{"keys": ["surface.screen.*", "surface.window.innerWidth", "surface.window.innerHeight",
"surface.window.outerWidth", "surface.window.outerHeight", "surface.window.screen*",
"surface.window.mozInnerScreen*", "surface.visualViewport.width", "surface.visualViewport.height",
"surface.computedStyle.body.width", "surface.computedStyle.body.inline-size",
"surface.computedStyle.body.perspective-origin", "surface.computedStyle.body.transform-origin"],
"why": "the declared screen and window; the body is as wide as the window"},
{"keys": ["state.*.innerWidth", "state.*.innerHeight", "state.*.outerWidth", "state.*.outerHeight",
"state.*.screenX", "state.*.screenY", "state.*.screen.*", "state.*.mozInnerScreen*", "state.*.events.*"],
"why": "the declared screen and window in each driven state (ci_host_gate.py INVARIANTS hold their relations); an event's screen - client is where the window puts the viewport"},
{"keys": ["surface.navigator.hardwareConcurrency", "surface.worker.hc"],
"why": "the declared core count"},
{"keys": ["surface.voices"],
"why": "the declared speech voices"},
{"keys": ["surface.webgl*.unmasked", "surface.webgl*.parameters.RENDERER",
"surface.webgl*.extension_parameters.WEBGL_debug_renderer_info.*",
"surface.webgl*.parameters.MAX_*", "surface.webgl*.extension_parameters.*.MAX_*",
"surface.webgpu.adapters.*"],
"why": "the declared GPU: its name and its limits (ANGLE gives NVIDIA one vertex uniform vector less)"}
],
"noise": [],
"network": [],
"measurement": [
{"keys": ["surface.document.hasFocus"],
"why": "retail was measured on a hidden desktop, where its window never has focus"}
],
"known_defects": [
{"keys": ["blend.*", "text.canvas.*", "text.char.*", "text.emoji.*", "text.fallback.*",
"text.pixelscan.*", "text.svg.*", "text.metrics.*.width", "text.metrics.*.actualBoundingBoxLeft",
"text.metrics.*.actualBoundingBoxRight", "text.fallbackwidth.*.serif",
"text.fallbackwidth.*.monospace"],
"why": "phase 4: text from idwr (DWrite 26100) on every OS; today Windows asks the host's DWrite and Linux FreeType. Only the rasterised glyphs, their advances and ink extents and the serif/monospace fallback widths differ (firefox-59 dumps): text.adjust, text.fonts, text.rect, text.units and the vertical metrics are held"},
{"keys": ["control.webgl1", "control.webgl2"], "legs": ["linux-x86_64", "linux-x86_64-debian12"],
"why": "WebGL draws through the host's driver (llvmpipe here, ANGLE on Windows); a host-independent rasterizer is its own project"}
]
}
+356
View File
@@ -0,0 +1,356 @@
<!doctype html>
<meta charset=utf-8>
<title>host-gate</title>
<body>
<script>
// host-gate/1: everything a page can read that the theory says is f(identity, Firefox code).
// TEXT (text.*), CONTROL (control.*), BLEND (blend.*), SURFACE (surface.*): whole APIs, not chosen fields.
// noise.*: only what varies between two launches of the same official build.
// diag.*: information for the job log (why a host answers what it does); the gate never compares it.
// Must be served from a secure context (http://127.0.0.1 or https) for WebGPU and media APIs.
(async () => {
const G = {format: 'host-gate/1', meta: {devicePixelRatio: window.devicePixelRatio, userAgent: navigator.userAgent}, items: {}, noise: {}};
const put = (k, v) => { G.items[k] = v; };
const noise = (k, v) => { G.noise[k] = v; };
const errs = e => 'ERR ' + ((e && e.name) || '') + ': ' + ((e && e.message) || String(e));
const safe = async (k, f) => { try { put(k, await f()); } catch (e) { put(k, errs(e)); } };
const b64 = u8 => { let s = ''; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); return btoa(s); };
const alphaOf = (g, w, h) => { const d = g.getImageData(0, 0, w, h).data, a = new Uint8Array(w * h); for (let i = 0; i < a.length; i++) a[i] = d[i * 4 + 3]; return a; };
const img = (g, w, h, rgba) => ({w, h, enc: rgba ? 'rgba8' : 'alpha8', data: rgba ? b64(new Uint8Array(g.getImageData(0, 0, w, h).data.buffer)) : b64(alphaOf(g, w, h))});
const canvas = (w, h, fn) => { const c = document.createElement('canvas'); c.width = w; c.height = h; const g = c.getContext('2d'); fn(g, c); return [g, c]; };
// a plain, comparable copy of any object: own + inherited enumerable data, functions as "function"
const plain = (o, depth = 2) => {
if (o === null || o === undefined) return o;
const t = typeof o;
if (t === 'number' || t === 'string' || t === 'boolean') return o;
if (t === 'function') return 'function';
if (t === 'bigint') return String(o);
if (depth < 0) return '…';
if (Array.isArray(o) || ArrayBuffer.isView(o)) return Array.from(o, v => plain(v, depth - 1));
const out = {}; for (const k in o) { try { out[k] = plain(o[k], depth - 1); } catch (e) { out[k] = errs(e); } }
return out;
};
const names = o => { try { return Object.getOwnPropertyNames(o).sort(); } catch (e) { return errs(e); } };
// ================================================================= TEXT
const PIX = "\u{1F6CD}1>'`amlρiюदे來˦\u{25578}に◌\u{2003E}ԩԨ";
const FONTS = ['Segoe UI', 'Arial', 'Times New Roman', 'Calibri', 'Consolas', 'Microsoft New Tai Lue', 'Myanmar Text', 'Microsoft PhagsPa',
'Segoe UI Emoji', 'Segoe UI Symbol', 'sans-serif', 'serif', 'monospace', 'system-ui'];
const PPEM = [4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 20, 32];
const TEXTS = {H: 'H', o: 'o', word: 'Hamburgefonstiv', digits: '0123456789', pixelscan: PIX};
const fam = f => /^(sans-serif|serif|monospace|system-ui)$/.test(f) ? f : `"${f}"`;
const drawText = (font, px, s, rgba) => {
const p = document.createElement('canvas').getContext('2d'); p.font = `${px}px ${font}`;
const w = Math.ceil(p.measureText(s).width) + 8, h = Math.ceil(px * 2) + 4;
const [g] = canvas(w, h, g => { g.fillStyle = 'black'; g.font = `${px}px ${font}`; g.fillText(s, 4, Math.ceil(px) + 2); });
return img(g, w, h, rgba);
};
const TM = ['width', 'actualBoundingBoxLeft', 'actualBoundingBoxRight', 'actualBoundingBoxAscent', 'actualBoundingBoxDescent',
'fontBoundingBoxAscent', 'fontBoundingBoxDescent', 'emHeightAscent', 'emHeightDescent', 'hangingBaseline', 'alphabeticBaseline', 'ideographicBaseline'];
const metrics = (font, px, s) => { const g = document.createElement('canvas').getContext('2d'); g.font = `${px}px ${font}`; const m = g.measureText(s);
return Object.fromEntries(TM.map(k => [k, m[k]])); };
for (const f of FONTS) { const F = fam(f);
for (const px of PPEM) for (const [t, s] of Object.entries(TEXTS)) { put(`text.canvas.${f}.${px}.${t}`, drawText(F, px, s)); put(`text.metrics.${f}.${px}.${t}`, metrics(F, px, s)); }
for (const px of [4, 8, 16]) [...PIX].forEach((ch, i) => put(`text.char.${f}.${px}.${i}`, drawText(F, px, ch)));
}
const EMOJI = {shop: '\u{1F6CD}', grin: '\u{1F600}', flag: '\u{1F1EE}\u{1F1F9}', family: '\u{1F468}‍\u{1F469}‍\u{1F467}', heart: '❤️', skin: '\u{1F44D}\u{1F3FD}'};
for (const f of ['Segoe UI Emoji', 'sans-serif']) for (const px of [8, 16, 32]) for (const [n, s] of Object.entries(EMOJI)) put(`text.emoji.${f}.${px}.${n}`, drawText(fam(f), px, s, true));
const PIXFONTS = ['Arial', 'Calibri', 'Cambria Math', 'Cambria', 'Candara', 'Comic Sans MS', 'Consolas', 'Constantia', 'Corbel', 'Courier New', 'Ebrima', 'Franklin Gothic', 'Gabriola', 'Georgia', 'Impact', 'Lucida Console', 'Lucida Sans Unicode', 'MS Gothic', 'MS PGothic', 'MV Boli', 'Malgun Gothic', 'Marlett', 'Microsoft Himalaya', 'Microsoft JhengHei', 'Microsoft New Tai Lue', 'Microsoft PhagsPa', 'Microsoft Sans Serif', 'Microsoft YaHei', 'Microsoft Yi Baiti', 'MingLiU-ExtB', 'Mongolian Baiti', 'PMingLiU-ExtB', 'Palatino Linotype', 'Segoe Print', 'Segoe Script', 'Segoe UI Symbol', 'Segoe UI', 'SimSun', 'SimSun-ExtB', 'Sylfaen', 'Trebuchet MS', 'Verdana', 'Webdings', 'Gadugi', 'Javanese Text', 'Microsoft JhengHei UI', 'Myanmar Text', 'Sitka Small', 'Yu Gothic'];
{ const seen = new Set();
for (const f of PIXFONTS) { const [g] = canvas(80, 10, g => { g.fillStyle = 'red'; g.font = 'normal 4px ' + f; g.fillText(PIX, 5, 5); });
const a = img(g, 80, 10); put(`text.pixelscan.${f}`, a); seen.add(a.data); }
put('text.pixelscan.distinct', seen.size); }
{ const box = document.createElement('div'); box.style.cssText = 'position:absolute;left:0;top:0;white-space:nowrap'; document.body.appendChild(box);
const span = (css, s) => { const e = document.createElement('span'); e.style.cssText = css; e.textContent = s; box.appendChild(e); const r = e.getBoundingClientRect();
const out = [r.x, r.y, r.width, r.height, e.offsetWidth, e.offsetHeight]; e.remove(); return out; };
for (const f of FONTS) { const F = fam(f).replace(/"/g, "'");
for (const [t, s] of Object.entries(TEXTS)) put(`text.rect.${f}.${t}`, span(`font:16px ${F}`, s));
const u = {}; for (const unit of ['ex', 'cap', 'ch', 'ic', 'lh', 'rex', 'rcap', 'rch', 'ric', 'rlh']) { const e = document.createElement('div'); e.style.cssText = `font:16px ${F};width:1${unit};height:1px`;
box.appendChild(e); u[unit] = e.getBoundingClientRect().width; e.remove(); } put(`text.units.${f}`, u);
for (const mode of ['0.5', 'ex-height 0.5', 'cap-height 0.7', 'ch-width 0.6', 'ic-width 1', 'from-font'])
put(`text.adjust.${f}.${mode}`, span(`font:16px ${F};font-size-adjust:${mode}`, TEXTS.word));
}
box.remove(); }
put('text.fonts.check', Object.fromEntries([...new Set([...FONTS, ...PIXFONTS])].map(f => [f, document.fonts.check(`16px ${fam(f)}`)])));
put('text.fonts.size', document.fonts.size);
const svgDraw = (attr, family, s) => new Promise(res => {
const src = `<svg xmlns="http://www.w3.org/2000/svg" width="240" height="40"><text x="4" y="26" font-family="${family}" font-size="18" ${attr}>${s}</text></svg>`;
const im = new Image(); im.onload = () => { const [g] = canvas(240, 40, g => g.drawImage(im, 0, 0)); try { res(img(g, 240, 40)); } catch (e) { res(errs(e)); } };
im.onerror = () => res('ERR load'); im.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(src); });
for (const f of ['Segoe UI', 'Arial', 'Times New Roman', 'serif'])
for (const [n, a] of Object.entries({plain: '', underline: 'text-decoration="underline"', linethrough: 'text-decoration="line-through"', overline: 'text-decoration="overline"'}))
put(`text.svg.${f}.${n}`, await svgDraw(a, f, TEXTS.word));
put('text.svg.emoji', await svgDraw('', 'Segoe UI Emoji', EMOJI.grin + EMOJI.flag));
const SCRIPTS = {latin: 'Hamburg', greek: 'αβγδε', cyrillic: 'жизнь', arabic: 'مرحبا', hebrew: 'שלום', devanagari: 'नमस्ते', bengali: 'বাংলা',
thai: 'สวัสดี', lao: 'ສະບາຍ', khmer: 'សួស្តី', myanmar: 'မင်္ဂလာ', sinhala: 'සිංහල', tamil: 'தமிழ்', ethiopic: 'ሰላም', tibetan: 'བོད་ཡིག',
georgian: 'ქართული', armenian: 'Հայերեն', cjk: '漢字中文', cjkextb: '\u{20000}\u{25578}', hiragana: 'ひらがな', hangul: '한국어', mongolian: 'ᠮᠣᠩᠭᠣᠯ',
cherokee: 'ᏣᎳᎩ', math: '∑∫√∞≠', arrows: '←↑→↓↔', box: '┌─┐│└┘', pua: '', symbols: '☀☂☃★♠'};
for (const g of ['sans-serif', 'serif', 'monospace']) for (const [n, s] of Object.entries(SCRIPTS)) {
put(`text.fallback.${n}.${g}`, drawText(g, 16, s)); put(`text.fallbackwidth.${n}.${g}`, metrics(g, 16, s).width); }
// ================================================================= CONTROL (no text)
const ctl = (k, w, h, fn) => { const [g] = canvas(w, h, fn); put(`control.${k}`, img(g, w, h, true)); };
ctl('rects', 64, 64, g => { g.fillStyle = '#c33'; g.fillRect(3.5, 3.5, 30, 20); g.strokeStyle = 'rgba(0,80,200,.6)'; g.lineWidth = 2.5; g.strokeRect(10.25, 15.75, 40, 30); });
ctl('arcs', 64, 64, g => { g.beginPath(); g.arc(32, 32, 20.3, 0, Math.PI * 1.7); g.lineWidth = 3; g.strokeStyle = '#080'; g.stroke();
g.beginPath(); g.ellipse(30, 30, 12, 7, 0.6, 0, 2 * Math.PI); g.fillStyle = 'rgba(200,100,0,.5)'; g.fill(); });
ctl('beziers', 64, 64, g => { g.beginPath(); g.moveTo(2, 60); g.bezierCurveTo(10, 0, 50, 70, 62, 4); g.quadraticCurveTo(40, 40, 5, 30);
g.lineWidth = 1.7; g.lineJoin = 'round'; g.lineCap = 'round'; g.setLineDash([4, 3]); g.stroke(); });
ctl('linear', 64, 32, g => { const l = g.createLinearGradient(0, 0, 64, 32); l.addColorStop(0, '#f00'); l.addColorStop(.5, 'rgba(0,255,0,.5)'); l.addColorStop(1, '#00f'); g.fillStyle = l; g.fillRect(0, 0, 64, 32); });
ctl('radial', 64, 64, g => { const r = g.createRadialGradient(20, 20, 2, 32, 32, 30); r.addColorStop(0, '#fff'); r.addColorStop(1, '#048'); g.fillStyle = r; g.fillRect(0, 0, 64, 64); });
ctl('conic', 64, 64, g => { const c = g.createConicGradient(0.3, 32, 32); c.addColorStop(0, 'red'); c.addColorStop(.5, 'yellow'); c.addColorStop(1, 'red'); g.fillStyle = c; g.fillRect(0, 0, 64, 64); });
ctl('pattern', 64, 64, g => { const [, p] = canvas(5, 5, h => { h.fillStyle = '#123'; h.fillRect(0, 0, 3, 3); }); g.fillStyle = g.createPattern(p, 'repeat'); g.translate(.5, .3); g.rotate(.2); g.fillRect(0, 0, 70, 70); });
ctl('shadow', 64, 64, g => { g.shadowColor = 'rgba(0,0,0,.6)'; g.shadowBlur = 6; g.shadowOffsetX = 3; g.shadowOffsetY = 2; g.fillStyle = '#e91'; g.fillRect(12, 12, 30, 30); });
for (const op of ['source-over', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'xor', 'lighter'])
ctl(`composite.${op}`, 32, 32, g => { g.fillStyle = 'rgba(30,140,220,.8)'; g.fillRect(2, 2, 20, 20); g.globalCompositeOperation = op; g.fillStyle = 'rgba(240,60,40,.7)'; g.beginPath(); g.arc(20, 20, 10, 0, 7); g.fill(); });
ctl('image_scaled', 48, 48, g => { const [, s] = canvas(7, 7, h => { for (let i = 0; i < 49; i++) { h.fillStyle = `rgb(${i * 5},${255 - i * 5},${(i * 37) % 255})`; h.fillRect(i % 7, (i / 7) | 0, 1, 1); } });
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; g.drawImage(s, 0, 0, 48, 48); });
ctl('filter', 48, 48, g => { g.filter = 'blur(2px) hue-rotate(40deg)'; g.fillStyle = '#3a6'; g.fillRect(8, 8, 30, 30); });
{ // toDataURL: the PNG with its per-launch "deBG" chunk taken out (that chunk is noise.png_deBG)
const [, c] = canvas(16, 16, g => { g.fillStyle = 'rgba(10,20,30,.5)'; g.fillRect(1, 1, 9, 9); });
const bin = atob(c.toDataURL().split(',')[1]); const u = Uint8Array.from(bin, ch => ch.charCodeAt(0));
const keep = [u.subarray(0, 8)]; let i = 8, deBG = null;
while (i < u.length) { const n = (u[i] << 24 | u[i + 1] << 16 | u[i + 2] << 8 | u[i + 3]) >>> 0; const t = String.fromCharCode(...u.subarray(i + 4, i + 8));
if (t === 'deBG') deBG = String.fromCharCode(...u.subarray(i + 8, i + 8 + n)); else keep.push(u.subarray(i, i + 12 + n)); i += 12 + n; }
const out = new Uint8Array(keep.reduce((a, x) => a + x.length, 0)); let o = 0; for (const k of keep) { out.set(k, o); o += k.length; }
put('control.toDataURL', {w: 16, h: 16, enc: 'png', data: b64(out)});
put('control.toDataURL_deBG_shape', deBG === null ? 'absent' : (/^[0-9A-F]{16}$/.test(deBG) ? 'hex16' : 'other:' + deBG.length));
noise('png_deBG', deBG); }
const glScene = version => { const c = document.createElement('canvas'); c.width = 32; c.height = 32;
const gl = c.getContext(version, {preserveDrawingBuffer: true, antialias: false}); if (!gl) return 'no ' + version;
const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return s; };
const pr = gl.createProgram(); gl.attachShader(pr, sh(gl.VERTEX_SHADER, 'attribute vec2 p; varying vec2 v; void main(){ v = p; gl_Position = vec4(p, 0.0, 1.0); }'));
gl.attachShader(pr, sh(gl.FRAGMENT_SHADER, 'precision mediump float; varying vec2 v; void main(){ gl_FragColor = vec4(fract(v.x*3.7), abs(sin(v.y*5.0)), 0.5+0.5*v.x*v.y, 1.0); }'));
gl.linkProgram(pr); gl.useProgram(pr);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-0.9, -0.8, 0.85, -0.7, 0.1, 0.95]), gl.STATIC_DRAW);
const loc = gl.getAttribLocation(pr, 'p'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
gl.clearColor(0.1, 0.2, 0.3, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
const px = new Uint8Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.UNSIGNED_BYTE, px); return {w: 32, h: 32, enc: 'rgba8', data: b64(px)}; };
put('control.webgl1', glScene('webgl')); put('control.webgl2', glScene('webgl2'));
// ================================================================= BLEND (Skia CPU blending of text)
const BL = {red: g => { g.fillStyle = '#d22'; }, alpha: g => { g.fillStyle = 'rgba(0,0,0,.45)'; }, global: g => { g.globalAlpha = .6; g.fillStyle = '#226'; },
overcolour: g => { g.fillStyle = '#9cf'; g.fillRect(0, 0, 200, 40); g.fillStyle = 'rgba(200,30,30,.7)'; }};
for (const f of ['Segoe UI', 'Arial', 'Times New Roman']) for (const px of [8, 16]) for (const [n, set] of Object.entries(BL)) {
const [g] = canvas(200, 40, g => { set(g); g.font = `${px}px "${f}"`; g.fillText('Hamburgefonstiv 0123', 4, 26); }); put(`blend.${f}.${px}.${n}`, img(g, 200, 40, true)); }
// ================================================================= SURFACE (whole APIs)
put('surface.window_own', names(window));
for (const n of ['Navigator', 'Document', 'HTMLDocument', 'Element', 'HTMLElement', 'Node', 'EventTarget', 'Screen', 'ScreenOrientation', 'Performance',
'HTMLCanvasElement', 'CanvasRenderingContext2D', 'OffscreenCanvas', 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext', 'BaseAudioContext',
'MediaDevices', 'Permissions', 'Notification', 'GPU', 'GPUAdapter', 'GPUDevice', 'StorageManager', 'Crypto', 'SubtleCrypto', 'CSS', 'History', 'Location',
'PluginArray', 'MimeTypeArray', 'MouseEvent', 'PointerEvent', 'KeyboardEvent', 'Worker', 'ServiceWorkerContainer', 'RTCPeerConnection', 'SpeechSynthesis',
'VisualViewport', 'FontFaceSet', 'Clipboard', 'ImageDecoder', 'VideoDecoder', 'AudioDecoder', 'VideoEncoder', 'WebTransport', 'LockManager', 'WakeLock', 'Gamepad',
'Scheduler', 'CookieStore', 'NetworkInformation', 'MediaCapabilities', 'MediaSource', 'MediaRecorder', 'IntersectionObserver', 'ResizeObserver', 'TextMetrics',
'CustomElementRegistry', 'Window'])
put(`surface.proto.${n}`, typeof window[n] === 'undefined' ? 'absent' : (window[n].prototype ? names(window[n].prototype) : names(window[n])));
put('surface.navigator', plain(navigator, 1));
put('surface.navigator.plugins', [...navigator.plugins].map(p => [p.name, p.filename, p.description, [...p].map(m => m.type)]));
put('surface.navigator.mimeTypes', [...navigator.mimeTypes].map(m => [m.type, m.suffixes, m.description]));
put('surface.screen', plain(screen, 1));
put('surface.screen.orientation', screen.orientation ? [screen.orientation.type, screen.orientation.angle] : 'absent');
put('surface.window', Object.fromEntries(['innerWidth', 'innerHeight', 'outerWidth', 'outerHeight', 'screenX', 'screenY', 'screenLeft', 'screenTop',
'devicePixelRatio', 'mozInnerScreenX', 'mozInnerScreenY', 'scrollMaxX', 'scrollMaxY', 'isSecureContext', 'crossOriginIsolated', 'name', 'closed', 'length']
.map(k => [k, window[k]])));
// the origin without its port: the port is the gate server's, not the browser's
put('surface.window.origin_scheme_host', location.protocol + '//' + location.hostname);
put('surface.visualViewport', window.visualViewport ? plain(visualViewport, 0) : 'absent');
put('surface.document', Object.fromEntries(['characterSet', 'compatMode', 'contentType', 'designMode', 'dir', 'visibilityState', 'hidden', 'fullscreenEnabled',
'pictureInPictureEnabled', 'pointerLockElement', 'hasStorageAccess'].map(k => [k, typeof document[k] === 'function' ? 'function' : document[k]])));
put('surface.document.hasFocus', document.hasFocus());
{ const Q = {}; const feat = {'prefers-color-scheme': ['light', 'dark'], 'prefers-reduced-motion': ['no-preference', 'reduce'], 'prefers-contrast': ['no-preference', 'more', 'less', 'custom'],
'prefers-reduced-transparency': ['no-preference', 'reduce'], 'forced-colors': ['none', 'active'], 'inverted-colors': ['none', 'inverted'], pointer: ['none', 'coarse', 'fine'],
hover: ['none', 'hover'], 'any-pointer': ['none', 'coarse', 'fine'], 'any-hover': ['none', 'hover'], 'color-gamut': ['srgb', 'p3', 'rec2020'], 'dynamic-range': ['standard', 'high'],
'video-dynamic-range': ['standard', 'high'], 'display-mode': ['browser', 'fullscreen', 'standalone', 'minimal-ui'], update: ['none', 'slow', 'fast'], scripting: ['none', 'initial-only', 'enabled'],
'overflow-block': ['none', 'scroll', 'paged'], 'overflow-inline': ['none', 'scroll'], orientation: ['portrait', 'landscape'], grid: ['0', '1'], monochrome: ['0'],
'-moz-platform': ['windows', 'macos', 'linux', 'android'], '-moz-windows-non-native-menus': ['0', '1'], '-moz-overlay-scrollbars': ['0', '1'], 'prefers-reduced-data': ['no-preference', 'reduce']};
for (const [f, vs] of Object.entries(feat)) Q[f] = vs.filter(v => matchMedia(`(${f}: ${v})`).matches);
for (const f of ['color', 'color-index', 'resolution', 'device-pixel-ratio']) Q['supports-' + f] = matchMedia(`(${f})`).matches;
Q.color_bits = [1, 2, 4, 6, 8, 10, 12, 16].filter(n => matchMedia(`(color: ${n})`).matches);
put('surface.mq', Q); }
{ const I = {}; const ctors = ['DateTimeFormat', 'NumberFormat', 'Collator', 'PluralRules', 'RelativeTimeFormat', 'ListFormat', 'Segmenter', 'DisplayNames', 'DurationFormat'];
for (const c of ctors) { try { I[c] = Intl[c] ? new Intl[c](undefined, c === 'DisplayNames' ? {type: 'region'} : undefined).resolvedOptions() : 'absent'; } catch (e) { I[c] = errs(e); } }
for (const k of ['calendar', 'collation', 'currency', 'numberingSystem', 'timeZone', 'unit']) { try { I['supported_' + k] = Intl.supportedValuesOf(k); } catch (e) { I['supported_' + k] = errs(e); } }
const d = new Date(Date.UTC(2026, 0, 15, 12, 0, 0)), s = new Date(Date.UTC(2026, 6, 15, 12, 0, 0));
I.offsets = [d.getTimezoneOffset(), s.getTimezoneOffset()]; I.strings = [d.toString(), s.toString(), d.toLocaleString(), (1234567.891).toLocaleString(), d.toLocaleDateString(undefined, {dateStyle: 'full'})];
I.languages = navigator.languages; put('surface.intl', I); }
const glAll = version => { const c = document.createElement('canvas'); const gl = c.getContext(version); if (!gl) return 'no ' + version;
const P = {}, proto = Object.getPrototypeOf(gl);
for (const k of Object.getOwnPropertyNames(proto.constructor)) if (/^[A-Z0-9_]+$/.test(k) && typeof gl[k] === 'number') {
const v = gl.getParameter(gl[k]); gl.getError(); if (v !== null && v !== undefined) P[k] = plain(v, 1); }
const ext = gl.getSupportedExtensions() || []; const E = {};
for (const e of ext) { const o = gl.getExtension(e); if (!o) continue; const ep = {};
for (const k in o) if (/^[A-Z0-9_]+$/.test(k) && typeof o[k] === 'number') { const v = gl.getParameter(o[k]); gl.getError(); if (v !== null && v !== undefined) ep[k] = plain(v, 1); }
E[e] = ep; }
const prec = {}; for (const st of ['VERTEX_SHADER', 'FRAGMENT_SHADER']) for (const pt of ['LOW_FLOAT', 'MEDIUM_FLOAT', 'HIGH_FLOAT', 'LOW_INT', 'MEDIUM_INT', 'HIGH_INT']) {
const p = gl.getShaderPrecisionFormat(gl[st], gl[pt]); prec[`${st}.${pt}`] = [p.rangeMin, p.rangeMax, p.precision]; }
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
return {parameters: P, extensions: ext, extension_parameters: E, precisions: prec, attributes: gl.getContextAttributes(),
unmasked: dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : 'absent'}; };
await safe('surface.webgl1', () => glAll('webgl')); await safe('surface.webgl2', () => glAll('webgl2'));
// getParameter must answer only where Firefox would: WebGL2-only enums on a WebGL1 context and the
// enums of extensions not enabled, each as [value, getError()] (official: null + INVALID_ENUM)
await safe('surface.webgl_invalid_enums', () => {
const val = x => (x === null || x === undefined) ? x : (typeof x === 'object' ? (ArrayBuffer.isView(x) || Array.isArray(x) ? Array.from(x) : String(x)) : x);
const ask = (gl, enums) => { const o = {}; gl.getError(); for (const [n, e] of enums) { let v; try { v = val(gl.getParameter(e)); } catch (x) { v = 'THROW ' + x.name; } o[n] = [v, gl.getError()]; } return o; };
const g1 = new Set(Object.getOwnPropertyNames(WebGLRenderingContext));
const only2 = Object.getOwnPropertyNames(WebGL2RenderingContext).filter(k => /^[A-Z0-9_]+$/.test(k) && !g1.has(k)).map(k => [k, WebGL2RenderingContext[k]]);
const EXT = Object.entries({MAX_TEXTURE_MAX_ANISOTROPY_EXT: 0x84FF, TEXTURE_MAX_ANISOTROPY_EXT: 0x84FE, MAX_VIEWS_OVR: 0x9631, UNMASKED_VENDOR_WEBGL: 0x9245,
UNMASKED_RENDERER_WEBGL: 0x9246, MAX_DRAW_BUFFERS_WEBGL: 0x8824, MAX_COLOR_ATTACHMENTS_WEBGL: 0x8CDF, FRAGMENT_SHADER_DERIVATIVE_HINT_OES: 0x8B8B,
VERTEX_ARRAY_BINDING_OES: 0x85B5, TIMESTAMP_EXT: 0x8E28, GPU_DISJOINT_EXT: 0x8FBB, QUERY_COUNTER_BITS_EXT: 0x8864, MAX_CLIP_DISTANCES_WEBGL: 0x0D32,
MAX_CULL_DISTANCES_WEBGL: 0x82F9, MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL: 0x82FA, PROVOKING_VERTEX_WEBGL: 0x8E4F, POLYGON_OFFSET_CLAMP_EXT: 0x8E1B,
CLIP_ORIGIN_EXT: 0x935C, CLIP_DEPTH_MODE_EXT: 0x935D, MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL: 0x88FC, DEPTH_CLAMP_EXT: 0x864F});
const c1 = document.createElement('canvas').getContext('webgl'), c2 = document.createElement('canvas').getContext('webgl2');
return {webgl1_webgl2only: ask(c1, only2), webgl1_ext_not_enabled: ask(c1, EXT), webgl2_ext_not_enabled: ask(c2, EXT)}; });
await safe('surface.webgpu', async () => { if (!navigator.gpu) return 'absent'; const W = {preferredCanvasFormat: navigator.gpu.getPreferredCanvasFormat(),
wgslLanguageFeatures: [...navigator.gpu.wgslLanguageFeatures].sort(), adapters: {}};
for (const [n, o] of Object.entries({none: undefined, low_power: {powerPreference: 'low-power'}, high_performance: {powerPreference: 'high-performance'}, fallback: {forceFallbackAdapter: true}})) {
const a = await navigator.gpu.requestAdapter(o); if (!a) { W.adapters[n] = null; continue; }
const L = {}; for (const k in a.limits) L[k] = a.limits[k];
const A = {features: [...a.features].sort(), limits: L, info: plain(a.info, 0)};
try { const d = await a.requestDevice({requiredFeatures: A.features}); A.device = 'ok'; d.destroy(); } catch (e) { A.device = errs(e); }
W.adapters[n] = A; }
return W; });
{ const types = ['video/mp4', 'video/webm', 'video/ogg', 'audio/mpeg', 'audio/mp4', 'audio/webm', 'audio/ogg', 'audio/wav', 'audio/flac', 'audio/aac',
'video/mp4; codecs="avc1.42E01E"', 'video/mp4; codecs="avc1.640028"', 'video/mp4; codecs="hev1.1.6.L93.B0"', 'video/mp4; codecs="hvc1.1.6.L93.B0"',
'video/mp4; codecs="av01.0.05M.08"', 'video/webm; codecs="av01.0.05M.08"', 'video/mp4; codecs="vp09.00.10.08"', 'video/webm; codecs="vp9"', 'video/webm; codecs="vp8"',
'video/webm; codecs="vp8, vorbis"', 'audio/mp4; codecs="mp4a.40.2"', 'audio/mp4; codecs="opus"', 'audio/webm; codecs="opus"', 'audio/ogg; codecs="vorbis"',
'audio/mp4; codecs="flac"', 'audio/mp4; codecs="ec-3"', 'audio/mp4; codecs="ac-3"', 'video/x-matroska', 'application/x-mpegURL', 'application/vnd.apple.mpegurl'];
const v = document.createElement('video');
put('surface.media.canPlayType', Object.fromEntries(types.map(t => [t, v.canPlayType(t)])));
put('surface.media.MediaSource', window.MediaSource ? Object.fromEntries(types.map(t => [t, MediaSource.isTypeSupported(t)])) : 'absent');
put('surface.media.MediaRecorder', window.MediaRecorder ? Object.fromEntries(types.map(t => [t, MediaRecorder.isTypeSupported(t)])) : 'absent');
const D = {}; const vcodecs = {avc: 'video/mp4; codecs="avc1.640028"', hevc: 'video/mp4; codecs="hvc1.1.6.L93.B0"', vp8: 'video/webm; codecs="vp8"', vp9: 'video/webm; codecs="vp09.00.10.08"',
av1: 'video/mp4; codecs="av01.0.05M.08"'};
for (const [n, ct] of Object.entries(vcodecs)) for (const type of ['file', 'media-source']) for (const [w, h, fr, br] of [[1280, 720, 30, 2e6], [1920, 1080, 60, 8e6], [3840, 2160, 30, 2e7]]) {
try { const r = await navigator.mediaCapabilities.decodingInfo({type, video: {contentType: ct, width: w, height: h, bitrate: br, framerate: fr}}); D[`${type}.${n}.${h}p${fr}`] = [r.supported, r.smooth, r.powerEfficient]; }
catch (e) { D[`${type}.${n}.${h}p${fr}`] = errs(e); } }
for (const ct of ['video/VP8', 'video/VP9', 'video/AV1', 'video/H264']) {
try { const r = await navigator.mediaCapabilities.decodingInfo({type: 'webrtc', video: {contentType: ct, width: 1280, height: 720, bitrate: 1e6, framerate: 30}}); D['webrtc.' + ct] = [r.supported, r.smooth, r.powerEfficient]; }
catch (e) { D['webrtc.' + ct] = errs(e); }
try { const r = await navigator.mediaCapabilities.encodingInfo({type: 'webrtc', video: {contentType: ct, width: 1280, height: 720, bitrate: 1e6, framerate: 30}}); D['webrtc-encode.' + ct] = [r.supported, r.smooth, r.powerEfficient]; }
catch (e) { D['webrtc-encode.' + ct] = errs(e); } }
for (const [n, ct] of Object.entries({aac: 'audio/mp4; codecs="mp4a.40.2"', opus: 'audio/webm; codecs="opus"', flac: 'audio/flac', mp3: 'audio/mpeg'})) {
try { const r = await navigator.mediaCapabilities.decodingInfo({type: 'file', audio: {contentType: ct, channels: '2', bitrate: 128000, samplerate: 48000}}); D['audio.' + n] = [r.supported, r.smooth, r.powerEfficient]; }
catch (e) { D['audio.' + n] = errs(e); } }
put('surface.media.capabilities', D); }
await safe('surface.audio', async () => { const c = new AudioContext(); const o = {sampleRate: c.sampleRate, baseLatency: c.baseLatency, state: c.state,
destination: plain(c.destination, 0), listener: Object.keys(plain(c.listener, 0)).length}; await c.close();
const oc = new OfflineAudioContext(1, 5000, 44100), an = oc.createAnalyser(), os = oc.createOscillator(), dc = oc.createDynamicsCompressor();
os.type = 'triangle'; os.frequency.value = 10000; dc.threshold.value = -50; dc.knee.value = 40; dc.attack.value = 0;
os.connect(dc); dc.connect(an); dc.connect(oc.destination); os.start(0); const buf = await oc.startRendering();
const ch = buf.getChannelData(0); let s = 0; for (let i = 4500; i < 5000; i++) s += Math.abs(ch[i]);
o.offline_sum = s; o.offline_reduction = dc.reduction; o.offline_head = Array.from(ch.subarray(4500, 4520)); return o; });
await safe('surface.voices', () => new Promise(res => { const get = () => speechSynthesis.getVoices().map(v => [v.name, v.lang, v.localService, v.default, v.voiceURI]);
const now = get(); if (now.length) return res(now); speechSynthesis.onvoiceschanged = () => res(get()); setTimeout(() => res(get()), 3000); }));
await safe('surface.permissions', async () => { const P = {}; for (const n of ['geolocation', 'notifications', 'push', 'persistent-storage', 'camera', 'microphone', 'midi',
'clipboard-read', 'clipboard-write', 'screen-wake-lock', 'storage-access', 'background-sync', 'accelerometer', 'gyroscope', 'magnetometer', 'local-fonts', 'payment-handler']) {
try { P[n] = (await navigator.permissions.query({name: n})).state; } catch (e) { P[n] = errs(e); } } return P; });
await safe('surface.storage', async () => { const e = await navigator.storage.estimate(); noise('storage_usage', e.usage); return {quota: e.quota, persisted: await navigator.storage.persisted()}; });
await safe('surface.devices', async () => (await navigator.mediaDevices.enumerateDevices()).map(d => [d.kind, d.label, d.deviceId === '' ? '' : 'id', d.groupId === '' ? '' : 'id']));
{ const style = el => { document.body.appendChild(el); const cs = getComputedStyle(el); const o = {}; for (let i = 0; i < cs.length; i++) o[cs[i]] = cs.getPropertyValue(cs[i]); el.remove(); return o; };
for (const [n, mk] of Object.entries({body: () => document.createElement('div'), button: () => document.createElement('button'), input: () => document.createElement('input'),
select: () => document.createElement('select'), textarea: () => document.createElement('textarea'), a: () => Object.assign(document.createElement('a'), {href: '#'})}))
put(`surface.computedStyle.${n}`, style(mk()));
const SC = ['AccentColor', 'AccentColorText', 'ActiveText', 'ButtonBorder', 'ButtonFace', 'ButtonText', 'Canvas', 'CanvasText', 'Field', 'FieldText', 'GrayText', 'Highlight',
'HighlightText', 'LinkText', 'Mark', 'MarkText', 'SelectedItem', 'SelectedItemText', 'VisitedText', 'ActiveBorder', 'ActiveCaption', 'AppWorkspace', 'Background',
'ButtonHighlight', 'ButtonShadow', 'CaptionText', 'InactiveBorder', 'InactiveCaption', 'InactiveCaptionText', 'InfoBackground', 'InfoText', 'Menu', 'MenuText',
'Scrollbar', 'ThreeDDarkShadow', 'ThreeDFace', 'ThreeDHighlight', 'ThreeDLightShadow', 'ThreeDShadow', 'Window', 'WindowFrame', 'WindowText',
'-moz-buttonhoverface', '-moz-buttonhovertext', '-moz-cellhighlight', '-moz-dialog', '-moz-dialogtext', '-moz-oddtreerow'];
const e = document.createElement('div'); document.body.appendChild(e); const C = {};
for (const c of SC) { e.style.color = ''; e.style.color = c; C[c] = getComputedStyle(e).color; } e.remove(); put('surface.systemColors', C);
const F = {}; const f = document.createElement('div'); document.body.appendChild(f);
for (const k of ['caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar', '-moz-button', '-moz-field', '-moz-list', '-moz-pull-down-menu', 'system-ui'])
{ f.style.font = ''; f.style.font = k === 'system-ui' ? '16px system-ui' : k; const cs = getComputedStyle(f); F[k] = [cs.fontFamily, cs.fontSize, cs.fontWeight, cs.fontStyle]; }
f.remove(); put('surface.systemFonts', F); }
{ const M = {}; for (const [n, x] of Object.entries({acos: .123, acosh: 1e308, asin: .123, asinh: 1, atanh: .5, atan: 2, sin: -1e300, sinh: 1, cos: 10.000000000123, cosh: 1,
tan: -1e300, tanh: 1, exp: 1, expm1: 1, log1p: 10, cbrt: 100, pow: 2}))
M[n] = n === 'pow' ? Math.pow(Math.PI, -100) : Math[n](x);
put('surface.math', M); }
{ const E = {}; const tries = {undef: () => null.x, call: () => (1)(), reduce: () => [].reduce((a, b) => a), json: () => JSON.parse('{'), range: () => new Array(-1), stack: () => { throw new Error('x'); }};
for (const [n, f] of Object.entries(tries)) { try { f(); } catch (e) { E[n] = [e.name, e.message, (e.stack || '').split('\n')[0].replace(/@.*$/, '@<page>')]; } }
put('surface.errors', E); }
await safe('surface.worker', () => new Promise(res => {
const src = `const t0 = performance.now(); postMessage({ua: navigator.userAgent, hc: navigator.hardwareConcurrency, lang: navigator.languages, platform: navigator.platform,
gpu: 'gpu' in navigator, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, t0});`;
const w = new Worker(URL.createObjectURL(new Blob([src], {type: 'text/javascript'}))); const t = performance.now();
w.onmessage = e => { noise('worker_start_ms', Math.round(performance.now() - t)); const d = e.data; delete d.t0; res(d); w.terminate(); };
setTimeout(() => res('timeout'), 5000); }));
await safe('surface.branding', () => Promise.all(['chrome://branding/locale/brand.properties', 'chrome://branding/content/about-logo.png',
'resource://app/localization/en-US/branding/brand.ftl'].map(u => new Promise(res => { const s = document.createElement('script'); let done = false;
const fin = v => { if (!done) { done = true; res([u, v]); } }; s.onload = () => fin('load'); s.onerror = () => fin('error'); s.src = u; document.head.appendChild(s); setTimeout(() => fin('timeout'), 3000); }))));
noise('history_length', history.length);
noise('main_loop_ms', await new Promise(r => { const t = performance.now(); setTimeout(() => r(Math.round(performance.now() - t)), 20); }));
// ================================================================= DIAG (information, never compared)
// diag.*: why this host's WebGL is what it is (no WebGL2, no MSAA). Last, so its extra contexts
// cannot disturb anything measured above; each is lost again once read.
await safe('diag.webgl', async () => {
const probe = async (version, attrs) => {
const c = document.createElement('canvas'), creation_errors = [];
c.addEventListener('webglcontextcreationerror', e => creation_errors.push(e.statusMessage));
let gl = null; const o = {};
try { gl = attrs ? c.getContext(version, attrs) : c.getContext(version); } catch (e) { o.thrown = errs(e); }
await new Promise(r => setTimeout(r, 0));
o.is_null = !gl; o.creation_errors = creation_errors;
if (!gl) return o;
const ask = e => { gl.getError(); let v; try { v = gl.getParameter(e); } catch (x) { return 'THROW ' + x.name; } const err = gl.getError(); return err ? 'GL error ' + err : plain(v, 1); };
o.attributes = gl.getContextAttributes();
o.strings = Object.fromEntries(['VENDOR', 'RENDERER', 'VERSION', 'SHADING_LANGUAGE_VERSION'].map(k => [k, ask(gl[k])]));
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
o.unmasked = dbg ? [ask(dbg.UNMASKED_VENDOR_WEBGL), ask(dbg.UNMASKED_RENDERER_WEBGL)] : 'absent';
o.SAMPLES = ask(gl.SAMPLES); o.SAMPLE_BUFFERS = ask(gl.SAMPLE_BUFFERS);
o.MAX_SAMPLES = 'MAX_SAMPLES' in gl ? ask(gl.MAX_SAMPLES) : 'absent';
const lose = gl.getExtension('WEBGL_lose_context'); if (lose) lose.loseContext();
return o; };
return {webgl1: await probe('webgl'), webgl1_fail_if_caveat: await probe('webgl', {failIfMajorPerformanceCaveat: true}),
webgl2: await probe('webgl2'), webgl2_fail_if_caveat: await probe('webgl2', {failIfMajorPerformanceCaveat: true})}; });
// ================================================================= STATES (state.*)
// The window in the states a page can drive it to: normal, fullscreen, back. Nothing here runs on load:
// fullscreen needs a user gesture, so the dump (ci_host_gate.py drive_states) calls these after 'done'
// and gives every click and move as real input. Defined last so surface.window_own does not list it.
window.__hostGateStates = (() => {
let events = {}, request = null, pending = null;
// each event type keeps the distinct (screen - client) offsets it was seen with
const record = e => { const p = [e.screenX - e.clientX, e.screenY - e.clientY], l = (events[e.type] = events[e.type] || []);
if (!l.some(q => q[0] === p[0] && q[1] === p[1])) l.push(p); };
const geometry = () => ({innerWidth, innerHeight, outerWidth, outerHeight, screenX, screenY, mozInnerScreenX, mozInnerScreenY,
screen: {width: screen.width, height: screen.height, availWidth: screen.availWidth, availHeight: screen.availHeight},
display_mode_fullscreen: matchMedia('(display-mode: fullscreen)').matches,
fullscreen_element: document.fullscreenElement !== null,
window_fullScreen: typeof window.fullScreen === 'boolean' ? window.fullScreen : 'absent'});
const sleep = ms => new Promise(r => setTimeout(r, ms));
// the geometry once it holds for 4 polls in a row (a transition resizes in steps); false if it never does in 3 s
const settle = async () => { let last = JSON.stringify(geometry()), still = 0;
for (let i = 0; i < 60 && still < 4; i++) { await sleep(50); const g = JSON.stringify(geometry()); still = g === last ? still + 1 : 0; last = g; }
return still >= 4; };
// the next fullscreenchange or fullscreenerror, or 'timeout' after ms: a failure is recorded, never waited on
const arm = ms => { request = null; pending = new Promise(res => {
let t = null;
const fin = how => { clearTimeout(t); document.removeEventListener('fullscreenchange', ok); document.removeEventListener('fullscreenerror', bad); res(how); };
const ok = () => fin('fullscreenchange'), bad = () => fin('fullscreenerror');
document.addEventListener('fullscreenchange', ok); document.addEventListener('fullscreenerror', bad);
t = setTimeout(() => fin('timeout'), ms); }); };
const asked = p => { request = 'pending'; p.then(() => { request = 'resolved'; }, e => { request = errs(e); }); };
return {
// listens to the mouse and adds the button whose click asks for fullscreen; returns its centre
prepare() {
for (const t of ['mousemove', 'mousedown', 'mouseup', 'click']) addEventListener(t, record, true);
const b = document.createElement('button'); b.textContent = 'fullscreen';
b.style.cssText = 'position:fixed;left:20px;top:20px;width:160px;height:40px;margin:0;z-index:2147483647';
b.addEventListener('click', () => asked(document.documentElement.requestFullscreen()));
document.body.appendChild(b);
const r = b.getBoundingClientRect(); return {x: r.left + r.width / 2, y: r.top + r.height / 2}; },
arm,
leave(ms) { arm(ms); asked(document.exitFullscreen()); },
async wait() { const how = await pending; const settled = await settle(); return {how, request: request === null ? 'not asked' : request, settled}; },
clear() { events = {}; },
measure() { return Object.assign(geometry(), {events}); },
};
})();
window.__hostGate = G;
if (location.protocol.startsWith('http')) { try { await fetch('/result' + location.search, {method: 'POST', body: JSON.stringify(G)}); } catch (e) {} }
document.title = 'done';
})();
</script>
+1 -1
View File
@@ -38,7 +38,7 @@ ROOT = pathlib.Path(__file__).resolve().parent.parent
#: information. These are the ones that drive a browser through the seam.
FILES = [
"tests/test_juggler_transport.py",
"tests/test_cloak.py",
"tests/test_hidden_desktop.py",
"tests/test_new_page_defaults.py",
"tests/test_cross_origin_iframe.py",
"tests/test_file_chooser.py",
+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env python3
"""Daily snapshot of the public counters, and the two README badges drawn from it.
python scripts/launch_counters.py --history H.csv --daily D.csv --badges DIR
python scripts/launch_counters.py --selftest
Run once a day by .github/workflows/counters.yml, which keeps the files on the
unprotected `badges` branch. Nothing here needs a person or a machine of ours:
every input is a public GitHub API answer and every output is a file on that
branch.
WHAT A LAUNCH IS. Every browser process the engine starts makes one GET to a
fixed release asset (platform/launch-counter in the engine series), and GitHub
counts the fetches as that asset's `download_count`. GitHub keeps only the
running total, never a history, which is why this snapshot exists: a day's
launches are the difference between two consecutive daily totals, and a day
nobody recorded is lost for good.
THE TOTAL IS A SUM, and its terms are fixed history:
* LAUNCHES_BASELINE_V3 is everything counted before the counter moved to the
two live assets below; those earlier assets no longer exist.
* usage_counter_v3 is the wrapper repo's asset, counted from zero. Engines
whose core does not declare the address ping it.
* usage_counter_v4 is the engine repo's asset above the value it already held
when it came back into use (USAGE_COUNTER_RESUMED_AT). Current cores point
every session at it.
The two populations are disjoint, so the launches are the sum.
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import json
import os
import re
import sys
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
ENGINE_REPO = "feder-cr/firefox_antidetect_patch"
WRAPPER_REPO = "feder-cr/invisible_playwright"
COUNTER_TAG = "usage-counter"
LAUNCHES_BASELINE_V3 = 2_084_136
USAGE_COUNTER_RESUMED_AT = 1_162_840
Api = Callable[[str], object]
def github_api(token: str | None) -> Api:
def get(path: str):
req = urllib.request.Request("https://api.github.com" + path)
req.add_header("Accept", "application/vnd.github+json")
if token:
req.add_header("Authorization", "Bearer " + token)
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
return get
def _releases(api: Api, repo: str) -> list[dict]:
out: list[dict] = []
page = 1
while True:
batch = api(f"/repos/{repo}/releases?per_page=100&page={page}")
if not batch:
return out
out.extend(batch)
page += 1
def _counter(api: Api, repo: str) -> int:
rel = api(f"/repos/{repo}/releases/tags/{COUNTER_TAG}")
return sum(a["download_count"] for a in rel["assets"])
def launches_total(usage_counter: int, usage_counter_v3: int) -> int:
return (LAUNCHES_BASELINE_V3 + usage_counter_v3
+ max(0, usage_counter - USAGE_COUNTER_RESUMED_AT))
def collect(api: Api) -> dict[str, int]:
"""Every key the history has always carried, read fresh."""
out: dict[str, int] = {}
binaries = 0
for r in _releases(api, ENGINE_REPO):
tag = r["tag_name"]
if tag == COUNTER_TAG:
continue
n = sum(a["download_count"] for a in r["assets"]
if a["name"].endswith((".zip", ".tar.gz")))
if n or tag.startswith("firefox-"):
out[tag] = n
binaries += n
out["total_binaries"] = binaries
out["usage_counter"] = _counter(api, ENGINE_REPO)
out["usage_counter_v3"] = _counter(api, WRAPPER_REPO)
out["usage_counter_v4"] = max(0, out["usage_counter"] - USAGE_COUNTER_RESUMED_AT)
out["launches_total"] = launches_total(out["usage_counter"], out["usage_counter_v3"])
out["stars"] = api(f"/repos/{WRAPPER_REPO}")["stargazers_count"]
return out
# ── history ─────────────────────────────────────────────────────────────────
def read_history(path: Path) -> dict[str, dict[str, int]]:
out: dict[str, dict[str, int]] = {}
if path.exists():
with path.open(encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
out.setdefault(row["date"], {})[row["key"]] = int(float(row["value"]))
return out
def append_snapshot(path: Path, day: str, data: dict[str, int]) -> list[str]:
"""Append today's rows. Idempotent per (date, key): a rerun the same day
writes only keys that are not there yet, and never a second value."""
seen = set(read_history(path).get(day, {}))
fresh = {k: v for k, v in data.items() if k not in seen}
if not fresh:
return []
new = not path.exists()
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8", newline="") as f:
w = csv.writer(f, lineterminator="\n")
if new:
w.writerow(["date", "key", "value"])
ff = sorted((k for k in fresh if re.fullmatch(r"firefox-\d+", k)),
key=lambda k: int(k.split("-")[1]))
rest = sorted(k for k in fresh if k not in ff)
for k in ff + rest:
w.writerow([day, k, fresh[k]])
return list(fresh)
def launches_per_day(history: dict[str, dict[str, int]]) -> list[tuple[str, int]]:
"""(day counted, launches) for each pair of snapshots ONE day apart.
The snapshot dated D is taken just after midnight UTC, so the difference
from D-1 is the launches of calendar day D-1. A gap between snapshots is
not a day and is never spread over the missing days.
"""
dates = sorted(d for d in history if "launches_total" in history[d])
out = []
for a, b in zip(dates, dates[1:]):
if (dt.date.fromisoformat(b) - dt.date.fromisoformat(a)).days != 1:
continue
delta = history[b]["launches_total"] - history[a]["launches_total"]
if delta > 0:
out.append((a, delta))
return out
def write_daily(path: Path, history: dict[str, dict[str, int]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="") as f:
w = csv.writer(f, lineterminator="\n")
w.writerow(["day_utc", "launches"])
w.writerows(launches_per_day(history))
# ── badges ──────────────────────────────────────────────────────────────────
VALUE_PAD = 6
COLOUR_LABEL = "#555"
CHAR_W = {".": 4.0, "M": 10.0, "k": 6.0} # Verdana 11px advances
DIGIT_W = 7.0
SAFE_VALUE = re.compile(r"^[0-9]+(\.[0-9]+)?[kM]?$")
@dataclass(frozen=True)
class Badge:
label: str
label_box: int # measured from the committed SVG
colour: str
file_name: str
key: str
BADGES = [
Badge("browser launches", 116, "#007ec6", "launches.svg", "launches_total"),
Badge("Stars", 43, "#e8a317", "stars.svg", "stars"),
]
def format_count(n: int) -> str:
"""Two decimals, TRUNCATED: an adoption figure is never rounded up."""
if n < 1000:
return str(n)
scaled, suffix = (n / 1000, "k") if n < 1_000_000 else (n / 1_000_000, "M")
text = f"{int(scaled * 100) / 100:.2f}".rstrip("0").rstrip(".")
return text + suffix
def render(value: str, badge: Badge) -> bytes:
if not SAFE_VALUE.match(value):
raise ValueError(f"refusing to draw an unexpected value: {value!r}")
box = int(sum(CHAR_W.get(c, DIGIT_W) for c in value) + VALUE_PAD)
total = badge.label_box + box
lx, vx = badge.label_box / 2, badge.label_box + box / 2
aria = f"{badge.label}: {value}"
lines = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20"'
f' role="img" aria-label="{aria}">',
f"<title>{aria}</title>",
'<linearGradient id="s" x2="0" y2="100%"><stop offset="0"'
' stop-color="#bbb" stop-opacity=".1"/><stop offset="1"'
' stop-opacity=".1"/></linearGradient>',
f'<clipPath id="r"><rect width="{total}" height="20" rx="3"'
' fill="#fff"/></clipPath>',
'<g clip-path="url(#r)">',
f'<rect width="{badge.label_box}" height="20" fill="{COLOUR_LABEL}"/>',
f'<rect x="{badge.label_box}" width="{box}" height="20"'
f' fill="{badge.colour}"/>',
f'<rect width="{total}" height="20" fill="url(#s)"/>',
"</g>",
'<g fill="#fff" text-anchor="middle"'
' font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">',
f'<text x="{lx:.1f}" y="15" fill="#010101" fill-opacity=".3">{badge.label}</text>',
f'<text x="{lx:.1f}" y="14">{badge.label}</text>',
f'<text x="{vx:.1f}" y="15" fill="#010101" fill-opacity=".3">{value}</text>',
f'<text x="{vx:.1f}" y="14">{value}</text>',
"</g>",
"</svg>",
]
return "\n".join(lines).encode("utf-8")
def write_badges(directory: Path, history: dict[str, dict[str, int]]) -> None:
directory.mkdir(parents=True, exist_ok=True)
for b in BADGES:
days = [d for d in history if b.key in history[d]]
if not days:
raise SystemExit(f"no {b.key} in the history")
(directory / b.file_name).write_bytes(
render(format_count(history[max(days)][b.key]), b))
# ── entry point ─────────────────────────────────────────────────────────────
def run(api: Api, history: Path, daily: Path, badges: Path, today: dt.date) -> int:
day = today.isoformat()
before = read_history(history)
written = append_snapshot(history, day, collect(api))
after = read_history(history)
write_daily(daily, after)
write_badges(badges, after)
print(f"[counters] {day}: wrote {len(written)} keys, "
f"launches_total={after[day]['launches_total']}")
previous = sorted(d for d in before if d < day)
if previous and (today - dt.date.fromisoformat(previous[-1])).days > 1:
# Recorded anyway, but a hole is a lost measurement: say it in the run.
print(f"::warning::no snapshot between {previous[-1]} and {day}: "
f"those days cannot be split")
return 0
def selftest() -> int:
import tempfile
fails = []
# The row of 2026-11-04 as recorded: the sum must give its total back.
if launches_total(2_758_110, 937_317) != 4_616_723:
fails.append("sum")
if format_count(4_616_723) != "4.61M" or format_count(2554) != "2.55k":
fails.append("format")
hist = {"2026-11-01": {"launches_total": 100}, "2026-11-02": {"launches_total": 160},
"2026-11-04": {"launches_total": 300}}
if launches_per_day(hist) != [("2026-11-01", 60)]:
fails.append("gap")
with tempfile.TemporaryDirectory() as t:
p = Path(t) / "h.csv"
append_snapshot(p, "2026-11-08", {"stars": 1})
if append_snapshot(p, "2026-11-08", {"stars": 2}) or read_history(p)["2026-11-08"]["stars"] != 1:
fails.append("idempotent")
print("selftest:", "OK" if not fails else "FAIL " + ", ".join(fails))
return 1 if fails else 0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--selftest", action="store_true")
ap.add_argument("--history", type=Path)
ap.add_argument("--daily", type=Path)
ap.add_argument("--badges", type=Path)
a = ap.parse_args()
if a.selftest:
return selftest()
if not (a.history and a.daily and a.badges):
ap.error("--history, --daily and --badges are required")
api = github_api(os.environ.get("GITHUB_TOKEN"))
return run(api, a.history, a.daily, a.badges, dt.datetime.now(dt.timezone.utc).date())
if __name__ == "__main__":
sys.exit(main())
+47
View File
@@ -0,0 +1,47 @@
import socket,json,subprocess,time,os,sys,base64
base=os.getcwd(); prof=base+'/prof'; os.makedirs(prof,exist_ok=True)
exe=base+'/ex3/core/firefox.exe'
open(prof+'/user.js','w').write('user_pref("marionette.port",2828);user_pref("browser.shell.checkDefaultBrowser",false);user_pref("datareporting.policy.dataSubmissionEnabled",false);user_pref("app.update.auto",false);user_pref("app.update.enabled",false);\n')
p=subprocess.Popen([exe,'-headless','-marionette','-remote-allow-system-access','-no-remote','-profile',prof,'about:blank'],env=dict(os.environ,MOZ_REMOTE_ALLOW_SYSTEM_ACCESS='1'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
s=None
for i in range(60):
try:
s=socket.create_connection(('127.0.0.1',2828),timeout=5);break
except Exception: time.sleep(1)
f=s.makefile('rwb',buffering=0)
def rd():
n=b''
while True:
c=s.recv(1)
if c==b':':break
n+=c
n=int(n);d=b''
while len(d)<n: d+=s.recv(n-len(d))
return json.loads(d)
mid=[0]
def cmd(name,params=None):
mid[0]+=1
m=json.dumps([0,mid[0],name,params or {}]).encode()
s.sendall(str(len(m)).encode()+b':'+m)
while True:
r=rd()
if r[0]==1 and r[1]==mid[0]: return r[2] if r[2] else r[3]
s.settimeout(60)
rd()
cmd('WebDriver:NewSession',{'capabilities':{}})
h=cmd('WebDriver:GetWindowHandles'); cmd('WebDriver:SwitchToWindow',{'handle':h[0]})
cmd('WebDriver:Navigate',{'url':'data:text/html,<body><p id=p>text</p>'})
js="""
const fonts=['menu','caption','icon','message-box','small-caption','status-bar','system-ui'];
const colors=['Canvas','CanvasText','LinkText','VisitedText','ActiveText','ButtonFace','ButtonText','ButtonBorder','Field','FieldText','GrayText','Highlight','HighlightText','Mark','MarkText','SelectedItem','SelectedItemText','AccentColor','AccentColorText','ActiveBorder','ActiveCaption','AppWorkspace','Background','ButtonHighlight','ButtonShadow','CaptionText','InactiveBorder','InactiveCaption','InactiveCaptionText','InfoBackground','InfoText','Menu','MenuText','Scrollbar','ThreeDDarkShadow','ThreeDFace','ThreeDHighlight','ThreeDLightShadow','ThreeDShadow','Window','WindowFrame','WindowText'];
const o={fonts:{},light:{},dark:{},selection:{}};
for(const f of fonts){const d=document.createElement('div');d.style.font=f==='system-ui'?'16px system-ui':f;document.body.appendChild(d);const c=getComputedStyle(d);o.fonts[f]={family:c.fontFamily,size:c.fontSize,weight:c.fontWeight,style:c.fontStyle,stretch:c.fontStretch};d.remove();}
for(const sch of ['light','dark']){for(const k of colors){const d=document.createElement('div');d.style.colorScheme=sch;d.style.color=k;d.style.backgroundColor=k;document.body.appendChild(d);o[sch][k]=getComputedStyle(d).color;d.remove();}
const d=document.createElement('div');d.style.colorScheme=sch;d.textContent='x';document.body.appendChild(d);const c=getComputedStyle(d,'::selection');o.selection[sch]={color:c.color,bg:c.backgroundColor};d.remove();}
return o;"""
r=cmd('WebDriver:ExecuteScript',{'script':js,'args':[]})
json.dump(r['value'] if 'value' in r else r,open(base+'/retail_theme.json','w'),indent=1)
print(json.dumps(r)[:1500])
finally:
subprocess.run(['taskkill','/F','/T','/PID',str(p.pid)],capture_output=True)
+9 -186
View File
@@ -1,201 +1,24 @@
#!/usr/bin/env python3
"""Run the FULL e2e suite (every test that opens the browser) against a binary.
"""Run this repository's FULL e2e suite (every test that opens the browser)
against a binary: the mandatory pre-release e2e gate of a firefox-N.
Every ``@pytest.mark.e2e`` test is excluded from the default `pytest` run
(`addopts = -m 'not slow and not e2e'`) because they need a real Firefox binary
and a display, and they skip themselves when no binary is available. That makes
them easy to forget - and "we can't afford for something to not work". This is
the gate that runs them all, deliberately, against a chosen binary.
It is the MANDATORY pre-release e2e gate: run it green against the freshly-built
release binary BEFORE un-drafting a firefox-N (alongside the fppro + WebRTC
realness gates). It is NOT in the public CI drive-gate - the hosted runners are
content-process unstable under a heavy headless interaction sequence (see
70-known-bugs / 60-ci-release-pipeline); this runs locally on reliable hardware.
Flake-resilience: under full-suite load a couple of interaction tests (dblclick,
hover/mouseenter) can flake even though they pass 3/3 in isolation, so failures
are reran up to twice on the known transient signatures. A genuinely broken
binary fails all attempts. The webrtc e2e fake a TCP-only SOCKS locally (no
proxy/secrets), so the whole suite is offline.
The run opens FOUR browsers at once by default. `--dist loadfile` is not
negotiable and the reason is on the line that sets it: two properties of this
suite depend on a file staying whole on one worker, and both were measured
failing when it did not.
The run itself - which tests, how many browsers at once, the rerun rules, the
deadline, and why each is what it is - lives ONCE, in
`invisible_core.testing.e2e`, for the three clients of the core. This file is
the entry the workflows and the documents call.
Usage:
python scripts/run_e2e.py <firefox-binary>
python scripts/run_e2e.py # uses $INVPW_BINARY_PATH
python scripts/run_e2e.py <binary> -n 8 # eight browsers at once
python scripts/run_e2e.py <binary> -n 1 # the old serial path, unchanged
python scripts/run_e2e.py <binary> -n 1 # the serial path, no xdist
"""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
_RERUN_SIGNATURES = "Timeout|context was destroyed|was detached|not visible|because of a navigation|TargetClosed"
#: Browsers opened at once. Four was asked for and four is what the default is;
#: it is not a measured optimum and there is no reason to believe one number
#: fits every machine, so `-n` moves it and `-n 1` puts the run back exactly on
#: the serial path this script had before parallelism existed.
_DEFAULT_PROCS = "4"
def _take_procs(argv: list[str]) -> tuple[str, list[str]]:
"""Pull `-n/--procs` out of the arguments, leaving the rest for pytest.
Hand-parsed rather than argparse because everything this script does not
recognise is forwarded to pytest verbatim, and argparse would have to be
taught every pytest flag in order to not eat one.
The value is kept as a STRING and handed to xdist unread, so `auto` and any
future spelling xdist accepts keep working without this function learning
about them. Only `0` and `1` are interpreted here, and they mean the same
thing: do not load xdist at all. That is not the same as `-n 1`, which
still runs the tests inside a worker subprocess - a difference that matters
the day this script is used to compare a parallel run against a serial one,
because then the serial arm must be the ORIGINAL path and not a
one-worker variant of the new one.
"""
procs, rest, i = _DEFAULT_PROCS, [], 0
while i < len(argv):
if argv[i] in ("-n", "--procs"):
if i + 1 >= len(argv):
print("run_e2e.py: -n needs a value (1 = serial)", file=sys.stderr)
raise SystemExit(2)
procs, i = argv[i + 1], i + 2
continue
rest.append(argv[i])
i += 1
return procs, rest
def main() -> int:
procs, extra = _take_procs(sys.argv[1:])
binary = extra[0] if extra else os.environ.get("INVPW_BINARY_PATH")
extra = extra[1:] if extra else []
if not binary:
print("usage: run_e2e.py <firefox-binary> (or set INVPW_BINARY_PATH)", file=sys.stderr)
return 2
if not Path(binary).exists():
print(f"ERROR: binary not found: {binary}", file=sys.stderr)
return 2
# An escape hatch in the environment is not neutral here: one e2e ASSERTS
# the behaviour it disables.
#
# `INVISIBLE_CORE_PIN=allow` tells the core to run a mismatched pair instead
# of repairing it. It is the normal way to drive a locally built engine, so
# it is often already exported in the shell that starts this run - and it is
# INHERITED by the venv subprocess that
# `test_the_mismatch_repairs_itself_at_import_without_a_restart` spawns.
# That test deliberately breaks an environment and requires importing the
# wrapper to fix it. With the variable set, the repair correctly declines,
# the version does not move, and the test fails for a reason that has
# nothing to do with the binary under test.
#
# Measured 2026-08-16: 1 failed / 143 passed in 14 minutes, and the same
# file re-run with the variable unset gave 4 passed in 2 minutes. Refusing
# up front costs a second; discovering it costs the whole run plus the time
# spent believing the product was broken.
#
# It is stripped, not merely warned about: a warning at the top of a
# 14-minute run scrolls away long before the failure appears.
env = {k: v for k, v in os.environ.items() if k != "INVISIBLE_CORE_PIN"}
if "INVISIBLE_CORE_PIN" in os.environ:
print("[run_e2e] INVISIBLE_CORE_PIN is set in this shell and has been "
"STRIPPED for the run: one e2e asserts the pin repair that the "
"variable disables, and it would fail for that reason alone.",
file=sys.stderr)
# One setting drives the whole suite: conftest's firefox_binary fixture and
# the webrtc e2e both resolve from these.
env["INVPW_BINARY_PATH"] = binary
env["STEALTHFOX_E2E_BINARY"] = binary
repo = Path(__file__).resolve().parent.parent
# ⛔ `--dist loadfile` IS NOT A TUNING CHOICE, IT IS A CORRECTNESS ONE, and
# xdist's default (`--dist load`, which hands out one test at a time) breaks
# this suite in two measured ways.
#
# 1. MODULE-SCOPED BROWSERS. `test_fingerprint_consistency.py` is 65 of the
# 193 e2e tests and opens ONE browser for all of them, from a
# module-scoped fixture. Scattered test-by-test across four workers, each
# worker that receives any of those tests builds its own copy of that
# fixture: four browsers where the file wants one, and the identity those
# 65 tests exist to prove is no longer being read off a single session.
#
# 2. TESTS THAT DEPEND ON AN EARLIER TEST IN THEIR OWN FILE.
# `test_binary_executes_after_fetch` fails 2 out of 2 in isolation and
# passes 9 out of 9 when its module runs whole, because a prior test in
# that file populates the venv it uses. Measured 2026-08-29, and it very
# nearly got recorded as a deterministic failure of the product.
#
# `loadfile` keeps every file whole on one worker, so both properties
# survive. The price is the ceiling: the longest single FILE is now the
# floor of the whole run, and with 65 of 193 tests in one file this run
# cannot go faster than that file no matter how many workers are asked for.
# That is why raising `-n` past a certain point buys nothing here, and the
# fix for it would be splitting that file, not adding workers.
parallel = [] if procs in ("0", "1") else ["-n", procs, "--dist", "loadfile"]
cmd = [
sys.executable, "-m", "pytest",
"-m", "e2e",
"-o", "addopts=", # override the default 'not e2e' deselection
"--reruns", "2", "--reruns-delay", "1",
"--only-rerun", _RERUN_SIGNATURES,
# A DEADLINE is not a flake, and retrying one multiplies it by three.
# `Timeout` in the signatures above was written for Playwright's
# TimeoutError, but it also matches `subprocess.TimeoutExpired` -
# measured, 2 tests produced 4 reruns - and the release/upgrade e2e
# spend their time in `pip install` calls whose timeouts run to 300s
# each. Retried twice that is 900s for one test, and the two files sum
# to 10050s of timeout budget against a 2400s job. That is how the job
# was killed at 40 minutes twice with nothing to show for it.
"--rerun-except", "TimeoutExpired", # a subprocess deadline
"--rerun-except", "Timeout >", # pytest-timeout's own deadline
# And a per-test deadline, so a hang FAILS WITH A NAME instead of eating
# the job. 420s is 4.5x the slowest legitimate test measured on CI
# (test_webgl_readpixels_no_masking_signature, 94.4s; the second slowest
# is 11.4s and the whole suite is 318s), and 1/6 of the job budget.
# METHOD=thread, not the signal default, and that is the whole point.
# Measured 2026-08-13 on the run of this very change: the suite wedged in
# `test_hover_triggers_mouseenter` and the 420s signal deadline came and
# went with NOTHING at 19.3 minutes, 21 minutes, 40. SIGALRM is delivered
# to the main thread and Python runs the handler at the next bytecode
# boundary; Playwright's sync API is blocked in a greenlet waiting on the
# driver socket, so that boundary never arrives. A watchdog THREAD does
# not need the hung thread to cooperate: it dumps every thread's stack
# and ends the process. The suite does not carry on, which is the price,
# and in exchange a hang stops being anonymous.
"--timeout", "420",
"--timeout-method", "thread",
"-p", "no:cacheprovider",
# -v, not -q, and the reason is a hang we could not name twice.
# Under -q pytest emits one character per test and the line only
# reaches the log when it is full, so a run that dies mid-line says
# nothing about where it died. Measured 2026-08-12 on two runs of the
# SAME commit: both printed the identical `.s....[ 50%]` line at 78
# seconds, one then finished in 4:47 and the other was killed by the
# 40-minute timeout with no second line - so the hang was somewhere in
# tests 73-141 and that is as close as the log could get. Same symptom
# on 2026-08-04. PYTHONUNBUFFERED was already set and is not the
# missing piece: the output does stream, the GRANULARITY was wrong.
# One line per test costs 141 lines and names the last one that ran.
"-v", "--tb=short",
] + parallel + extra
print(f"[run_e2e] binary={binary}")
print(f"[run_e2e] browsers at once: {procs if parallel else '1 (serial)'}")
print(f"[run_e2e] {' '.join(cmd)}")
return subprocess.run(cmd, cwd=repo, env=env).returncode
from invisible_core.testing.e2e import main
if __name__ == "__main__":
sys.exit(main())
sys.exit(main(sys.argv[1:], repo=Path(__file__).resolve().parent.parent))
+218
View File
@@ -0,0 +1,218 @@
"""The expected values of tests/test_css_calc_is_windows_e2e.py.
Run it with `python -I`. Two steps, because a number is only worth testing if
the two C libraries give a different page-visible text for it:
python -I scripts/ucrt_css_calc.py dump OUT # on Windows: ucrtbase.dll's f32 functions
python -I scripts/ucrt_css_calc.py dump OUT # on Linux: the host's libm
python -I scripts/ucrt_css_calc.py pick WIN LINUX tests/data/ucrt_css_calc.txt
`dump` computes, for a fixed grid of inputs, what the style engine (Servo's
calc.rs) makes of ``calc(1px * sin(x))`` and the others, and the text it then
serializes. The style engine does every step in f32 (CSSFloat): the library
function is the f32 one (sinf, cosf, tanf, asinf, acosf, atanf, atan2f, expf,
logf, powf), an angle is converted to degrees with one f32 multiplication, and
a number is written by cssparser's dtoa_short: the shortest decimal that
reads back as that f32, rounded half up to 6 significant digits. So two
libraries whose results differ in the last f32 bit only show on the page when
that bit moves the 6th digit - which `pick` looks for.
`pick` keeps every input whose text differs between the two dumps, and a few
that do not (the control: the same text from both libraries), in the format
the test reads:
<fn> <args...> <text on Windows>
The reference is ucrtbase's FMA3 code path, the one every Windows 11 CPU runs
(the same one idwr_math reproduces); the SSE2 fallback of older CPUs can differ in
the last bit and is not what a page on Windows 11 reads.
Inputs are exact in f32 (multiples of a power of two), so the page and this
script read the same number whatever the CSS parser does with decimals.
"""
from __future__ import annotations
import ctypes
import math
import struct
import sys
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path
#: Rust's f32::to_degrees multiplier, as an f32.
RAD_TO_DEG = struct.unpack("<f", struct.pack("<f", 57.2957795130823208767981548141051703))[0]
#: How many differing inputs of each function `pick` keeps, and how many of the
#: ones that agree.
KEEP_DIFFERENT = 6
KEEP_SAME = 3
def f32(x: float) -> float:
return struct.unpack("<f", struct.pack("<f", x))[0]
def load_libm():
if sys.platform == "win32":
lib = ctypes.CDLL("ucrtbase.dll")
else:
lib = ctypes.CDLL("libm.so.6")
funcs = {}
for name, nargs in (("sinf", 1), ("cosf", 1), ("tanf", 1), ("asinf", 1), ("acosf", 1),
("atanf", 1), ("atan2f", 2), ("expf", 1), ("logf", 1), ("powf", 2)):
fn = getattr(lib, name)
fn.restype = ctypes.c_float
fn.argtypes = [ctypes.c_float] * nargs
funcs[name] = fn
return funcs
def shortest_f32(x: float) -> str:
"""The shortest decimal text that reads back as this f32."""
for digits in range(1, 10):
text = "%.*e" % (digits - 1, x)
if f32(float(text)) == x:
return text
return "%.8e" % x
def serialize(x: float) -> str:
"""cssparser's number text for an f32: 6 significant digits, half up,
no trailing zeros, no exponent in the range the grid stays in."""
if x == 0:
return "0"
d = Decimal(shortest_f32(x))
exp = d.adjusted()
q = d.quantize(Decimal(1).scaleb(exp - 5), rounding=ROUND_HALF_UP)
text = format(q.normalize(), "f")
return "0" if text in ("-0", "") else text
def decimal(k: int, shift: int) -> str:
"""k / 2**shift as an exact decimal text."""
d = Decimal(k) / Decimal(2 ** shift)
return format(d.normalize(), "f")
def grid():
"""(fn, args as texts) for every case of the dump."""
out = []
for fn, lim, shift in (("sin", 16, 10), ("cos", 16, 10), ("tan", 16, 10)):
for k in range(-lim << shift, (lim << shift) + 1):
out.append((fn, [decimal(k, shift)]))
# Finer, over the stretch where the functions bend the most.
for k in range(-(4 << 13), (4 << 13) + 1):
out.append(("tan", [decimal(k, 13)]))
for k in range(-(8 << 12), (8 << 12) + 1):
out.append(("atan", [decimal(k, 12)]))
for k in range(-(4 << 12), (4 << 12) + 1):
out.append(("exp", [decimal(k, 12)]))
for k in range(1, 32 * 1024 + 1):
out.append(("log", [decimal(k, 10)]))
for a in range(-128, 129):
for b in range(-128, 129):
if a or b:
out.append(("atan2", [decimal(a, 6), decimal(b, 6)]))
for k in range(-4096, 4097):
out.append(("asin", [decimal(k, 12)]))
out.append(("acos", [decimal(k, 12)]))
for k in range(-8 * 512, 8 * 512 + 1):
out.append(("atan", [decimal(k, 9)]))
for a in range(-64, 65):
for b in range(-64, 65):
if a or b:
out.append(("atan2", [decimal(a, 4), decimal(b, 4)]))
for k in range(-10 * 256, 10 * 256 + 1):
out.append(("exp", [decimal(k, 8)]))
for k in range(1, 64 * 64 + 1):
out.append(("log", [decimal(k, 6)]))
for a in range(2, 513):
for b in (2, 3, 5, 7, 10):
out.append(("log", [decimal(a, 3), str(b)]))
for a in range(-32, 33):
for b in range(-32, 33):
out.append(("hypot", [decimal(a * 3, 4), decimal(b * 5, 4)]))
for a in range(4, 257):
for b in range(-64, 65):
out.append(("pow", [decimal(a, 4), decimal(b, 4)]))
return out
def evaluate(lib, fn, args):
"""(text, unit) the page shows, from f32 steps."""
v = [f32(float(a)) for a in args]
if fn in ("sin", "cos", "tan", "exp"):
return serialize(f32(lib[fn + "f"](v[0]))), "px"
if fn == "log":
if len(v) == 1:
return serialize(f32(lib["logf"](v[0]))), "px"
return serialize(f32(f32(lib["logf"](v[0])) / f32(lib["logf"](v[1])))), "px"
if fn == "hypot":
# powi(2) is a product, the sum is f32, sqrt is exact in IEEE: no library
# function here, so no difference between the two - the control.
return serialize(f32(math.sqrt(f32(f32(v[0] * v[0]) + f32(v[1] * v[1]))))), "px"
if fn == "pow":
return serialize(f32(lib["powf"](v[0], v[1]))), "px"
if fn in ("asin", "acos", "atan"):
return serialize(f32(f32(lib[fn + "f"](v[0])) * RAD_TO_DEG)), "deg"
if fn == "atan2":
return serialize(f32(f32(lib["atan2f"](v[0], v[1])) * RAD_TO_DEG)), "deg"
raise ValueError(fn)
def dump(out: Path) -> None:
lib = load_libm()
lines = []
for fn, args in grid():
text, unit = evaluate(lib, fn, args)
if text in ("nan", "inf", "-inf") or "e" in text.lower():
continue
lines.append("%s %s %s%s" % (fn, " ".join(args), text, unit))
out.write_text("\n".join(lines) + "\n")
print("wrote %s: %d cases (%s)" % (out, len(lines), sys.platform))
def read(path: Path) -> dict:
cases = {}
for line in path.read_text().splitlines():
parts = line.split()
cases[tuple(parts[:-1])] = parts[-1]
return cases
def pick(win: Path, linux: Path, out: Path) -> None:
a, b = read(win), read(linux)
chosen = ["# Expected text of getComputedStyle for calc(1px * f(args)) (word-spacing)",
"# and of rotate: f(args) for the angle functions, from ucrtbase.dll's f32",
"# functions. Generated by scripts/ucrt_css_calc.py (python -I) - do not edit.",
"# <fn> <args...> <text on Windows>"]
stats = []
for fn in ("sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "log", "pow", "hypot"):
keys = sorted(k for k in a if k[0] == fn and k in b)
different = [k for k in keys if a[k] != b[k]]
same = [k for k in keys if a[k] == b[k]]
# Spread over the list, not the first ones.
step_d = max(1, len(different) // KEEP_DIFFERENT)
quarter = max(1, len(same) // 4)
take = different[::step_d][:KEEP_DIFFERENT] + same[quarter::quarter][:KEEP_SAME]
stats.append("%s: %d of %d differ" % (fn, len(different), len(keys)))
for k in take:
chosen.append("%s %s" % (" ".join(k), a[k]))
out.write_text("\n".join(chosen) + "\n")
print("\n".join(stats))
print("wrote %s" % out)
def main(argv) -> int:
if len(argv) == 3 and argv[1] == "dump":
dump(Path(argv[2]))
elif len(argv) == 5 and argv[1] == "pick":
pick(Path(argv[2]), Path(argv[3]), Path(argv[4]))
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+6 -1
View File
@@ -194,7 +194,12 @@ def main() -> int:
import os
env = dict(os.environ)
env["INVPW_BINARY_PATH"] = a.binary
env["PYTHONPATH"] = str(ROOT)
# ⛔ THIS CHECKOUT'S `src` TOO, or the suite measures whatever wrapper is
# INSTALLED: `ROOT` alone only makes `scripts._upstream_alias` importable,
# and `invisible_playwright` then resolves to the editable install, which
# from a worktree is somebody else's tree on somebody else's commit. A
# branch measured that way reports main's numbers as its own.
env["PYTHONPATH"] = os.pathsep.join([str(ROOT), str(ROOT / "src")])
if not a.per_file:
print("running: %s" % " ".join(argv[3:]))
+5 -3
View File
@@ -11,7 +11,7 @@ the user receives.
| folder | what it is | license |
|---|---|---|
| `_pw/` | Playwright's Python client, version **1.61.1** | Apache-2.0 (`_pw/LICENSE`) |
| `_pw/` | Playwright's Python client, version **1.61.0** | Apache-2.0 (`_pw/LICENSE`) |
The client's namespace is `invisible_playwright._pw` instead of `playwright`, so
it does not collide with a stock `playwright` that might be installed alongside
@@ -50,7 +50,8 @@ did so on evidence rather than on the code looking finished:
- The ability to RE-DERIVE three things that were extracted from the bundle.
All three artefacts are committed and still valid; what is gone is
regenerating them. `injected.js` (the selector engines, actionability and
`expect` that run in the page), `_juggler/keylayout.py`, and the four rules
`expect` that run in the page), `keylayout.py` (both in `invisible_core.juggler`
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
`prefs_byte_parity.py` compares our `user.js` writer against - now frozen in
`tests/gates/driver_prefs_rules.json` with the sha of the bundle and of the
exact window they came from.
@@ -79,7 +80,8 @@ They are history now, kept because they say what the fork was for:
- **Neutralized `_exposeConsoleApi`** and **removed `console.debug`** from the
injected code, both because a page could observe them. ⛔ Not lost: those
changes are in `injected.js`, which is extracted, committed, and still what
the server injects. `gen_injected_source.py --check` refuses any bundle that
the server injects (from `invisible_core.juggler` since 0.30.0). The core's
`scripts/gen_injected_source.py --check` refuses any bundle that
does not carry the `MODIFIED by invisible_playwright` markers, so an upstream
bundle can never be mistaken for ours.
File diff suppressed because it is too large. Load diff
+81 -43
View File
@@ -123,12 +123,14 @@ from dataclasses import dataclass
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
from weakref import WeakKeyDictionary
from . import _behaviour, _pacing
from ._pacing import (
DONE, SLEEP, Ev as _Ev, clamp_to_viewport as _clamp,
fine_timer as _fine_timer,
fit_timeline as _fit_timeline,
from invisible_core.juggler import (
DONE, SLEEP, Ev as _Ev, Pacer, PointerPersona, Step,
clamp_to_viewport as _clamp, fine_timer as _fine_timer,
fit_timeline as _fit_timeline, initial_pointer, landing_point,
plan_aimless_move, plan_approach, plan_idle, plan_scroll,
steps_from_waypoints, tail_within,
)
from invisible_core.seedmix import sub_seed
# The escape hatch. ``INVPW_CURSOR_ENGINE`` picks who generates the motion:
# "python" (default) - this module, seeded from the session seed
@@ -232,8 +234,10 @@ def _reset_warnings() -> None:
# Anything else is treated as "no generator available" and the session falls
# back to the browser's own expansion, which is always a working browser.
try: # pragma: no cover - exercised by the import-failure test via monkeypatch
from . import _motion as _motion_mod # type: ignore[attr-defined]
except Exception as _motion_exc: # noqa: BLE001 - a broken _motion must not break launching
# The package that publishes the generator: `_motion_factory` looks the
# factory up on it by name, and the tests put a stub module here.
from invisible_core import juggler as _motion_mod # type: ignore[attr-defined]
except Exception as _motion_exc: # noqa: BLE001 - a broken generator must not break launching
_motion_mod = None # type: ignore[assignment]
_MOTION_IMPORT_ERROR: Optional[BaseException] = _motion_exc
else:
@@ -248,7 +252,7 @@ else:
#: It moved into _pacing on 2026-09-16, with the discipline that reads it, so
#: the server's drag obeys the same floor as the client's cursor. Re-exported
#: here because it is part of this module's published surface.
MIN_EVENT_INTERVAL_MS = _pacing.MIN_EVENT_INTERVAL_MS
from invisible_core.juggler import MIN_EVENT_INTERVAL_MS # noqa: E402 - re-exported, see above
_MOTION_FACTORY_NAMES = ("CursorMotion", "MotionProfile", "new_motion")
@@ -270,7 +274,7 @@ def _motion_factory() -> Optional[Callable[..., Any]]:
_warn_once(
"no-motion",
"no cursor motion generator found "
"(invisible_playwright._motion.CursorMotion)" + detail + "; falling "
"(invisible_core.juggler.CursorMotion)" + detail + "; falling "
"back to the browser's own motion for this process. This is a broken "
"install, not a configuration.",
)
@@ -369,9 +373,21 @@ def page_motion_seed(session_seed: int, ordinal: int) -> int:
in which tabs happened to move. Same session seed plus same tab ordinal
gives the same path, which is what makes a replayed seed replay the
cursor. Kept inside int31 for consistency with the rest of the seeding.
⛔ EVERY BIT OF THE ORDINAL COUNTS, not only the low 16. A page the site
opened is numbered in a space of its own above bit 62 (`_behaviour.
popup_number`), and with the old mask two popups shared a path whenever
their numbers agreed on 16 bits. The higher bits are folded in only when
there are any, so the pages the script asks for (0, 1, 2 ...) keep the
seeds they always had.
"""
ordinal = int(ordinal)
h = (int(session_seed) & 0xFFFFFFFF) * 0x9E3779B1
h = (h ^ ((int(ordinal) & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
h = (h ^ ((ordinal & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
high = ordinal >> 16
while high > 0:
h = ((h ^ (high & 0xFFFF)) * 0xC2B2AE35) & 0xFFFFFFFF
high >>= 16
h ^= h >> 16
return h & 0x7FFFFFFF
@@ -379,17 +395,25 @@ def page_motion_seed(session_seed: int, ordinal: int) -> int:
class _Session:
"""Everything a session hands to the pages underneath it."""
__slots__ = ("seed", "max_seconds", "_ordinal")
__slots__ = ("seed", "max_seconds")
def __init__(self, seed: int, max_seconds: float) -> None:
self.seed = int(seed)
self.max_seconds = float(max_seconds)
self._ordinal = 0
def next_ordinal(self) -> int:
n = self._ordinal
self._ordinal += 1
return n
def page_number(page: Any) -> int:
"""The page's number in the session, as the server gave it.
⛔ READ FROM THE PAGE, NEVER COUNTED HERE. The server sends it in the
page's initializer (`PageDispatcher.number`: the number the client
reserved at the `new_page()` call, or a popup's derived one), and the
server draws the page's acts under it. This cursor used to count its own,
at each page's FIRST MOVEMENT: a script that created two pages and moved
on the second first gave the second page 0 here and 1 there - two
counters for one fact, with two different orders ([B237]).
"""
return int(page._initializer["pageNumber"])
class _PageCursor:
@@ -402,7 +426,7 @@ class _PageCursor:
self.seed = int(seed)
self.max_seconds = float(max_seconds)
self._profile = _build_profile(factory, self.seed, self.max_seconds)
self.persona = _behaviour.PointerPersona.from_seed(self.seed)
self.persona = PointerPersona.from_seed(self.seed)
self.x: Optional[float] = None
self.y: Optional[float] = None
self.busy = False
@@ -447,7 +471,7 @@ class _PageCursor:
"using the behaviour planner's instead."
% (type(exc).__name__, exc),
)
return _behaviour.initial_pointer(self.seed, (float(w), float(h)))
return initial_pointer(self.seed, (float(w), float(h)))
def here(self, page: Any) -> Tuple[float, float]:
"""Current pointer position, placing it first if it has never moved."""
@@ -494,7 +518,7 @@ class _PageCursor:
float(getattr(p, "y", None) if hasattr(p, "y") else p[1]),
nominal)
for p in raw]
return _behaviour.steps_from_waypoints(
return steps_from_waypoints(
raw, kind=kind, lead_ms=lead_ms, bounds=bounds
)
@@ -503,7 +527,7 @@ class _PageCursor:
def rng(self, tag: str) -> random.Random:
"""A per-(page, action, purpose) stream. Reproducible from the seed."""
return random.Random(
_behaviour._sub_seed(self.seed, "%s:%d" % (tag, self.action))
sub_seed(self.seed, "%s:%d" % (tag, self.action))
)
@@ -587,19 +611,21 @@ async def _dispatch(
*,
timer: Any = None,
emit_last: bool = True,
origin: Optional[Tuple[float, float]] = None,
) -> int:
"""The ASYNCHRONOUS driver of :class:`._pacing.Pacer`. Returns events sent.
"""The ASYNCHRONOUS driver of :class:`invisible_core.juggler.Pacer`. Returns events sent.
The rules it obeys - absolute deadlines from one ``t0``, drop rather than
send late, never two events in one instant - are not written here: they are
in :mod:`._pacing`, because the server's drag is synchronous and has to obey
the same ones. This function supplies a clock and a way of waiting; it makes
no decision the pacer has not already made.
send late while the drop stays within reach, never two events in one
instant - are not written here: they are in :mod:`._pacing`, because the
server's drag is synchronous and has to obey the same ones. This function
supplies a clock, a way of waiting and where the pointer starts from; it
makes no decision the pacer has not already made.
"""
tm = timer if timer is not None else _TIMER
if not evs:
return 0
pacer = _pacing.Pacer(evs, emit_last=emit_last)
pacer = Pacer(evs, emit_last=emit_last, origin=origin)
with _fine_timer():
while True:
what, arg = pacer.step(tm.now())
@@ -678,9 +704,10 @@ def _cursor_for_page(page: Any) -> Optional[_PageCursor]:
factory = _motion_factory()
if factory is None:
return None
seed = page_motion_seed(session.seed, page_number(page))
try:
cursor = _PageCursor(
page_motion_seed(session.seed, session.next_ordinal()),
seed,
session.max_seconds,
factory,
)
@@ -805,20 +832,29 @@ async def _target_point(frame: Any, selector: str, position: Any) -> Optional[Tu
async def _hits(handle: Any, x: float, y: float) -> bool:
"""Does (x, y) actually land on this element?
"""Does (x, y), in the same main-frame space as the box, land on this element?
A bounding box is not the element. An inline link that wraps across two
lines, a rotated control, a rounded button: all of them have points inside
their box that belong to something else. The centre is checked by the
automation layer itself; a point we chose has to be checked by us, or we
would be turning working clicks into hit-target failures.
⛔ THE QUESTION GOES TO THE SERVER, WHICH ANSWERS IT FOR THE ACTION TOO
(`Actions.hit_target`). It used to be answered here with
`document.elementFromPoint`, in the element's own document but at the
main frame's coordinates: in a nested frame that asked about another
place, and in a shadow root the hit is the host, never the control. Both
rejected every off-centre point, so those clicks went to the exact
geometric centre, one number for every install. `checkHitTarget` is a
method of this package's server, not of Playwright's protocol: the Node
driver arm (`INVPW_TRANSPORT=driver`) refuses it, and there the landing
falls back to the centre.
"""
try:
return bool(await handle.evaluate(
"(el, p) => { const e = document.elementFromPoint(p.x, p.y);"
" return !!e && (e === el || el.contains(e) || e.contains(el)); }",
{"x": x, "y": y},
))
return bool(await handle._channel.send(
"checkHitTarget", None, {"point": {"x": x, "y": y}},
is_internal=True))
except _page_errors():
return False
@@ -884,7 +920,8 @@ async def _travel(
await raw_move(x, y)
cursor.x, cursor.y = x, y
await _dispatch(evs, emit, timer=timer, emit_last=False)
await _dispatch(evs, emit, timer=timer, emit_last=False,
origin=(cursor.x, cursor.y))
cursor.x, cursor.y = to_x, to_y
cursor.last_event_at = (timer or _TIMER).now()
return 0.0
@@ -909,7 +946,8 @@ async def _run_steps(
await emit_move(x, y)
cursor.x, cursor.y = x, y
await _dispatch(evs, move, emit_wheel, timer=timer, emit_last=emit_last)
await _dispatch(evs, move, emit_wheel, timer=timer, emit_last=emit_last,
origin=(cursor.x, cursor.y))
if not emit_last and evs:
cursor.x, cursor.y = evs[-1].x, evs[-1].y
cursor.last_event_at = (timer or _TIMER).now()
@@ -952,16 +990,16 @@ def _plan_fidget(cursor: _PageCursor, page: Any, timer: Any) -> List[Any]:
# A movement that ends nowhere in particular. If every movement of a
# session terminates on a control then the SET OF ENDPOINTS is a
# signature on its own, whatever the paths between them look like.
steps = _behaviour.plan_aimless_move(
steps = plan_aimless_move(
cursor.seed, cursor.persona, here, bounds,
nonce=cursor.action, render=cursor.renderer(bounds),
)
return _behaviour.tail_within(steps, budget, here, bounds)
steps = _behaviour.plan_idle(
return tail_within(steps, budget, here, bounds)
steps = plan_idle(
cursor.seed, cursor.persona, here, bounds, gap_ms,
nonce=cursor.action, render=cursor.renderer(bounds),
)
return _behaviour.tail_within(steps, budget, here, bounds)
return tail_within(steps, budget, here, bounds)
# ── the wrappers ────────────────────────────────────────────────────────────
@@ -1156,7 +1194,7 @@ async def _choose_landing(frame: Any, cursor: Any, selector: str,
return _Aim(box, (box["x"] + float(position["x"]),
box["y"] + float(position["y"])), None)
landing = _behaviour.landing_point(
landing = landing_point(
(box["x"], box["y"], box["width"], box["height"]),
cursor.rng("cursor:landing"),
spread=_LANDING_SPREAD, keep=_LANDING_KEEP,
@@ -1199,7 +1237,7 @@ async def _walk_onto(cursor: Any, page: Any, aim: _Aim, move: Any,
await _run_steps(cursor, fidget, raw, budget_s=spent, timer=timer)
budget = max(budget - spent, 0.2)
steps = _behaviour.plan_approach(
steps = plan_approach(
cursor.seed, cursor.persona, cursor.here(page), aim.rect, bounds,
nonce=cursor.action, landing=aim.landing,
render=cursor.renderer(bounds),
@@ -1310,7 +1348,7 @@ def _scroll_plan(cursor: _PageCursor, page: Any, delta_x: float, delta_y: float
if ticks < 2:
return []
bounds = _bounds(page)
steps = _behaviour.plan_scroll(
steps = plan_scroll(
cursor.seed, cursor.persona, cursor.here(page), bounds,
ticks=ticks, tick_dy=1.0, nonce=cursor.action,
render=cursor.renderer(bounds),
@@ -1334,7 +1372,7 @@ def _scroll_plan(cursor: _PageCursor, page: Any, delta_x: float, delta_y: float
dx, dy = delta_x * frac, delta_y * frac
used_x += dx
used_y += dy
out.append(_behaviour.Step(x=s.x, y=s.y, delay_ms=s.delay_ms,
out.append(Step(x=s.x, y=s.y, delay_ms=s.delay_ms,
kind="wheel", dx=dx, dy=dy))
return out
+7 -1
View File
@@ -98,11 +98,17 @@ def assert_playwright_range() -> None:
if t(seal.playwright_min) <= t(have) <= t(seal.playwright_max):
return
# Spelled by the tool that installed this package (`invisible_core.installer`):
# a written `pip install` is a command the venv the README makes does not have.
from invisible_core.installer import install
from invisible_core.pin import format_command
fix = format_command(install("invisible-playwright", f"playwright=={seal.playwright_max}"))
msg = (f"playwright {have} is outside the range this engine was tested with "
f"({seal.playwright_min} .. {seal.playwright_max}, from the seal for {seal.tag}).\n"
f"The Juggler protocol schema is closed-world: an untested client can kill every "
f"session at context creation.\n"
f'Run: pip install "playwright=={seal.playwright_max}" '
f"Run: {fix} "
f"(or set INVISIBLE_PLAYWRIGHT_SKEW=allow to proceed anyway)")
if os.environ.get("INVISIBLE_PLAYWRIGHT_SKEW") == "allow":
warnings.warn(msg, RuntimeWarning, stacklevel=2)
+15 -12
View File
@@ -1,20 +1,23 @@
"""The Juggler client in Python: the break from Playwright, piece by piece.
"""The Playwright side of the engine: a server that speaks Playwright's protocol and drives Juggler.
| module | what it does |
|---|---|
| `protocol.py` | GENERATED by `scripts/gen_juggler_protocol.py` reading the `Protocol.js` that lives inside the SHIPPED binary: 71 commands, 34 events |
| `connection.py` | the pipe to Juggler. JSON delimited by a zero byte; fd 3/4 on POSIX, inheritable HANDLEs on Windows |
| `lifecycle.py` | frame tree, navigations, the four load states |
| `injected.py` | loads `injected.js` into the UTILITY world and calls it: selectors and actionability |
| `injected.js` | extracted from the bundle with `scripts/gen_injected_source.py`. It is not upstream: it carries the fork's stealth fixes |
| `server.py` | the Playwright channel: browsers, contexts, pages, frames, routes; every call ends in the Juggler client |
| `dispatcher.py` | the object tree Playwright's client talks to, and the guids it names them by |
| `_marshal.py` | values across the channel, both ways |
| `transport.py` | the in-process transport between the client and this server |
| `perimeter.py` | what the server refuses on purpose, said as errors rather than pretended |
⛔ **No product module imports this package yet**: it is inert by
construction, and stays that way until `_impl` leans on it. What is missing
lives in `docs/firefox-stealth-architecture/32-stacco-da-playwright.md` §6,
which is also the only place where the design and the inventory of
constraints live.
⛔ THE JUGGLER CLIENT ITSELF IS NOT HERE. Since 0.30.0 the pipe, the protocol
mirror, the frame lifecycle, the injected script, the input actions, the
keyboard and the human rhythm (`connection`, `protocol`, `lifecycle`,
`injected`, `actions`, `keyboard`, `keylayout`, `_profile`, `_behaviour`,
`_motion`, `_pacing`) live once in `invisible_core.juggler`, shared with
invisible-selenium and invisible-puppeteer (decision D85). A copy of any of them
in this folder is the defect that move removed, and
`tests/test_juggler_lives_in_the_core.py` refuses it.
⛔ **What lives here REACHES the user**, because it sits under
⛔ What lives here REACHES the user, because it sits under
`src/invisible_playwright/`. A tool that only serves us goes in `scripts/`,
which the wheel does not include.
"""
+90 -57
View File
@@ -15,47 +15,72 @@ there has to move.
from __future__ import annotations
import json
import re
from typing import Any, Dict, List, Optional
def _as_callable(expression: str, argument: Any) -> str:
"""Wrap an expression so it can always be CALLED with the argument.
def _js_number(value: Any) -> str:
"""A number as JavaScript prints it in a template literal: `111`, never
Python's `111.0` (the timeout of an expect's call log, [B341])."""
number = float(value)
return str(int(number)) if number.is_integer() else repr(number)
<M> PLAYWRIGHT SENDS BOTH FORMS DOWN THE SAME FIELD. `page.evaluate("1+1")`
and `page.evaluate("() => document.title")` arrive as the same
`expression` string, and the client does not say which is which. Evaluating
the raw string works for the first and, for the second, produces a FUNCTION
OBJECT: no error, no exception, and the caller gets None back for a call
that looked fine.
Measured on 2026-08-27: `page.evaluate("() => !!x")` answered None, and the
assertion that caught it read like the browser had changed behaviour.
def _caller_timeout(params: Dict, default_ms: float = 30000) -> Optional[float]:
"""The caller's timeout off the wire, in seconds; None is no limit.
So the string is wrapped and the result called if it turned out to be a
function. Deciding by shape - does it start with `(` or `function` or
`async` - is the version that gets it wrong: `(1+2)` starts with a
parenthesis and is not a function.
<M> THE ARGUMENT GOES IN HERE, IN THE SAME PASS, AND THAT IS THE WHOLE
POINT. It used to be spelled `r(ARG)` and the caller substituted it
afterwards with `.replace("ARG", ...)` - over a string that already held
the caller's expression. So every uppercase `ARG` a caller wrote was
rewritten to the argument's JSON, inside their own code, silently.
Measured on 2026-09-14 by driving it: `'CARGO'.length` answered 6 instead
of 5, because the source that ran was `'CnullO'.length`; a selector
`[data-role='TARGET']` became `[data-role='TnullET']` and matched nothing;
`/ARGH/` became `/nullH/`; and `const ARG = 5` was a SyntaxError. The three
letters need only appear inside a longer word - MARGIN, LARGE, CHARGE - and
three of those four failures are silent, which is the bad kind.
A format string is only scanned where the format string itself is, so the
expression is an ARGUMENT to `%` and never a place `%` looks. The sibling
wrapper in `op_eval_on_selector` was already written this way.
Milliseconds on the wire. `0` is no limit in Playwright, and until 0.34.0
it was read as `params.get("timeout") or 30000`, in four places, so a
`click(timeout=0)` gave up at 30 s and a `launch(timeout=0)` at 60 (B278,
B276). Absent, the default the operation has when nobody says.
"""
return ("(() => { const r = (%s);"
" return typeof r === 'function' ? r(%s) : r; })()"
% (expression, json.dumps(argument, default=str)))
wanted = params.get("timeout")
if wanted == 0:
return None
if isinstance(wanted, (int, float)) and wanted > 0:
return float(wanted) / 1000.0
return default_ms / 1000.0
#: What JavaScript's `String.prototype.trim` removes, WhiteSpace and
#: LineTerminator, and nothing else: Python's `str.strip()` also removes U+0085
#: and U+001C-U+001F, and keeps U+FEFF.
_JS_WHITESPACE = ("\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004"
"\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f"
"\u205f\u3000\ufeff")
def _as_script(expression: str) -> str:
"""The caller's text as Playwright evaluates it ([B340]).
Playwright's server passes `page.evaluate`'s text through
`normalizeEvaluationExpression` and its utility script runs it with
`globalThis.eval`: the text is a SCRIPT, so a statement with its semicolon
is fine and the value is the script's completion value, and when that
value is a function it is called with the argument (`_run_callers_code`
in `server.py`). The client sends both forms down the same field without
saying which, so the function is recognised by what the script produced,
never by its shape: `(1+2)` starts with a parenthesis and is not one.
⛔ UNTIL [B340] THE TEXT WAS PUT INSIDE AN EXPRESSION, `const r = (TEXT);`,
so that its result could be called in the same pass, and an expression is
all a pair of parentheses holds: `setTimeout(...);` died with "missing ) in
parenthetical" where Playwright runs it. And the page could see that
scaffolding around the caller's code. Nothing is added now; the text is
normalised as Playwright normalises it when the client does not say
whether it is a function: trimmed as JavaScript trims, and a `function` or
`async function` DECLARATION put in parentheses, so that it is a value
rather than a statement whose completion value is undefined.
⛔ AND THE ARGUMENT IS NOT IN THE TEXT. It used to be written into the
wrapper, once as a placeholder that a `.replace` then hunted for inside the
caller's own code (`'CARGO'.length` answered 6, measured 2026-09-14). It is
a protocol argument of the call now, so there is nothing to find.
"""
text = expression.strip(_JS_WHITESPACE)
if re.match(r"(async)?\s*function(\s|\()", text):
text = "(" + text + ")"
return text
def _deserialize(value: Any) -> Any:
@@ -79,16 +104,6 @@ def _deserialize(value: Any) -> Any:
return None
def _with_argument(params: Dict) -> str:
"""The expression, callable, with the caller's argument placed in it.
<M> THE ONLY PLACE THAT BUILDS THIS. `wait_for_function` used to repeat the
two lines inline, which is how one of the two could have been fixed and the
other left alone.
"""
return _as_callable(params["expression"], _deserialize(params.get("arg")))
def _js_string(value: str) -> str:
"""A Python string as a JavaScript literal.
@@ -161,20 +176,38 @@ def _headers_array(raw) -> List[Dict[str, str]]:
return out
#: Juggler's `cause` and `internalCause` are `nsIContentPolicy` constant names
#: (`causeTypeToString` in NetworkObserver.js), so they arrive as
#: `TYPE_XMLHTTPREQUEST`, never `xmlhttprequest`. This is the table the
#: Playwright driver's ffNetworkManager uses for the same event.
_CAUSE_TO_RESOURCE_TYPE = {
"TYPE_INVALID": "other", "TYPE_OTHER": "other",
"TYPE_SCRIPT": "script", "TYPE_IMAGE": "image",
"TYPE_STYLESHEET": "stylesheet", "TYPE_OBJECT": "other",
"TYPE_DOCUMENT": "document", "TYPE_SUBDOCUMENT": "document",
"TYPE_REFRESH": "document", "TYPE_XBL": "other", "TYPE_PING": "other",
"TYPE_XMLHTTPREQUEST": "xhr", "TYPE_OBJECT_SUBREQUEST": "other",
"TYPE_DTD": "other", "TYPE_FONT": "font", "TYPE_MEDIA": "media",
"TYPE_WEBSOCKET": "websocket", "TYPE_CSP_REPORT": "other",
"TYPE_XSLT": "other", "TYPE_BEACON": "other", "TYPE_FETCH": "fetch",
"TYPE_IMAGESET": "image", "TYPE_WEB_MANIFEST": "manifest",
}
_INTERNAL_CAUSE_TO_RESOURCE_TYPE = {
"TYPE_INTERNAL_EVENTSOURCE": "eventsource",
}
def _resource_type(params: Dict) -> str:
"""⛔ Juggler says `cause`, Playwright says `resourceType`, and the two
vocabularies only partly overlap. An unmapped cause becomes `other`, which
is what upstream does too - guessing a nicer name would make
`request.resource_type` disagree with itself between the two transports."""
cause = (params.get("cause") or params.get("internalCause") or "").lower()
return {
"document": "document", "subdocument": "document",
"stylesheet": "stylesheet", "script": "script",
"image": "image", "imageset": "image",
"font": "font", "media": "media",
"xmlhttprequest": "xhr", "fetch": "fetch",
"websocket": "websocket", "beacon": "other",
}.get(cause, "other")
"""⛔ Juggler says `cause`, Playwright says `resourceType`. The cause is
the `nsIContentPolicy` constant's NAME, `TYPE_DOCUMENT`; this table used
to be keyed by `document`, so every request came out `other` - a page
load, a fetch and an XHR alike. An unmapped cause is still `other`, as
in the driver, so `request.resource_type` agrees across transports."""
internal = params.get("internalCause") or ""
cause = params.get("cause") or ""
return (_INTERNAL_CAUSE_TO_RESOURCE_TYPE.get(internal)
or _CAUSE_TO_RESOURCE_TYPE.get(cause)
or "other")
def _button(name: Optional[str]) -> int:
@@ -1,142 +0,0 @@
"""Writing the profile a Firefox launch is given, and reading back what it is.
⛔ Leaves, like the ones in `_marshal`: none of them mentions a dispatcher.
What they have in common is a different subject - a directory on disk and the
`user.js` inside it - which is why they are not in the same module. One
`_helpers.py` holding both would be the bucket every project grows and nobody
can name.
Re-exported from `server.py`: `tests/gates/prefs_byte_parity.py` and the
transport tests import `_write_user_js`, `_host_of` and `_domain_matches` from
there.
"""
from __future__ import annotations
import json
import pathlib
import shutil
from typing import Any, Dict, Optional
def _remove_profile(directory: str) -> None:
"""Take away a profile WE created. Never one the caller named.
⛔ IT MUST NOT RAISE. This runs while the session is already going away,
and on Windows a file can still be held for a moment after the process that
owned it exits. A profile left behind is a few dozen megabytes; an
exception here would be a shutdown that fails for a reason nobody cares
about, on a path the caller has already stopped watching.
"""
shutil.rmtree(directory, ignore_errors=True)
def _write_user_js(profile_dir: str, prefs: Dict) -> int:
"""The prefs, into the profile, BEFORE the browser starts.
⛔ WITHOUT THIS THE PYTHON PATH LAUNCHES A BROWSER THAT IS NOT THE PRODUCT,
and it does so silently. Two hundred prefs arrive in `firefoxUserPrefs` on
every `launch`, and the first draft of this server threw them away and
started Firefox on an empty temporary profile. Everything worked - pages
loaded, clicks landed, the tests were green - and every stealth declaration
the package exists to make was simply absent.
It was caught by a closed shadow root, of all things: the engine patch that
lets a locator reach inside one is gated on `StealthEngineActive()`, which
is a pref. The same probe found the root through `_juggler` directly and
lost it through the public API, and the only difference between those two
arms was who wrote the profile. A gate for a completely different feature
is what made the absence visible; nothing was checking for it directly.
⛔ AND THEY ARE WRITTEN, NOT SENT. Our fork already removed prefs from the
protocol - `Browser.enable` does not accept them any more - because a
browser configured on the second launch is a browser that was wrong on the
first. This mirrors what the driver's `defaultArgs` does, in Python.
⛔ Gecko HAS NO FLOAT PREF TYPE: a fraction must be written as a STRING, or
the parser fails on that line and IGNORES EVERY LINE AFTER IT. That is not
a hypothetical - `ui.textScaleFactor` written as a number once killed the
browser on the second context, and the failure looked nothing like a prefs
problem.
"""
import os
lines = []
# ⛔ INSERTION ORDER, NOT SORTED. The driver uses `Object.keys()`, and the
# two writers have to agree BYTE FOR BYTE - sorting produces a file that is
# equally correct and not identical. Caught by
# `tests/gates/prefs_byte_parity.py` on its very first real run, which is
# the whole argument for keeping a judge around.
for name in prefs:
value = prefs[name]
if isinstance(value, bool):
rendered = "true" if value else "false"
elif isinstance(value, int):
rendered = str(value)
elif isinstance(value, float):
# ⛔ A string, deliberately. See the docstring.
rendered = json.dumps(str(value))
else:
rendered = json.dumps(str(value))
lines.append('user_pref(%s, %s);' % (json.dumps(name), rendered))
os.makedirs(profile_dir, exist_ok=True)
# ⛔ NO HEADER COMMENT, and no sorting either. The driver writes neither,
# and this file has to match the driver's BYTE FOR BYTE - that is the
# criterion item 1 was written with. A header is one line of difference in
# a comparison whose whole value is that it finds differences.
body = "\n".join(lines) + "\n"
# ⛔ `write_bytes`: on Windows a text-mode write translates every newline,
# and a prefs file is read by the browser, not by git.
with open(os.path.join(profile_dir, "user.js"), "wb") as handle:
handle.write(body.encode("utf-8"))
return len(lines)
def _read_version(executable: str) -> str:
"""The base version, from `application.ini` next to the binary.
⛔ Read, never assumed: this project has three separate incidents where a
folder name or a guess about the version sent a whole evening of
measurements against the wrong build.
"""
ini = pathlib.Path(executable).parent / "application.ini"
try:
for line in ini.read_text(encoding="utf-8",
errors="replace").splitlines():
if line.startswith("Version="):
return line.split("=", 1)[1].strip()
except OSError:
pass
return "0.0"
def _only_set(params: Dict) -> Dict:
"""The parameters that were actually given, with the absent ones REMOVED.
⛔ IN A CLOSED-WORLD SCHEMA, `null` AND ABSENT ARE DIFFERENT ANSWERS.
Juggler validates every field it is handed: an Optional that arrives as
`null` is not "not provided", it is a value of the wrong type, and the
command is REJECTED at runtime with `Object "<root>.clip" is undefined,
but has some scheme`. Measured on 2026-08-28 on `Page.screenshot`, whose
clip and quality are both optional and were both being sent as null.
⛔ AND THIS IS NOT DONE INSIDE `Connection.send`, tempting as that is:
some commands mean something BY sending null. `Browser.setGeolocationOverride`
with `geolocation: null` CLEARS the override, and stripping it there would
turn "stop pretending to be somewhere" into "do nothing".
"""
return {k: v for k, v in params.items() if v is not None}
def _host_of(url: str) -> str:
"""The host of a url, without importing a parser for three characters."""
without_scheme = url.split("://", 1)[-1]
return without_scheme.split("/", 1)[0].split(":", 1)[0].lower()
def _domain_matches(cookie_domain: str, host: str) -> bool:
"""⛔ A LEADING DOT MEANS "AND EVERY SUBDOMAIN", and dropping it turns a
site-wide cookie into one that matches nothing. Comparing the two strings
directly is the version that looks right and returns an empty list."""
domain = (cookie_domain or "").lstrip(".").lower()
if not domain or not host:
return False
return host == domain or host.endswith("." + domain)
Loaded 100 of 313 files, more files were not shown because too many files have changed in this diff. Show more