Compare commits

...
Author SHA1 Message Date
feder-crandClaude Sonnet 5.5 4ea36371f5 ci: e2e.yml runs the Control+A e2e on Windows, on the published engine, as a job of its own (dispatchable alone with only=windows-control-a)
tests/test_control_a_selects_all_in_a_field_e2e.py (5 ways to press the shortcut x an <input> and a <textarea>, in-process and served to the stock
client) is red on the keyboard that held Shift for the capital A and was measured on Linux; the keyboard of a user is Windows. The new job
installs the wrapper (which pins the core of the release), fetches the published engine and runs that file on windows-latest with bash as the
shell, behind the same core-on-index gate as the Linux job: skipped with the reason in the summary until the core is on the index. The
workflow_dispatch input `only` lets it run alone (`windows-control-a`) without the 40 minutes of the Linux job.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:41:31 +01:00
feder-crandClaude Sonnet 5.5 9b0f474bc8 tests: Control+A selects all in an input and a textarea, in-process and served to the stock client (e2e, red on the keyboard that held Shift for the capital A)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:41:30 +01:00
feder-crandClaude Sonnet 5.5 97ba055d77 Release 0.51.0: the CHANGELOG line of the process tests says only what is proven
Markdown only. The line that came with the end-to-end process tests carried a count of red runs and a cause of the extra
process that nothing saved; it now says that these are tests only and what they ask for.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:22:27 +01:00
feder-crandClaude Opus 5.5 54b2f26c69 tests: the popup process case runs its own browser in a thread of its own
The e2e of the previous commit failed at setup: the module's browser of the
matrix keeps a sync client open in the test's thread, and a second sync client
refuses to start inside its loop ("Sync API inside the asyncio loop"). The case
now opens its quiet browser in a thread with no loop and hands back its result
or its error. Same count of tests (34), still no skip on any system.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:04:14 +01:00
feder-crandClaude Opus 5.5 6d23f75229 tests: the popup process case has a browser that starts no process by itself, and asks by name on Linux
test_the_other_site_popup_runs_in_another_process counted every content process
between two reads, so a process the browser starts by itself (the pool refill,
the preloaded New Tab page and, in some countries, a process for a Mozilla
site) was taken for the popup's doing. It now has a browser of its own, on each
transport, with no preallocated processes and no preloaded New Tab page
(test-only prefs), so the count between two reads is the popup's. On Linux it
also asks by name that one of the new processes is the process of localhost.

It still runs on Windows, with no skip: the required suite wrapper.e2e.page
collects this file on both systems with an exact count, which is unchanged (34).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:01:53 +01:00
feder-crandClaude Sonnet 5.5 beff30e822 tests: ask for the processes of a site by its name, never count between two reads
The e2e tests that looked at content processes compared the set of
"Isolated Web Co" processes before and after an action. The browser starts
processes of its own: the pool refill, and a process for a Mozilla site
(webIsolated=https://mozgcp.net) that the New Tab page starts about a second
after its own, with any page. Under load it was born between the two reads:
the same-site control was red in 14 of 30 runs of the whole e2e suite
([P] -> [P, P2]), the cross-site test could pass on that process alone, and
the service-worker test could read it as a process left behind.

With the test-only pref fission.processSiteNames a content process that hosts
a site is named by that site (http://a.test^u on Linux, cut at 15
characters). tests/_processes.py now returns the processes of one site by that
name; the bench and the service-worker test use it. Linux only, as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:01:13 +01:00
feder-crandClaude Sonnet 5.5 1382a83540 tests: the fake pip of the wait test is a regular package, so the pip of the environment cannot shadow it
CI (runs 43196645121, 43196645144): 2 tests of the wait for the index failed on every Python of both systems. The shim was a directory with a
__main__.py and no __init__.py: a namespace package, which loses to the regular package `pip` of an environment that has one (a local uv venv
has none, so it passed there). The real pip ran, said "No matching distribution" for 9.9.9 and the shim was called 0 times. Reproduced in a venv with pip;
red without the __init__.py, green with it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:00:36 +01:00
feder-crandClaude Sonnet 5.5 299fc9f5da user-install: the wait asks pip, not the JSON page of the index, and fails saying what is missing; the upgrade test installs the version its listing named
Ledger #476 of 0.50.1: the Linux job failed in test_upgrade_e2e ("the upgrade did not move the wrapper", '0.49.1' != '0.49.1') three
minutes after the upload. The step that waits for the index had asked the per-version JSON endpoint, which answered; the listing of
`pip index versions` had 0.50.1; the `pip install --upgrade` that followed was still served the 0.49.1 page.

The wait now runs `pip download --no-deps --no-cache-dir invisible-playwright==X` (the client and the index the install uses), for at most
ten minutes, and ends in "::error::the index does not have X yet, after N minutes" instead of a warning and a run that fails later. The
upgrade test takes previous and latest from one listing and installs `WRAPPER==latest`. Four unit tests run the script of the step with a
pip that fails until its Nth call; the core's install_job gate still passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:00:36 +01:00
feder-crandClaude Sonnet 5.5 fe5cb50ed3 Release 0.51.0: the CHANGELOG and the README say only what is proven (counter: what the package refuses and whose repository counts; the real name of the async class; the popup numbers of the register; Windows memory only; addBinding out)
Markdown only. Following the fact check of the release texts: the launch counter is refused by the package's launcher and server
(not "not optional" for the engine alone) and counted in the engine's repository; preload_newtab names the async class by its real
path and keeps only the Windows numbers that have a saved run, with the engine they were taken on; the protocol mirror line about
Page.addBinding is out (not shown for the pinned engine); the differences section no longer claims a comparison run nobody saved;
the popup known issue states where, with which client, on which engines and with how much load it was seen, with the numbers of the
register, and that the correction is in 0.51.1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:49:06 +01:00
feder-crandClaude Sonnet 5.5 2d1bc68b26 tests: the HTTP/3 test server finds a port that TCP and UDP both bind where the system's picks fall in a refused UDP range
wrapper.e2e.web on the Windows runner (republish run 43230437094) failed three tests with "no port free for both TCP and UDP",
and the pre-push failed the same way on a work machine: Windows hands out ephemeral TCP ports in sequence and keeps excluded
ranges of a hundred ports for UDP in the same zone, so the old loop (fifty times the system's pick) got fifty consecutive numbers
inside one refused range. The first try is still the system's pick; the others are drawn at random below the dynamic range, as
the witness already does (same constants), and the refusals are named in the error.

Two tests with a fake socket layer (TCP picks 50000, 50001, ...; UDP refuses 50000-50199): the old loop is red on it, this one
finds a number outside the range; and a server that can bind nothing says so after a bounded number of tries. wrapper.unit.udp
goes from 219 to 221 tests (ci/required-suites.json).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:12:49 +01:00
feder-crandClaude Sonnet 5.5 3b594b85ed tests: the two tests that ask the resolver trap from the test process say that the test stands for the browser
Since fc10e257ca the trap counts only the questions of a browser process, found by the process that holds the socket in
/proc/net. That is only possible on Linux; on Windows every question counts, so the pre-push (Windows) stayed green
while test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer failed on Linux (republish run
43230437094, wrapper.unit.udp/linux: 1 failed, 218 passed): the test asks from its own python, which is not a browser,
and the question went to `foreign`. The same holds for the resolv.conf test of the root legs.

Both tests now pass is_browser=lambda pid: True. The trap itself is unchanged, so the realness leg judges the same code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:58:21 +01:00
feder-crandClaude Sonnet 5.5 8d1356cb69 Release 0.51.0: the served launch cannot turn the launch counter off (a client's firefoxUserPrefs, bare or marked, are refused with the core's message); the history says it is no longer possible
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:41:19 +01:00
feder-crandClaude Sonnet 5.5 0a5961270a Release 0.51.0: the README says what the launch counter is and how to turn it off; the CHANGELOG says what is known to be wrong (popups opened without a route, as measured)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:30:14 +01:00
feder-cr 07b7b74e08 Release 0.51.0: engine firefox-63, pin invisible-core 63.66.0; CHANGELOG for the UDP line 2026-11-12 14:00:10 +01:00
feder-crandClaude Opus 5.5 710ee498ba juggler: an early download finish lives only as long as it can be read
The review of 6a50ad1 found three cases where an entry of _finished_early
stayed for the life of the browser: (a) a download announced while its
context was already closed, whose finish came after; (b) a finish after the
client released the artifact; (c) a finish of a uuid never announced.

The browser now keeps, per announced download, the context it belongs to,
until its finish or the end of that context. A finish whose download was
announced and whose artifact is gone writes nothing; only a finish of a
download not announced yet leaves an early entry, and those are bounded (64,
the oldest dropped first). The end of a context forgets its downloads that
never finished.

Tests, red on 6a50ad1 (4 of 10): (e) gone context, (f) released artifact,
(g) never-announced finishes are bounded, (h) the end of a context forgets.

NOT proven: that the engine ever sends a finish after the end of a context,
or a finish before the announcement. On one connection Juggler says a
download's creation before its end (TargetRegistry.js interceptDownloadRequest
then onDownloadComplete), so the early path is defensive. The e2e of tiny
downloads is a proof of use, not of the order; its docstring says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:54:42 +01:00
feder-crandClaude Sonnet 5.5 9883d3f455 juggler: a download that finished before it was announced is finished
BrowserDispatcher._on_download_finished keeps the error of a download whose
artifact does not exist yet; a successful download has no error (None), and
_on_download_created popped it with a None default and tested `is not None`,
so the artifact was never marked finished and save_as, path and failure
waited forever. A module-level sentinel tells "nothing recorded" from
"finished with no error". The entry is also popped before the
unknown-context early return, so it no longer stays in the dict.

Tests: unit file (red on the old code for the success and the gone-context
cases) and a served-browser e2e with ten 300-byte and ten 1-byte downloads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:54:42 +01:00
feder-cr 7c79ba1ed4 Merge remote-tracking branch 'origin/main' into release/0.51.0-prep (#477, #478, #480) 2026-11-12 13:54:41 +01:00
feder-crandClaude Sonnet 5.5 fc10e257ca tests: the resolver trap counts the BROWSER (a browser process and what it starts), not the test process nor the core it runs: the core asks github.com for the latest GeoIP tag as root, the test says the browser asked
Measured on Linux: a process named firefox and its child counted 20 of 20 each; the test's own python and an orphan of the same user foreign 20 of 20 each.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:50:37 +01:00
feder-crandClaude Sonnet 5.5 78277565f5 tests: the resolver trap counts the questions of the processes of the test (the socket's inode, the process that holds it, its parents), not of a user; a question of any other process is listed with its pid and command
Runs 43188313516 and 43211837926: on the runner the agent of the runner, as root like the browser under sudo, asks for github.com, api.github.com and its orchestrator
through the trap's /etc/resolv.conf, and a user filter cannot tell it from the browser (6 realness tests red). Measured on Linux, 40 questions of a descendant and
40 of an orphan process of the same user: 40 counted, 40 foreign, each with its pid and command. One whose process cannot be traced is judged by its user, one whose
socket is gone counts as the browser's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:38:35 +01:00
feder-crandClaude Sonnet 5.5 0a0d0d689d tests: the sandbox leg finds the tab processes (forked by the fork server, their argv has no 'tab' at the end): the kind comes from the last word, else from the Name in /proc/<pid>/status
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:14:07 +01:00
feder-crandClaude Sonnet 5.5 ff02f112fe ci: wrapper.unit.udp counts the three tests of the witness port pick (198)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:45:34 +01:00
feder-crandClaude Opus 5.5 016eccab9e tests: the UDP witness binds TCP and UDP on one number even where the system's picks fall in a refused UDP range
Witness("127.0.0.1") failed with WinError 10013 in three unit tests of
wrapper.unit.udp on a Windows work machine, while the push before had passed
them. Windows hands out ephemeral TCP ports in sequence and keeps excluded
ranges of a hundred ports for UDP in the same zone: the witness asked the
system for a TCP port twenty times, got twenty consecutive numbers inside one
UDP range, and gave up.

Now each try binds TCP and then UDP on the same number, and if either is
refused both are released and another number is tried: the first is the
system's own pick, the others are drawn at random below both Windows'
dynamic range and Linux's ephemeral range, so they are not the next of a
sequence. 200 tries at most, then an error that names the address and the
last refusals. A port asked for is tried once and its refusal raised.

Test, red on the old code (2 of 3): a fake socket layer whose TCP picks are
sequential and whose UDP refuses 50000-50199. Real sockets on that machine,
20 runs of the witness tests each: old 19 of 20 green, new 20 of 20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:44:58 +01:00
feder-crandClaude Sonnet 5.5 db5c7ef565 ci: the preload_newtab e2e moves to wrapper.e2e.udp (seen green on Windows, 10 runs of 10): udp 43, exit 7
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:33:18 +01:00
feder-crandClaude Sonnet 5.5 5459a6b59e ci: wrapper.e2e.udp.sandbox (Linux, a normal user, the browser's sandbox on): the socket process and a tab process must have a seccomp filter, plus the three situations of the UDP line (a proxy with UDP, no proxy, a proxy without UDP with the ICE name by DoH)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:11:56 +01:00
feder-crandClaude Sonnet 5.5 483f9af50a tests: the constructor signature knows preload_newtab; the witness takes TCP first (Windows excluded ranges); the preload_newtab e2e (seen green as root on Linux) joins wrapper.e2e.udp.exit (9)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:00:55 +01:00
feder-crandClaude Sonnet 5.5 1d33f56100 ci: wrapper.unit.udp counts the three tests of preload_newtab (195); its e2e is in no suite until it has been seen green
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:55:51 +01:00
Federico EliaandClaude Sonnet 5.5 285e3ba93e ci: never cancel a run of main, one run per pull request commit, and test it (#477)
e2e.yml and tests.yml already ran once per commit of a pull request (push is
filtered to main, pull_request to PRs against main), but their concurrency
group was keyed on the ref and cancelled in progress everywhere. For a push to
main the ref is always refs/heads/main, so the next push cancelled the e2e
run of the commit before it, and scripts/e2e_is_green.py refuses a release
whose e2e check-run is `cancelled`. The group is now keyed on the pull request
number and cancels only on pull_request; every other event gets a group
unique to the run, so nothing on main is cancelled or replaced while pending.

user-install.yml had a group keyed on the ref that cancelled its own weekly
run when a manual one started on main; it follows the same rule. publish-wiki
no longer cancels a publish in progress. Triggers, workflow and job names
(`e2e`, `e2e (linux, xvfb)`, `gate`) are unchanged.

tests/test_ci_runs_once_per_commit.py pins the triggers the release reads, the
cancel rule and the hunt cap (max-parallel <= 8), with known-bad inputs for
each checker. It reads the workflows with a small parser because PyYAML is
not a dependency of this package.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:55:02 +01:00
feder-crandClaude Sonnet 5.5 966e2d6a8b launcher: preload_newtab, the option of the core that turns off the preloaded New Tab page
InvisiblePlaywright(preload_newtab=...) (sync, async and launch_server)
hands the core's option of the same name over, only when it is not None:
a wrapper paired with a core that does not know it cannot meet a
TypeError for a caller who never used it. None keeps the retail's
behaviour; False writes browser.newtab.preload false (no privileged-about
process); True says the retail's value aloud; a pref in extra_prefs wins.

Tests: the kwarg reaches the core only when asked and is a parameter of
every entry point; the e2e reads the process types from the engine's log
(MOZ_LOG=Process:5): privilegedabout exists by default and is absent with
the option, on every platform.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:54:21 +01:00
feder-crandClaude Sonnet 5.5 d13a9442c5 tests: a loss is not a drop - behind a proxy that cannot carry the UDP of a PeerConnection, nothing of the browser reaches a witness direct (suite wrapper.e2e.udp.exit)
The e2e that check 'no srflx' cannot tell the fail-closed rule from a leak: at an address nothing routes a datagram sent direct arrives nowhere, exactly as a dropped one.
A witness (_witness.py: a STUN server and a TCP listener at 198.51.100.10, held on lo, reachable by the browser directly) hears who contacts it, and the gateways leave from ANOTHER
documentation address (the exit, 198.51.100.9; the test gateway's TCP now leaves from it too, opt-in: tcp_from_exit). In each fail-closed scenario - a SOCKS5 proxy that refuses UDP, one whose UDP
leaves from another address, one whose relay never answers, an HTTP proxy - the witness hears no datagram and no connection from a source that is not the exit; a send direct is red. The controls
that make the green mean something: the same page with no proxy IS heard by the witness (datagram and connection), and behind a coherent gateway the witness hears the exit only.
Proved in the container on the giro 3 Linux binary (green, 7 tests of the suite). The witness and the gateway's source binding have unit tests (192). Counts: wrapper.e2e.udp.exit 7, wrapper.unit.udp 192.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:42:35 +01:00
feder-cr 2effeb1594 Merge remote-tracking branch 'origin/main' into udp/wrapper-r6 (0.50.1 notes, no_wait_after) 2026-11-12 11:36:56 +01:00
Federico EliaandClaude Fable 5.2 15d7608867 tests: no_wait_after is judged on the order of events, not on seconds (#478)
The test said the click must come back in under 2.5 s while /slow slept 3 s.
That measured the runner: on a loaded one the click alone took longer (2 of 30
runs of the suite, every run on one CPU) with nothing wrong in the product.

/slow is now an answer the server holds until the test lets it go. The click
with no_wait_after=True must come back while the answer is still held (the
order is: click returned, then answered; the url is still the old one). A new
test holds the other half: a plain click on the same link does not come back
until the answer is given, and returns on the new page.

Known-bad input, run before trusting it: the same test with no_wait_after
removed from the click is red on the order (answered, then click returned).

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:32:43 +01:00
Federico EliaandClaude Fable 5.2 2d9cf3a82f CHANGELOG 0.50.1: the known differences from stock Playwright, and two fixes the entry had left out (#480)
Under [0.50.1], after the record of its publication:
- Fixed: a popup reaches the client as with Playwright's own Firefox (no limit
  of time, the destination's url, load reachable), and the opener's download
  event comes after the popup's page event.
- Known differences from stock Playwright, each with its measurement: the url
  of a popup that turns into a download, the url of a frame of another site at
  DOMContentLoaded, the longer click of the library client, and back/forward
  restoring the page from the back-forward cache.

Documentation only: no published byte changes.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:32:17 +01:00
feder-crandClaude Sonnet 5.5 05420d83ce tests: the resolver trap counts the questions of the user that runs the test, by the owner of the socket (/proc/net), not by name; unit.udp 189
Run 43188313516: on a runner the agent of the runner asks for github.com, api.github.com and its orchestrator through the /etc/resolv.conf the trap
rewrites, and the trap blamed the browser (6 realness tests and 1 DoH test). A question whose socket belongs to another user is answered and
listed in trap.foreign, not counted. The owner is read on receipt, before the answer: measured on Linux, 3000 questions that wait for their answer,
0 unreadable; one that cannot be read counts as the browser's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:21:47 +01:00
feder-crandClaude Sonnet 5.5 03d18c853d tests: the DoH session built by hand launches on a virtual display too, and a test reads every direct InvisiblePlaywright(...) of the DoH and realness files (unit.udp 181)
Run 43188313516: test_a_session_without_a_proxy_resolves_with_the_system_resolver died with "no DISPLAY environment variable specified": it builds its
session by hand (not through _launch) and was not covered. The new test parses the files of the two suites and fails on a construction without headless=.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:17:40 +01:00
feder-cr 23b17c33ef Merge remote-tracking branch 'origin/main' into udp/wrapper-r6 (the ledger of 0.50.1) 2026-11-12 11:02:12 +01:00
github-actions[bot]andfeder-cr fb888c09cf record 0.50.1 as published (#476)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-12 10:53:57 +01:00
feder-crandClaude Sonnet 5.5 3f56ac2e69 The old table test expects beacon for TYPE_BEACON, as the pinned driver says
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:43:22 +01:00
feder-crandClaude Sonnet 5.5 8621f0a5d6 request.resource_type agrees with the pinned driver: a beacon is beacon, a CSP report cspreport
The table that turns a Juggler cause into a Playwright resource type was a copy of the driver's and had gone stale: the pinned
driver (1.61, coreBundle.js ffNetworkManager) says `beacon` for TYPE_BEACON and `cspreport` for TYPE_CSP_REPORT; ours said `other`
for both. Measured on cnbc.com and scmp.com, our engine and Playwright's own Firefox side by side: the same POSTs (2 and about 8
per page) are `other` here and `beacon` on stock, so a client or a route filter that looks for beacons saw none.

Test (red on the old table): the driver's own table is read from the installed package and every cause it names must map to the
same type here; the next driver version that changes it fails the test, nothing is updated by hand.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:43:22 +01:00
feder-crandClaude Sonnet 5.5 9956adc386 tests: the chain by name keeps its walk on Windows (exit of the lab on loopback, with the pref) beside the one without the pref (wrapper.e2e.udp.exit, Linux)
d41ea7e moved the whole file to the Linux-only suite. Now the file holds two tests: the walk with an exit that is not loopback and no pref (wrapper.e2e.udp.exit, Linux, root), and the walk with the exit on 127.0.0.2 and media.peerconnection.ice.loopback (wrapper.e2e.udp, Linux and Windows). Selected by node id; wrapper.e2e.udp 41 again; the notes of the two suites say why.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:42:43 +01:00
feder-crandClaude Sonnet 5.5 72997c957c tests: three e2e modules of the UDP line are bound to the engine that carries it, as the others are
test_networkidle_through_a_served_browser_with_routes_e2e.py (red on firefox-61 and 62: its engine fix, 0972db59da, is in the 63), test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py
and test_turn_over_tcp_is_tried_for_real_e2e.py (red before the UDP line) had only pytest.mark.e2e, so the e2e job of main, which fetches the PUBLISHED engine, would run them
against it. They now carry usefixtures(the_udp_line): they skip on an older engine and run on the candidate (REVIEW-63 #14). The collected counts do not change
(21, 1, 2); the ids stay in ci/required-suites.json, and a skip on the candidate is still red there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:41:44 +01:00
feder-crandClaude Sonnet 5.5 bd853bc040 tests: the QUIC of the gateway test works on Windows: the relay leaves from the host's address, is told by its port, and a send that fails is said; unit tests (unit.udp 176)
On Windows the e2e read h2 on five visits and 'the server saw QUIC from []': the relay of the gateway sent from 127.0.0.1 to an address of its own
host (WinError 10051, nothing sends from loopback to the host's address there) in a timer that ignored every OSError, after logging the datagram as carried.

- the coherent gateway of the h3 test leaves from the host's address on every system (exit_host), and its fake STUN is bound there too (Windows sends
  neither from the host's address to loopback, 10049, nor the reverse); the relay is told from a client that came direct by the PORT it sends from
  (Gateway.exit_ports, H3Server.quic_peer_addrs); it forwards only to this host (forward_only_to): the browser's own QUIC to the Internet stays in the lab.
- Gateway._later records a send that raised (send_errors) and the report of the test shows it; the test asserts there is none.
- the relay's sockets turn SIO_UDP_CONNRESET off on Windows and a ConnectionResetError no longer ends the thread that reads.
- unit tests: a failing send is recorded and reported; a relay that leaves from the host's address reaches a server there, by a port in exit_ports and not
  one of a direct client; the fake STUN answers through it. Red on the old helpers (they have no exit_host/exit_ports/send_errors).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:28:49 +01:00
feder-crandClaude Sonnet 5.5 7a0d55f4ce tests: the DoH, stress and ICE-names e2e always launch on a virtual display (headless=True, as the UDP and realness e2e); the helper that looked at the display of the host is gone; unit tests (unit.udp 177)
A test does not behave differently by the display of the machine it runs on. Replaces the helper of 302af97.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:15:10 +01:00
feder-crandClaude Sonnet 5.5 d867282c99 tests: the chain by name reads its srflx and its relay from the page with a gateway exit that is not loopback, and the loopback pref is gone
The exit of the lab is 198.51.100.9 (documentation, RFC 5737), held on lo with ip addr add for the length of the test; nICEr accepts it as a mapped
address (nr_stun_transport_addr_check rejects only wildcard, loopback and link-local), so the product's own setting is what is under test, not a pref that
is off in production. The page must read a srflx equal to the gateway's exit and the relay candidate of the TURN server it asked.
The file moves to a suite of its own, wrapper.e2e.udp.exit (Linux only, root): adding an address to an interface needs administrator and changes the network
of the host, so the Windows suite does not collect it (a skipped test would turn the verdict red). Chain takes exit_host; the TURN helper test runs for two exits.
Red on the old code: with the 127.0.0.2 exit and no pref the test fails at 0, 65 and 130 ms; green on the giro 3 Linux binary at 130 and 0 ms (container).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:14:02 +01:00
feder-crandClaude Sonnet 5.5 302af97575 tests: the DoH, stress and ICE-names e2e ask for a virtual display on a Linux machine that has none; unit tests (unit.udp 173)
Run 43176569993: 19 of 19 of wrapper.e2e.doh on Linux died at the launch with "no DISPLAY environment variable specified". Those files launched a headed browser without a screen (the runner has none, and the suite runs under sudo). The other e2e launch with headless=True, which is a headed browser on an Xvfb the wrapper starts itself. A machine with a display, and Windows, are left as they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:09:13 +01:00
feder-cr 47725170de Merge remote-tracking branch 'origin/main' into udp/wrapper-r3-next (0.50.1 is on main)
# Conflicts:
#	src/invisible_playwright/_juggler/server.py
#	tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py
#	tests/test_popup_destinations_e2e.py
#	tests/test_popups_reach_the_client_e2e.py
2026-11-12 09:52:27 +01:00
feder-crandClaude Sonnet 5.5 d56ea298b4 tests: the comment of the first-datagram test says why the core's discovery of the exit fails in the lab (no echo service is reachable), not that a fixed time zone skips it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:51:58 +01:00
b46e5a32d3 Release 0.50.1: networkidle on a reused page and on a routed served browser, a page handed over when ready (pin invisible-core 62.65.0) (#455)
* docs: the agent links and the command name the repo as it is now

Two things were broken for a reader on main, not one.

Thirteen links pointed at github.com/feder-cr/AIHawk. GitHub redirects a
NAME to the OBJECT that carried it, not to the content: after the September
swaps that name belongs to invisible_dots, which has seven wiki pages, so
AIHawk/wiki/<page> lands on its wiki Home. It answers 200 with different
content, which means a reader who clicks does not find the page and a search
engine sees a soft-404 across about 150 indexed URLs.

Seven occurrences said `uvx aihawk`, a command that does not exist. One sat
in a front-matter description, which is the snippet search engines show, and
one in a block meant to be copied: `claude mcp add stealth -- uvx aihawk`.
The command is invisible-playwright-mcp, on PyPI at 0.70.16.

All eight link targets were checked one by one and resolve to themselves with
the page title, no redirect.

Three things stay as they are, which only reading them showed. The
`pip install invisible-playwright` line matches what this engine's own README
teaches for the library, so the page is consistent rather than broken.
CHANGELOG.md keeps the old name because a changelog entry says what was true
then. And the fixture in scripts/sync_article_pixels.py keeps it because it is
the deliberate wrong case, a pixel for ANOTHER repo.

One sentence went away instead of being renamed: "shipped inside AIHawk" made
sense when AIHawk was the larger product containing the server. The server and
the repository are now the same thing, so "shipped inside itself" was circular.

(cherry picked from commit d9c8e46dce)

* test: the docs name the MCP server's repository and command as they are now

feder-cr/AIHawk now leads to an unrelated repository and answers 200, which no
link checker reports; `uvx aihawk` does not exist. The README and docs/ are
read for both.

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

* tests: the Fission bench counts the processes that host a site, not every new content process

test_same_site_other_port_stays_in_process was red on the e2e of the 0.50.0 commit ("a same-site frame
started a process: [13443]"): the bench counted every `-contentproc ... tab` pid, and the engine starts a
preallocated content process to refill its pool whenever it gets to it. On Linux the engine names a content
process by its remote type (ContentChild::SetProcessName, prctl PR_SET_NAME): "Isolated Web Co" once it
hosts a site of strategy 1, "Web Content" while preallocated. Measured on firefox-62: a cross-site frame
renames a preallocated process and a new "Web Content" refills the pool; a same-site frame changes neither.
The two tests that count processes skip off Linux, where no process carries a name.

Unit test with the measured processes: 3 red on the old bench, 3 green here. e2e on firefox-62 (candidate
#6, Linux): the bench file 17 passed; the two counting tests 15 of 15 runs green.

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

* tests: a closed context is checked for the processes of its sites, not for every content process

test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process was red on the e2e of the 0.50.0
tag ([2, 2, 2, 5, 5], 5 <= 2). Measured on firefox-62 (Linux), the test's own scenario 10 times with every
process named: no "Isolated Web Co" left after any close; the 3 more are "Web Content", the engine's pool of
preallocated processes filling up behind the closed contexts (5 runs of 10, new pids each time). Not a leak:
the count read the refill.

The helper of the bench moves to tests/_processes.py and both tests use it. The context test counts the
processes that host a site: at least one while the page is open (or the count proves nothing), none a few
seconds after `close` answers (the engine waits for them inside close and kills the ones that stay). Off
Linux it skips, as the bench's two counting tests do: no other system names the process.

Unit tests (tests/unit/test_processes_counts_sites.py) from the measured processes, the closed-context case
included. e2e on firefox-62 (candidate #6, Linux): the context test 10 of 10; run_e2e.py on the two files and
the unit test 18 passed. The old counter, same scenario: 5 of 10 runs would fail.

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

* Release 0.50.1: 0.50.0 with the process-counting e2e corrected (0.50.0 never reached the index)

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

* tests: the same-site control puts its frame in the shown page; CHANGELOG: 0.50.0's entry is 0.50.1's

The e2e of #451 saw a new "Isolated Web Co" once after a.test/plain -> a.test/same-site ([10878] -> [10878,
11208]). Not a process of an earlier test: it was created after the first read and only this worker's
descendants are counted. It is the top-level navigation: when the old document may enter the back-forward
cache, the browsing context is replaced (mReplaceBrowsingContext, dom/ipc/ProcessIsolation.cpp) and the new
one may be placed in another process of the same site (dom.ipc.processCount.webIsolated = 4). Measured on
firefox-62 (candidate #6, Linux): 0 of 30 runs alone (bfcache on and off), 0 of 57 under 4 workers. The test
was written for the frame, so the frame is now added to the page already shown and the top never navigates:
20 of 20 runs green.

0.50.0 never reached the index, so the changelog gate refused its heading; its entry now opens 0.50.1.

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

* tests: networkidle through a served browser whose context routes every request, on a reused page

launch_server() plus a stock Playwright client, a context route that aborts image/font/media and continues the rest, a
page with sendBeacon, the same font twice, a frame of another site, a worker, redirects, requests the page cancels while a
slow route decides, 100 requests at once, and a slow client that answers concurrently (async). Every shape reaches
networkidle on firefox-62; one page reused for twelve addresses too. The leak that tf-fetch meets on real sites needs
end events the engine loses, which no local page produces: its deterministic red/green is in the core
(tests/test_networkidle_on_a_reused_page.py of invisible-core); this file guards the remote path end to end.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 47182f0cd85fea08fc45e36f1c91d2d570722f14)
(cherry picked from commit e46f2dcf3eb361e6af0fedcdf6e1189f0ac330b6)

* server: the answer to a request the browser has already closed is not an error (Cannot find request), as stock sendMayFail

A page cancels requests while a route is deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with
its document, the favicon of the page a goto just left). The engine takes the request out of its held set at once and the
late continue/abort/fulfill meets "Cannot find request" or NS_BINDING_ABORTED. Stock Playwright sends the interception
commands as may-fail and tells the client nothing; ours passed the error up, the client kept it as the error of the whole
connection and raised it on the NEXT route command, which was then never sent: its request stayed held in the engine, its
handler failed too, and so on down the page. Seen on a real news page: six held requests in a row, one a beacon, and
networkidle never came.

RouteDispatcher._send now treats "Cannot find request" and a closed target as done (still disposed); any other protocol
error still reaches the client.

Tests: the e2e with a plain handler (no try) on a page that removes an iframe whose requests are held (red before:
networkidle never; green after), and a static guard that every op of RouteDispatcher goes through _send and that _send
swallows exactly those two. The same defect was found a month earlier by richardpowellus (#351), with the favicon of the
previous page: his test is added in the next commit.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the stock Playwright client is required by the networkidle e2e (explicit failure, never a skip); the dev extra pins it

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 91223226f5bba25edff9af0e8b1fd6b5bfea2227)
(cherry picked from commit 612b18c02b95e9b5833d62b6595d4a0ff324aac2)

* tests: answering a route the next navigation already aborted does not raise (the case of #351: the favicon of the page just left)

Sixty sequential routed gotos on a loopback page: 4-12 of them failed on the old server, every failing continue_ being
the previous document's favicon, aborted by the next navigation while the route sat with the handler. Red on main (in-process
path), green with the fix of RouteDispatcher._send.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Release 0.50.1: pin invisible-core 62.64.0; CHANGELOG for the networkidle fixes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit e63ef8e61ea42e7f8df7c1bde206f3bf86fc18f7)

* A route answer the engine refuses is the engine's business, whatever its wording

The server took one wording ("Cannot find request") of an answer to a closed request as done and passed every other
protocol error up to the client. The engine also says "NS_BINDING_ABORTED
[nsIInterceptedChannel.resetInterceptionWithURI]" when the channel was cancelled while the answer was on its way: the
same event, and the client kept it as the error of the connection and raised it on its next route command.

Stock Playwright sends the three interception commands as may-fail and tells the client nothing, whatever the engine
says. So does RouteDispatcher._send now: every ProtocolError is swallowed, the route is disposed after it.

Tests: the static guard no longer allows a re-raise inside the handlers; a unit test feeds three wordings (red on the
old code for two of them).

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

* tests: the descriptors of the spawn are asserted by running it, not by reading the core's source

test_the_spawn_keeps_the_two_hardwired_descriptors asserted that the source of the core's _spawn_posix contains
`pass_fds=(its_read, its_write, 3, 4)`. Core 62.64.0 starts the engine with posix_spawn and file actions, so the words are gone
and the test failed on every Linux unit suite although the behaviour is the same (and better).

The test now runs the spawn: a parent with nothing open on 3 and 4 and its pipes far from them launches a program that reads
fd 3 and answers on fd 4 (the contract of nsRemoteDebuggingPipe.cpp), and the answer must come back and the child must hold no
descriptor above 4 of the parent's. Same shape as the core's own test
(test_the_pipe_of_the_engine_reaches_its_fixed_descriptors). No skip: the file is already POSIX-only.

The other tests of the file do not read source text (checked: no getsource/inspect/read_text left).
Ran the parent program on Linux with core 62.64.0 (image tetra-invisible:run1b-final): pong:ping:0.

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

* The page dispatcher waits for Page.ready before the page is handed over (needs invisible-core with Lifecycle.wait_for_page_ready)

Same defect and fix as in the core's page (see the core commit): a goto sent right after new_page could meet the page's initial about:blank.
The pin of invisible-core moves with the core release that carries wait_for_page_ready.

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

* Pin invisible-core==62.65.0 (a page handed over when the engine says it is ready); changelog

The core that carries Lifecycle.wait_for_page_ready is invisible-core 62.65.0 (draft PR invisible_core#238), not on the index yet:
the pin check of this push is skipped on purpose (INVISIBLE_PIN_CHECK=skip).

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

* tests: the stand-in engine of the registry test says Page.ready, as the real one does (the page is handed over on it)

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

* tests: new_page and a popup are handed over only when the engine says Page.ready (red without the wait in PageDispatcher, green with it)

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

* A page is built at once and announced when the engine says Page.ready (the wait inside the constructor held a popup's first request behind a page that did not exist yet, and lost its commit and load)

- PageDispatcher no longer waits in __init__; wait_until_ready() is called by the adoption between the construction and the announcement
  (context 'page' event, newPage answer). A detach while waiting ends the wait; a page that is not ready in time is disposed.
- The main frame's initializer carries what the lifecycle already knows (url, name, load states), as every other frame's does.
- Tests: unit (a popup exists and listens while it waits; what it does before its ready reaches its frame; red on 6a60dce) and e2e
  (a popup of a link, noopener or window.open reaches an in-process and a stock client of a served browser within 2 s, with and
  without a context route; 15 of 16 red on 6a60dce, 16 green).

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

* tests: the stand-in pages say wait_until_ready; the popup e2e reaches the stock client as the other served tests do

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

* tests: the popup reaches the client from another site too (a link, noopener, window.open: 16 more cases, in-process and through a served browser)

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

* A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready

- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
  destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
  (newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
  (BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
  engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
  the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
  address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
  then) in-process and through a served browser: the 25 s ones red on b09d620.

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

* A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it

- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

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

* A popup tells its listeners the load it reached before it was announced; an unannounced frame has no address of its own

- The popup is announced when the engine says Page.ready, which is when its document commits, so its domcontentloaded and load may be said
  before the client has the page: page.on('load') registered in the handler of the page event never fired (Playwright's does, measured by
  the independent run: destinations of 4 s and 25 s). FrameDispatcher.emit records those two states while the page is not announced and
  PageDispatcher.announce says them again right after the page event, in their order and under one lock; the first time they already set
  the state wait_for_load_state reads, so it returns at once. Only popups: a requested page is announced as before.
- The main frame is created with the address the lifecycle knows, '' if it has committed nothing (an attachment's empty tab), not
  about:blank: Playwright says '' there.
- Tests: unit (the two states after the page event, in order; red on 2f153c7); e2e: a listener registered in the handler of the page event
  hears the load of a slow popup, wait_for_load_state in the handler returns in under 2 s (in-process and a stock client over a served
  browser, window.open and link).

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

* A popup whose target goes away while its page is being built is announced and closed, not waited for for ever

A download's empty tab is closed by the engine within milliseconds; on a loaded machine its page is still being built when the detach arrives.
_handle_detach recorded it as early (nobody in _building to tell) and the adoption then waited for a Page.ready that never comes: the
popup was never announced (test_popup_destinations_e2e, the download on the opener, failed once in a full suite run). The adoption now
looks at the early detaches when it registers the page as waiting.

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

* A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does

The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

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

* tests: the helper of the popup destinations does not shadow the browser fixture (ruff F811)

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

* tests: the popup tests do not fail on the machine's speed (no 2 s limit)

A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

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

* The adoption of a target is one explicit state machine, proved over every order of the engine's events

Four patches of the same race (a detach before the ready, during the build, between the build and the wait, a command answered 'cannot find
session') and a fifth the exhaustive test found (a detach while the adoption waits for the main frame of a tab the engine never announced:
the wait went on for 20 s and the popup was discarded; this is the order the runner produced for the download popups: 3 of 4 lost).

- _Adoption: the single record of a target between its attach and its announcement: state (attached, building, waiting, announced), gone
  (set by the engine's detach AT ANY MOMENT), page, opener, context. It replaces _adopting, _building, _openers and _detached_early.
- Every wait of the adoption looks at gone (the main-frame wait polls it), every state change is one method (_enter_building, _enter_waiting,
  _enter_announced), a command that finds the session gone ends in the same place as a detach, a closing context takes away every adoption
  of it in any state (end_waits_of).
- Invariant: an attached target that is not a page a caller asked for gives the client exactly one page event, at its ready or at its
  disappearance (and its close right after), unless its context closed first.
- Test: test_every_order_of_the_events_of_a_popup_gives_one_page_event stops the adoption thread at six points of its own and delivers the
  engine's events (frame, commit, ready, detach, in every prefix) at every one of the eight moments: 635 orders, none sampled. Mutation
  check: without the gone-aware main-frame wait 24 orders break, without the tolerance of the command error 42, without the close after the
  page 374; without the early-gone check of _enter_waiting the adoption hangs.

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

* The adoption keeps a short trace per target and writes it where a popup is dropped or fails

The log of a CI run says that a popup was not announced and not in which order the engine's events came. Each target in flight keeps (in memory,
at most 60 short strings, nothing afterwards) what the engine said (frame, commit, ready, detach) and what the adoption did (building, waiting,
announced), with the milliseconds since the attach. It is written in the warning of a failed adoption, in the error the newPage waiter gets, in
the timeout of a requested page, and in browser._dropped (the last 16 targets dropped with their context).

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

* The WebGL determinism test says why the browser could not make a context

One run in 31 of the e2e on a loaded Linux runner failed this test with "reason='gl null'" and nothing else: getContext('webgl') gave the page null. The browser
says why in the `webglcontextcreationerror` event (statusMessage: the failure list, e.g. "tryNativeGL (FEATURE_FAILURE_EGL_LOAD_3)", "Initializing WebGL backbuffer
failed.", "GL error 0x505 occurred during OpenGL context initialization"), and each of the paths that can produce null on Linux in our engine writes a different one
(library not loaded, display not initialised, context not created, GL out of memory, backbuffer not allocated). The test reads the event and puts it in the
assertion, and tries webgl2 on a fresh canvas (the old canvas already had the failed type).

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

* tests: the same-site control of the Fission bench measures the frame, not the process pool

The control counted the processes that host a site between two reads, with the default pool of three preallocated content processes: a pool
process handed to a site after the first read moved the count without the frame having asked for anything ([63248] -> [63248, 63386] on a
four-worker runner; the same family as 5402da4, ff2123e and fef0bc5). The control now runs in a browser with dom.ipc.processPrelaunch.fission.number
at 0, where a process of a site appears only because a site needed one, and says so if the page of the site has no process to compare with.

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

* The download of a tab that is not announced yet is said after the page event of the tab

The tab opened for an attachment is announced when the engine takes it away, a few milliseconds after it says the download; the download
(reported on the opener) went to the client first, the popup after: the order the other way round from Playwright's, and a client that read
the popup the moment the download arrived found none on a one-CPU machine (the 4 download cases of GitHub, 3 of 4 red; the same on a one-CPU
container: 1, 0, 2 of 50 on a90dadc). The adoption holds the download on its record and says it right after the page event (never lost: also
when the tab is dropped or fails).

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

* A download is taken with the record's removal in one step, and the opener of a target not announced is remembered: no step of the adoption can lose it

The failure branch said the pending downloads BEFORE it removed the record: a download created between the two found the record, queued on it, and
nobody said it. Taking the pending downloads and removing the record are now one step under the browser's lock, in the three branches
(announced, dropped with its context, failed); the opener of a target that ended without being announced is kept for the last 16 targets, so a
download that comes after the record is gone is still said, on the opener. Test: the download is forced into the gap of the failing adoption
(red on 65f7580: said 0 times, now once).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-11-12 09:51:23 +01:00
feder-crandClaude Sonnet 5.5 e88e664a50 tests: the chain by name allows loopback in ICE, because the lab's exit is 127.0.0.2 and a retail Firefox throws away an answer whose mapped address is loopback
The giro 3 gate was red on test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick. Measured on the giro 3 Linux binary (strace of the socket
that talks to the relay + the gateway's own log): the gateway delivers the TURN server's 401 and then its success (type 0x0103) within 5 ms, the browser
reads both, answers the 401 with credentials, and never accepts the success: it retransmits the same Allocate 5 times in the 2 s of the page. The
success carries XOR-MAPPED-ADDRESS 127.0.0.2 (where the gateway's datagrams leave from, by design of the test) and nICEr rejects a loopback mapped address as
bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) unless the ICE context allows loopback (turn_client_ctx.cpp; the flag is set from
media.peerconnection.ice.loopback in nricectx.cpp). The same TURN server answers a direct browser at a non-loopback address and the allocation completes in
60 ms, so the chain is sound. With the pref the chain test passes at 130 ms of round trip on the giro 3 binary; without it it fails at 0, 65 and 130 ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:50:34 +01:00
feder-crandClaude Sonnet 5.5 bacf03ad21 tests: the CONNECT helper of the HTTP proxy tests reads the answer one byte at a time, so the first bytes of the tunnel are not lost with the head; unit test (unit.udp 166)
When the far side wrote and closed at once, the 200 and the first bytes of the tunnel could reach the socket in one segment, and _connect_raw dropped everything after the blank line: the caller read the end of the stream instead of the data (run 43176569993, test_a_connect_to_loopback_is_relayed_and_one_that_would_leave_it_is_refused).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:49:01 +01:00
feder-crandClaude Sonnet 5.5 9357e790b3 tests: the first datagram of a PeerConnection is judged with the session's UDP declared coherent, and the core's own probe is not counted as the engine's association
The giro 3 gate was red on this test: with a fixed time zone the core does not discover the TCP exit, so it cannot compare it with the UDP probe's mapped
address and declares the UDP of the proxy unmeasured; the engine then treats the proxy as a router that drops UDP, asks it for no association and sends
nothing (measured on the giro 3 Linux binary: the gateway saw ONE ASSOCIATE for the whole test, the core's probe; the layer was pushed on the PC's
socket and what was sent was dropped). The test gives the core the gateway's TCP exit as every e2e of the line does (egress_by_proxy), and it no longer counts
the probe's association (the first of the gateway, made before the browser exists) as one that was ready before the PeerConnection - it passed an
engine that asked for none. Green on the giro 3 Linux binary (run 43164943499).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:40:33 +01:00
feder-cr 1466ac6433 wrapper: the opener kept for the downloads of a target whose adoption failed lives until the engine detaches the target, and none is made for a target already detached; unit tests (unit.page 34) 2026-11-12 09:09:31 +01:00
feder-cr bf5c6dabb3 ci: wrapper.unit.page counts the popup-order test and the changed page tests of release/0.50.1 8049df3 (32) 2026-11-12 09:06:24 +01:00
feder-cr e992255d38 Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3-next 2026-11-12 09:04:57 +01:00
feder-crandClaude Sonnet 5.5 8049df3c33 A download is taken with the record's removal in one step, and the opener of a target not announced is remembered: no step of the adoption can lose it
The failure branch said the pending downloads BEFORE it removed the record: a download created between the two found the record, queued on it, and
nobody said it. Taking the pending downloads and removing the record are now one step under the browser's lock, in the three branches
(announced, dropped with its context, failed); the opener of a target that ended without being announced is kept for the last 16 targets, so a
download that comes after the record is gone is still said, on the opener. Test: the download is forced into the gap of the failing adoption
(red on 65f7580: said 0 times, now once).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:58:48 +01:00
feder-cr e4edf5f81f ci: the realness e2e (32) is a required suite, its helpers (24) join wrapper.unit.udp (165) 2026-11-12 08:54:35 +01:00
feder-crandClaude Sonnet 5.5 7a094c3bbc tests: the realness check without a real proxy - six declared exits, the values a page reads, and the judges
The manual check drove the browser through a paid proxy and compared what a page reads with the proxy's exit. This is the
same check against a local SOCKS5 gateway that declares its exit: a local site that tells a connection the gateway opened from
a direct one, FakeDoh for the names, and the core's own geo database as the truth for the zone and the country.

* test_realness_behind_a_declared_exit_e2e.py: one launch per exit (six, in six countries), read by five tests (the address a
  site sees and no connection past the gateway; nothing of the host in the WebRTC candidates and SDP; the names reach the gateway
  and not the system resolver; the zone, the offsets read two ways and a worker; the language of the page, a worker and the
  Accept-Language header against the exit's country), plus the vendored detection page loaded behind the gateway.
* _realness_support.py: the exits, ExitGateway (remembers the ports of the connections it opened), the site, the reads, the judges.
* test_the_realness_helpers.py: the judges and the gateway/site correlation held to golden reads, no browser.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:53:37 +01:00
feder-cr 7272ea8f64 tests: the iptables fallback of the resolver trap is gone (the cause was the trap's own threads holding the port, fixed in 4933f8c); wrapper.unit.udp 141 2026-11-12 08:49:52 +01:00
feder-crandClaude Sonnet 5.5 a70f2fecaf tests: the discovery of the exit of a context stays covered now that the DoH e2e declare it away
The DoH e2e declare the exit the core asks for (their subject is the roads of the browser). The discovery itself keeps its own test: it goes
through the gateway of the context, by name, only to the services of the core, never through another context's gateway, and a gateway that
refuses them never makes the measurement say coherent. wrapper.unit.udp 140 -> 142.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:43:55 +01:00
feder-crandClaude Sonnet 5.5 65f7580182 The download of a tab that is not announced yet is said after the page event of the tab
The tab opened for an attachment is announced when the engine takes it away, a few milliseconds after it says the download; the download
(reported on the opener) went to the client first, the popup after: the order the other way round from Playwright's, and a client that read
the popup the moment the download arrived found none on a one-CPU machine (the 4 download cases of GitHub, 3 of 4 red; the same on a one-CPU
container: 1, 0, 2 of 50 on a90dadc). The adoption holds the download on its record and says it right after the page event (never lost: also
when the tab is dropped or fails).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:42:59 +01:00
feder-crandClaude Sonnet 5.5 4933f8cdba tests: the resolver trap ends its threads before it closes its sockets, so its port is free for the next test (no more "Address already in use" on 127.0.0.1-8:53)
The answering threads sit in accept()/recvfrom(); on Linux a close() from another thread does not wake them and the kernel keeps the socket
bound until the call returns, which it never did: every trap left its address taken, and the eighth trap of a run found all eight taken
(reproduced here in a container: 19 DoH e2e, the 6 tests after the 8th trap are errors; alone, the same file passes). The loops now wake every
0.2 s to look at a flag; the teardown sets it, joins the threads, and then closes the sockets.

- test_a_closed_trap_gives_its_port_back_at_once (wrapper.unit.udp 139 -> 140): a trap on a free port is closed and a second one on the same
  port must bind 127.0.0.1 again; red on the old code on Linux.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:42:36 +01:00
feder-cr bfb67e0c2c tests: a port 53 that cannot be bound is redirected from 127.0.0.2 to a free port (iptables nat OUTPUT), the rules go with the trap 2026-11-12 08:27:48 +01:00
feder-crandClaude Sonnet 5.5 2022ecf32a tests: two connections on one page may nominate a peer-reflexive end; the road is what is judged
On the round 3 gate (Linux, run 43164943499) the nominated pair was host to prflx: the other connection's mDNS name was not resolved yet when its
connectivity check arrived, and the address the check came from is learned as peer-reflexive. That is the same direct local road, so the test accepts
host or prflx at each end, over UDP at both ends, and refuses what is a different road: a relay, a server-reflexive candidate (through the proxy or the
network), or TCP. The open time stays judged against the responder's first retry, and printed beside the retail window.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:21:06 +01:00
feder-cr 5ae6833299 tests: the DoH e2e declare the exit the UDP measurement asks for; the gateway's page is reached by an address; e2e.udp is split in e2e.udp and e2e.web; the trap says who holds port 53 2026-11-12 08:19:16 +01:00
feder-crandClaude Sonnet 5.5 a90dadc204 tests: the same-site control of the Fission bench measures the frame, not the process pool
The control counted the processes that host a site between two reads, with the default pool of three preallocated content processes: a pool
process handed to a site after the first read moved the count without the frame having asked for anything ([63248] -> [63248, 63386] on a
four-worker runner; the same family as 5402da4, ff2123e and fef0bc5). The control now runs in a browser with dom.ipc.processPrelaunch.fission.number
at 0, where a process of a site appears only because a site needed one, and says so if the page of the site has no process to compare with.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:17:52 +01:00
feder-crandClaude Sonnet 5.5 210161d9b6 The WebGL determinism test says why the browser could not make a context
One run in 31 of the e2e on a loaded Linux runner failed this test with "reason='gl null'" and nothing else: getContext('webgl') gave the page null. The browser
says why in the `webglcontextcreationerror` event (statusMessage: the failure list, e.g. "tryNativeGL (FEATURE_FAILURE_EGL_LOAD_3)", "Initializing WebGL backbuffer
failed.", "GL error 0x505 occurred during OpenGL context initialization"), and each of the paths that can produce null on Linux in our engine writes a different one
(library not loaded, display not initialised, context not created, GL out of memory, backbuffer not allocated). The test reads the event and puts it in the
assertion, and tries webgl2 on a fresh canvas (the old canvas already had the failed type).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:16:43 +01:00
feder-crandClaude Sonnet 5.5 1542fede01 The adoption keeps a short trace per target and writes it where a popup is dropped or fails
The log of a CI run says that a popup was not announced and not in which order the engine's events came. Each target in flight keeps (in memory,
at most 60 short strings, nothing afterwards) what the engine said (frame, commit, ready, detach) and what the adoption did (building, waiting,
announced), with the milliseconds since the attach. It is written in the warning of a failed adoption, in the error the newPage waiter gets, in
the timeout of a requested page, and in browser._dropped (the last 16 targets dropped with their context).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:16:36 +01:00
feder-crandClaude Sonnet 5.5 5426744bc6 The adoption of a target is one explicit state machine, proved over every order of the engine's events
Four patches of the same race (a detach before the ready, during the build, between the build and the wait, a command answered 'cannot find
session') and a fifth the exhaustive test found (a detach while the adoption waits for the main frame of a tab the engine never announced:
the wait went on for 20 s and the popup was discarded; this is the order the runner produced for the download popups: 3 of 4 lost).

- _Adoption: the single record of a target between its attach and its announcement: state (attached, building, waiting, announced), gone
  (set by the engine's detach AT ANY MOMENT), page, opener, context. It replaces _adopting, _building, _openers and _detached_early.
- Every wait of the adoption looks at gone (the main-frame wait polls it), every state change is one method (_enter_building, _enter_waiting,
  _enter_announced), a command that finds the session gone ends in the same place as a detach, a closing context takes away every adoption
  of it in any state (end_waits_of).
- Invariant: an attached target that is not a page a caller asked for gives the client exactly one page event, at its ready or at its
  disappearance (and its close right after), unless its context closed first.
- Test: test_every_order_of_the_events_of_a_popup_gives_one_page_event stops the adoption thread at six points of its own and delivers the
  engine's events (frame, commit, ready, detach, in every prefix) at every one of the eight moments: 635 orders, none sampled. Mutation
  check: without the gone-aware main-frame wait 24 orders break, without the tolerance of the command error 42, without the close after the
  page 374; without the early-gone check of _enter_waiting the adoption hangs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:13:47 +01:00
feder-cr 973927fdb7 tests: the trap-policy test reads the trap fixture in conftest.py (6b moved it there with the lint of the fixtures) 2026-11-12 06:23:06 +01:00
feder-crandClaude Sonnet 5.5 071cf8d697 tests: the fixtures that several e2e files share are in conftest.py, not imported from a sibling file (ruff F811, the lint of the tests job)
A fixture imported from a twin file and then named as a test argument is a redefinition: 60 F811 in the new tests of the UDP line, the
same error that turned the 0.50.1 CI red. The collection does not change: the same 2187 tests (1422 by default), the same setup plan
(fixture order and scope per test, compared with --setup-plan before and after).

- conftest.py: doh, gateway, trap, watcher, pages (DoH e2e), socks5_tcp_only, local_https_page (WebRTC e2e) and browser (the two-transport
  fixture of the popup tests). The heavy imports are inside the bodies, so a run without the e2e extras still collects.
- _doh_support.py (ZONE, Pages) and _socks_servers.py (Socks5TcpOnly, was _Socks5TcpOnly in test_webrtc_realness.py): the plain code the
  fixtures need, in support modules, not in a test file.
- The twin files keep what is not a test argument (the autouse _hermetic_session and the helpers, imported by name); the sibling files
  stop importing the fixtures. The four `# noqa: F811` of test_popup_destinations_e2e.py are gone: ruff passes with --ignore-noqa.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 06:02:15 +01:00
feder-cr 7af5b84954 Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3 2026-11-12 05:47:21 +01:00
feder-crandClaude Sonnet 5.5 a18e967675 tests: the popup tests do not fail on the machine's speed (no 2 s limit)
A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:47:12 +01:00
feder-crandClaude Sonnet 5.5 64dc8d3476 tests: the popup tests do not fail on the machine's speed (no 2 s limit)
A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:44:57 +01:00
feder-cr bd46760313 ci: wrapper.e2e.udp counts 68 (the three ICE rows of test_webrtc_realness: default, content process asked, no socket process asked; the engine locks both prefs) 2026-11-12 05:29:21 +01:00
feder-crandClaude Sonnet 5.5 2283d40198 tests: a caller that asks for the ICE in the content process, or for no socket process, gets the srflx through the relay all the same (the engine locks both prefs)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:29:12 +01:00
feder-crandClaude Sonnet 5.5 012fc862ef tests: two connections on one page are judged on the road they take, not on the clock of the machine
The test asserted a median of 30-55 ms, the time of a fast machine. On a GitHub runner the same healthy engine takes 67 ms (Windows) and
122 ms (Linux) and the gate was red on both: an absolute time is a verdict on the machine.

Every one of the five cold launches is now judged on what the machine cannot change:
* the data channel opens and echoes;
* each connection gathered a UDP host candidate named by mDNS (a run without UDP is the reserved-port failure: the socket could not bind and
  the connection fell back to TCP);
* the nominated pair, read from the browser's own statistics, is host to host over UDP at both ends (no road through TCP; a succeeded pair
  means the other connection's mDNS name was resolved);
* it opens in less than the responder's first retry (3 s): a name that does not come back opens only at the retry.
The time is printed beside the retail window, as a measure.

Run on the firefox-63 candidate engine: passes, [38, 39, 39, 73, 77] ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:23:06 +01:00
feder-cr 8c7e413b68 tests: the resolver trap takes the first loopback address it can bind for port 53 (a hosted runner can hold 127.0.0.1:53) and writes that address in resolv.conf 2026-11-12 05:19:56 +01:00
feder-crandClaude Sonnet 5.5 bbf4019940 tests: the helper of the popup destinations does not shadow the browser fixture (ruff F811)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:17:48 +01:00
feder-cr 4e1f2ecf40 tests: the resolver trap says why it could not bind (the error of the socket) 2026-11-12 05:12:04 +01:00
feder-cr 6f9b87c860 ci: test_a_page_that_moves_on_e2e.py is required in wrapper.e2e.page (114): the e2e of the engine fix for a navigation the page overtook 2026-11-12 05:05:54 +01:00
feder-cr a072aa22b8 ci: the page and popup suites count the tests of release/0.50.1 6200bc2 (e2e.page 100, unit.page 24) 2026-11-12 04:40:13 +01:00
feder-cr 328ed0738e Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3 2026-11-12 04:39:51 +01:00
feder-crandClaude Sonnet 5.5 6200bc29ed A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does
The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 04:10:00 +01:00
feder-crandClaude Sonnet 5.5 b05741f538 A popup whose target goes away while its page is being built is announced and closed, not waited for for ever
A download's empty tab is closed by the engine within milliseconds; on a loaded machine its page is still being built when the detach arrives.
_handle_detach recorded it as early (nobody in _building to tell) and the adoption then waited for a Page.ready that never comes: the
popup was never announced (test_popup_destinations_e2e, the download on the opener, failed once in a full suite run). The adoption now
looks at the early detaches when it registers the page as waiting.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:51:28 +01:00
feder-cr 95c7e156ac tests: the first visit of the h3 e2e is h2 because the fixture has no HTTPS record (the retail read h3 first in 3 sessions of 15); the FakeDoh never serves type 65 and the tests assert it 2026-11-12 03:48:26 +01:00
feder-crandClaude Sonnet 5.5 620f969655 A popup tells its listeners the load it reached before it was announced; an unannounced frame has no address of its own
- The popup is announced when the engine says Page.ready, which is when its document commits, so its domcontentloaded and load may be said
  before the client has the page: page.on('load') registered in the handler of the page event never fired (Playwright's does, measured by
  the independent run: destinations of 4 s and 25 s). FrameDispatcher.emit records those two states while the page is not announced and
  PageDispatcher.announce says them again right after the page event, in their order and under one lock; the first time they already set
  the state wait_for_load_state reads, so it returns at once. Only popups: a requested page is announced as before.
- The main frame is created with the address the lifecycle knows, '' if it has committed nothing (an attachment's empty tab), not
  about:blank: Playwright says '' there.
- Tests: unit (the two states after the page event, in order; red on 2f153c7); e2e: a listener registered in the handler of the page event
  hears the load of a slow popup, wait_for_load_state in the handler returns in under 2 s (in-process and a stock client over a served
  browser, window.open and link).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:33:32 +01:00
feder-cr adf96a2b15 ci: the drive gate launches through the core (the engine waits for the session's road; bare Playwright never sends it); the declaration test does not resolve an engine 2026-11-12 03:16:20 +01:00
feder-cr 2167538130 ci: the page and popup suites of 0.50.1 are required (wrapper.e2e.page 96, wrapper.unit.page 17), wrapper.unit.udp counts 113 after the merge 2026-11-12 02:56:16 +01:00
feder-cr 440bbb36e6 Merge branch 'release/0.50.1' into udp/wrapper-r3
# Conflicts:
#	src/invisible_playwright/_juggler/server.py
#	tests/test_every_route_command_is_answered_may_fail.py
2026-11-12 02:54:06 +01:00
feder-crandClaude Sonnet 5.5 2f153c76ff A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it
- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:42:32 +01:00
feder-crandClaude Sonnet 5.5 fbceeafb65 A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready
- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
  destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
  (newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
  (BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
  engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
  the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
  address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
  then) in-process and through a served browser: the 25 s ones red on b09d620.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:19:46 +01:00
feder-crandClaude Sonnet 5.5 b09d620930 tests: the popup reaches the client from another site too (a link, noopener, window.open: 16 more cases, in-process and through a served browser)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 01:11:02 +01:00
feder-crandClaude Sonnet 5.5 776c00afe2 tests: the stand-in pages say wait_until_ready; the popup e2e reaches the stock client as the other served tests do
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:58:07 +01:00
feder-crandClaude Sonnet 5.5 ba5b51cf91 A page is built at once and announced when the engine says Page.ready (the wait inside the constructor held a popup's first request behind a page that did not exist yet, and lost its commit and load)
- PageDispatcher no longer waits in __init__; wait_until_ready() is called by the adoption between the construction and the announcement
  (context 'page' event, newPage answer). A detach while waiting ends the wait; a page that is not ready in time is disposed.
- The main frame's initializer carries what the lifecycle already knows (url, name, load states), as every other frame's does.
- Tests: unit (a popup exists and listens while it waits; what it does before its ready reaches its frame; red on 6a60dce) and e2e
  (a popup of a link, noopener or window.open reaches an in-process and a stock client of a served browser within 2 s, with and
  without a context route; 15 of 16 red on 6a60dce, 16 green).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:56:01 +01:00
feder-crandClaude Sonnet 5.5 14c24347c5 tests: h3 behind a proxy follows the definitive retail (never h3 at visit 1, h3 within 5 visits, h2 every visit without usable UDP)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:38:20 +01:00
feder-crandClaude Sonnet 5.5 99c7fc93aa ci: the hosts-file e2e is required in wrapper.e2e.doh
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:20 +01:00
feder-crandClaude Sonnet 5.5 a61465b2be tests: the engine never reads the host's hosts file, with a proxy or without (MOZ_LOG per process, with a control)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:16 +01:00
feder-crandClaude Sonnet 5.5 47536b5e64 tests: the refused-once e2e says what it measures and what it does not
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:16 +01:00
feder-crandClaude Sonnet 5.5 4f95aa3797 ci: the resolver-race and DoH-under-stress e2e (wrapper.e2e.doh, 17) and the FakeDoh levers unit tests (wrapper.unit.udp, 110) are required
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:45 +01:00
feder-crandClaude Sonnet 5.5 6a60dcebb7 tests: new_page and a popup are handed over only when the engine says Page.ready (red without the wait in PageDispatcher, green with it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:32 +01:00
feder-crandClaude Sonnet 5.5 7927e30679 tests: the refused-once e2e shortens the DNS negative cache, so it measures a temporary block and not Firefox's 60 s failure cache
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 bf2a3c33b0 tests: the DoH of a proxied context when it is slow (2 s per answer) and when it refuses a name once; FakeDoh gains delay_s, delay_names and fail_first (written ahead of the engine)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 03d96a7baa tests: a context with a proxy resolves by DoH through it and a context without one never uses the DoH; the first navigation of a fresh context never asks the system resolver (written ahead of the engine)
The context-only test also asserts that the DoH log holds no name but the proxied context's, that no handshake failed and that the
default context's background lookups reach the system resolver (the trap, where it runs). New race test: eight contexts created
and navigated back-to-back, a launch-proxy variant, and a proxied context beside one without a proxy. The DoH e2e docstrings
follow the per-context rule.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 7db28e4611 tests: the stand-in engine of the registry test says Page.ready, as the real one does (the page is handed over on it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:21:38 +01:00
feder-crandClaude Sonnet 5.5 f76240893e Pin invisible-core==62.65.0 (a page handed over when the engine says it is ready); changelog
The core that carries Lifecycle.wait_for_page_ready is invisible-core 62.65.0 (draft PR invisible_core#238), not on the index yet:
the pin check of this push is skipped on purpose (INVISIBLE_PIN_CHECK=skip).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:14:02 +01:00
feder-crandClaude Sonnet 5.5 d5c0e410de The page dispatcher waits for Page.ready before the page is handed over (needs invisible-core with Lifecycle.wait_for_page_ready)
Same defect and fix as in the core's page (see the core commit): a goto sent right after new_page could meet the page's initial about:blank.
The pin of invisible-core moves with the core release that carries wait_for_page_ready.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:13:19 +01:00
feder-crandClaude Sonnet 5.5 422e675b86 ci: the context-only-proxy DoH e2e (wrapper.e2e.doh, 12) and the host-address helper unit tests (wrapper.unit.udp, 97) are required
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:36:39 +01:00
feder-crandClaude Sonnet 5.5 1c7bcf9dee tests: a context that is the only proxy resolves its names by DoH through it (red while TRR stays mode 0 for context-only proxies, green with engine 9bff9cf8de)
A session launched with no proxy, a context made with its own SOCKS5 gateway, a page at a name only the FakeDoh can resolve: the
name must be asked to the DoH by that gateway, the page reached by address through it, nothing to the DoH directly and no
question about the zone to the resolver of the machine. Review finding 4 (the e2e that was missing).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:37 +01:00
feder-crandClaude Sonnet 5.5 84fd375562 ProxyEgressNonVerificabile: the docstring says what goes unconfirmed (timezone and locale), not an address
The engine no longer declares an egress address (the host network is drawn from the seed); only the timezone and the locale are
decided from the egress. Reworded like ProxyEgressDrifted, with a test on the text that fails on the old wording. Review
finding 30.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 d596ee81c8 tests: one helper for the address of this host, computed before any server starts, a host without a default route skips
this_host_address() and its two copies connected a UDP socket to 192.0.2.1 and raised OSError on a host with no default route;
in the chain it was evaluated as an argument after the TURN server, the resolver and the page were already listening, so the
test errored and leaked three listeners instead of skipping. The helper is now tests/_host_address.py (OSError => pytest.skip),
the chain asks it first, and the three copies are gone. Review finding 29.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 66d5090a0b tests: the declared-network e2e no longer sets variables the engine does not read
STEALTHFOX_WEBRTC_PUBLIC_IP and STEALTHFOX_WEBRTC_DISABLE_IPV6 are not read by the engine or the core (the unit test of the
declaration bans them in the environment); the e2e set and deleted them and imported _FAKE_EGRESS only for that. Dead setup
that said the egress still feeds WebRTC. Review finding 27.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 3a1dc8df9b tests: the gather without a proxy and the ICE-name e2e wait for the engine that carries the UDP line
test_the_gather_is_real_without_a_proxy (in wrapper.e2e.udp) had no the_udp_line, unlike the other tests of its file, and the
ICE-name e2e (wrapper.e2e.doh) resolves a name through the proxy of a context, which the engine firefox-63 does. On an older
engine they skip with the reason; on the candidate (firefox-63-candidate) they run, so the exact lists of
ci/required-suites.json are unchanged. The networkidle e2e stays ungated: it needs no proxy and no UDP, and is fixed by the
Python of the core and the wrapper on any engine. Review finding 14.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 5b87926543 ci: the warm-pool and the TURN-over-TCP e2e are required in wrapper.e2e.udp (61 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:29:44 +01:00
feder-crandClaude Sonnet 5.5 b396e055ce A TURN server over TCP is connected to and waited for, direct and behind SOCKS5 (e2e)
A TCP stand-in for a TURN server on this machine's address accepts, reads and closes N ms after the accept; the page asks for a
TURN allocation over TCP. A retail Firefox connects, sends the Allocate request and hears 701 when the server closes (accept
at 48 ms, 701 and the gathering complete at 850 ms with N=800). The candidate engine never connected: no accept, no bytes, 701 within
9-28 ms with the gathering complete, direct and through the gateway alike.

Red on the firefox-63 candidate build; green expected with the engine commit that binds the wildcard of the declared family.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:28:22 +01:00
feder-crandClaude Sonnet 5.5 68bb2b8e8f tests: the first datagram of a PeerConnection does not wait for a UDP association (red on the giro 2 binary: 396 ms)
The pool of UDP associations was warmed only in the process of the HTTP connections (the parent); the sockets of the PeerConnections
are made in the socket process, which found it empty and made its association from scratch: three answered steps before the first
STUN datagram. A gateway that answers every step after 130 ms makes it visible: on the giro 2 binary the first datagram leaves 396 ms
after the birth of the PeerConnection. The test asserts it leaves within 250 ms, and that an association was granted before.

The gateway of the tests now also keeps the wall-clock origin of its times and the instant of every accepted connection.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:27:55 +01:00
feder-crandClaude Sonnet 5.5 c14f2b1e9a ci: the ICE-name e2e is part of wrapper.e2e.doh (11 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:20:42 +01:00
feder-crandClaude Sonnet 5.5 bfedd53850 tests: the ICE server name of a PeerConnection is resolved in the context of its page, by the proxy of that context (red until the resolver carries the OriginAttributes)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:20:03 +01:00
feder-crandClaude Sonnet 5.5 e868714339 tests: the h3 e2e turn off Firefox's check of third-party roots (a self-signed test server stops HTTP/3 otherwise: measured)
The Alt-Svc is learned and the QUIC handshake of validation passes with the override, then Firefox closes the connection itself because the chain
ends in a root it does not know, and every visit stays h2. With network.http.http3.disable_when_third_party_roots_found off the three visits read
h2, h3, h3 (3 runs of 3, no proxy, on the engine of the first round).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:15:44 +01:00
feder-crandClaude Sonnet 5.5 36ecd11e99 tests: the chain by name declares the FakeDoh's own provider (doh.gateway.test): the DoH of Mozilla is HSTS-preloaded and takes no override
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:07:23 +01:00
feder-crandClaude Sonnet 5.5 80672c69a3 tests: the fake DoH of the e2e uses a name that is not HSTS-preloaded (doh.gateway.test at 192.0.2.53), declared through extra_prefs
Firefox refuses certificate overrides for HSTS-preloaded/pinned hosts, so a self-signed fake for
mozilla.cloudflare-dns.com could never be accepted. The test now declares its own provider
(network.trr.uri, network.trr.bootstrapAddr) and counts every connection of the browser, including
the background traffic of the default context whose TLS fails by design, at the gateways.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:59:17 +01:00
feder-crandClaude Sonnet 5.5 a21e1decb9 tests: the descriptors of the spawn are asserted by running it, not by reading the core's source
test_the_spawn_keeps_the_two_hardwired_descriptors asserted that the source of the core's _spawn_posix contains
`pass_fds=(its_read, its_write, 3, 4)`. Core 62.64.0 starts the engine with posix_spawn and file actions, so the words are gone
and the test failed on every Linux unit suite although the behaviour is the same (and better).

The test now runs the spawn: a parent with nothing open on 3 and 4 and its pipes far from them launches a program that reads
fd 3 and answers on fd 4 (the contract of nsRemoteDebuggingPipe.cpp), and the answer must come back and the child must hold no
descriptor above 4 of the parent's. Same shape as the core's own test
(test_the_pipe_of_the_engine_reaches_its_fixed_descriptors). No skip: the file is already POSIX-only.

The other tests of the file do not read source text (checked: no getsource/inspect/read_text left).
Ran the parent program on Linux with core 62.64.0 (image tetra-invisible:run1b-final): pong:ping:0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:59:15 +01:00
feder-crandClaude Sonnet 5.5 ecf384a923 ci: the no-proxy gather is a required test of wrapper.e2e.udp (58 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:58:25 +01:00
feder-crandClaude Sonnet 5.5 a8cc2c842e A keepalive fetch is a request of the page for the client, in a real browser
e2e: the page sends a plain fetch, a keepalive fetch (cors and no-cors) and a beacon; the client must hear a `request`
for each and an end for each. Measured on the firefox-62 engine: the server received the keepalive fetches and the client
heard no `request` for them (stock Playwright's Firefox reports them). Red until the engine attributes the request to
its page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:44:20 +01:00
feder-crandClaude Sonnet 5.5 5da874d67f tests: HTTP/3 is judged on three visits of one page (h2, h3, h3 with UDP free; h2 three times without), as a retail Firefox reads them
Reference: retail 159 Linux, 15 of 15 each way (invisible_WebRTC captures/h3-fallback): with
UDP free the first visit is h2 and the second and third h3; with UDP dropped every visit is
h2 and the later loads are as fast as the first.

- _h3_server: the TCP side speaks HTTP/2 by ALPN (h2 library; HTTP/1.1 only for a client that
  offers nothing else), carrying Alt-Svc: h3; it answered HTTP/1.1 only, so the first visit
  could never read h2. One HTML document over TCP and QUIC; tcp_alpn recorded.
- test_http3_through_the_proxy_e2e: the retail method (one context, three gotos, a pause of 2 s
  after each load, nextHopProtocol of the navigation entry) on six roads: no proxy and a SOCKS5
  with coherent UDP -> h2,h3,h3 (QUIC through the relay, the server never sees this host);
  SOCKS5 that refuses UDP / leaves from another address / never answers (the declared udp is
  asserted) and an HTTP proxy -> h2,h2,h2, no QUIC at the server, no page datagram at the relay,
  visits 2 and 3 no more than 1.5 s slower than visit 1. An h3 on visit 1 is named as an error.
- _udp_line: expected_protocols / judge_visits (the sequence and the judgement, unit-tested).
- test_the_h3_line_helpers (unit): the server really negotiates h2, says Alt-Svc, answers the
  same document over h3; the judge names each mistake.
- ci/required-suites.json: wrapper.e2e.udp 53 -> 57 (the http3 file has 6 tests, was 2).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:43:33 +01:00
feder-crandClaude Sonnet 5.5 f3e3ce164d tests: the e2e of the UDP relay hand the core the STUN server its gateway answers (udp_stun_servers), and the dropped-UDP cases expect the new behaviour
The core now MEASURES the UDP exit of a SOCKS5 proxy before declaring it; only `coherent`
makes the engine send UDP to the relay. A gateway of the tests that is not asked the right
way is declared `no` and its e2e would fail for a reason that is not the product's.

- _socks_servers: MEASURE_NUMBER (the fake STUN by a number of its own, so the measurement
  is told apart from the page's STUN_NUMBER), Gateway.measure_servers, silent_udp() (relay
  granted, STUN never answered -> unmeasured), relay_host on every factory.
- _udp_line (new): measure_servers, egress_by_proxy (the TCP exit of each gateway: a context
  proxy is measured against its own), declared_udp (what the launch measured; absent is not
  `unmeasured`), one place for every e2e.
- test_webrtc_realness: one launch helper behind a gateway; the relay tests, the two-contexts
  and the TURN-over-TCP tests use the exits of their own gateways; the dropped-UDP case is one
  helper with three roads (refused: no, another exit: no, never answered: unmeasured) that
  asserts the declared udp, no srflx, 701, and that the page's UDP never reached the relay.
- test_the_whole_udp_chain_by_name_e2e: the chain is told its own TCP exit (it was a
  documentation address the chain's UDP does not leave from, i.e. `no`) and asserts coherent.
- test_the_udp_line_helpers (unit): the real measurement of the core against each gateway
  and the chain; the helper's list is `ip:port` IPv4 literals the core takes.
- ci/required-suites.json: wrapper.e2e.udp 51 -> 53 (two new tests, listed by name).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:38:12 +01:00
feder-crandClaude Sonnet 5.5 2329dc6c1c wrapper: the STUN servers are a launch parameter kept on the session (udp_stun_servers); the caller never declares udp
- InvisiblePlaywright(..., udp_stun_servers=None) (sync and async) and launch_server(...,
  udp_stun_servers=None) take "ip:port" IPv4 literals (None = the core's two public defaults;
  a name or a bad port raises ValueError naming the parameter) and keep them on the session.
  The launch's geo step uses them, and so does every later new_context(proxy=...): the server
  keeps the list on the browser it launches (the list rides to the server in the launcher's
  composed prefs like the session seed and is taken out before the profile is written), so the
  per-context call needs no new parameter. Nothing of it reaches the browser's environment,
  argv, prefs or pipe (tested).
- The proxy command is built by the core's context_proxy_command / launch_proxy_command: the
  `udp` field is the measurement, never what the caller wrote; configure_proxy(udp=) is gone
  and the launch's measure reaches Browser.setBrowserProxy through the core's per-proxy memory.
- The constructor-signature pin records the new keyword.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:14 +01:00
feder-crandClaude Sonnet 5.5 52e520dd92 wrapper: a proxy given to a context declares its measured UDP exit (udp) in Browser.setContextProxy
The core measures where a SOCKS5 proxy's UDP leaves from and the answer is the optional
field `udp` of the proxy declaration. The wrapper hands it on:

- the launcher, the async launcher and launch_server pass the udp their geo step measured
  to configure_proxy(udp=), so it reaches Browser.setBrowserProxy;
- the server's launch (a client that composed no session) declares the proxy with what the
  geo step remembered, never coherent without a measurement;
- BrowserDispatcher._apply_context_options, the one place new_context(proxy=...) of the sync,
  async and remote clients ends in, measures the context proxy BEFORE Browser.setContextProxy
  is sent (the core discovers the TCP exit through it and measures the UDP beside it, once per
  proxy, cached by endpoint and a hash of the credentials) and the result goes in `udp`.

Tests: a recorder in place of the engine, the fake SOCKS5 gateway with a UDP relay and a STUN
server only the relay reaches, declared through STEALTHFOX_UDP_STUN_SERVERS.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:13 +01:00
feder-crandClaude Sonnet 5.5 73c070ebb1 wrapper: every context carries the position the core declares for the session
The geo step is asked with the session seed (launcher, async_api, the served
browser, the default session) and the core's SessionGeo.geolocation_override()
(latitude, longitude, accuracy) becomes the standard `geolocation` context
option in _default_context_kwargs: the default context, each new_context /
new_page and each context of a remote client get Browser.setGeolocationOverride
through the existing path (server.py _apply_context_options). A geolocation given by the
caller wins; no coordinates, nothing is sent; the permission is never granted
here. Tests written ahead: tests/test_the_session_position_reaches_every_context.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:00 +01:00
feder-crandClaude Sonnet 5.5 1d564f5732 A route answer the engine refuses is the engine's business, whatever its wording
The server took one wording ("Cannot find request") of an answer to a closed request as done and passed every other
protocol error up to the client. The engine also says "NS_BINDING_ABORTED
[nsIInterceptedChannel.resetInterceptionWithURI]" when the channel was cancelled while the answer was on its way: the
same event, and the client kept it as the error of the connection and raised it on its next route command.

Stock Playwright sends the three interception commands as may-fail and tells the client nothing, whatever the engine
says. So does RouteDispatcher._send now: every ProtocolError is swallowed, the route is disposed after it.

Tests: the static guard no longer allows a re-raise inside the handlers; a unit test feeds three wordings (red on the
old code for two of them).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 21:20:59 +01:00
feder-crandClaude Sonnet 5.5 6f25adc2e5 tests: the git identity of the verdict test is a plain word
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:47:48 +01:00
feder-crandClaude Sonnet 5.5 cd062e2c59 tests: the DoH prefs follow the new split (the core declares the provider, the engine the state and the excluded names)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:45:16 +01:00
feder-crandClaude Sonnet 5.5 5a617dd899 ci: the verdict judge closes the holes a review found (main comparison, complete, exact counts, xunit2, commit, list validation, DoH trap)
- main: --main-required compares when the file is there; --main-has-no-list (the gate's declaration that main was checked
  out and has none) passes declared; a missing path without it is red. A failed download is no longer "main has no list".
- complete: every (suite, os) of the list reported a green result, no stranger, one commit, one binary per OS.
- exact: every row says whether collected must equal min_tests; the result json carries verdict green|red.
- the junit must be xunit2 (classname present, no file/line); the commit is --commit or git HEAD, never GITHUB_SHA;
  --binary is mandatory and must exist; --seal is read (it carries no sha256 of the binary: said, not compared).
- the list is validated by args, judge and complete (exit 2 with the reason); against main also exact, os, tests, marker.
- DoH e2e: with INVPW_REQUIRE_TRAP=1 a resolver trap that cannot run or bind is a failure, not a silent skip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:37:00 +01:00
feder-crandClaude Sonnet 5.5 793ea3d191 tests: the DoH negative control does not skip where the resolver trap cannot run (Windows reaches the page by a name the system resolves by itself)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:24:38 +01:00
feder-crandClaude Sonnet 5.5 154a9de475 ci: the list of mandatory suites and its one judge (ci/required-suites.json, scripts/ci_verdict.py)
The list names three suites with the least number of tests each must collect (wrapper.e2e.udp 51,
wrapper.e2e.doh 8, wrapper.unit.udp 86). ci_verdict.py prints the pytest arguments of a suite and judges
its junit: a failure, an error, a skip, too few tests, a required file or node id that did not pass, and
a list that lost a suite, a minimum or a test against main are all red, each said with its reason.

The leak watcher's file defined a test that skipped on every host; the two resolver-trap tests now exist
one per host (collected, never skipped), so the unit suite allows no skip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:24:09 +01:00
feder-cr 8c92c764b7 Merge #392 (docs: the agent links and the command name the MCP repo as it is now) into the 0.50.1 release 2026-11-11 20:22:43 +01:00
feder-cr 000fa7a3ad Release 0.50.1: pin invisible-core 62.64.0; CHANGELOG for the networkidle fixes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit e63ef8e61ea42e7f8df7c1bde206f3bf86fc18f7)
2026-11-11 20:22:42 +01:00
6a5b7e014a tests: answering a route the next navigation already aborted does not raise (the case of #351: the favicon of the page just left)
Sixty sequential routed gotos on a loopback page: 4-12 of them failed on the old server, every failing continue_ being
the previous document's favicon, aborted by the next navigation while the route sat with the handler. Red on main (in-process
path), green with the fix of RouteDispatcher._send.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:22:29 +01:00
feder-cr b78c5bb67c tests: the stock Playwright client is required by the networkidle e2e (explicit failure, never a skip); the dev extra pins it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 91223226f5bba25edff9af0e8b1fd6b5bfea2227)
(cherry picked from commit 612b18c02b95e9b5833d62b6595d4a0ff324aac2)
2026-11-11 20:22:14 +01:00
228576009b server: the answer to a request the browser has already closed is not an error (Cannot find request), as stock sendMayFail
A page cancels requests while a route is deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with
its document, the favicon of the page a goto just left). The engine takes the request out of its held set at once and the
late continue/abort/fulfill meets "Cannot find request" or NS_BINDING_ABORTED. Stock Playwright sends the interception
commands as may-fail and tells the client nothing; ours passed the error up, the client kept it as the error of the whole
connection and raised it on the NEXT route command, which was then never sent: its request stayed held in the engine, its
handler failed too, and so on down the page. Seen on a real news page: six held requests in a row, one a beacon, and
networkidle never came.

RouteDispatcher._send now treats "Cannot find request" and a closed target as done (still disposed); any other protocol
error still reaches the client.

Tests: the e2e with a plain handler (no try) on a page that removes an iframe whose requests are held (red before:
networkidle never; green after), and a static guard that every op of RouteDispatcher goes through _send and that _send
swallows exactly those two. The same defect was found a month earlier by richardpowellus (#351), with the favicon of the
previous page: his test is added in the next commit.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:22:14 +01:00
feder-cr bc816cb1ae tests: networkidle through a served browser whose context routes every request, on a reused page
launch_server() plus a stock Playwright client, a context route that aborts image/font/media and continues the rest, a
page with sendBeacon, the same font twice, a frame of another site, a worker, redirects, requests the page cancels while a
slow route decides, 100 requests at once, and a slow client that answers concurrently (async). Every shape reaches
networkidle on firefox-62; one page reused for twelve addresses too. The leak that tf-fetch meets on real sites needs
end events the engine loses, which no local page produces: its deterministic red/green is in the core
(tests/test_networkidle_on_a_reused_page.py of invisible-core); this file guards the remote path end to end.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 47182f0cd85fea08fc45e36f1c91d2d570722f14)
(cherry picked from commit e46f2dcf3eb361e6af0fedcdf6e1189f0ac330b6)
2026-11-11 20:22:14 +01:00
feder-crandClaude Sonnet 5.5 7ef736ca73 tests: the UDP line e2e need the engine that carries it (firefox-63); a missing websockets, aioquic or h2 is a failure, not a skip
The dev extra installs all three; a gate that skips for want of one proves nothing. main's e2e fetches the published engine 62, where the
declared network, the DoH through the proxy and the SOCKS5 UDP layer do not exist: those tests skip there and run on the candidate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:17:28 +01:00
feder-crandClaude Sonnet 5.5 d6f5c884b4 tests: the TURN name of the udp chain is resolved by the DoH through the proxy, not by the gateway
Chain is now a DohGateway (one SOCKS5 gateway in tests/): a CONNECT to the DoH goes to a FakeDoh whose zone is the TURN and
the page names, the datagram to TURN_IP goes to the TURN server by address (type 1), a name on the relay or a query to port 53
is dropped and recorded. DnsServer and the type-3 branch are gone. DohGateway takes the Gateway options (UDP relay, rtt) and
delays its tunnels by half the round trip like the base gateway. explain() lists what the DoH, the gateway, the TURN server and
the page saw, and says why.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:15:44 +01:00
feder-cr cbd9f5db5b Merge the process-counting e2e (#451) into the 0.50.1 release 2026-11-11 20:15:37 +01:00
feder-crandClaude Sonnet 5.5 183219ce18 tests: the names of a proxied session go to DoH through the proxy (written ahead of the engine)
E2E for the contract of core-19/motore-18, plus the hermetic helpers they stand
on, which are unit-tested now: a hand-written DoH server (h2 and HTTP/1.1), a
SOCKS5 gateway and an HTTP proxy that hand the DoH CONNECT to it and tag each
query with their name, a connection watcher and a resolver trap. The e2e skip
without a binary and cannot be green before the engine that keeps the contract.
test_integration follows the core: no host_ip pref, no DNS gate switch, TRR mode 3.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:10:33 +01:00
feder-crandClaude Sonnet 5.5 5c66186464 tests: a page reached over IPv6 gathers host candidates on a machine declared without IPv6 (hermetic, [::1], no proxy)
Red on an engine before ddaf867f03: the gathering is empty. Needs the firefox-63 build to run: not run here.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:08:21 +01:00
feder-crandClaude Sonnet 5.5 7ddb451af7 tests: the stock Playwright client is required by the networkidle e2e (explicit failure, never a skip); the dev extra pins it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:06:56 +01:00
feder-crandClaude Sonnet 5.5 98d9a799f6 server: the answer to a request the browser has already closed is not an error (Cannot find request), as stock sendMayFail
A page cancels requests while a route is deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with
its document). The engine takes the request out of its held set at once and the late continue/abort/fulfill meets
"Cannot find request". Stock Playwright sends the interception commands as may-fail and tells the client nothing; ours
passed the error up, the client kept it as the error of the whole connection and raised it on the NEXT route command,
which was then never sent: its request stayed held in the engine, its handler failed too, and so on down the page. Seen
on a real news page: six held requests in a row, one a beacon, and networkidle never came.

RouteDispatcher._send now treats "Cannot find request" and a closed target as done (still disposed); any other protocol
error still reaches the client.

Tests: the e2e with a plain handler (no try) on a page that removes an iframe whose requests are held (red before: networkidle
never, 25 s; green after; the fetch and image shapes were green before too), and a static guard that every op of
RouteDispatcher (abort, continue, fulfill, redirect) goes through _send and that _send swallows exactly those two.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:06:10 +01:00
feder-crandClaude Sonnet 5.5 f9221ae3c2 tests: networkidle through a served browser whose context routes every request, on a reused page
launch_server() plus a stock Playwright client, a context route that aborts image/font/media and continues the rest, a
page with sendBeacon, the same font twice, a frame of another site, a worker, redirects, requests the page cancels while a
slow route decides, 100 requests at once, and a slow client that answers concurrently (async). Every shape reaches
networkidle on firefox-62; one page reused for twelve addresses too. The leak that tf-fetch meets on real sites needs
end events the engine loses, which no local page produces: its deterministic red/green is in the core
(tests/test_networkidle_on_a_reused_page.py of invisible-core); this file guards the remote path end to end.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:06:10 +01:00
feder-crandClaude Sonnet 5.5 41f7bec7a7 dev extra: aioquic, so the two HTTP/3 e2e run in the gate instead of being skipped by importorskip
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 19:31:39 +01:00
feder-crandClaude Sonnet 5.5 56b33a7740 UDP line: the e2e of the proxy for a context, the chain by name, the declared host network, and the wrapper that declares it
Squash of the local integration branch (one branch for the candidate):
- e2e behind a gateway with coherent UDP (the cost of a gather, two contexts, a proxy without UDP, TURN over TCP of a context,
  HTTP/3 through the proxy) and one hermetic SOCKS5 gateway helper under them;
- the whole UDP chain by name behind a gateway at 130 ms (hermetic);
- the declared host network e2e (interfaces, ports, two connections);
- the wrapper declares the host network from the session seed (no srflx, no UDP verdict, no host_ip any more);
- the integration test follows the declared network and the DoH of the session proxy.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 18:34:26 +01:00
Federico EliaandClaude Opus 5.5 b6d32402f2 README: browser launches up top, in a big badge row (#453)
The launch count was a small badge at the very bottom. It now opens the
README, under the banner, next to engine downloads and stars. The daily
counters job also writes launches.json and downloads.json on the badges
branch; shields.io draws the big badges from them, so the numbers still
come only from our snapshot.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:15:12 +01:00
feder-crandClaude Opus 5.5 fef0bc5ea7 tests: the same-site control puts its frame in the shown page; CHANGELOG: 0.50.0's entry is 0.50.1's
The e2e of #451 saw a new "Isolated Web Co" once after a.test/plain -> a.test/same-site ([10878] -> [10878,
11208]). Not a process of an earlier test: it was created after the first read and only this worker's
descendants are counted. It is the top-level navigation: when the old document may enter the back-forward
cache, the browsing context is replaced (mReplaceBrowsingContext, dom/ipc/ProcessIsolation.cpp) and the new
one may be placed in another process of the same site (dom.ipc.processCount.webIsolated = 4). Measured on
firefox-62 (candidate #6, Linux): 0 of 30 runs alone (bfcache on and off), 0 of 57 under 4 workers. The test
was written for the frame, so the frame is now added to the page already shown and the top never navigates:
20 of 20 runs green.

0.50.0 never reached the index, so the changelog gate refused its heading; its entry now opens 0.50.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:47:54 +01:00
feder-crandClaude Opus 5.5 2bc12eb80b Release 0.50.1: 0.50.0 with the process-counting e2e corrected (0.50.0 never reached the index)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:59:28 +01:00
feder-crandClaude Opus 5.5 ff2123ef58 tests: a closed context is checked for the processes of its sites, not for every content process
test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process was red on the e2e of the 0.50.0
tag ([2, 2, 2, 5, 5], 5 <= 2). Measured on firefox-62 (Linux), the test's own scenario 10 times with every
process named: no "Isolated Web Co" left after any close; the 3 more are "Web Content", the engine's pool of
preallocated processes filling up behind the closed contexts (5 runs of 10, new pids each time). Not a leak:
the count read the refill.

The helper of the bench moves to tests/_processes.py and both tests use it. The context test counts the
processes that host a site: at least one while the page is open (or the count proves nothing), none a few
seconds after `close` answers (the engine waits for them inside close and kills the ones that stay). Off
Linux it skips, as the bench's two counting tests do: no other system names the process.

Unit tests (tests/unit/test_processes_counts_sites.py) from the measured processes, the closed-context case
included. e2e on firefox-62 (candidate #6, Linux): the context test 10 of 10; run_e2e.py on the two files and
the unit test 18 passed. The old counter, same scenario: 5 of 10 runs would fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:40:29 +01:00
feder-crandClaude Opus 5.5 5402da4d80 tests: the Fission bench counts the processes that host a site, not every new content process
test_same_site_other_port_stays_in_process was red on the e2e of the 0.50.0 commit ("a same-site frame
started a process: [13443]"): the bench counted every `-contentproc ... tab` pid, and the engine starts a
preallocated content process to refill its pool whenever it gets to it. On Linux the engine names a content
process by its remote type (ContentChild::SetProcessName, prctl PR_SET_NAME): "Isolated Web Co" once it
hosts a site of strategy 1, "Web Content" while preallocated. Measured on firefox-62: a cross-site frame
renames a preallocated process and a new "Web Content" refills the pool; a same-site frame changes neither.
The two tests that count processes skip off Linux, where no process carries a name.

Unit test with the measured processes: 3 red on the old bench, 3 green here. e2e on firefox-62 (candidate
#6, Linux): the bench file 17 passed; the two counting tests 15 of 15 runs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:18:54 +01:00
Federico EliaandClaude Opus 5.5 82d88c848f Release 0.50.0: engine firefox-62 (Fission strategy 1), pin invisible-core 62.63.0 (#450)
* grant_permissions: the permission names are the engine's, a name outside the table is refused, and no origin is every origin

The wrapper passed the web names (geolocation, notifications) to the engine, which keeps a grant under its own
(geo, desktop-notification) and stored one under a name it never reads: a page of a context that had been granted
geolocation and given a position was still denied. The table is the Playwright client's for this browser
(playwright-core ffBrowser.js, doGrantPermissions); a name outside it is an error, as there. A grant with no
origin was sent as the empty string, which the engine's lookup reads as false and answers with '*', where nothing
was held: it is now '*'. Tests: the table and the refusals as units, and the position of a granted page as an e2e
that fails on the old code (denied, or no answer).

* tests: the sentinels of the isolation strategy hold strategy 1, not 0

The baseline of a core that runs Fission (strategy 1, autostart, four isolated content processes) is what the
firefox-62 engine is built for: the Juggler reaches an iframe of another process like any other. The four unit
tests of test_cross_origin_iframe.py held the opposite (strategy 0, autostart off, one isolated process) and are
turned round: strategy 1, autostart on, fission.autostart.session absent (the parent writes it), four isolated
processes, the default of a translated profile 1, and an override to 0 only when a caller sets it. They fail on
invisible-core 61.62.0 and pass on a core with the strategy-1 baseline (invisible_core ffced25); the pin moves with
that core. The module text says why a harness of two ports of one host is one site and where the iframes that leave
the process are held.

* changelog: Fission (strategy 1) and the permission names, to be confirmed by the firefox-62 build

* e2e: the bench for Fission strategy 1 (a.test / b.test, a -> b -> a): two tests that hold it, eight that say what is not done yet

The prefs are an overlay of the file (strategy 1, autostart, four isolated processes, the test hosts through
network.dns.localDomains); the wrapper's baseline stays at strategy 0. Tests 1 and 2 pass today (a cross-site
frame adds a content process, a same-site one does not); tests 3 to 10 fail today on the empty url of a frame of
another process, the missing context, the missing parent chain, describeNode on a cross-origin element, the init
script that does not reach the other process, and the console that does not arrive.

(cherry picked from commit a8edf34d5f2da5e5e142359efe0dfaa801f5d57d)

* e2e: the bench of Fission strategy 1 reads the client's events while it waits, and holds three cases of step 1

The sync client takes the engine's events only inside its own calls: the waits of the bench now go through
page.wait_for_timeout. Added: a context of the top survives a frame of another process coming and going (a guard),
the frame of another process comes back after the top is restored from the back-forward cache, and a removed frame
of another process leaves page.frames and the page keeps answering.

(cherry picked from commit b9483514bb0be7712f378e1fbdc9ffd5701634b3)

* e2e: the bench splits the restore from the back-forward cache in the frames that come back and the url and contexts that come with them

The first is green with the parent re-announcing the frames it knows; the second stays red until the parent's
registry of navigations (step 3) and the mux's re-announcement of contexts (step 2b). set_extra_http_headers is not
in the wrapper's perimeter, so the removed-frame test uses the init script alone.

(cherry picked from commit 47a9d6f59ab237e173fe3c271fa37cbafe6e0668)

* e2e: element-to-frame and iframe geometry across processes (Fission strategy 1)

(cherry picked from commit 3ec3752333e76baaebdbbd78263028237fdda86a)

* tests: the crash of an iframe's process leaves the tab (firefox-62, Fission)

Kills the process that holds the iframe (found through the engine over Marionette, required to differ from the top's) and asserts the tab stays, no Page.crashed or close, and the page answers. Red on firefox-61: the unpatched engine closes the tab.

(cherry picked from commit 1e90ff23b3c3827cac943f926f30eeccaa6ec3aa)

* tests: the mouse events of the page and of a same-process iframe keep their order and values

Sequences recorded on firefox-61 (click, double click, right click with contextmenu, moves with the button down), through page.mouse; the test passes there and has to pass on the engine whose mouse takes the APZ route (a click on an iframe of another site needs the hit test).

(cherry picked from commit 4374fcab3c3e6718239cd36bad9c2970e1626aec)

* Test that the identity is the same in the top document and in every iframe

One local server on 127.0.0.1, 127.0.0.2 and 127.0.0.3 serves a top page with an
iframe on a second site (holding a nested frame on the top's own site) and an
iframe on a third site. Each document reads a fixed canvas drawing, a fixed
OfflineAudioContext buffer, the WebGL debug renderer info, the Intl time zone,
the navigator language and user agent, the screen geometry, the pixel ratio and
a font of the bundle, and posts them to the top; the test asserts they are equal
everywhere. screenX and screenY are read and not compared.

It runs under strategy 0 (what the core writes today) and under strategy 1
(fission.autostart and webContentIsolationStrategy=1 as extra_prefs). Each run
proves where the iframes ran from inside the page: one iframe spins for 400 ms
and the top times a 10 ms timer, which stalls only in a shared process.

The negative case is the machine the seed describes (WebGL renderer and screen),
because the 2D canvas and the audio buffer carry no per-seed value. The pure
comparison has unit tests with known-bad inputs.

(cherry picked from commit 76cae1a19abd65b30b72ea317dc42110541c8745)

* e2e: an iframe nested too deep names no frame, and a frame of another process comes out of the cache with the top

(cherry picked from commit 7f71460d799d8271346f470b0b2ad06c0a5315fb)

* e2e: the Fission tests that firefox-61 cannot pass wait for firefox-62

Measured on the released firefox-61 (Linux, run_e2e.py, 4 browsers): these twelve fail there and nothing else in
the six Fission files does. Ten of the bench (the steps that are not in firefox-61) and two of the
element-to-frame file (an <embed> of another process and the detach of a removed iframe). They now take
engine_at_least("firefox-62"), so the gate on firefox-61 is green (43 passed, 13 skipped) and the candidate runs them.

* e2e: a navigation that changes the process is stopped, replaced, refused or cut the way one that does not is

* e2e: an iframe whose src goes to another site shows the new address in the frame list

* A frame that left the page answers a call with "Frame was detached", not "Target page, context or browser has been closed"

The server disposed the dispatcher of a frame as soon as the lifecycle retired it, so the next call on the Frame object (an
iframe a script or a framework removed) named a guid that no longer existed and was answered as if the page had closed.
Measured with a process per site and without it: frame_element, evaluate, content and query_selector on a removed iframe,
all four. Playwright's driver never disposes a Frame at detach; the call reaches its dispatcher, which refuses it with
"Frame was detached". The frame stays registered (collected with its page or by its bucket, as the driver's), refuses every
call, and its element handles go with it.

Test: test_a_detached_frame_answers_detached.py (7 of its 10 fail on the old server code); test_frame_dispatch.py still
passes; test_a_removed_iframe_is_detached (the Fission e2e) passes on an engine with the Juggler of the integration.

* e2e: a worker leaves with its page for the back-forward cache and comes back the same (Fission strategy 1)

A document starts a worker that counts; the top goes forward (same site or another, by page.goto or by the page's
own location.href) and comes back from the cache (pageshow.persisted is checked). The protocol events the client
receives must say: workerCreated, workerDestroyed before the new page commits, workerCreated again with the same
workerId once after the restore's contexts are cleared, no workerDestroyed after it, one live worker that answers 3.
The worker lives in the top or in a frame of another site. engine_at_least("firefox-62"): it skips on firefox-61.

Measured on repacks of fission/integration (Linux, strategy 1): red on bdf02eb9d8 and on 1e9ff6dec0. In the top the
worker comes back under a new workerId; in the out-of-process frame it is not announced again.

* changelog: the Fission and permission-name entries are under 0.50.0

* e2e: the frames have their urls when goto returns (an iframe of another site, 50 runs, nothing waited for)

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

* e2e: a goto to the address the page is at ends, 20 times, on nine kinds of page (sites isolated)

Plain, big, revalidated with a 304, fresh in the cache, never stored, a frame of its own site, a frame of another
site (also revalidated), a -> b -> a, and the same query twice. Red on the engine of fission/integration 14e826b7b5
(load not reached, navigation started and neither committed nor aborted), green with the Juggler fix.

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

* A launch that names no session gets one: op_launch writes a composed session into every profile

A bare BrowserType.launch on the server (Playwright's own suite, any client of invisible_playwright._pw)
sent no prefs, and op_launch wrote into user.js only what the client sent: the engine came up with
Mozilla's defaults, no persona, every value a page reads taken from the machine. On Linux the first window
then also held the first-run policy tab of TelemetryReportingPolicy (the Terms of Use the core declares
accepted were not), and the first new_page failed with "Browser.newPage: Unexpected number of tabs in the
new window: 2": 15 of 15 bare launches on firefox-61 and on the firefox-62 candidate; with
datareporting.policy.firstRunURL emptied alone, 1 tab every time.

The launcher marks what it composes (COMPOSED_PREF, taken out before user.js like the seed); an unmarked
launch gets the session InvisiblePlaywright() composes with the server's defaults (new seed, humanize off as
in launch_server), with the caller's prefs on top. launch_server already sent a composed session: its e2e
and a unit test on the mark guard it. The one network step of composing (the egress IP) has one name,
_session.session_geo, which the unit tests answer offline.

Tests: test_a_launch_without_a_session_gets_one.py (4 unit: red on the old code, the profile held 0 prefs),
test_a_launch_without_a_session_gets_one_e2e.py (a bare launch has one tab and says Windows on the Linux
engine: red on the old code with "Unexpected number of tabs: 2"; every context of a served browser is the
same Windows machine). Unit suite 1128 passed on the firefox-62 candidate image.

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

* A launch that names no session also gets the session's environment variables

The variables `build_env` adds (the font manifest, the display backend, the crash reporter, the WebRTC
declaration with a proxy) are added to the environment of a launch that names no session, wherever the
caller named none of the same name. Unit tests: the manifest reaches a bare launch, a variable the caller
names wins, a composed launch gets nothing it did not send.

Measured before keeping it: no page-visible difference. On the firefox-62 candidate (Linux) and on
firefox-61 (Windows) a page of a bare launch lists the same families with and without the manifest: the
bundle's (Segoe UI, Calibri, the substitutes such as Helv and MS Sans Serif), none of the host's (FreeSans,
Unifont, Liberation Sans in the container; Segoe UI Variable on the Windows host). The engine uses its
packaged copy when the variable is absent.

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

* The session of a bare launch is composed through the launch's proxy; e2e: behind a proxy the page reads the egress as its srflx

`launch(proxy=...)` reaches `session_for_launch`, and the session is composed through it as
`InvisiblePlaywright(proxy=...)` composes: the egress measured there is the address the session's
environment declares for WebRTC (STEALTHFOX_WEBRTC_PUBLIC_IP). The engine is still told the proxy by
op_launch (Browser.setBrowserProxy), as before.

e2e test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx: a bare launch behind the local
TCP-only SOCKS5 of test_webrtc_realness.py, the egress answered with 203.0.113.7 (RFC 5737). The page must
read a srflx of that address. Red on the prefs-only commit (no srflx of the egress: host candidates only)
and on release/firefox-62 (the two-tab refusal); green here. Unit suite green on the firefox-62 candidate.

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

* tests: the named environment of an unmarked launch carries the session's variables, and still nothing of the server's

test_the_launch_handler_hands_the_named_environment_to_the_engine asserted the engine got exactly the named
variables (plus the session's TMP). An unmarked launch now also gets the variables of the session the server
composes for it (font manifest, display backend, crash reporter): the test reads them from
_session.default_session and keeps its point, WAYLAND_DISPLAY of the server's own process stays out.
It went red on 36cffac, which I committed without running the whole unit suite.

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

* tests: the same-document navigation test attaches the frame it reports on

The engine announces a frame (Page.frameAttached) before any event of it, and from invisible-core's fix on
release/firefox-62 the lifecycle makes frames of that event alone: an event of a frame it does not know is
dropped. The three tests of this file reported events of a frame "F1" they never attached, which only the old
auto-creation accepted. Green with the old core and with the new one.

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

* tests: the gates of the shelved line ask for firefox-63 again; firefox-62 is the Fission release

#444 renumbered the engine gates when the shelved line (idwr text, canvas colours and ICC readback, maths,
media decoding, WebGL arithmetic, the Linux system-theme refusal) was firefox-62. That line is firefox-63 now
and firefox-62 is Fission (one process per site), which has none of those properties: on the firefox-62
candidate 14 of those tests ran and failed (WebGL dot, canvas text, ClearType, ICC, fonts and colours,
WebCodecs). The seventeen files #444 touched ask for firefox-63 (comments and docstrings too), conftest.py
names the same number, and tests/unit/test_engine_at_least.py checks that 61 and 62 skip a gate that asks 63.
The Fission tests (bench, worker, crash, oop_frame_element, goto to the same url, raw launch, mouse events,
cross-origin iframe) keep firefox-62. Default suite: 1131 passed, 8 skipped; the three reds are the install
metadata of the shared Python.

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

* tests: the hand-built InjectedScript of the adopt test has the detached frames the wait for a world reads

invisible-core 62's wait for a frame's world ends at the frame's detach and reads InjectedScript._gone, which __init__
makes. test_adopt_is_one_wire_call_for_both_crossings builds the object without __init__ and sets what __init__ gives
it by hand; it now sets _gone too. (Red on the core with the detach wait: "no attribute '_gone'".)

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

* Release 0.50.0: pin invisible-core 62.63.0 (engine firefox-62, Fission strategy 1)

CHANGELOG 0.50.0: the engine entry, and the fixes of the bare launch and of a detached frame; the
Fission and permission-name entries were waiting for the firefox-62 build, which shows them (candidate #6).

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

* tests: the docstring of the bare-launch e2e says what the served browser is for, not who runs it

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

* tests: the gates of the shelved line ask for firefox-64; firefox-63 is the coherent UDP

The 16 e2e files of the shelved line (idwr text, colours, maths, media, WebGL, host-free Linux),
conftest's description of engine_at_least and its unit test: firefox-62 and firefox-63 skip them.

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

* tests: the refused iframe's address is read by scheme and host, not by a prefix of the string

CodeQL (incomplete URL substring sanitization) flagged the startswith on the frame's url; the
split url says the same thing and cannot match a longer host. The file passes on firefox-62 (5 of 5).

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 12:39:30 +01:00
github-actions[bot]andfeder-cr e2a006d1c9 record 0.49.1 as published (#449)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 20:17:23 +01:00
Federico EliaandClaude Sonnet 5.5 c33b9dd8f2 0.49.1: the firefox-61 engine through invisible-core 61.62.0 (#448)
* Add INVPW_GC_EVERY_NAV: optional Heap.collectGarbage every N main-frame navigations

Off by default. The collection is sent from a daemon thread (never from the
reader thread, which would deadlock), with at most one in flight; a round
due while one runs is skipped and counted, and every error is swallowed.

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

* INVPW_GC_EVERY_NAV: send the collection with the page session; fix page.request_gc

Juggler answers Heap.collectGarbage from its page handler. Sent with the
browser-level connection it fails with 'Handler for does not implement method',
so the first version of the option counted every collection as failed, and
page.request_gc() has been failing the same way.

The option now sends with the session of the page that committed (a thread of its
own, one in flight); op_request_gc uses the page session too. Tests fail on the
old code and pass on the fix; measured on the engine: collections take 0.02-0.09 s
and the values a page reads are identical with the option on and off.

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

* INVPW_GC_MODE=minimize: the option can send Heap.minimizeMemory, with a fallback to gc

INVPW_GC_MODE=gc|minimize (default gc) says what INVPW_GC_EVERY_NAV sends. minimize sends the
Juggler command that runs about:memory's "Minimize memory usage" (engine commit 2423b7c242 of
the engine's juggler/minimize branch); on an engine without it the first round logs one
warning and falls back to Heap.collectGarbage for that round and every later one (the
engine's answer, "method '...' is not supported", is the sign).

Unit tests for the mode, the fallback and the other errors; e2e (engine_at_least firefox-61)
that the engine takes the command and, as documentation, that minimize evicts the bfcache
(pageshow.persisted false on go_back) where nothing sent leaves it true. Measured on the
engine with the command, and on the one without: the first and third e2e fail there.

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

* INVPW_GC_MODE: the command must be named in the error that makes minimize fall back to gc

A fallback on any error saying "is not supported" would turn the mode down for good on an
unrelated error; the sign of an engine without the command is its answer naming it
("method 'Heap.minimizeMemory' is not supported", or 'does not implement method "..."').
Also the docs say what the command is: the memory manager's MinimizeMemoryUsage.

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

* tests: the minimize e2e uses a plain protocol client, and the protocol-name scan lets the engine-gated name through

The e2e imported the installed Playwright (test_fork forbids it) and the vendored client has no
connect: it now speaks the protocol over the served WebSocket, like the other served-browser e2e.
Re-run on an engine with the command (all three pass) and on one without (the first and the third
fail, with the fallback warning).

Heap.minimizeMemory is written by navgc.py for an engine the published core's protocol mirror does
not describe yet, behind a fallback to the older command. test_protocol_names_are_declared keeps it
in AHEAD_OF_THE_MIRROR, still checks every other name, and a last test fails when the mirror gets
the command, saying to delete it from the list.

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

* The periodic collection option is out: only the page.request_gc() fix stays

The engine has no behaviour that stock Playwright's Juggler lacks, and a server option that
sends a memory command on a schedule is one. INVPW_GC_EVERY_NAV and INVPW_GC_MODE, navgc.py,
the hook in the commit path, their unit tests, the e2e of the engine command and the entry in
the protocol-name scan leave the branch.

What stays is a defect of the standard API: page.request_gc() sent Heap.collectGarbage on the
browser connection, whose handler does not have it, so it failed on every call; it is now sent
with the session of the page. The test fails on main's server.py and passes here.

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

* 0.49.1: page.request_gc() works on a served browser

A change to the package's code takes a new version and a changelog entry: 0.49.0 is published.

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

* tests: the web fonts of closed contexts leave WebRender's shared archive (firefox-61)

A probe opens N contexts, each with a page that loads a web font of its own
bytes, closes them, and reads explicit/gfx/webrender/resource-cache/fonts from
a memory report (Marionette, chrome scope) before, with contexts open, and
after. On firefox-60 the archive keeps ~1 MB per closed context (10/20/40
contexts: 10.4/19.8/40.7 MB, measured); the test asserts it is back at what it
was from firefox-61 and is skipped on an older engine.

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

* Disable the context cache while a route is active, as upstream

Playwright's ffBrowser.doUpdateRequestInterception sends
Browser.setCacheDisabled with the same flag as Browser.setRequestInterception.
The server sent only the second, so a routed context filled the engine's cache2
on disk. op_set_interception now sends both, for the same context.

* tests: a context that ends leaves no content process (e2e, from firefox-61)

A page that registers a service worker whose script is `for (;;) {}` kept its content process alive
after its context was closed. The test closes three such contexts and counts the web content
processes after each; on an engine without the fix the count grows by one per context ([4, 5, 6]),
with it it does not. Skipped on an engine older than firefox-61.

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

* 0.49.1: the firefox-61 engine through invisible-core 61.62.0 (prepared, not pushed)

Pin to the core that carries the firefox-61 seal (the core is not published yet) and the changelog of the
engine's four fixes, on top of the four open branches this release carries: page.request_gc() (#442), the
context route and the cache (#447), the web fonts of closed contexts (#445) and the processes of an ended
context (#446).

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

* tests: the process count of an ended context is compared from the second context on, over five

On the Linux gate the count after the three contexts was [2, 3, 3]: the first context adds one process
that is not the leak (a spare content process the engine starts when the first page takes one) and
then the line is flat, and counts[2] <= counts[0] failed on the engine WITH the fix. Five contexts, and
the last must not be above the second: with the fix [.., 3, 3, 3], on the old engine every context adds
one ([4, 5, 6, 7, 8] measured on Windows). Run on both engines locally.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 19:46:25 +01:00
Federico EliaandClaude Sonnet 5.5 ebaed54e0e tests: the engine gates that ask for firefox-61 ask for firefox-62 (#444)
The corrections release is firefox-61 now, and the shelved line (idwr text, canvas colours and ICC
readback, maths, media decoding, WebGL arithmetic, the Linux system-theme refusal) is firefox-62.
The seventeen files whose engine_at_least gate asked for firefox-61 ask for firefox-62, comments and
docstrings too; conftest.py names the same number in its comment and docstring.

tests/unit/test_engine_at_least.py: the engines firefox-61 and firefox-61-candidate are skipped by a
gate that asks for 62. With the old minimum (61) three of its cases fail; with 62 the file passes.

Default suite in a clean checkout: 1084 passed, 9 skipped.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 16:55:10 +01:00
github-actions[bot]andfeder-cr 8de4cd2c9f record 0.49.0 as published (#443)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 15:03:28 +01:00
Federico EliaandClaude Opus 5.5 087117dfc6 0.49.0: the firefox-60 engine through invisible-core 60.61.0 (#441)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:27:39 +01:00
Federico EliaandClaude Sonnet 5.5 b85c8f49a1 tests: the body of a document the tab left is evicted (e2e, from firefox-60) (#440)
The engine of firefox-60 evicts, when the main frame commits a navigation, the bodies of the documents the tab
left, as Chromium does; a body over the cap already answered 'evicted'. The test serves two pages from a local
server, reads the bodies of the current document, then of the one that was left, and checks that the second
context and the page still work after the bodies are gone.

Gated with engine_at_least('firefox-60'): skipped on firefox-59 (checked with the real gate), and run by hand
against a copy of the firefox-59 engine with the fix it passes, against the unmodified one the first test fails
with 'DID NOT RAISE'.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 12:07:59 +01:00
Federico EliaandClaude Sonnet 5.5 e82ae18bac tests: the engine gates that ask for "firefox-60" ask for "firefox-61", the name of the shelved line (#439)
Seventeen e2e files skip unless the engine is at least "firefox-60": the idwr text, the canvas
colours and ICC readback, the maths, the media decoding, the WebGL arithmetic, the Linux system
theme refusal. Those are the goals of the line that is now called firefox-61. The name firefox-60
is the next release of the engine (firefox-59 plus the Juggler memory fixes), which has none of
them: with the gates at 60 they would have run on it and failed. They ask for 61 now, and a unit
test says that engines 60 and 60-candidate are skipped by a gate that asks for 61 (it fails with
the old minimum, which let 60 run).

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 12:01:53 +01:00
github-actions[bot]andfeder-cr b1887220a3 record 0.48.1 as published (#438)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 11:03:31 +01:00
Federico EliaandClaude Sonnet 5.5 f3d083aa85 0.48.1: the browser never opens its crash reporter, launch_server is public (#437)
* e2e: the run stops at the first refusal of the engine instead of launching for 26 minutes

Against a firefox-59 engine whose gate wanted a declaration the core no longer made (59.58.0), the
suite went on for 26 minutes, launching the browser for each test, being refused each time with the
same sentence, and opening a crash window per refusal on the desktop. tests/engine_refusal.py reads
the text of a failed e2e report and, when it holds the engine's own refusal ("stealth: X is not
declared. Engine rule 7" or the scale refusal), stops the run with that sentence as the reason:
session.shouldstop on the serial path, the controller's shouldstop under xdist (a worker is never
stopped alone). A test that expects a refusal passes, so it never reaches the plugin; a unit test
that only quotes the sentence does not count.

The unit tests read the sentence; the integration tests run pytest over twenty e2e-marked tests of
which the second fails with the refusal, serial and with -n 2: the old suite ran all twenty (the two
fail without the plugin, and a failure that is not a refusal still runs all twenty).

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

* launch_server, launch_server_async and RemoteServer are on the package; the README shows a server and a client

The server API was reachable only through invisible_playwright._juggler.remote, a private path.
`from invisible_playwright import launch_server` now works, with launch_server_async and
RemoteServer, and they are in __all__. The README section "Serving one browser to many clients"
gets a complete example: a server with launch_server() and a Playwright for Python client that
connects to its ws_endpoint, how to install the extra, where it listens and how the browser ends,
and one line for a client in another language. The example was run against the real engine (the
server printed its address, the client read "Example Domain" and closed, the server's browser stayed
up until Enter).

The test checks the exports and reads the README block against the package; four of its five tests
fail on the old code.

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

* 0.48.1: invisible-core 59.60.0 (the browser never opens its crash reporter), launch_server on the package

Pins invisible-core 59.60.0, whose launch environment carries MOZ_CRASHREPORTER_DISABLE=1. The
version is 0.48.1 and the CHANGELOG names the crash reporter, the exported launch_server with its
README example and the e2e run that stops at the engine's first refusal.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 10:29:20 +01:00
github-actions[bot]andfeder-cr 8f86007065 record 0.48.0 as published (#436)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 09:16:28 +01:00
Federico EliaandClaude Sonnet 5.5 1ff8ed5785 0.48.0: launch_server, and the engine firefox-59 through invisible-core 59.59.0 (#435)
* wire: a protocol message is JSON, and a transport that proves it

_juggler/wire.py: dumps/loads/round_trip, and WireError naming the path of the first
value JSON would change or lose (bytes, sets, objects, non-string keys, NaN/inf).
JsonWireTransport (INVPW_WIRE=json) puts that wire between the client and the server
of the in-process transport, in both directions: a non-JSON client message raises from
send, a non-JSON reply fails its call with the path, a non-JSON event is recorded in
wire_errors. Local use is unchanged (no JSON unless asked).

tests/test_the_wire_is_json.py: 12 unit tests; the reply-that-is-not-JSON test fails
when emit_message forwards unchecked. The unit suite has the same results with and
without INVPW_WIRE=json; running the e2e suite on the wire is the next step.

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

* wire: the server reads a 1.62 message like a 1.61 one, fixed at Dispatcher.handle

Playwright 1.62 moved the call's timeout from the parameters to the metadata,
so a 1.62 client's timeout was lost and every call waited 30 s. handle() now
folds the variants into one shape (_juggler/variants.py), with no version
check: a timeout in the parameters wins, one in the metadata fills the gap,
unknown fields pass unread. scroll is ignored on purpose (documented); a
webp screenshot, screencastFrameAck, waitForFunction on a selector and
virtual credentials refuse that one command with their reason.

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

* wire: a 1.62 screencastFrameAck is accepted and does nothing

The server already acknowledges each screencast frame to the engine, so a client that
acknowledges every frame (1.62's does) is answered, not failed.

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

* wire: a Dialog is an object of the protocol, and the server stops reading the client's registry

The Dialog was a fused class: no __create__, no guid, no channel. The server
built it with Server.twin(page guid), looked into the client's guid registry
(bind_impl_objects/bind_twins) and called BrowserContext._on_dialog through
Connection.deliver_event.

Now DialogDispatcher (TYPE Dialog, parent the Page, initializer type/message/
defaultValue/page, methods accept/dismiss) is announced with __create__ and
then carried by the context's `dialog` event; _dialog.py is a ChannelOwner as
in Playwright, with its case in _object_factory.py, and the event reaches the
listener through Connection.dispatch like any other. Removed: _emit_fused_dialog,
send_async, Server.bind_twins/twin/deliver/run_blocking/call_soon, the
transport's bind_impl_objects/run_blocking/call_soon, Connection.deliver_event
(dispatch is upstream's again) and the bind calls in both context managers.
The reader's pause stays: accept/dismiss answer through
PageDispatcher.answer_dialog, in the worker. diff_protocol no longer lists
Dialog as an expected difference.

Tests: test_a_dialog_is_a_protocol_object.py fails on the old code; the pause
test now covers the answer over the channel.

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

* remote: launch_server() serves one browser to any protocol client over a WebSocket

One launch, one registry, a connection per client: objects are owned by the
client that made them, a client leaving closes its contexts and not the browser.
initialize answers with BrowserType, LocalUtils, Browser and a Playwright root
carrying preLaunchedBrowser. No version check, no limit of ours; the identity
stays the server's. A dialog, which cannot cross the wire, is dismissed.

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

* remote: the Playwright initializer names every required type of spec 1.62

A client built on the 1.62 spec (playwright-go's newPlaywright) reads chromium, firefox, webkit,
android and electron from the Playwright initializer without checking for a missing one and
panics: 'fromChannel: expected *channel, got <nil>'. chromium and webkit are BrowserTypes whose
calls refuse with a reason; Android and Electron likewise. Announced before Playwright.

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

* pin invisible_core 59.57.0 (the pin PR 413 proposes), engine firefox-59

One core for the image that serves this wrapper: the unit suite and a quick e2e (the served
browser answering a plain client, add_script_tag, dialog pause) run on core 59.57.0.

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

* server: "no-override" is not sent to the engine as a colour scheme, motion or forced-colors value

The Go client (and Playwright's null) says "not overridden" with the string
"no-override". The server passed it to Browser.setColorScheme (and the motion
and forced-colors commands), whose enum has no such member, so the engine
refused the whole newContext. Now nothing is sent and the context keeps the
persona's declared theme; explicit dark/light/no-preference still go out.
Page.setEmulatedMedia treats it as a reset (field left out, empty medium).

Tests: unit (6 of 11 fail on the old server) and an e2e with a light and a
dark persona that reads prefers-color-scheme through a Go-style context.

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

* remote: the pointer's walk is drawn by the server, once, for every client

The in-process client patched Frame._click/hover/dblclick/tap/check,
Mouse.click and Mouse.wheel and sent N mouseMove before each action; a
client that is not ours sent one Frame.click and the page saw one
mousemove (measured with humanize=True on a served browser). The walk
(approach, off-centre landing, idle fidget, scroll detents) moves to
_juggler/pointer.py, built per page from the session seed, the page's
number and the humanize budget, and called by FrameDispatcher and the
Page mouse ops. The in-process client now sends the plain action.

- an explicit mouse.move stays the caller's: the server walks it only
  when the in-process client marks it (humanise); a standard client's
  move reaches the page as the exact point it named
- who draws travels in the launch prefs (invisible.server.pointer), so
  the engine's own expansion and INVPW_CURSOR_ENGINE=off are not
  humanised twice
- golden from 5d9ad70 (tests/data/pointer_golden.json, with its origin
  and generator): a Frame.click reaching the server draws the same
  engine events, same coordinates and instants, as the client did

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

* server: Mouse.click puts one mousemove on its point, not two

Pointer.click_at sent the endpoint as a move of its own and then Actions.click_at
moved onto it again as its own approach before the press: the engine got two
mousemove with the same coordinates at the same instant, which no mouse reports
and a page can count. The defect predates the move of the walk to the server
(it was the client's Mouse._click); it is corrected at the source instead of
being preserved, for every transport (op_mouse_click is the one path).

- pointer.py: click_at sends the stroke and lets the click's own approach be the
  one move onto the point; the hand is re-synced after the click.
- golden: only the explicit_pointer session (the one with a Mouse.click)
  changes, regenerated by tests/data/pointer_golden_origin.py
  --revise-mouse-click, which refuses unless the result is the old session minus
  that one repeated move; the origin says why.
- tests: no two consecutive equal mousemove in a humanised Mouse.click (fails on
  the old code), plus an e2e with one real browser that counts them in the page.

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

* server: a stroke from standstill does not open with the point it stands on

The first waypoint of a stroke is its start. When the engine has already been
told the pointer is on that pixel (a move that stopped there, then a pause), the
stroke sent it again: a zero-displacement mousemove no mouse reports. Pointer.
_travel now skips a first waypoint that coincides with the position the engine
knows; a pointer the engine was never told about (the page's first movement,
from the seeded start point) still opens with its first waypoint.

- golden: only the explicit_pointer session changes (one mousemove fewer; t, x,
  y and type of every other event unchanged, latency draws follow the ordinal),
  regenerated by pointer_golden_origin.py --revise-standstill, which refuses
  unless the other three sessions equal the server's run event for event.
- tests: no repeated or zero-displacement mousemove from standstill after 0, 0.2
  and 5 s, for click and move (fail on the old code); e2e with one real browser.

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

* server: a closed context leaves nothing in the registry, the browser's lists or the wire's error log

The three children of a context (Debugger, Tracing, APIRequestContext) were
announced under the browser and adopted by the context on the wire, but dispose
forgets a subtree by walking parent, so they outlived every context: 3 registry
entries per context (500 contexts: 1,500). browser.contexts kept every closed
context with its options and owner, browser._artifacts every download, and a
Stream's file stayed open when its parent's dispose forgot it (the cascade does
not call dispose on a descendant). New Dispatcher.released(), called for the
object and for each descendant the cascade forgets, lets go of what other
objects hold of it. RemoteEndpoint.wire_errors keeps the last 32, not all.

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

* remote: an opt-in memory probe (INVPW_MEM_LOG) and malloc trim (INVPW_MALLOC_TRIM), both off by default

INVPW_MEM_LOG=<file> writes a JSON line every INVPW_MEM_LOG_INTERVAL seconds
(default 2) and at each context close: uss/rss, registry objects, contexts,
clients, the bytes and messages queued in the clients' outboxes (read from the
queue at sampling time, free when the probe is off), gc counts and glibc
mallinfo2. INVPW_MALLOC_TRIM=1 calls malloc_trim(0) after each message of 64 KiB
or more has been sent and at each context close (Linux only; elsewhere ignored
with one warning). With both off nothing is built or loaded and the wire is
byte-identical.

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

* server: the guid registry collects its oldest dispatchers like Playwright's server

Per bucket (the object's type; Frame is MainFrame or Frame), past the limit the oldest
tenth is disposed with __dispose__ {reason: "gc"} to its owner and its subtree silently,
as dispatchers/dispatcher.ts of Playwright 1.62 does: 10000, JSHandle and ElementHandle
100000, one value per type in dispatcher.GC_LIMITS (INVPW_GC_LIMITS lowers some without
editing code). The registry is walked once per batch, not once per object. An event on a
disposed object is dropped, a request or frame already collected is not named again.

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

* server: a request and a response keep what they hold, not what the wire carried

Measured on a real browser (one context, 95 navigations, ~100 subresources each) a Request
was 4.5 KB and a Response 6.0 KB: headers as a list of dicts kept twice (initializer and
raw_headers), the POST body and the timing in the initializer. Headers are now a tuple of
interned (name, value) pairs rebuilt on demand, the certificate is one object per distinct
certificate, the remote address a pair, and the initializer is replaced after the
__create__ by a copy without headers, postData and timing (a new dict: a message waiting in
a queue still holds the old one). Dispatcher.announced() is the hook; released() clears a
request's and a response's state when they leave the registry. 0.84 KB each, and the same
run ends at 73 MB instead of 149 MB.

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

* server: Request, Response and Route collect at 2000, and nothing younger than 10 s is collected

Two declared differences from Playwright's collector (dispatcher.GC_LIMITS, docstring):
the three network types have a limit of 2000 instead of 10000, and an object younger than
GC_MIN_AGE_S is never a victim, so what a client was just handed (the Go client uses a
request inside the callback of its event) stays valid however fast the bucket fills.
Measured on a real browser, one context, 95 navigations of pages with ~100 subresources
and heavy headers: 193 MB at 10000, 74 MB (flat from navigation 25) at 2000.

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

* remote: malloc_trim is on by default on Linux; INVPW_MALLOC_TRIM=0 turns it off

After a context closes and after each message of 64 KiB or more is sent, the served browser
calls malloc_trim(0) when the libc has it (glibc on Linux). Slack's runs of 95 navigations: the
free memory glibc held (fordblks) went from 13 MB to 177 MB by default. Off Linux, with musl or
a libc without the function, nothing is called and nothing is said. No mallopt here:
MALLOC_ARENA_MAX=2 is process-wide, the launcher's to set (README). The probe stays off
and free unless INVPW_MEM_LOG is set.

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

* docs: the registry's collection limits and what they mean for a program that holds many old requests

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

* release 0.48.0: launch_server, and the engine firefox-59 through invisible-core 59.57.0

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

* ci: the missing-websockets message is spelled by the installer, and two tests share a fixture without redefining it

The message named a written pip install, which the way-in check refuses; it is built with
invisible_core.installer now, as _engine.py does. The two tests imported a fixture and
took it as an argument (F811); they bind it by assignment instead.

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

* ci: the pointer test reaches its fixture module the way the other tests do, not through a tests package that CI does not have

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

* test: the trim test waits for the trim, which the writer runs after the send

A fixed read of the trim count right after the reply failed on a slow runner (the client
holds the reply before the writer's next line runs). A delayed trim fails the old test and
passes this one.

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

* test: the WebGL e2e looks at the engine processes below its own test, not at the first one on the machine

With several workers in /proc the scan over every process could be handed another worker's
browser, which had not drawn yet and maps only the host's libgallium (GTK's GLX): red on one run of
the Linux gate and green on the next, same engine and core. The test now walks the tree under its
own process, asks that at least one process there maps the engine's libEGL and libgallium and that
none maps a host libEGL; a unit test with two trees on one machine fails a whole-machine scan.

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

* test: a click's stroke is judged by its shape, not by how many mousemoves reached the page

The pacer drops a sample it cannot send on time, so the same stroke is 15 events on an idle machine
and 6 to 9 on a loaded one (Windows with 32 busy processes; the Linux gate with four workers got
9). The e2e asked for more than 10 and failed on the gate with a real stroke: it left from
(1116, 731), came in steps and ended on the click. It now asks that the stroke left from far away,
came in at least one step and ended on the target with no repeated mousemove; the standstill test
asks for something before the landing, not for 6 events. The unit test holds the gate's page events
as data: the old rule refuses them, the shape rule accepts them, and a jump, two events, a miss, a
start on the target and a repeat are refused. Ten idle runs and three loaded runs pass on Windows;
the old test fails under load.

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

* Pin invisible-core 59.58.0; the pinning page drops the two keys that core no longer accepts

59.58.0 is on PyPI. Besides the same numbers from a seed on Python 3.11 to 3.14 (the red
py3.11 job), it stops declaring the glyph coverage ladder and forces no sRGB output profile, so
the pin keys font.alpha_ladder and desktop.srgb_output are refused by the validator; the pinning
page listed both and test_pinning_doc caught it. Their rows are gone.

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

* Pin invisible-core 59.59.0 (59.57.0 and the version-independent float arithmetic)

59.59.0 is 59.57.0 plus only the fix for the two builtins that differ between Python versions
(sum() of floats and math.log2), which was the red py3.11 job. It keeps the glyph coverage
ladder the firefox-59 engine's declaration gate requires and the sRGB output pin, so the
pinning page lists font.alpha_ladder and desktop.srgb_output again.

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

* The server answers NaN, the infinities and -0 as Playwright's tag, not as a bare number

Found by the e2e run on the strict JSON wire: page.evaluate_handle("() => NaN").json_value()
passed in process and failed with "$.result.value.n: nan is not JSON". The server's serializer
answered {"n": nan}, which Python writes as the bare word NaN and no other JSON reader accepts.
Playwright sends {"v": "NaN"} (and "Infinity", "-Infinity", "-0"); so does the server now. The
unit test fails on the old serializer (9 of 11) and the e2e that found it passes on both wires.

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

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 08:44:54 +01:00
Federico EliaandClaude Sonnet 5.5 0eee28d093 e2e: the refusal of a missing system theme pref is expected on Linux only (#433)
On Windows the engine takes the system fonts and colours from the toolkit as
retail does (StealthVerifySystemTheme returns unless MOZ_WIDGET_GTK), so a
launch without ui.highlight, ui.-moz-field or ui.font.menu does not refuse
there. Candidate 42673795394's Windows gate ran the test and got DID NOT RAISE
three times. The refusal test now skips on win32; the control launch still runs.

tests/unit/test_theme_refusal_drop.py checks the skip mark on the refusal test
and its absence on the control; it fails on the test without the mark.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 21:13:45 +01:00
Federico EliaandClaude Sonnet 5.5 ccb0ff051f e2e: the refusal test launches the engine with the crash reporter off (#431)
The three missing-pref cases end in a deliberate abort (the engine refuses the launch), and each
opened the crash reporter on the desktop of whoever ran it.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:51:34 +01:00
Federico EliaandClaude Sonnet 5 0321737429 e2e: the B-frame order test uses the RDD process, like a real user (#432)
media.rdd-process.enabled=false and media.gpu-process-decoder=false left
the content process with no video decoder at all on Linux: WebCodecs'
configure() rejected with no decoder found for video/avc (MOZ_LOG
WebCodecs:5/MediaDecoder:5 confirms it, not a guess), fast and clean. The
hang the test actually showed was separate: flush() rejects right after
that, and nothing caught it inside the test's own new Promise, so resolve()
never ran and Playwright's own 30s evaluate timeout is what finally fired.
A real user always has the RDD process; dropping those two prefs runs the
default path instead of a configuration retail never has. flush() now
settles the promise on either outcome, so a real decode failure surfaces
immediately instead of hanging for 30s.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 17:51:25 +01:00
Federico EliaandClaude Sonnet 5.5 e8b57121e1 e2e: the dot() reads a zero's sign as the GPU does (zeros of both signs in the vectors, the comparison keeps the sign) (#430)
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:42:17 +01:00
Federico EliaandClaude Sonnet 5.5 fa0d19cca3 e2e: the fontconfig test fails on an open of the host's configuration, not on the parent's existence probe (#429)
Candidate 42640321957 failed it on one lstat("~/.fonts.conf") of the parent: the parent builds
the content sandbox's permissions (SandboxBrokerPolicyFactory::InitContentPolicy) and asks
whether each path exists. It opens nothing, no byte of those files enters the process, and a
page cannot see it; the sandbox policy is not touched.

The criterion is now: a process that OPENS a host fontconfig or font path fails (an open
that fails with ENOENT too), and a content process that does anything there fails (stat,
access, readlink). The parent's existence probes are ignored, with the reason in the module.
tests/unit/test_fontconfig_criterion.py runs it on fake strace lines: the lstat passes; a
parent that opens /etc/fonts/fonts.conf or ~/.fonts.conf, and a content process that stats a
host font directory, fail.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:36:37 +01:00
Federico EliaandClaude Sonnet 5.5 1e23d20e0c e2e: the missing-system-theme-pref helper's regex compiles, with a unit test that fails on the old one (#427)
The regex that finds a pref's line in user.js had a lone backslash before its closing bracket
(an unterminated character set): every case of the e2e died with re.error before launching
a browser (candidate 42624473465, Windows gate). tests/unit/test_theme_refusal_drop.py runs
the helper on a user.js of its own and fails on the old regex.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:09:20 +01:00
Federico EliaandClaude Sonnet 5.5 3481f419c7 e2e: coloured canvas text and ClearType keys are drawn as retail Windows draws them (from firefox-60) (#428)
tests/data/canvas_text_ref only compares black text on white under one ClearType state, which
hides what a text-mask hook changes: 12 of 14 coloured cases differ from retail on an engine
that quantises its A8 masks.

New e2e, with hashes from retail Firefox 159.0 on Windows (headless, same pages, same bundled
fonts):
- the 14 coloured cases (7 colour pairs x Arial 16/33 px) with the seed's configuration;
- 39 cases (25 black of canvas_text_ref + the 14 coloured) under three ClearType keys,
  1800/100, 1400/50 and 2200/0, one launch per key with the font.cleartype_gamma and
  font.cleartype_contrast pins. The failure message lists each differing case.

The pin, the font check and the server of the existing canvas text test move to
tests/_canvas_text.py, which both tests import. The reference holds pages, hashes and
metadata only (scripts/build_canvas_text_colors_refs.py rebuilds it from the saved bytes);
tests/unit/test_canvas_text_colors_refs.py checks its structure and that the keys give
different hashes.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:35:47 +01:00
Federico EliaandClaude Sonnet 5.5 5c0de53221 e2e: a WebGL dot() gives the bits of the GPU family the persona declares (from firefox-60) (#426)
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:25:58 +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 c23612e295 test: the docs name the MCP server's repository and command as they are now
feder-cr/AIHawk now leads to an unrelated repository and answers 200, which no
link checker reports; `uvx aihawk` does not exist. The README and docs/ are
read for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:49:05 +01:00
feder-cr 11b9e08b1a docs: the agent links and the command name the repo as it is now
Two things were broken for a reader on main, not one.

Thirteen links pointed at github.com/feder-cr/AIHawk. GitHub redirects a
NAME to the OBJECT that carried it, not to the content: after the September
swaps that name belongs to invisible_dots, which has seven wiki pages, so
AIHawk/wiki/<page> lands on its wiki Home. It answers 200 with different
content, which means a reader who clicks does not find the page and a search
engine sees a soft-404 across about 150 indexed URLs.

Seven occurrences said `uvx aihawk`, a command that does not exist. One sat
in a front-matter description, which is the snippet search engines show, and
one in a block meant to be copied: `claude mcp add stealth -- uvx aihawk`.
The command is invisible-playwright-mcp, on PyPI at 0.70.16.

All eight link targets were checked one by one and resolve to themselves with
the page title, no redirect.

Three things stay as they are, which only reading them showed. The
`pip install invisible-playwright` line matches what this engine's own README
teaches for the library, so the page is consistent rather than broken.
CHANGELOG.md keeps the old name because a changelog entry says what was true
then. And the fixture in scripts/sync_article_pixels.py keeps it because it is
the deliberate wrong case, a pixel for ANOTHER repo.

One sentence went away instead of being renamed: "shipped inside AIHawk" made
sense when AIHawk was the larger product containing the server. The server and
the repository are now the same thing, so "shipped inside itself" was circular.

(cherry picked from commit d9c8e46dce)
2026-11-06 19:47:58 +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
343 changed files with 61392 additions and 4780 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
+78
View File
@@ -0,0 +1,78 @@
# ─────────────────────────────────────────────────────────────────────────────
# 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
# docs/badges/launches.json, docs/badges/downloads.json - read by shields.io
# for the big row at the top of the README
#
# 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 }})
+64 -8
View File
@@ -34,18 +34,43 @@ on:
- 'docs/**'
- 'LICENSE'
workflow_dispatch:
inputs:
only:
description: "Which job. `windows-control-a` runs only the Windows job of the keyboard shortcut (after the core of a release is on the index and its engine is published); `all` runs the whole workflow."
required: false
default: "all"
type: choice
options:
- all
- windows-control-a
permissions:
contents: read
# One run of this workflow per branch at a time. A newer push cancels the older
# in-flight run as a whole, cleanly, instead of leaving its queued jobs to be
# cancelled one by one - which left the run marked failed even though nothing
# had actually failed. Keyed by workflow + ref so tests and e2e never cancel
# each other; only an older run of THIS workflow on the same branch is replaced.
# A newer push to a pull request cancels the older in-flight run of THIS
# workflow on that pull request as a whole, cleanly, instead of leaving its
# queued jobs to be cancelled one by one - which left the run marked failed even
# though nothing had actually failed. Keyed by workflow + pull request number,
# so tests and e2e never cancel each other.
#
# NEVER on main. The release gate (scripts/e2e_is_green.py) asks for the e2e
# check-run of the commit being tagged, and a cancelled one refuses the release:
# with the group keyed by ref, the next push to main cancelled the run of the
# commit before it. Outside a pull request the group is unique to the run
# (`github.run_id`), so every commit of main keeps its own finished run, and a
# pending run is not replaced by a newer one either (a group with a fixed name
# drops the older pending run, cancel or not).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# 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,
@@ -59,7 +84,7 @@ jobs:
e2e:
name: e2e (linux, xvfb)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
@@ -155,3 +180,34 @@ jobs:
path: ${{ runner.temp }}/e2e-watchdog.log
if-no-files-found: warn
retention-days: 14
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it is SKIPPED, with the reason in the
# summary, until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
e2e-windows-control-a:
name: e2e (windows, Control+A)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: windows-latest
timeout-minutes: 20
# `run:` blocks are PowerShell on Windows unless said otherwise (e2e-hunt.yml had a ParserError on its first launch there).
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (the stock client is in the dev extra)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The keyboard shortcut selects all (the browser opens on the runner's desktop, as in e2e-hunt.yml)
env:
PYTHONUNBUFFERED: "1"
run: INVPW_BINARY_PATH="$FF" python -u -m pytest -m e2e -p no:cacheprovider -v tests/test_control_a_selects_all_in_a_field_e2e.py
@@ -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
+4 -1
View File
@@ -51,9 +51,12 @@ on:
permissions:
contents: write
# A publishing workflow is never cancelled half-way: the second run waits for
# the first (a newer pending run replaces an older pending one, which is
# harmless: the wiki is rebuilt in full from the repository each time).
concurrency:
group: publish-wiki
cancel-in-progress: true
cancel-in-progress: false
jobs:
publish-wiki:
+33
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
@@ -153,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
+73 -3
View File
@@ -15,9 +15,20 @@ permissions:
# cancelled one by one - which left the run marked failed even though nothing
# had actually failed. Keyed by workflow + ref so tests and e2e never cancel
# each other; only an older run of THIS workflow on the same branch is replaced.
# A newer push to a pull request cancels the run it supersedes. Never on main:
# outside a pull request the group is unique to the run (`github.run_id`), so
# every commit of main keeps its own finished run (see e2e.yml for why).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# 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
@@ -86,6 +97,57 @@ jobs:
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
@@ -266,7 +328,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, claims, version]
needs: [core-on-index, unit, docs-api, english, claims, version, way-in, install-job]
if: always()
runs-on: ubuntu-latest
steps:
@@ -277,7 +339,9 @@ jobs:
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
@@ -293,9 +357,15 @@ jobs:
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
+55 -34
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,15 +58,25 @@ 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
# Only a new push to a ledger pull request cancels the run it supersedes. The
# weekly schedule and a manual run (both on main) never cancel each other.
concurrency:
group: user-install-${{ github.ref }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
install:
@@ -88,48 +102,55 @@ 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
# earlier, which is the most expensive kind of red: it looks exactly like the
# real defect this workflow exists to catch.
# MEASURED AGAIN 2026-11-12 (0.50.1, ledger #476): the per-version JSON endpoint
# of PyPI answered at once, `pip index versions` listed 0.50.1, and the
# `pip install --upgrade` of the Linux job still resolved 0.49.1 (the Windows job,
# started later, was green). Those are three different pages of the index, and
# the job only needs the one pip installs from.
#
# Bounded at five minutes, so a genuinely forgotten publish still fails. The
# 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.
# So the question asked here is pip's own: `pip download invisible-playwright==X`,
# the same client, the same index, no cache. Bounded at ten minutes: a forgotten
# publish still fails, and it fails HERE, saying that the index does not have the
# version, instead of three steps later as a test that compares two versions.
#
# 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 ten
# 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'
import json, os, sys, time, tomllib, urllib.error, urllib.request
import os, subprocess, sys, tempfile, time, tomllib
dist = tomllib.load(open("pyproject.toml", "rb"))["project"]["name"]
version = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"]
url = f"https://pypi.org/pypi/{dist}/{version}/json"
deadline = time.monotonic() + 300
deadline = time.monotonic() + 600
deadline = min(deadline, time.monotonic() + float(os.environ.get("INDEX_WAIT_SECONDS", "600")))
poll = float(os.environ.get("INDEX_WAIT_POLL", "15"))
n = 0
said = ""
while True:
n += 1
try:
with urllib.request.urlopen(url, timeout=30) as r:
if json.load(r).get("urls"):
print(f"::notice::{dist} {version} is on the index (attempt {n})")
sys.exit(0)
except urllib.error.HTTPError as e:
if e.code != 404:
print(f"::warning::index returned HTTP {e.code}; not waiting further")
sys.exit(0)
except OSError as e:
print(f"index unreachable ({e}); retrying")
if time.monotonic() >= deadline:
print(f"::warning::{dist} {version} still not on the index after 300s; "
f"running the checks anyway so a real absence is reported")
r = subprocess.run([sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir",
"--disable-pip-version-check", "--quiet", "-d", tempfile.mkdtemp(),
f"{dist}=={version}"], capture_output=True, text=True)
if r.returncode == 0:
print(f"::notice::pip downloads {dist} {version} from the index (attempt {n})")
sys.exit(0)
time.sleep(10)
said = (r.stderr.strip().splitlines() or [""])[-1]
if time.monotonic() >= deadline:
minutes = int(float(os.environ.get("INDEX_WAIT_SECONDS", "600")) // 60) or 1
print(f"::error::the index does not have {dist} {version} yet, after {minutes} minutes "
f"and {n} attempts (pip said: {said})")
sys.exit(1)
time.sleep(poll)
PY
- name: Linux runtime libraries for the browser
+8
View File
@@ -22,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
+646 -1
View File
@@ -6,6 +6,650 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.51.0] - 2026-11-12
### Changed
- Engine firefox-63 through invisible-core 63.66.0, which this version pins. Behind a proxy: names are resolved by the browser's own
DNS-over-HTTPS through the proxy (not by the machine's resolver; checked with a resolver trap on Linux), WebRTC and HTTP/3 send
their UDP through the proxy's relay when its UDP was measured to leave from the same address as its TCP, and a proxy whose UDP
does not hold (including one whose UDP leaves from another address) is treated as a router that drops it (HTTP/3 falls back to
HTTP/2, ICE gathers no server-reflexive candidate). A proxy given to a context declares its own measured UDP exit. The interface
list WebRTC gathers is the network the session declares.
- A STUN server list can be given at launch (`udp_stun_servers`) for the measurement of the proxy's UDP.
- Every context carries the position the core declares for the session (the geolocation override of the context).
- The package's launcher and server refuse the two prefs that govern the launch counter, `invisible_firefox.usage_ping.enabled` and
`invisible_firefox.usage_ping.url`, in `extra_prefs` (and in the `firefoxUserPrefs` of a served launch). The engine counts launches with
an anonymous GET to the `usage-counter` release of the engine's repository (`feder-cr/firefox_antidetect_patch`).
### Added
- `preload_newtab=False` turns off the preloaded New Tab page, on request only (`InvisiblePlaywright`,
`invisible_playwright.async_api.InvisiblePlaywright` and `launch_server`): by default the browser keeps it, as a retail Firefox does.
A retail Firefox keeps the New Tab page ready in a content process of its own; with the option it is not started. `None` writes
nothing, `True` says the retail value aloud, and a `browser.newtab.preload` in `extra_prefs` wins over it. Needs invisible-core
63.66.0. Measured on Windows (run 43211271731), on an engine build of the firefox-63 candidate line (not the published engine), one
page of a site, five alternating runs: the browser's processes together take 448-454 MB as shipped and 231-239 MB with the option
(private memory 301-307 against 158-171 MB).
### Fixed
- A request the browser resumed and whose channel is replaced and cancelled before the replacement starts (a `fetch` with
`keepalive`, a beacon) is reported as failed, so it no longer keeps `networkidle` from arriving (engine firefox-63).
- A navigation the page overtakes (`location.replace`) ends, and the document that overtook it is told (engine firefox-63).
- A click in a frame under a CSS transform is mapped back to the point the frame shows, and a click in a frame scrolls the
element in even when its point is inside the main viewport (invisible-core 63.66.0).
- `request.resource_type` agrees with the pinned driver: a beacon is `beacon` and a CSP report is `cspreport` (it said `other`).
- A download whose finish is seen before its announcement is marked finished: `save_as`, `path` and `failure` used to wait for ever on it.
The early finishes the browser keeps are bounded (64) and forgotten with their context. (That the engine sends a finish before the
announcement is not proven; the path is defensive.)
- The opener kept for the downloads of a target whose adoption failed lives until the engine detaches the target, and none is
made for a target already detached.
- Tests only: the end-to-end tests that look at content processes ask for the processes of a site by its name and no longer compare two counts.
### Known differences from stock Playwright
What a script that drives the browser can observe, from the configuration of Playwright's own Firefox and of a retail Firefox (no
comparison run is saved). The result of a `window.open` (`null` or a window) is read by the page; the others are what the script sees.
- **A `window.open` from a script with no user gesture is blocked, as in a retail Firefox.** Playwright's own Firefox turns the popup
blocker off (`dom.disable_open_during_load` false in its `playwright.cfg`); a retail Firefox keeps it on, and so does this browser. So
`page.evaluate("window.open(url)")` returns `null` to the page and no `page` event comes; the same `window.open` from a click opens
the popup on both. To get stock's behaviour: open the popup from a click; or pass
`extra_prefs={"dom.disable_open_during_load": False}` for the session, knowing that a page then sees a browser that differs from a
retail Firefox.
### Known issues
- **A popup opened without a route can be announced while it is still on `about:blank`.** A popup opened with no route on the context
(a `target=_blank` link, or `window.open` from a click) can be announced to the client while it is still on `about:blank`; its `url`
then stays `about:blank`, or its `load` never arrives. Seen on a Windows runner with the library's client in the same process and four
workers running the popup tests in parallel (`test_popups_reach_the_client_e2e.py`, 20 runs): with the firefox-63 engine 17 cases of 640
in 12 of 20 runs; with the published firefox-62 engine (so also with 0.50.1) 15 cases of 640. On Linux (the firefox-63 engine) 0 red in
20 runs. In the last two runs with Playwright's own client over a served browser none was red. The defect is in the hand-over of the popup's page in this
package, not in the engine; the correction is in 0.51.1. Not measured: a served launch with numbers of its own, other machines, a run
without parallel workers, macOS.
## [0.50.1] - 2026-11-12
0.50.0 was tagged and never published: its end-to-end gate was red on two tests that counted processes.
0.50.1 is 0.50.0 with those tests corrected.
### Changed
- Engine firefox-62 through invisible-core 62.63.0, which this version pins: firefox-61 plus Fission
and the Juggler for frames in another process. When `goto` returns, the frames below have the
address of their first document (an iframe of another site used to be listed with an empty url
for a moment); a `goto` to the address the page is already at ends; a late event of a frame that
left the page no longer brings it back into `page.frames`.
- Fission: iframes of another site run in a content process of their own (isolation strategy 1,
`fission.autostart` on, four isolated content processes), as in retail Firefox on desktop. The
strategy comes from the invisible-core baseline of the firefox-62 engine, whose Juggler reaches a
frame in another process like any other. The tests that held strategy 0
(`tests/test_cross_origin_iframe.py`) now hold strategy 1, and the Fission end-to-end tests
(frame tree, element to frame, geometry, input, crash of an iframe process, identity of the
iframe and of its page) run on that engine.
### Fixed
- `goto(wait_until="networkidle")` arrives on a page that is reused for many addresses, and on a served browser whose
context routes every request, as with a stock Firefox. Two causes, both ours. A route answered after the browser had
already closed its request (a fetch the page aborted, an image it replaced, an iframe it removed, a beacon cancelled
with its document) came back to the client as an error, which the client kept for the whole connection and raised on the
next route command; that command was never sent, its request stayed held in the engine, and so on down the page. The
server now takes such an answer as done, whatever wording the engine gives it ("Cannot find request", or "NS_BINDING_ABORTED"
when the channel was cancelled while the answer was on its way), as Playwright's own server does. The same defect was found a month earlier by richardpowellus
(#351), on the favicon of the page a `goto` had just left; his test is part of this release. And the core counted the requests in flight
with one integer per page, never reset by a navigation, so one request whose end never arrived kept every later address
from going idle (invisible-core 62.64.0 keeps them by request id, per document, and does not keep the requests of a
frame that already left: a beacon sent at `pagehide` is announced after its frame is gone).
- A `goto` sent right after `new_page` is no longer "interrupted by another navigation to about:blank" on a loaded machine. The page was
handed to the caller as soon as its main frame was announced, while the engine had not yet committed the page's own initial
`about:blank`; a navigation answered before that commit lost to it. The page is now handed over when the engine says it is
ready (`Page.ready`), as Playwright's own page is (invisible-core 62.65.0, `Lifecycle.wait_for_page_ready`; a page closed before
it was ready ends the wait with an error at once).
- A launch that names no session (Playwright's own `BrowserType.launch` against the server) gets a
session composed the way `InvisiblePlaywright()` composes one: prefs, environment and, behind a
proxy, the egress the page reads as its WebRTC address. It used to come up with Mozilla's
defaults, and on Linux its first `new_page` failed with "Unexpected number of tabs in the new
window: 2".
- A frame that left the page (an iframe a script removed) answers a call with "Frame was
detached", as Playwright does, not "Target page, context or browser has been closed".
- `grant_permissions` uses the permission names of the engine. `geolocation` and `notifications` used
to reach the engine under the web names while it keeps a grant under `geo` and
`desktop-notification`, so a page of a context that had been granted geolocation and given a
position was still denied. The names are those of the Playwright client for this browser
(`geolocation`, `persistent-storage`, `push`, `notifications`, `screen-wake-lock`); any other name
raises `Unknown permission`, as it does there, and a grant with no origin is a grant for every
origin.
- The end-to-end tests that count content processes count the ones that host a site, not every content
process that is new. The engine keeps a pool of preallocated processes and refills it whenever it gets
to it, so a refill landing between two reads looked like a process the test had caused (a same-site
frame, a closed context with a service worker that never stops). Measured on firefox-62: a closed context
leaves no process of its site. On Linux the process is named by the site it hosts; elsewhere these
tests skip.
- A popup (a `target=_blank` link, `window.open`) reaches the client as it does with Playwright's own Firefox: when its
destination answers, with no limit of time, with the destination's address as its url, and with `load` reachable on
it. It used to be given up on after 20 s, could be announced with `about:blank` as its url, and about one in a
hundred was never announced. A destination that never becomes a page (a 204, a server that never answers) is not
announced, as on stock. Measured against stock destination by destination, with answers after 4 s and after 25 s: 18
cases of 18; and 128 popups announced of 128 across the two transports (the library client, a stock client over
`launch_server`).
- For a popup whose answer is a download, the opener's `download` event comes after the popup's `page` event, as on
stock. With little CPU the download could arrive and the page never be announced. Measured on a runner limited to
one CPU: 8 runs red of 10 before, 0 of 10 after.
### Known differences from stock Playwright
Measured against Playwright's own Firefox with the same script, on this version. None of them is a value a page
reads; they are what a script that drives the browser can observe.
- **The url of a popup that turns into a download.** A link or a `window.open` whose answer is an attachment gives, as on
stock, a `page` event, a `download` event on the opener, and a popup that closes at once. The popup's `url` at the `page`
event is `about:blank` here and the empty string on stock. Measured: 8 cases of 8 (link and `window.open`, the library
client and a stock client over `launch_server`), against 4 of 4 on stock.
- **The url of a frame of another site at the page's `DOMContentLoaded`.** A frame of another site runs in another process,
as in a retail Firefox, and commits its navigation after the page's `DOMContentLoaded`; stock Playwright keeps frames in
the page's process. So `frame.url` read right after `goto(..., wait_until="domcontentloaded")` can be the empty string.
After `load` it is always set. Measured, 30 runs each: after `load` the url was there 30 times here and 30 on stock; at
`DOMContentLoaded` once here and 30 times on stock. Wait for `load`, or for the frame's own navigation, before reading it.
- **A click takes longer with the library client.** From `click()` on a link to the `page` event of the popup it opens:
0.8 to 1.7 s more than stock with the library client, and the same as stock (within 0.1 s) with a stock client over
`launch_server`. Measured on 64 popups per transport and on destinations that answer after 4 s and after 25 s. The
same run with `humanize=False` was not measured.
- **Back and forward restore the page from the back-forward cache.** As in a retail Firefox, `go_back` and `go_forward`
bring the page back as it was; Playwright's own Firefox loads it again. So a script that runs when the page loads does
not run again here. Measured on a 17-step journey with the same script on both: on its three back and forward steps
the page's load-time requests were sent again on stock (6 beacons each) and not here (0, 2 and 0, the two being the
ones a page sends when it is left); every step ended on the same page, and the other 14 steps sent the same requests.
## [0.49.1] - 2026-11-10
### Changed
- Engine firefox-61 through invisible-core 61.62.0, which this version pins: firefox-60 plus four
fixes. A context that ends no longer leaves a content process behind when a service worker
that never stops keeps it alive (the engine kills the processes of the container that stay);
the shared font resources of a closed window leave WebRender's pool with it; `Page.screenshot`
empties its canvas on every way out; `Page.setEmulatedMedia` names the media features it
refuses, in English.
- A context route turns the context's cache off while it is active, as Playwright does.
### Fixed
- `page.request_gc()` works on a served browser. It sent the engine's `Heap.collectGarbage` on the
browser-level connection, whose handler does not have it, so every call failed with
`Handler for does not implement method "Heap.collectGarbage"`; it is now sent with the session
of the page, as the engine answers it.
## [0.49.0] - 2026-11-10
### Changed
- Engine firefox-60 through invisible-core 60.61.0, which this version pins: firefox-59 plus
the Juggler's memory fixes. A tab no longer keeps the documents it left alive (they used to
stay as detached windows after leaving the back/forward cache), and a main-frame navigation
drops the response bodies of the documents it left, as Chromium does: `response.body()` of
such a response raises the evicted error Playwright already returns for Firefox.
## [0.48.1] - 2026-11-10
### Added
- `launch_server`, `launch_server_async` and `RemoteServer` are importable from
`invisible_playwright`, and the README's "Serving one browser to many clients" has a
complete example: a server, and a Playwright for Python client that connects to its
`ws_endpoint`.
### Changed
- invisible-core 59.60.0, which this version pins. The browser never opens its crash
reporter: the launch environment carries `MOZ_CRASHREPORTER_DISABLE=1`, so an engine that
refuses a launch no longer leaves a "Crash Reporter" window on a Windows desktop.
- The e2e run stops at the first refusal of the engine instead of launching the browser for
every test (a change to the test suite, not to the package).
## [0.48.0] - 2026-11-10
### Added
- `launch_server()` serves one browser on a WebSocket to any Playwright client: the
Playwright initializer is the one of protocol 1.62, a call's timeout is read from its
metadata or its parameters, a Dialog is a protocol object, and the pointer's path is
drawn by the server, once, for every client.
### Changed
- Engine firefox-59 (Firefox 159.0), through invisible-core 59.59.0, which this version
pins. On Linux WebGL draws on the engine's own GL, never the host's, under X11 too, and
every extension the persona declares answers as on Windows. The same seed gives the same
pointer path, typing and persona on Python 3.11 to 3.14 (59.59.0 replaces the two builtins
that differ between versions).
- The server collects its oldest protocol objects as Playwright's does, with a lower limit
for `Request`, `Response` and `Route` (2000, not 10000; nothing younger than 10 seconds).
A program that holds more than 2000 requests or responses in hand for longer than 10
seconds gets "Target closed" on the oldest ones. `INVPW_GC_LIMITS` changes the limits.
- A closed context leaves nothing in the server's registry.
## [0.47.1] - 2026-11-08
### Changed
- invisible-core 58.56.0, which this version pins. A persona has the keyboards
Windows installs with its language and country, read from Windows'
locale.nls (English US besides Persian, Azerbaijani, Bashkir, Cherokee and
Sakha; Russian besides Belarusian, Tatar and Armenian; Hindi Traditional for
Hindi), and switches as a user does: left Alt + Shift to the next language,
Ctrl + Shift to the next keyboard of the same language. The keyboard pref
carries Windows' own form (LANGID:KLID joined by semicolons).
## [0.47.0] - 2026-11-08
### Changed
- Engine firefox-58 (Firefox 159.0), through invisible-core 58.55.0, which
this version pins.
- A persona has the keyboards Windows installs with its language: the
language's, and the second one (English US with Russian, Greek, Arabic,
Hebrew and most languages not written in Latin letters). A character the
active keyboard lacks is typed on the other one, after left Alt + left
Shift, Windows' default switch; `press("x")` on a Russian or Greek session
no longer raises "unknown key". Only a character no keyboard has is inserted
as text.
- `scroll_into_view_if_needed()` is the engine's own scroll, only when needed.
### Fixed
- In the engine: a navigation Firefox refuses before any channel (a
restricted port) ends with its error instead of never; a request held by
`route()` that the page cancels is no longer held; `unroute` with a request
that can no longer be resumed no longer fails; a session cookie set with
`expires: -1` is kept, `sameSite: "None"` is SameSite=None, and a cookie
Firefox refuses fails `add_cookies()` with Firefox's reason.
## [0.46.4] - 2026-11-08
### Fixed
- The engine and the GeoIP database install when GitHub's direct release
links fail. Through invisible-core 57.54.0, which this version pins: each
release file is fetched from the API route first and from the direct link
second, and one download attempt tries both, so a 504 on one route is
served by the other at once. On 2026-11-08 every direct link answered 504
while the API route served the same files.
## [0.46.3] - 2026-11-08
### Changed
- Engine firefox-57 (Firefox 159.0), through invisible-core 57.53.0, which
this version pins. The WebGL extensions a page sees are decided once, by
the engine's WebGL host, from the persona's declared list: the content
process no longer has a list of its own, an extension the host's GPU
cannot serve is never created (its calls stay harmless), and
`getSupportedExtensions()` lists them in Firefox's own order, the only
order a retail Firefox gives (the WebGL 1 list had `EXT_sRGB` before
`EXT_shader_texture_lod`).
## [0.46.2] - 2026-11-07
### Changed
- The persona types on the keyboard a Windows install gives its language in
its country, for every language: German in Switzerland on the Swiss
keyboard, Dutch on US-International, Polish, Czech, Turkish, Greek, Hebrew,
Arabic and the rest on their own keyboards; a language Windows has no
profile for takes the keyboard of the country's main language; Japanese and
Korean type on the keyboard under the IME. The session passes its country to
the server, which only had the language list before. The tables come from
invisible-core 56.53.0, which this version pins, read from the bytes of the
Windows layout files rather than from the machine.
## [0.46.1] - 2026-11-07
### Fixed
- The typing rhythm uses the hand of the key on the persona's keyboard, through
invisible-core 56.52.0, which this version pins: on a German keyboard `z`
was counted as a left-hand key and an Italian `ò` had no hand, so the
same-hand and alternate-hand timings were applied to the wrong pairs. The
US keyboard is unchanged.
- The pyproject comment on the dependencies names the server that exists
(`_juggler/`), not a Node driver (`tests/test_pyproject_names_real_paths.py`).
## [0.46.0] - 2026-11-07
### Changed
- Engine firefox-56 (Firefox 159.0), through invisible-core 56.51.0. A WebGL
extension the persona declares can now be called without killing the
browser: the host serves every declared extension wherever its GL can, and
an entry point whose extension is off returns instead of asserting. Until
now one `provokingVertexWEBGL()` call on Linux took the main process down,
one page in 5,000 (`tests/test_a_declared_webgl_extension_survives_its_use_e2e.py`).
- The persona types on the keyboard of its language. The server reads the
language the launcher decided for the session (`intl.accept_languages`) and
hands the matching layout to every page's hands: Italian, German, French,
Spanish, Brazilian (ABNT2) and British keyboards, read from the layouts
Windows ships, with Firefox's own `keyCode`s on Windows; everything else
stays on the US keyboard. Until now every persona typed on one US table with
Chromium's key codes: an Italian persona typed `ò` with no key event at all
and `@` as Shift+Digit2, and every persona sent 186/187/189 for `;`/`=`/`-`
where Firefox sends 59/61/173. The tables and the keyboard live in
invisible-core 56.51.0, which this version pins
(`tests/test_the_keyboard_follows_the_session_language.py`).
- A dialog (`alert`, `confirm`, `prompt`) is answered after the pause a
reader takes, counted from the moment it opened: a reaction part and a
reading part that grows with the words, both drawn from the session's seed
and clamped, one draw per dialog. Until now `Page.handleDialog` left in the
same millisecond `Page.dialogOpened` arrived, whether the client dismissed
the dialog itself (no handler) or a handler called `accept()`; a page timing
`alert()`'s return saw single-digit milliseconds. Only the remainder is
waited, so a handler that took its time is not made slower, and a session
with no seed (humanising off) answers at once as before
(`_juggler/dialogs.py`, `tests/test_a_dialog_is_answered_after_a_pause.py`).
### Removed
- Linux arm64 is no longer supported from firefox-56: no engine is built for
it. firefox-55 is the last engine with a Linux arm64 build. The engines are
Linux x86_64 and Windows x86_64; Windows on ARM64 still runs the x86_64
engine.
- `scripts/ci_font_gate.py` and its test. The host gate
(`scripts/ci_host_gate.py`) asks the general question, whether anything a
page reads comes from the host, and it covers the font list. It ran green
on the firefox-55 release, which was the condition for removing the font
gate.
## [0.45.0] - 2026-11-04
The pin moves to invisible-core 55.50.0, which brings the firefox-55 engine.
Firefox is still 159.0.
### Changed
- What a page reads about the graphics card is the identity's, on every host.
Each identity now stands for one real Windows 11 GPU, and Firefox's
graphics blocklist answers as Firefox 159 for Windows answers on that GPU.
A host whose adapter Firefox would block (a virtual machine, a CI runner)
no longer turns WebGL2 or antialiasing off.
- `navigator.gpu.requestAdapter()` returns the adapter of Firefox 159 for
Windows on every identity, with the same features and limits, also on hosts
without a GPU.
- Text is measured and drawn the same way on every OS (the Windows
DirectWrite implementation): on Linux, text metrics and rendering are those
of Windows.
- A 2D canvas is drawn on the CPU on every host, so its pixels no longer
depend on the host GPU.
- WebRTC video encoding support is the same as Firefox 159 for Windows,
whatever encoders the host has.
- A new profile opens straight on the page: the first-run terms-of-use dialog
of Firefox no longer covers it and the page has focus and input at once.
- Fullscreen follows the identity's screen.
- 17 seeds in 1500 get a different GPU: the identities that drew a
Direct3D 10 class card (which has no Windows 11 driver) now draw a current
GeForce card.
### Fixed
- `getParameter` answers state the page has set (depth function, stencil,
blend, pixel store, draw buffers) from the live context instead of its
initial value; the stencil masks are 4294967295 as on Firefox 159.
- `getParameter(MAX_VIEWS_OVR)` answers 4 wherever `OVR_multiview2` is
offered, instead of the host's value.
- The CSS system colour `-moz-dialog` is white, as on Firefox 159.
### Tests
- The host gate: what a page reads at a given seed is compared between
Windows and Linux hosts and with official Firefox 159, including the
window in fullscreen and back.
### Known issues
- On Linux arm64 `navigator.gpu.requestAdapter()` returns null.
- On Linux `maxBindingsPerBindGroup` differs from Firefox 159 for Windows.
## [0.44.1] - 2026-10-31
The pin moves to invisible-core 54.49.0. The engine is the same firefox-54
(Firefox 159.0).
### Fixed
- `navigator.mediaCapabilities.decodingInfo({type: "webrtc"})` no longer
reports the host GPU's hardware decoding for VP8, VP9 and AV1. The answer is
now the same as Firefox 159 on Windows, on Windows and Linux alike. AV1
follows the identity's AV1 setting.
## [0.44.0] - 2026-10-31
The pin moves to invisible-core 54.48.0, which brings the firefox-54 engine:
Firefox 159.0.
### Changed
- invisible-core 53.48.0 -> 54.48.0, sealed to the firefox-54 engine (Firefox
159.0). Every identity reports what Firefox 159 reports: its User-Agent, its
WebGL extensions and its branding.
- A click on an element that is already in full view no longer scrolls the
page. The element is brought to the centre only when part of it is outside
the viewport, as Chromium's scrollIntoViewIfNeeded does.
### Fixed
- Downloads reach Playwright: `page.expect_download()`, `Download.save_as()`,
`path()`, `failure()`, `delete()` and `cancel()` work, and a `goto` that ends
in a download fails with "Download is starting" instead of hanging until its
timeout. Contexts created with `accept_downloads=False` cancel downloads.
- `BrowserContext.set_offline()` works instead of being refused: an offline
context loads nothing and reports `navigator.onLine === false`.
### Tests
- e2e: a clicked download and a navigation that ends in a download.
- e2e: no scroll for an element in full view, also inside a same-origin frame;
an element below the fold is centred.
- e2e: set_offline stops loads and set_offline(False) resumes them.
## [0.43.0] - 2026-10-24
The pin moves to invisible-core 53.48.0, which brings the firefox-53 engine.
### Fixed
- After a page that runs in a content process of its own (served with
Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy, as challenge
pages are) sends itself to a page that does not, locators, `inner_text` and
`query_selector` no longer fail for good with "Cannot find object with id"
when a read was made on the first page. The engine's context ids are now
unique for the session, and an element handle kept across such a move can no
longer reach a different node.
### Changed
- The exposed fonts are the set of a clean Windows: Leelawadee, Microsoft
Uighur, Wingdings 2 and Wingdings 3, which such a machine does not have, are
no longer exposed (67 families).
### Tests
- e2e: reads on an isolated page, then on the page it sends itself to.
- The font gate checks that the engine's own manifest declares exactly the
canonical families, none more and none less.
## [0.42.0] - 2026-10-24
The pin moves to invisible-core 52.48.0, which brings the firefox-52 engine.
### Changed
- invisible-core 51.48.0 -> 52.48.0, sealed to the firefox-52 engine (Firefox
151.0). A 2D canvas, on the page or offscreen, now reads back exactly as it
was drawn, as on retail Firefox: the canvas noise is applied to WebGL and
WebGPU readback only, which is unchanged.
- A `toDataURL`/`toBlob` PNG carries the per-session `deBG` chunk retail
Firefox 151 writes after IDAT; the pixels are untouched.
- 1920x1080 panels are drawn at 125% and 150% as often as the Windows fleet
is, so more seeds report a display scale above 1 (core).
- ClearType gamma and contrast are a declared persona field. Every seed keeps
the untuned machine's values today.
### Tests
- e2e: a 2D canvas reads back as drawn on a page canvas and on an
OffscreenCanvas, and screenshots follow the persona's display scale.
## [0.41.0] - 2026-10-21
The pin moves to invisible-core 51.48.0, which brings the firefox-51 engine.
### Changed
- invisible-core 50.48.0 -> 51.48.0, sealed to the firefox-51 engine (Firefox
151.0). The canvas noise now spares two-colour blends (`edge_tolerance`
replaces `edge_step` in the core).
### Added
- `font.system_text_quality` is documented on the pinning page. It was already
pinnable (0 none, 4 standard antialiasing, 5 ClearType; default 5) and
documented nowhere.
## [0.40.0] - 2026-10-19
The pin moves to invisible-core 50.48.0, on the same firefox-50 engine.
### Fixed
- **`expect()` works for every condition, not two families.** The server
re-wrote Playwright's assertions in Python one condition at a time and had
written `to_have_count` and the `to_be_*` states; `to_have_text`,
`to_contain_text`, `to_have_value`, `to_have_values`, `to_have_attribute`,
`to_have_class`, `to_contain_class`, `to_have_css`, `to_have_id`,
`to_have_js_property`, `to_be_focused`, `to_be_empty`, `to_be_in_viewport`,
`to_have_title`, `to_have_url` and the accessibility ones answered "is not
implemented yet". Each reading is now Playwright's own `expect`, from the
injected script this package already ships, called the way Playwright's
server calls it: strict mode, `element(s) not found`, and a JavaScript error
that ends the wait with its message. On Playwright's own suite, its expect
tests on firefox-49 went from 30 of 94 passing to 75, with none lost.
- `to_have_js_property` with an object, an array or a date as the expected
value is refused by name: the page's value lives in another realm, and
comparing it would always report a difference. Primitives are compared.
`to_match_aria_snapshot` is refused by name too: its template is YAML that
Playwright's server parses, and this one has no parser for it.
- A failed `expect` reports an object as the object. The client read the value
the server sent twice, the second time as if it were still in its wire form,
so `{"a": 1}` failed with `KeyError: 'id'` instead of the assertion's message,
and `{"v": "x"}` or `{"n": 5}` were reported as `x` and `5`. The vendored
client had the two reads from Playwright 1.61.0, which still has them; the
second one is gone.
- A failed `expect` prints its call log, as Playwright's does: the assertion
and its timeout (`Expect "to_be_visible" with timeout 5000ms`), what it
waited for (`waiting for locator("#a1")`), and what each reading found
(`locator resolved to <input/>`, `unexpected value "Go"`). The message said
what was expected and what was seen, and nothing of the wait in between.
- `page.goto` follows the context's `base_url`. The server never read it, so
`goto("/empty.html")` in a context created with a base failed with
"Invalid url /empty.html"; it now navigates to the base's `/empty.html`, as
Playwright does. The address is resolved by the engine's own URL parser,
the one that then navigates to it.
- `page.evaluate`, `evaluate_handle`, `wait_for_function` and the
element-scoped evaluations run the caller's text as a script, as Playwright
does. The server put it inside an expression so that it could call the
result in the same pass, so a statement with its semicolon,
`setTimeout(() => {...}, 2000);`, died with "missing ) in parenthetical".
The text is now evaluated on its own and a function it produces is called
with the argument, and the page sees the caller's code without anything
around it. `wait_for_function` evaluates a function predicate once per
document and calls it on every turn, as Playwright's poll does.
### Changed
- **The user-install job runs on the ledger pull request**, not on
`release: published`, which never fired: the Release is created with
GITHUB_TOKEN, and an event that token causes starts no other workflow.
CI checks the wiring with `python -m invisible_core.install_job`.
- The release tests keep out of the venvs they build every variable the
core's library reads, as `invisible_core.install_job.LEAKS` lists them: an
engine folder, a seal file or a GitHub token in the caller's shell no
longer changes what they measure.
- The publish workflow checks the version and the ledger against the index
before it uploads (`invisible_core.release check --verify-index`), as the
pre-push hook does: a clone without the hook can no longer skip it.
- **The vendored client's README says what actually differs from upstream.**
`_pw/README.md` named `_impl/_driver.py`, a file removed with the Node driver,
as the only changed file, while eight files carry the
`# MODIFIED by invisible_playwright` marker; it now lists them, in English.
- **`_pw/` is no longer excluded from the English gate.** The upstream code is
English already, so the folder exclusion only hid our own text: the README
and the error raised for `chromium` and `webkit`, now in English.
- `THIRD_PARTY_FORK.md` gives the vendored client's version as 1.61.0, which is
what `_pw/_repo_version.py` and the development pin say.
## [0.39.0] - 2026-10-18
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 launch no longer writes `TZ` into the browser's
environment. On Windows no `TZ` could satisfy both the C runtime and ICU, so
some zones showed the machine's time inside a Worker, and zones outside a
ten-row table were never covered; that is gone with it.
### Changed
- The IANA-to-POSIX conversion is no longer imported or used. Code that took
`IANA_TO_POSIX_TZ` from the core has to stop: the core 50.47.0 removes it.
## [0.38.0] - 2026-10-18
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 and more -
are declared by the persona instead of read from the machine it runs on, and
each of them can be pinned ([pinning](docs/pinning.md)).
### Changed
- **The way in is uv.** The README installs with one complete block per
system: uv from its own installer, `uv init --python ">=3.11" my-project`,
`uv add invisible-playwright`, `uv run invisible-playwright fetch`.
CONTRIBUTING, the guides and the issue template teach the same, and CI
refuses an install instruction that is not uv
(`python -m invisible_core.way_in`, core 49.45.0).
- **A remedy this package prints is the command for your environment.** In a
venv uv made, which has no pip, a broken install was told to run
`pip install --force-reinstall invisible-playwright`; it is now told the uv
command, and an environment pip made is still told pip, through its own
interpreter.
### Fixed
- The Docker guide's base image has a Python older than this package needs,
and the arm64 guide's Debian image an externally managed one, so neither
install line could work: uv now brings the interpreter. The installation
guide no longer lists macOS, which has had no engine since 2026-08-26.
## [0.37.0] - 2026-10-17
The pin moves to invisible-core 49.44.0, on the firefox-49 engine.
### Changed
- **Your code runs in a world of its own, where a page that replaced a
standard API cannot count your calls.** `evaluate`, `evaluate_handle`,
`wait_for_function`, `eval_on_selector(_all)`, `locator.evaluate`,
`handle.evaluate` and `set_content` ran in the page's own realm, so a
call to `document.querySelector` went through whatever the page had
put in its place: a Cloudflare challenge wraps it, and one lookup of
its token field from an evaluate got the clearance refused. They now
run in a world with the page's principal where a name the standard
defines is the native one, and every other name is the page's:
`window.__NEXT_DATA__`, a node's `__vue__` and the page's functions
answer as before.
On what the page created (its classes, their instances, its plain objects)
the page's definitions win, `toString` and `valueOf` included, and an
object your code hands to the page keeps its identity and looks to the
page like its own (`instanceof Array` holds, its `constructor` is the
page's). What changes, and it is declared rather than accidental: a name
the standard defines for one of the browser's own objects wins even where
the page redefined it on that object itself (a setter the page put on one
input's `value` does not run; `.wrappedJSObject` gives the page's own
view); a bare assignment to an undeclared name creates a global of your
world, not of the page (`window.x = 1` still reaches the page); and your
code's own `eval` is not governed by the page's Content-Security-Policy,
which governs the page's (`window.eval`) as before. Needs firefox-49.
- **`request.post_data` holds the body with no route as well.** Until
firefox-48 the engine read a request's body only while a route was set, so
every POST of a page with no route answered `None`, like a form sent empty.
It now reads every body up to 10 MB, as Playwright's does, and the upload
reaches the site whole. Needs firefox-49.
- **`response.security_details()` names the certificate, and
`response.from_service_worker` says when a service worker answered.**
The engine reported neither (`None` and `False` for every response); it now
reports both as Playwright's does. Needs firefox-49.
### Fixed
- **`eval_on_selector`, `eval_on_selector_all`, `locator.evaluate` and
`handle.evaluate` see what the page put on an element.** They ran
behind the automation's own view, where `el.__vue__` and the methods
of a custom element's class do not exist.
- **The browser's favicon request no longer reaches the client.** A
`page.route("**/*")` handler saw `GET /favicon.ico` now and then, as did the
`request`, `response` and `requestfinished` listeners, and a
`route.fallback(post_data=...)` rewrote it too. As in Playwright, the favicon,
and a request it redirects to, now sends no event, reaches no route handler
and is not a request `networkidle` waits on. Unlike Playwright it is not
aborted under a route: it goes to the site, as from any Firefox.
- **A request held after interception was switched off no longer stalls the
session.** Its release was sent from the thread that delivers the engine's
events and waited for a reply only that thread could read; the next command
of the page then waited forever.
- **`route.abort()` with no error code fails the request with
`NS_ERROR_FAILURE`, as in Playwright on Firefox.** It failed with
`NS_ERROR_ABORT`, the code of `route.abort("aborted")`.
- **A route that sends a navigation to another URL lands there.**
`route.fallback(url=...)` or `route.continue_(url=...)` on a document
request made `goto` fail with "reported committed on ..., which is not where
it went", and the response kept the URL the request was sent with. The
response is now the routed URL's, and `goto` lands on it.
## [0.36.2] - 2026-10-17
The pin moves to invisible-core 48.43.0, still on the firefox-48 engine.
@@ -1586,7 +2230,8 @@ browser reads that decision.
repository that builds and ships the engine. The engine's compiled default
says the same from the next build. Engines older than firefox-21 do not read
the pref and are not counted. To opt out of the ping, set
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`.
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`. (Since 0.51.0 this is no longer possible: the
counter cannot be turned off or redirected.)
- **The `browser launches` badge is back.** It was removed in 0.7.2 because the
counter behind it lived on a repository that had been deleted, so the badge
would have redrawn a frozen number every morning. The counter has lived on
+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
+9535
View File
File diff suppressed because it is too large. Load diff
+83 -14
View File
@@ -7,6 +7,11 @@
<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>
<p align="center">
<a href="https://github.com/feder-cr/invisible_playwright/blob/badges/counters/launches_daily.csv"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffeder-cr%2Finvisible_playwright%2Fbadges%2Fdocs%2Fbadges%2Flaunches.json&style=for-the-badge" alt="browser launches"></a>
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffeder-cr%2Finvisible_playwright%2Fbadges%2Fdocs%2Fbadges%2Fdownloads.json&style=for-the-badge" alt="engine downloads"></a>
<a href="https://github.com/feder-cr/invisible_playwright/stargazers"><img src="https://img.shields.io/github/stars/feder-cr/invisible_playwright?style=for-the-badge&logo=github&color=e8a317" alt="GitHub stars"></a>
</p>
<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>
@@ -31,14 +36,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`.
---
@@ -108,6 +130,50 @@ with InvisiblePlaywright(proxy=proxy) as browser:
Schemes supported: `socks5`, `socks4`, `http`, `https`. DNS is routed through the proxy by default, no local leak.
### Serving one browser to many clients
`launch_server()` serves one browser on a WebSocket to any Playwright client. Install the
extra that carries the WebSocket library with `uv add "invisible-playwright[remote]"`.
```python
# server.py
from invisible_playwright import launch_server
with launch_server(seed=42, headless=True) as server:
print(server.ws_endpoint) # ws://127.0.0.1:<port>/<secret>
input("serving, press Enter to stop")
```
```python
# client.py: any Playwright client; this one is Playwright for Python (uv add playwright)
import sys
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.firefox.connect(sys.argv[1]) # the address the server printed
page = browser.new_page()
page.goto("https://example.com")
print(page.title())
browser.close() # ends this client; the server's browser keeps running
```
The server listens on `127.0.0.1` with a random secret path; `host=`, `port=` and `path=` choose
another address. A client in another language (Node, Java, .NET, Go) connects to the same
address with the `connect` call of its own Playwright. The browser belongs to the server and
ends with `server.close()` (or with the `with` block).
On Linux, set `MALLOC_ARENA_MAX=2` in the environment of the process that runs it (glibc keeps a memory
arena per thread otherwise); the server already hands freed memory back with `malloc_trim`
(`INVPW_MALLOC_TRIM=0` turns that off).
The server keeps its protocol objects in a registry and, like Playwright's own server,
collects the oldest ones when a type grows past a limit (`__dispose__` with reason `gc`).
Its limits are Playwright's, except `Request`, `Response` and `Route`, which are 2000
instead of 10000, and nothing younger than 10 seconds is ever collected. A client that
keeps more than 2000 requests or responses in hand for longer than that gets "Target
closed" on the oldest ones; one that uses them inside its callback is not affected. Set
`INVPW_GC_LIMITS="Request=10000,Response=10000,Route=10000"` to get Playwright's numbers.
### Timezone
The browser timezone follows `timezone=`:
@@ -148,6 +214,11 @@ not carry raises, and the error lists the ones it does.
Full list of pinnable keys, how pinning interacts with the Bayesian sampler, and common patterns are in **[docs/pinning.md](docs/pinning.md)**.
### Launch counter
The engine counts launches with an anonymous GET to the `usage-counter` release of the engine's repository (`feder-cr/firefox_antidetect_patch`) on GitHub. This package's launcher and server refuse the two prefs that govern it, `invisible_firefox.usage_ping.enabled` and `invisible_firefox.usage_ping.url`, in `extra_prefs`.
---
## CLI
@@ -167,11 +238,11 @@ invisible-playwright version # wrapper, core and engine versions, and where the
**If you would rather prompt than script.** This page is the engine, as a Python
library. Two ways to use it without writing code, both one line: from an MCP client
you already have (Claude Code, Claude Desktop, Cursor),
`claude mcp add stealth -- uvx aihawk`, see
[the MCP server page](https://github.com/feder-cr/AIHawk/wiki/mcp-server); or with an
`claude mcp add stealth -- uvx invisible-playwright-mcp`, see
[the MCP server page](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server); or with an
interface and a model included, needing only an OpenRouter key,
`uvx aihawk ui --openrouter-key sk-or-...`, see
[AIHawk](https://github.com/feder-cr/AIHawk). Same engine underneath, and the second
`uvx invisible-playwright-mcp ui --openrouter-key sk-or-...`, see
[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp). Same engine underneath, and the second
is a client of the first.
All of it reads better, and is searchable, in
@@ -215,8 +286,8 @@ two around it are how most people reach it:
- **[invisible_core](https://github.com/feder-cr/invisible_core)** - seed to
fingerprint to preferences, plus proxy and geolocation. This package pins it.
- **[AIHawk](https://github.com/feder-cr/AIHawk)** - this engine as an MCP
server (`uvx aihawk`, for any client that brings its own
- **[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp)** - this engine as an MCP
server (`uvx invisible-playwright-mcp`, for any client that brings its own
model) and, in the same package, an interface with a model included, from
one command. The interface is a client of the server, with no private path
to the browser.
@@ -305,7 +376,5 @@ 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>
<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>
<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>
</p>
+11
View File
@@ -0,0 +1,11 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 43, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_declared_host_network_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 57 = 1+7+6+1+21 from the five files + 21 from the 10 UDP-line tests of test_webrtc_realness.py (parametrized). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name."},
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed."},
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 221, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 44, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py"], "marker": "unit", "needs_root": false, "note": "24 (counted at the collection; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
]
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "AI agent retry loops trip rate limits, not fingerprints"
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the AIHawk wiki."
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 17
@@ -9,10 +9,10 @@ nav_order: 17
# AI agent retry loops trip rate limits, not fingerprints
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/AIHawk/wiki/agent-retry-loops-rate-limits)**
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/invisible_playwright_mcp/wiki/agent-retry-loops-rate-limits)**
The one-paragraph version: an agent that retries and re-plans multiplies its
requests, and volume is scored server-side against your address and account.
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "Why AI browser agents have their own timing signal"
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the AIHawk wiki."
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 10
@@ -9,10 +9,10 @@ nav_order: 10
# Why AI browser agents have their own timing signal
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[The timing signal AI agents give off](https://github.com/feder-cr/AIHawk/wiki/ai-agent-timing-signal)**
**[The timing signal AI agents give off](https://github.com/feder-cr/invisible_playwright_mcp/wiki/ai-agent-timing-signal)**
The short version it still owes you here: a think-act loop pauses for model
latency, and that pause repeats with a regularity no human produces. The
+1 -1
View File
@@ -224,7 +224,7 @@ this whole page is about.
one. Pick on the agent loop, then fix the machine, then consider the engine.
**Is there any agent route to an engine-level fingerprint?** Two, and they are not
equivalent. `uvx aihawk` launches through the engine, so the
equivalent. `uvx invisible-playwright-mcp` launches through the engine, so the
seeded profile and the humanised pointer come with it. Microsoft's own Playwright
MCP server takes a browser and an executable path, which runs the engine but
carries no `firefox_user_prefs`, so every session on a given build shares one
+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

+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "browser-use gets detected: what you can and cannot change"
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the AIHawk wiki."
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 2
@@ -9,10 +9,10 @@ nav_order: 2
# browser-use gets detected: what you can and cannot change
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/AIHawk/wiki/browser-use-getting-blocked)**
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/invisible_playwright_mcp/wiki/browser-use-getting-blocked)**
The unchanged short answer: browser-use exposes a real set of levers
(`executable_path`, `user_data_dir`, `proxy`, `headless`, `args`), all of
@@ -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 ...
@@ -1,6 +1,6 @@
---
title: "Computer-use agents and browser fingerprint detection"
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the AIHawk wiki."
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 6
@@ -9,10 +9,10 @@ nav_order: 6
# Computer-use agents and browser fingerprint detection
This page moved to the AIHawk wiki, retargeted at the question people
This page moved to the invisible_playwright_mcp wiki, retargeted at the question people
actually search:
**[Claude computer use detected as a bot](https://github.com/feder-cr/AIHawk/wiki/claude-computer-use-detected-as-bot)**
**[Claude computer use detected as a bot](https://github.com/feder-cr/invisible_playwright_mcp/wiki/claude-computer-use-detected-as-bot)**
The core of it, kept here in brief: a coordinate-clicking agent never
generates the DOM-automation tells, so `navigator.webdriver` advice mostly
+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
+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
+5 -5
View File
@@ -20,7 +20,7 @@ Playwright, or not to touch Firefox, at all.
These pages are for developers wiring an agent to this engine. The
agent-experience side - what to run, which agent products compare how, what to
check when an agent gets blocked - lives on the
[AIHawk wiki](https://github.com/feder-cr/AIHawk/wiki), the agent built on this
[invisible_playwright_mcp wiki](https://github.com/feder-cr/invisible_playwright_mcp/wiki), the agent built on this
same engine.
## Framework integrations
@@ -34,15 +34,15 @@ same engine.
## Computer-use and screenshot agents
- [Back a computer-use agent with a real browser engine](back-computer-use-agent-real-browser.md) - implement the screenshot-and-click Computer interface over an invisible_playwright page, and its honest limits.
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the AIHawk wiki; the page here points across.)
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [DOM-reading vs screenshot agents: which stealth helps](dom-reading-vs-screenshot-agents.md) - which stealth signal helps depends on whether the agent reads DOM or clicks pixels.
## How AI agents get detected
- [AI browser agents and stealth: what fits and what does not](ai-browser-agents-stealth.md) - most agents drive Chromium over CDP, so a stealth Firefox does not drop in.
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the AIHawk wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the AIHawk wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the AIHawk wiki; the page here points across.)
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [Playwright 1.62 Ships MCP In the Box](playwright-162-built-in-mcp.md) - the MCP server and a new playwright-cli are now bundled into core, runnable via `npx playwright mcp` with no separate install.
## Running agents at scale and on servers
+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
+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
@@ -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
+2 -2
View File
@@ -22,8 +22,8 @@ the thing it describes, and several of them record something we got wrong first.
- **[Integrations](integrations/)** - running this inside Scrapy, Crawlee, Robot
Framework, CodeceptJS, test runners and Playwright MCP, including which frameworks
it does not fit and why.
- **[The agent on top](https://github.com/feder-cr/AIHawk/wiki)** - this engine also
drives [AIHawk](https://github.com/feder-cr/AIHawk), an AI agent you instruct in
- **[The agent on top](https://github.com/feder-cr/invisible_playwright_mcp/wiki)** - this engine also
drives [invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp), an AI agent you instruct in
plain language; its wiki covers the agent layer the way this one covers the
browser: comparisons, blocked agents, and task guides.
+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.
+9 -8
View File
@@ -1,6 +1,6 @@
---
title: "Using invisible_playwright with Microsoft's Playwright MCP"
description: "There is a server for this engine, inside AIHawk: uvx aihawk. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
description: "There is a server for this engine: uvx invisible-playwright-mcp. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
parent: "Integrations"
nav_order: 7
---
@@ -8,13 +8,12 @@ nav_order: 7
# Using invisible_playwright with Microsoft's Playwright MCP
**There is a server for this engine:**
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
shipped inside AIHawk.
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server).
One line, and it carries the seeded profile and the humanised pointer that the
route on this page cannot:
```bash
claude mcp add stealth -- uvx aihawk
claude mcp add stealth -- uvx invisible-playwright-mcp
```
This page is for the other case: you are already committed to Microsoft's
@@ -32,10 +31,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:
@@ -120,8 +121,8 @@ knowing before you trust the session.
## Short answers to the questions that lead here
**Is there an MCP server for this project?** Yes:
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
`uvx aihawk`. It launches through the engine, so the seeded
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server),
`uvx invisible-playwright-mcp`. It launches through the engine, so the seeded
profile and the humanised pointer come with it.
Microsoft's own `playwright-mcp` also accepts `--browser firefox` together with
+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.
+30 -1
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.*`
@@ -167,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. |
@@ -179,6 +181,33 @@ 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
+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
@@ -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
+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
+2 -2
View File
@@ -189,8 +189,8 @@ supply a clean IP, human pacing, and session reuse for the layers a browser cann
[how to test whether the browser itself is the problem](how-to-test-bot-detection.md), and
[rate limiting your scraper so volume stops being the signal](how-to-rate-limit-your-scraper-playwright.md).
If the traffic is produced by an AI agent rather than a script, the pacing and
retry layers have their own failure modes, mapped on the AIHawk wiki:
[why does my AI agent get blocked?](https://github.com/feder-cr/AIHawk/wiki/why-does-my-ai-agent-get-blocked)
retry layers have their own failure modes, mapped on the invisible_playwright_mcp wiki:
[why does my AI agent get blocked?](https://github.com/feder-cr/invisible_playwright_mcp/wiki/why-does-my-ai-agent-get-blocked)
---
+6 -6
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.36.2"
version = "0.51.0"
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==48.43.0",
"invisible_core==63.66.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,8 @@ 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", "cryptography>=41"]
remote = ["websockets>=13"]
dev = ["websockets>=13", "aioquic>=1.2", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41", "h2>=4,<5"]
[tool.pytest.ini_options]
markers = [
@@ -243,7 +244,6 @@ release_tags = ["v"]
# exclusion that names nothing is refused by the gate.
[tool.invisible.english]
excluded = [
"src/invisible_playwright/_pw/",
"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))
+184
View File
@@ -0,0 +1,184 @@
"""Builds tests/data/canvas_text_ref_colors/refs.json from the bytes retail Firefox drew.
The reference of tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py: coloured
canvas text, and 39 cases (25 of black text on white, 14 coloured) under three ClearType
keys, all measured on retail Firefox 159.0 on Windows with tests/data/canvas_text_ref_colors/
index.html (the 14 coloured cases) and tests/data/canvas_text_ref/index.html (the 25 black
ones). The measuring harness saved, for every case, the RGBA bytes of the canvas
(<name>.rgba) and a <name>.json with its id, width, height and sha256:
<BYTES>/colors/retail/<name>.{json,rgba} the 14 coloured cases, retail's own
ClearType state (the seed's)
<BYTES>/keys/<gamma>_<contrast>/retail/<name>.{json,rgba}
the 39 cases under that key; the case
id of a coloured one is "color:<id>"
python -I scripts/build_canvas_text_colors_refs.py --bytes <BYTES> \
[--keys 1800_100,1400_50,2200_0] [--out tests/data/canvas_text_ref_colors/refs.json]
The repository holds no .rgba: they are 270 kB each. The script hashes an .rgba when the
directory has it (and stops if that is not the sha256 its .json says, or the size is not
width x height x 4); when only the .json is there (a byte file kept only where the engine
differed) it takes the hash the harness wrote. It stops too when the black cases under
1800/100 are not the ones tests/data/canvas_text_ref/refs.json holds for the same ids, or
when the coloured cases under 1800/100 differ from the ones of colors/retail (same machine,
same key: they are one measurement). Standard library only.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "tests" / "data" / "canvas_text_ref_colors"
BASE_REFS = ROOT / "tests" / "data" / "canvas_text_ref" / "refs.json"
DEFAULT_KEYS = "1800_100,1400_50,2200_0"
SEED_KEY = "1800_100"
DATE = "2026-11-09"
#: The prefs of the retail profile for the keys (user.js), gamma and contrast per key.
RETAIL_PREFS = {
"gfx.canvas.accelerated": False,
"gfx.font_rendering.cleartype_params.gamma": "<gamma>",
"gfx.font_rendering.cleartype_params.enhanced_contrast": "<contrast>",
"gfx.font_rendering.cleartype_params.cleartype_level": 100,
"gfx.font_rendering.cleartype_params.pixel_structure": 1,
"gfx.font_rendering.cleartype_params.rendering_mode": 0,
}
#: The coloured cases of colors/retail were measured with the machine's own ClearType prefs,
#: and gfx.canvas.accelerated off.
COLORS_RETAIL_PREFS = {"gfx.canvas.accelerated": False}
class BuildError(ValueError):
"""The saved bytes cannot be this reference."""
def colors_of_page(html):
"""[[name, fg, bg], ...] and [sizes] from the measuring page, as the page declares them."""
m = re.search(r"const COLORS = (\[\[.*?\]\]);", html, re.S)
s = re.search(r"const SIZES = (\[[^\]]*\]);", html)
if not m or not s:
raise BuildError("index.html declares no COLORS / SIZES")
return json.loads(m.group(1)), json.loads(s.group(1))
def read_dir(d):
"""{case id: {"width", "height", "sha256"}} of the .json files of one directory."""
d = Path(d)
if not d.is_dir():
raise BuildError("%s is not a directory" % d)
out = {}
for j in sorted(d.glob("*.json")):
m = json.loads(j.read_text(encoding="utf-8"))
sha, w, h = m["sha256"], int(m["w"]), int(m["h"])
rgba = j.with_suffix(".rgba")
if rgba.is_file():
data = rgba.read_bytes()
if len(data) != w * h * 4:
raise BuildError("%s: %d bytes, not %d x %d x 4" % (rgba, len(data), w, h))
got = hashlib.sha256(data).hexdigest()
if got != sha:
raise BuildError("%s: sha256 %s, its json says %s" % (rgba, got, sha))
if not re.fullmatch(r"[0-9a-f]{64}", sha):
raise BuildError("%s: sha256 %r is not 64 hex digits" % (j, sha))
if m["id"] in out:
raise BuildError("%s: case %r twice in %s" % (j.name, m["id"], d))
out[m["id"]] = {"width": w, "height": h, "sha256": sha}
return out
def build(bytes_dir, keys, page_html, base):
colors, sizes = colors_of_page(page_html)
color_ids = ["%s|%s" % (c[0], s) for c in colors for s in sizes]
bytes_dir = Path(bytes_dir)
seed = read_dir(bytes_dir / "colors" / "retail")
if sorted(seed) != sorted(color_ids):
raise BuildError("colors/retail has %s, the page draws %s" % (sorted(seed), sorted(color_ids)))
spec = {"%s|%s" % (c[0], s): {"name": c[0], "fg": c[1], "bg": c[2], "size": s}
for c in colors for s in sizes}
out_colors = {i: {"id": i, **spec[i], **seed[i]} for i in color_ids}
out_keys = {}
for tag in keys:
gamma, contrast = (int(x) for x in tag.split("_"))
cases = read_dir(bytes_dir / "keys" / tag / "retail")
black = {i: v for i, v in cases.items() if not i.startswith("color:")}
col = {i[len("color:"):]: v for i, v in cases.items() if i.startswith("color:")}
if sorted(col) != sorted(color_ids):
raise BuildError("key %s: coloured cases %s, the page draws %s"
% (tag, sorted(col), sorted(color_ids)))
for i in black:
if i not in base["cases"]:
raise BuildError("key %s: %r is not a case of canvas_text_ref" % (tag, i))
out_keys[tag] = {
"gamma": gamma, "contrast": contrast, "count": len(black) + len(col),
"black": {i: {"id": i, **black[i]} for i in sorted(black)},
"colors": {i: {"id": i, **col[i]} for i in color_ids},
}
if SEED_KEY in out_keys:
k = out_keys[SEED_KEY]
for i, v in k["black"].items():
if v["sha256"] != base["cases"][i]["sha256"]:
raise BuildError("%s under %s: %s, canvas_text_ref/refs.json has %s"
% (i, SEED_KEY, v["sha256"], base["cases"][i]["sha256"]))
for i, v in k["colors"].items():
if v["sha256"] != out_colors[i]["sha256"]:
raise BuildError("%s under %s differs from colors/retail: %s vs %s"
% (i, SEED_KEY, v["sha256"], out_colors[i]["sha256"]))
arial = [f for f in base["fonts"] if f["family"] == "Arial"]
if len(arial) != 1:
raise BuildError("canvas_text_ref/refs.json has no single Arial entry")
return {
"test_page": "index.html",
"black_page": "../canvas_text_ref/index.html",
"text": base["text"],
"firefox": base["firefox"],
"canvas": base["canvas"],
"cleartype": base["cleartype"],
"fonts": arial,
"capture": {
"date": DATE,
"origin": "retail Firefox 159.0 (build %s, firefox.exe sha256 %s) on Windows, "
"headless, canvases read back with getImageData; bytes saved by the "
"measuring harness: colors/retail (the 14 coloured cases) and "
"keys/<gamma>_<contrast>/retail (39 cases per key) of the win-asset "
"analysis of 2026-11-09"
% (base["firefox"]["buildid"], base["firefox"]["exe_sha256"]),
"colors_prefs": COLORS_RETAIL_PREFS,
"keys_prefs": RETAIL_PREFS,
},
"colors": {"count": len(out_colors), "cases": out_colors},
"keys": out_keys,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--bytes", required=True, metavar="DIR",
help="directory with colors/retail and keys/<gamma>_<contrast>/retail")
ap.add_argument("--keys", default=DEFAULT_KEYS,
help="ClearType keys, gamma_contrast, comma separated (default %(default)s)")
ap.add_argument("--out", default=str(DATA / "refs.json"))
a = ap.parse_args(argv[1:])
keys = [k for k in a.keys.split(",") if k]
try:
refs = build(a.bytes, keys, (DATA / "index.html").read_text(encoding="utf-8"),
json.loads(BASE_REFS.read_text(encoding="utf-8")))
except (BuildError, KeyError, ValueError) 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", newline="\n")
print("%d coloured cases, %d keys x %d cases -> %s"
% (refs["colors"]["count"], len(refs["keys"]),
next(iter(refs["keys"].values()))["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))
+22 -8
View File
@@ -3,8 +3,20 @@
A raw `firefox --screenshot` proves nothing about automation: a juggler-less
binary renders a screenshot just fine and ships broken (firefox-8 did exactly
that). This DRIVES the binary the way users will - Playwright launches it over
the juggler pipe and exercises real paths.
that). This DRIVES the binary the way users will - the wrapper (and the core under
it) launches it over the juggler pipe and exercises real paths.
⛔ THROUGH THE CORE, NOT THROUGH BARE PLAYWRIGHT. Since firefox-63 the engine holds
every channel that asks the proxy service until the client has said how the
session leaves the host (`Browser.setBrowserProxy`, or the explicit
`Browser.setNoBrowserProxy` of a session without a proxy): nothing may leave the
host before that. Stock Playwright sends the first only when it is given a proxy,
so a bare `p.firefox.launch_persistent_context(executable_path=...)` navigates
nowhere: run 43134774602, `Page.goto: Timeout 30000ms` on every leg, three
attempts. The core's launch sends the decision FIRST, and declares the first run
(terms of use, pre-onboarding) that this script used to copy into user.js, so
the copy is gone with it. The job installs the core under test (core_ref, from
git) and the wrapper, and seals the binary, before this script runs.
Three levels (see `--click` / `--full`):
@@ -133,12 +145,14 @@ def _drive(exe: str, url: str, level: str) -> str:
"""One run. `level` is "smoke", "click" or "full". Returns the UA."""
interacts = level in ("click", "full")
full = level == "full"
from playwright.sync_api import sync_playwright
from invisible_playwright import InvisiblePlaywright
with sync_playwright() as p:
browser = p.firefox.launch(executable_path=exe, headless=True)
# The core declares the first run and sends the session's road before anything else; the seal of the binary is
# INVISIBLE_SEAL_FILE (the job sets it), and `binary_path` is the binary under test.
with InvisiblePlaywright(seed=42, binary_path=exe, headless=True, humanize=False) as browser:
ctx = browser.new_context()
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 +177,7 @@ 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()
# SMOKE asserts (always).
assert "Firefox" in ua, f"unexpected UA (binary not driving correctly): {ua!r}"
@@ -171,7 +185,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())
+501
View File
@@ -0,0 +1,501 @@
#!/usr/bin/env python3
"""CI verdict - the one judge of the mandatory test suites (stdlib only).
`ci/required-suites.json` lists the suites a round must run, per operating system, with the number of tests each must
collect. A test that is skipped, deselected or never collected is a hole nobody sees, so this script reads the junit
pytest wrote and fails on every one of them.
ci_verdict.py args --required ci/required-suites.json --suite wrapper.e2e.udp --os linux [--with-marker]
prints, one per line, the pytest arguments of the suite (files and node ids); with --with-marker, `-m` and the
suite's marker come first. An error (exit 2) if the suite does not run on that OS or the list is malformed.
ci_verdict.py judge --required ci/required-suites.json --suite wrapper.e2e.udp --os linux
--junit junit.xml --binary PATH [--commit SHA] [--seal gate.seal.json]
[--out result/wrapper.e2e.udp.linux.json]
[--main-required PATH | --main-required PATH --main-has-no-list]
reads the junit, writes the result json (with `verdict`: "green" or "red") and exits 1, printing EVERY problem
with its reason, one per line, when: the junit or the row is missing; the junit is not xunit2 (a testcase with
no `classname`); a test failed, errored or was skipped; fewer tests were collected than `min_tests`, or, when
the row is `exact`, any number other than `min_tests` (a deselected test is not in the junit: `min_tests` goes
up by hand when a test is added, never silently); a required file or node id did not pass; the binary is
missing (--binary is mandatory: without it exit 2) or the commit cannot be known; the --seal is unreadable.
With --main-required (the list of main) the list only grows: a suite of main is gone, its minimum went down,
its `exact` went from true to false, its os or tests lost an element, or its marker changed is red.
What the file of main is can be said only by the gate, which checks main out (a failed download is not
"main has no list"): the file exists -> it is compared; it does not exist and the gate passed
--main-has-no-list (main was checked out and has no such file) -> passed, declared; it does not exist
without --main-has-no-list -> RED, "it is not known what main has".
The commit is --commit SHA or `git rev-parse HEAD` in the current directory (the checkout of the wrapper),
NEVER GITHUB_SHA (in a called workflow it is the commit of the engine's repository). --seal reads the seal of
the gate: the seal that `python -m invisible_core seal` writes, and the release seal, carry NO sha256 of the
engine binary (an asset's `sha256` is the one of the archive, `omni_sha256` the one of omni.ja), so there is
nothing to compare it with: the summary says so and the result records `seal_binary_hash: "absent"`.
ci_verdict.py complete --required ci/required-suites.json --results DIR
DIR holds the result json files `judge` wrote (also in subfolders: one artifact `result-<suite>-<os>` each).
Exit 1, one problem per line, when: a (suite, os) of the list has no result; a result is not green; a result
is of a (suite, os) that is not in the list, or twice; the commit is not the same in every result, or the
binary sha256 is not the same in every result of one OS (or missing).
The list is validated by all three commands (a malformed one is exit 2, with the reason, never green): ids unique; per
row `os` a non-empty subset of {linux, windows}, `tests` a non-empty list of unique strings, `min_tests` an integer > 0,
`exact` a bool, `marker` a string, `needs_root` a bool or a list of the row's OSes.
A required entry of "tests" is a file (at least one test of it must exist and EVERY one collected must pass) or a node
id `tests/x.py::name` (that test must pass; a parametrized test is matched on the name before `[`, and every one of its
parameters must pass).
What the gate must do (it is not done here):
* run pytest as `env -u PYTEST_ADDOPTS python -m pytest ... -p no:rerunfailures -o junit_family=xunit2
--junitxml=junit.xml` (no addopts from outside, no rerun that turns a failure green, a junit that keeps `classname`;
a junit with no `classname`, or with `file`/`line`, is red);
* on the Linux leg of the DoH suite, export INVPW_REQUIRE_TRAP=1 (the resolver trap must run, never be skipped);
* pass --commit or run in the checkout of the wrapper, pass --binary, and check out main before --main-required.
Exit 0 on a green verdict, 1 on a red one, 2 on a wrong use or a malformed list.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
OSES = ("linux", "windows")
class Usage(Exception):
pass
class BadList(Usage):
"""The required list itself is malformed (exit 2)."""
# --------------------------------------------------------------------------------------------- the required list
def _is_int(value):
return isinstance(value, int) and not isinstance(value, bool)
def validate_list(data):
"""-> the list of reasons why `data` is not a well-formed required list (empty if it is)."""
if not isinstance(data, list):
return ["the required list must be a JSON list of suites"]
if not data:
return ["the required list is empty"]
problems, seen = [], set()
for i, row in enumerate(data):
if not isinstance(row, dict):
problems.append("row %d is not an object" % i)
continue
sid = row.get("id")
where = "row %d" % i
if not isinstance(sid, str) or not sid.strip():
problems.append("%s has no id (a non-empty string)" % where)
else:
where = "row %d (%s)" % (i, sid)
if sid in seen:
problems.append("%s: the id appears more than once" % where)
seen.add(sid)
oses = row.get("os")
oses_ok = (isinstance(oses, list) and oses and all(isinstance(o, str) for o in oses)
and set(oses) <= set(OSES) and len(set(oses)) == len(oses))
if not oses_ok:
problems.append("%s: os must be a non-empty list of distinct values among %s, not %r"
% (where, "/".join(OSES), oses))
tests = row.get("tests")
if not (isinstance(tests, list) and tests and all(isinstance(t, str) and t.strip() for t in tests)):
problems.append("%s: tests must be a non-empty list of non-empty strings" % where)
elif len(set(tests)) != len(tests):
problems.append("%s: tests has duplicates: %s"
% (where, ", ".join(sorted({t for t in tests if tests.count(t) > 1}))))
if not _is_int(row.get("min_tests")) or row.get("min_tests") <= 0:
problems.append("%s: min_tests must be an integer > 0, not %r" % (where, row.get("min_tests")))
if not isinstance(row.get("exact"), bool):
problems.append("%s: exact must be true or false, not %r" % (where, row.get("exact")))
if not isinstance(row.get("marker"), str) or not row.get("marker").strip():
problems.append("%s: marker must be a non-empty string, not %r" % (where, row.get("marker")))
root = row.get("needs_root", False)
if not isinstance(root, bool):
if not (isinstance(root, list) and all(isinstance(o, str) for o in root) and set(root) <= set(OSES)
and (not oses_ok or set(root) <= set(oses))):
problems.append("%s: needs_root must be a bool or a list of the OSes of the row, not %r" % (where, root))
return problems
def _read_json_list(path):
try:
return json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise Usage("cannot read the required list %s: %s" % (path, exc))
def load_required(path):
data = _read_json_list(path)
problems = validate_list(data)
if problems:
raise BadList("the required list %s is malformed:\n %s" % (path, "\n ".join(problems)))
return data
def find_suite(suites, suite_id, os_name):
if os_name not in OSES:
raise Usage("--os must be one of %s, not %r" % (", ".join(OSES), os_name))
rows = [s for s in suites if isinstance(s, dict) and s.get("id") == suite_id]
if not rows:
raise Usage("no suite %r in the required list" % suite_id)
if len(rows) > 1:
raise Usage("the suite %r appears %d times in the required list" % (suite_id, len(rows)))
row = rows[0]
if os_name not in row.get("os", []):
raise Usage("the suite %r does not run on %s (it runs on: %s)"
% (suite_id, os_name, ", ".join(row.get("os", [])) or "nowhere"))
return row
# ------------------------------------------------------------------------------------------------- the junit
def node_id(classname, name):
"""`tests.test_x` + `test_y[p]` -> `tests/test_x.py::test_y[p]`; a class segment (capitalised) goes after the file."""
parts = [p for p in (classname or "").split(".") if p]
module, klass = [], []
for i, part in enumerate(parts):
if part[:1].isupper() and module:
klass = parts[i:]
break
module.append(part)
if not module:
return name or ""
return "::".join(["/".join(module) + ".py"] + klass + [name or ""])
def parse_junit(path):
"""-> (list of (node id, outcome) with outcome in passed|failed|errors|skipped, names of the testcases that are not
xunit2). Only xunit2 is accepted: a testcase with no `classname` cannot be told which file it is in, and the extra
`file`/`line` attributes are what junit_family=xunit1 writes (pytest 9: it keeps the classname AND adds them)."""
root = ET.parse(path).getroot()
out, no_class = [], []
for case in root.iter("testcase"):
if not (case.get("classname") or "").strip() or case.get("file") is not None or case.get("line") is not None:
no_class.append(case.get("name") or "?")
nid = node_id(case.get("classname"), case.get("name"))
tags = {child.tag for child in case}
if "error" in tags:
outcome = "errors"
elif "failure" in tags:
outcome = "failed"
elif "skipped" in tags:
outcome = "skipped"
else:
outcome = "passed"
out.append((nid, outcome))
return out, no_class
def read_junit(path):
return parse_junit(path)[0]
def _base(nid):
"""The node id without the parameters of its last segment."""
return nid.split("[", 1)[0]
def required_status(entry, cases):
"""-> None if the required entry is satisfied, else why not. EVERY collected test of the entry must have passed."""
if "::" in entry:
mine = [o for n, o in cases if n == entry or _base(n) == entry]
what = "node id"
else:
mine = [o for n, o in cases if n.split("::", 1)[0] == entry]
what = "file"
if not mine:
return "the %s %s did not run (it is not in the junit)" % (what, entry)
bad = sorted({o for o in mine if o != "passed"})
if bad:
return "the %s %s has tests that did not pass (%s)" % (what, entry, ", ".join(bad))
return None
def sha256_of(path):
if not path or not os.path.isfile(path):
return None
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def commit_sha(explicit):
"""--commit, else `git rev-parse HEAD` in the current directory. Never GITHUB_SHA (in a called workflow it is the
commit of the engine's repository, not of the wrapper)."""
if explicit:
return explicit.strip() or None
try:
sha = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=30,
check=True).stdout.strip()
except (OSError, subprocess.SubprocessError):
return None
return sha or None
# ------------------------------------------------------------------------------------------------ against main
def _int(value):
return value if _is_int(value) else 0
def against_main(current, main):
"""The list only grows: every suite of main is still here, with no lower minimum, no exact turned off, no lost
test or OS and the same marker. `main` is read leniently (it may be older than the current format)."""
problems = []
if not isinstance(main, list):
return ["the list of main is not a JSON list: it cannot be compared"]
by_id = {s.get("id"): s for s in current if isinstance(s, dict)}
for old in main:
if not isinstance(old, dict):
continue
sid = old.get("id")
new = by_id.get(sid)
if new is None:
problems.append("the suite %s of main is gone from the list" % sid)
continue
if _int(new.get("min_tests")) < _int(old.get("min_tests")):
problems.append("the minimum of %s went down: %s on main, %s here"
% (sid, old.get("min_tests"), new.get("min_tests")))
if old.get("exact") is True and new.get("exact") is not True:
problems.append("the suite %s is no longer exact, as it is on main" % sid)
lost = [t for t in old.get("tests", []) if t not in new.get("tests", [])]
if lost:
problems.append("the suite %s lost %d required test(s) that main has: %s" % (sid, len(lost), ", ".join(lost)))
lost_os = [o for o in old.get("os", []) if o not in new.get("os", [])]
if lost_os:
problems.append("the suite %s no longer runs on %s, where main runs it" % (sid, ", ".join(lost_os)))
if old.get("marker") != new.get("marker"):
problems.append("the marker of %s changed: %r on main, %r here" % (sid, old.get("marker"), new.get("marker")))
return problems
# ------------------------------------------------------------------------------------------------ the commands
def cmd_args(ns):
row = find_suite(load_required(ns.required), ns.suite, ns.os)
lines = []
if ns.with_marker and row.get("marker"):
lines += ["-m", row["marker"]]
lines += list(row.get("tests", []))
# bytes, so that Windows does not turn the newlines into CRLF (a CR would stay glued to the last argument)
sys.stdout.buffer.write("".join(line + "\n" for line in lines).encode("utf-8"))
sys.stdout.buffer.flush()
return 0
def _seal_problems(path, result):
"""The seal of the gate must be readable. It has no sha256 of the binary to compare (see the docstring)."""
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("not a JSON object")
except (OSError, ValueError) as exc:
result["seal_binary_hash"] = "unreadable"
return ["the seal %s cannot be read: %s" % (path, exc)]
result["seal_binary_hash"] = "absent"
print("note: the seal %s carries no sha256 of the engine binary (an asset's sha256 is the one of the archive): "
"the binary was not compared with it" % path)
return []
def cmd_judge(ns):
problems = []
result = {"suite": ns.suite, "os": ns.os, "commit": commit_sha(ns.commit), "binary_sha256": sha256_of(ns.binary),
"collected": 0, "passed": 0, "failed": 0, "skipped": 0, "errors": 0, "missing_tests": [],
"problems": problems}
code_on_red = 1
try:
suites = load_required(ns.required)
row = find_suite(suites, ns.suite, ns.os)
except BadList as exc:
problems.append(str(exc))
return _finish(ns, result, 2)
except Usage as exc:
problems.append("no result for this row: %s" % exc)
return _finish(ns, result, code_on_red)
if result["commit"] is None:
problems.append("the commit of the wrapper is not known (no --commit and `git rev-parse HEAD` failed here)")
if result["binary_sha256"] is None:
problems.append("the binary %s does not exist: a result with no hash of the engine is not a result" % ns.binary)
if ns.seal:
problems += _seal_problems(ns.seal, result)
counts = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
cases = []
if not os.path.isfile(ns.junit):
problems.append("the junit %s is missing: the suite %s did not report on %s" % (ns.junit, ns.suite, ns.os))
else:
try:
cases, no_class = parse_junit(ns.junit)
if no_class:
problems.append("the junit is not xunit2: %d testcase(s) have no classname or carry file/line (e.g. %s); the gate must run "
"pytest with -o junit_family=xunit2" % (len(no_class), no_class[0]))
except (ET.ParseError, OSError) as exc:
problems.append("the junit %s cannot be read: %s" % (ns.junit, exc))
for _n, outcome in cases:
counts[outcome] += 1
collected = len(cases)
if counts["failed"]:
problems.append("%d test(s) failed" % counts["failed"])
if counts["errors"]:
problems.append("%d test(s) ended in error" % counts["errors"])
if counts["skipped"]:
problems.append("%d test(s) were skipped: a required suite allows no skip" % counts["skipped"])
minimum = row.get("min_tests")
if collected < minimum:
problems.append("collected %d test(s), fewer than the minimum %s" % (collected, minimum))
elif row.get("exact") and collected != minimum:
problems.append("collected %d test(s), but the suite is exact: %s, not more (a test was added: raise min_tests "
"by hand)" % (collected, minimum))
missing = []
for entry in row.get("tests", []):
why = required_status(entry, cases)
if why:
missing.append(entry)
problems.append(why)
if ns.main_has_no_list and not ns.main_required:
problems.append("--main-has-no-list without --main-required: it says nothing")
elif ns.main_required:
exists = os.path.isfile(ns.main_required)
if exists and ns.main_has_no_list:
problems.append("the list of main %s exists, but --main-has-no-list says main has none" % ns.main_required)
elif exists:
try:
problems += against_main(suites, _read_json_list(ns.main_required))
except Usage as exc:
problems.append(str(exc))
elif ns.main_has_no_list:
print("the list of main %s does not exist and the gate declares that main was checked out and has none: "
"nothing to compare" % ns.main_required)
else:
problems.append("the list of main %s does not exist and main was not declared to have none "
"(--main-has-no-list): it is not known what main has, so the list cannot be compared"
% ns.main_required)
result.update(counts, collected=collected, missing_tests=missing)
return _finish(ns, result, code_on_red)
def _finish(ns, result, code_on_red):
problems = result["problems"]
result["verdict"] = "red" if problems else "green"
if ns.out:
out = Path(ns.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
if problems:
for p in problems:
print("VERDICT RED %s/%s: %s" % (ns.suite, ns.os, p))
return code_on_red
print("VERDICT GREEN %s/%s: %d collected, %d passed" % (ns.suite, ns.os, result["collected"], result["passed"]))
return 0
def cmd_complete(ns):
suites = load_required(ns.required)
expected = {(s["id"], o) for s in suites for o in s["os"]}
problems = []
folder = Path(ns.results)
if not folder.is_dir():
problems.append("the results folder %s does not exist: no suite reported" % ns.results)
found = {} # (suite, os) -> (path, data)
for path in sorted(folder.rglob("*.json")) if folder.is_dir() else []:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
problems.append("%s cannot be read as a result: %s" % (path, exc))
continue
if not (isinstance(data, dict) and isinstance(data.get("suite"), str) and isinstance(data.get("os"), str)):
problems.append("%s is not a result of judge (no suite and os)" % path)
continue
key = (data["suite"], data["os"])
if key not in expected:
problems.append("%s is the result of %s/%s, which is not in the required list" % (path, key[0], key[1]))
continue
if key in found:
problems.append("%s/%s has two results: %s and %s" % (key[0], key[1], found[key][0], path))
continue
found[key] = (path, data)
for suite, os_name in sorted(expected - set(found)):
problems.append("%s/%s has no result: the leg did not report" % (suite, os_name))
for key, (path, data) in sorted(found.items()):
if data.get("verdict") != "green":
why = data.get("problems") or ["no verdict in the result"]
problems.append("%s/%s is not green (%s): %s" % (key[0], key[1], data.get("verdict"), "; ".join(map(str, why))))
elif data.get("problems"):
problems.append("%s/%s says green but lists problems: %s" % (key[0], key[1], "; ".join(map(str, data["problems"]))))
commits = {}
shas = {}
for key, (_path, data) in found.items():
commits.setdefault(data.get("commit"), []).append("%s/%s" % key)
shas.setdefault(key[1], {}).setdefault(data.get("binary_sha256"), []).append("%s/%s" % key)
if None in commits:
problems.append("no commit in the result of: %s" % ", ".join(sorted(commits[None])))
if len([c for c in commits if c]) > 1:
problems.append("the legs ran at different commits: %s"
% "; ".join("%s: %s" % (c, ", ".join(sorted(v))) for c, v in sorted(commits.items(), key=str)))
for os_name, by_sha in sorted(shas.items()):
if None in by_sha:
problems.append("no binary sha256 in the result of: %s" % ", ".join(sorted(by_sha[None])))
if len([s for s in by_sha if s]) > 1:
problems.append("the %s legs ran with different binaries: %s" % (
os_name, "; ".join("%s: %s" % (s, ", ".join(sorted(v))) for s, v in sorted(by_sha.items(), key=str))))
if problems:
for p in problems:
print("COMPLETE RED: %s" % p)
return 1
print("COMPLETE GREEN: %d result(s), all green, one commit, one binary per OS" % len(found))
return 0
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
sub = ap.add_subparsers(dest="cmd", required=True)
a = sub.add_parser("args", help="print the pytest arguments of a suite")
a.add_argument("--required", required=True)
a.add_argument("--suite", required=True)
a.add_argument("--os", required=True)
a.add_argument("--with-marker", action="store_true", help="print -m and the marker of the suite first")
j = sub.add_parser("judge", help="judge the junit of a suite")
j.add_argument("--required", required=True)
j.add_argument("--suite", required=True)
j.add_argument("--os", required=True)
j.add_argument("--junit", required=True)
j.add_argument("--binary")
j.add_argument("--commit")
j.add_argument("--seal")
j.add_argument("--out")
j.add_argument("--main-required")
j.add_argument("--main-has-no-list", action="store_true",
help="the gate checked main out and the list is not there (a failed checkout is not this)")
c = sub.add_parser("complete", help="check that every (suite, os) reported green at one commit")
c.add_argument("--required", required=True)
c.add_argument("--results", required=True)
ns = ap.parse_args(argv)
try:
if ns.cmd == "judge":
if not ns.binary:
raise Usage("judge needs --binary (the engine the suite ran against: its hash goes in the result)")
return cmd_judge(ns)
if ns.cmd == "complete":
return cmd_complete(ns)
return cmd_args(ns)
except Usage as exc:
print("ci_verdict: %s" % exc, file=sys.stderr)
return 2
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))
-19
View File
@@ -65,25 +65,6 @@ EXPECTED_DIFFERENCES = {
# this line is where to start.
("ElementHandle", "event", "previewUpdated"),
("JSHandle", "event", "previewUpdated"),
# ⛔ `Dialog` FUSED on 2026-08-29: no `__create__`, no channel, no
# `BrowserContext.dialog` wire event - see `_pw/_impl/_dialog.py`. The
# driver still allocates a real channel object for it (parented under
# `Page`, with `type`/`message`/`defaultValue`/`page` in its initializer)
# and announces it with a `dialog` event on `BrowserContext`; this server
# builds the same object directly, on the connection's read-loop thread,
# and hands it straight to the listener through the twin bridge in
# `InProcessTransport.bind_impl_objects`. The three lines below were
# measured EMPTY before this fusion - `capture_protocol.py`'s scripted
# session did not open a dialog at all, so a `PARITY` verdict for this
# type would have been vacuous, not a confirmation. It now clicks a
# button that calls `alert()` and accepts it, so the gap below is a
# measured, argued difference, not an unexercised one.
("Dialog", "initializer", "type"),
("Dialog", "initializer", "message"),
("Dialog", "initializer", "defaultValue"),
("Dialog", "initializer", "page"),
("Dialog", "parent", "Page"),
("BrowserContext", "event", "dialog"),
}
+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>
+341
View File
@@ -0,0 +1,341 @@
#!/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 latest(history: dict[str, dict[str, int]], key: str) -> int:
days = [d for d in history if key in history[d]]
if not days:
raise SystemExit(f"no {key} in the history")
return history[max(days)][key]
# The big row at the top of the README is drawn by shields.io from these
# files (its "endpoint" badge), so the numbers stay ours and the look is theirs.
@dataclass(frozen=True)
class Endpoint:
label: str
colour: str
logo: str
file_name: str
key: str
ENDPOINTS = [
Endpoint("browser launches", "FF7139", "firefoxbrowser", "launches.json", "launches_total"),
Endpoint("engine downloads", "2EA44F", "github", "downloads.json", "total_binaries"),
]
def endpoint_json(value: str, e: Endpoint) -> bytes:
if not SAFE_VALUE.match(value):
raise ValueError(f"refusing to publish an unexpected value: {value!r}")
return (json.dumps({
"schemaVersion": 1, "label": e.label, "message": value,
"color": e.colour, "namedLogo": e.logo, "logoColor": "white",
"cacheSeconds": 3600,
}, indent=2) + "\n").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:
(directory / b.file_name).write_bytes(
render(format_count(latest(history, b.key)), b))
for e in ENDPOINTS:
(directory / e.file_name).write_bytes(
endpoint_json(format_count(latest(history, e.key)), e))
# ── 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")
# The README's top row reads these two files through shields.io.
h = {"2026-11-11": {"launches_total": 5_319_939, "total_binaries": 232_924, "stars": 2569}}
write_badges(Path(t) / "b", h)
got = json.loads((Path(t) / "b" / "launches.json").read_text(encoding="utf-8"))
if (got.get("schemaVersion"), got.get("label"), got.get("message")) != (1, "browser launches", "5.31M"):
fails.append("endpoint launches")
got = json.loads((Path(t) / "b" / "downloads.json").read_text(encoding="utf-8"))
if got.get("message") != "232.92k":
fails.append("endpoint downloads")
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)
+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:]))
+1 -1
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
+4
View File
@@ -68,6 +68,7 @@ from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION
from invisible_core import GeoTimezoneError, resolve_session_timezone
from invisible_core import ensure_binary, ensure_geoip_mmdb
from .launcher import InvisiblePlaywright
from ._juggler.remote import RemoteServer, launch_server, launch_server_async
# `__version__` describes the CODE that is about to run; the install record is
# a different fact and keeps a name that says so, the way `invisible_core` does.
@@ -79,6 +80,9 @@ from ._version import __install_record_version__, __version__
__all__ = [
"InvisiblePlaywright",
"launch_server",
"launch_server_async",
"RemoteServer",
"ensure_binary",
"ensure_geoip_mmdb",
"get_default_stealth_prefs",
File diff suppressed because it is too large. Load diff
+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)
+55 -75
View File
@@ -15,9 +15,18 @@ there has to move.
from __future__ import annotations
import json
import math
import re
from typing import Any, Dict, List, Optional
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)
def _caller_timeout(params: Dict, default_ms: float = 30000) -> Optional[float]:
"""The caller's timeout off the wire, in seconds; None is no limit.
@@ -34,74 +43,45 @@ def _caller_timeout(params: Dict, default_ms: float = 30000) -> Optional[float]:
return default_ms / 1000.0
def _as_callable(expression: str, argument: Any) -> str:
"""Wrap an expression so it can always be CALLED with the argument.
#: 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")
<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 _as_script(expression: str) -> str:
"""The caller's text as Playwright evaluates it ([B340]).
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.
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.
<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.
⛔ 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.
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.
⛔ 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.
"""
return "(() => { %s })()" % _invocation(expression, argument)
def _invocation(expression: str, argument: Any, *receivers: str) -> str:
"""The statements that evaluate the caller's expression and, when it is a
function, call it with `receivers` first and the argument last.
<M> THE ONLY PLACE THAT SPELLS THE CALL. The main-world wrapper above and
the three element-scoped ones (`handle.evaluate`, `eval_on_selector`,
`eval_on_selector_all`) used to write it out each on its own, and that is
how the argument reached `handle.evaluate` and was dropped by the other
two: a callback reading its second parameter got `undefined` there.
The main-world output is pinned byte for byte by
`test_the_argument_does_not_rewrite_the_expression.py`, because that one
runs as the page.
"""
return ("const r = (%s); return typeof r === 'function' ? r(%s) : r;"
% (expression,
", ".join(receivers + (json.dumps(argument, default=str),))))
def _called_on(params: Dict, receiver: str) -> str:
"""The body of an element-scoped wrapper: the caller's function called
with `receiver` and the caller's argument, Playwright's `fn(element, arg)`.
"""
return _invocation(params["expression"], _deserialize(params.get("arg")),
receiver)
def _element_function(params: Dict) -> str:
"""The declaration `handle.evaluate` and `eval_on_selector` both send: one
element, then the argument. Both run in the utility world."""
return "(injected, el) => { %s }" % _called_on(params, "el")
text = expression.strip(_JS_WHITESPACE)
if re.match(r"(async)?\s*function(\s|\()", text):
text = "(" + text + ")"
return text
def _deserialize(value: Any) -> Any:
@@ -125,16 +105,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.
@@ -166,6 +136,15 @@ def _serialize(value: Any, counter: Optional[Dict] = None) -> Any:
return {"v": "null"}
if isinstance(value, bool):
return {"b": value}
if isinstance(value, float):
# NaN, the infinities and -0 are not JSON numbers: Playwright sends them as a tag
# (`{"v": "NaN"}`), and a bare `{"n": nan}` is refused by a strict wire.
if math.isnan(value):
return {"v": "NaN"}
if math.isinf(value):
return {"v": "Infinity" if value > 0 else "-Infinity"}
if value == 0.0 and math.copysign(1.0, value) < 0:
return {"v": "-0"}
if isinstance(value, (int, float)):
return {"n": value}
if isinstance(value, str):
@@ -210,7 +189,8 @@ def _headers_array(raw) -> List[Dict[str, str]]:
#: 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.
#: Playwright driver's ffNetworkManager uses for the same event (the pinned driver's table is read by
#: tests/test_resource_types_match_the_pinned_driver.py: a beacon is `beacon`, a CSP report `cspreport`).
_CAUSE_TO_RESOURCE_TYPE = {
"TYPE_INVALID": "other", "TYPE_OTHER": "other",
"TYPE_SCRIPT": "script", "TYPE_IMAGE": "image",
@@ -219,8 +199,8 @@ _CAUSE_TO_RESOURCE_TYPE = {
"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_WEBSOCKET": "websocket", "TYPE_CSP_REPORT": "cspreport",
"TYPE_XSLT": "other", "TYPE_BEACON": "beacon", "TYPE_FETCH": "fetch",
"TYPE_IMAGESET": "image", "TYPE_WEB_MANIFEST": "manifest",
}
_INTERNAL_CAUSE_TO_RESOURCE_TYPE = {
@@ -0,0 +1,72 @@
"""A dialog is answered after the time a reader would take, not at pipe speed.
⛔ WHAT IT REPLACES. `alert`, `confirm` and `prompt` were answered in the same
millisecond they opened: the client's auto-dismiss (no handler registered) and
a handler's own `accept()`/`dismiss()` both sent `Page.handleDialog` the moment
the event reached them. No person closes a dialog before it has been painted,
let alone read; a page timing `alert()`'s return saw a few milliseconds where
every browser in the world shows hundreds. The stock driver does the same, so
this is not a tell of one driver but of all of them, which is exactly why a
site can afford to test for it.
The pause is drawn from the session's seed, like every other rhythm of this
package: one seed, one reader, the same reader on every machine. It has a
reaction part (noticing the dialog, moving to the button) and a reading part
that grows with the words. Both are log-normal, both clamped, and each dialog
of a page draws its own, so two dialogs with the same text do not take the
same time.
The remainder is what is waited: a handler that spent its own time deciding is
not asked to wait again for what already passed.
"""
from __future__ import annotations
import hashlib
import math
import random
from typing import Optional
#: Noticing the dialog and reaching the button: median and spread (log-normal).
REACTION_MEDIAN_MS = 650.0
REACTION_SIGMA = 0.35
#: Reading, per word.
PER_WORD_MEDIAN_MS = 230.0
PER_WORD_SIGMA = 0.30
#: No reader is faster or slower than this.
FLOOR_MS = 350.0
CEILING_MS = 8000.0
def _rng(seed: int, page: int, ordinal: int) -> random.Random:
"""One stream per (seed, page, dialog). Hashed to an int on purpose:
`random.Random` seeds a tuple through `hash()`, and the hash of a str
changes from one process to the next."""
key = f"dialog:{seed}:{page}:{ordinal}".encode()
return random.Random(int.from_bytes(hashlib.sha256(key).digest()[:8], "big"))
def _log_normal(rng: random.Random, median: float, sigma: float) -> float:
return median * math.exp(rng.gauss(0.0, sigma))
def plan_answer_ms(seed: Optional[int], page: int, ordinal: int,
message: str) -> float:
"""How long after it opened this dialog is answered, in ms.
`seed` is None when the session has no rhythm (humanising off): then there
is no pause, which is what every other seeded rhythm does with None."""
if seed is None:
return 0.0
rng = _rng(seed, page, ordinal)
words = len(message.split())
total = _log_normal(rng, REACTION_MEDIAN_MS, REACTION_SIGMA)
for _ in range(words):
total += _log_normal(rng, PER_WORD_MEDIAN_MS, PER_WORD_SIGMA)
return min(CEILING_MS, max(FLOOR_MS, total))
def remaining_ms(planned_ms: float, opened_at: float, now: float) -> float:
"""What is still to wait: the plan minus the time already gone since the
dialog opened (both clocks in seconds, from the same monotonic source)."""
elapsed_ms = (now - opened_at) * 1000.0
return max(0.0, planned_ms - elapsed_ms)
+175 -43
View File
@@ -31,11 +31,14 @@ be, and the failure surfaces later, in a property access far from the cause.
"""
from __future__ import annotations
import contextvars
import itertools
import os
import threading
from typing import Any, Callable, Dict, Optional
import time
from typing import Any, Callable, Dict, List, Optional
from . import perimeter
from . import perimeter, variants
# One class for a target that is gone, raised here for a disposed object and
# by the connection for a closed pipe. Defined there, the lower layer.
from invisible_core.juggler.connection import TargetClosedError # noqa: F401 - re-exported on purpose
@@ -43,6 +46,43 @@ from invisible_core.juggler.connection import TargetClosedError # noqa: F401 -
#: HOW MANY DISPATCHERS OF ONE BUCKET THE REGISTRY KEEPS, AS PLAYWRIGHT'S SERVER DOES
#: (1.62, `dispatchers/dispatcher.ts` `maxDispatchersForBucket`): a bucket is the object's
#: type - a Frame is 'MainFrame' or 'Frame' - and past its limit the oldest tenth of the
#: bucket is disposed with `__dispose__` {reason: "gc"}, which a client reads as "collected
#: to prevent unbounded heap growth". ONE VALUE PER TYPE, here, so it can be lowered in one
#: place; `INVPW_GC_LIMITS="Request=1000,Response=1000"` lowers some without editing code
#: ("default=N" changes the default).
#:
#: TWO DIFFERENCES FROM PLAYWRIGHT, and the only two. (1) Request, Response and Route are
#: 2000, not 10000: a context that lives through a hundred navigations of real pages
#: (~100 subresources each, ~200 objects per navigation) held 18,000 of them, and with real
#: headers that is 190 MB of process (measured on a real browser, 95 navigations, one
#: context, objects already light) against 70 MB with 2000. A client reads a request in the
#: callback of its event (the Go client keeps none beyond it) and 2000 is ten navigations.
#: (2) An object younger than GC_MIN_AGE_S is never collected, so what a client was just
#: handed is valid for the length of any callback however fast the bucket fills: Playwright
#: collects the oldest tenth whatever its age.
GC_LIMIT_DEFAULT = 10000
GC_LIMITS: Dict[str, int] = {"JSHandle": 100000, "ElementHandle": 100000,
"Request": 2000, "Response": 2000, "Route": 2000}
GC_MIN_AGE_S = 10.0
def gc_limits_from_env(environ: Optional[Dict[str, str]] = None) -> Dict[str, int]:
"""`GC_LIMITS` with the default under "default", and what `INVPW_GC_LIMITS` overrides."""
environ = os.environ if environ is None else environ
limits = dict(GC_LIMITS)
limits["default"] = GC_LIMIT_DEFAULT
for item in (environ.get("INVPW_GC_LIMITS") or "").split(","):
name, _, value = item.partition("=")
try:
limits[name.strip()] = max(1, int(value))
except ValueError:
continue
return limits
class ProtocolException(Exception):
"""A failure the client should see as a protocol error, with its reason.
@@ -59,9 +99,37 @@ class ExpectNotMet(ProtocolException):
reads (`_frame.py` `_expect`) to build its AssertionError: `received` is
the last value seen, serialized, and `timedOut` says the wait ran out."""
def __init__(self, message: str, details: Dict) -> None:
def __init__(self, message: str, details: Dict,
log: Optional[List[str]] = None) -> None:
super().__init__(message)
self.details = details
#: The call's log, which the reply carries as `log` ([B341]).
self.log = list(log or [])
class CallLog:
"""What one call did, line by line: the log Playwright's server keeps per
call (its progress, `metadata.log`) and sends with a failure, where the
client prints it under "Call log:" ([B341]). `title` is the one the
client sent in the call's metadata, as Playwright's `renderTitleForCall`
reads it, or the method's name."""
def __init__(self, title: str) -> None:
self.title = title
self.lines: List[str] = []
def log(self, line: str) -> None:
self.lines.append(line)
#: The call this thread is answering. Set by `Server.handle` around the
#: dispatch; each worker thread answers one call at a time.
_CURRENT_CALL: "contextvars.ContextVar[CallLog]" = contextvars.ContextVar("call")
def current_call() -> CallLog:
"""The log of the call being answered, or a fresh one outside a call."""
return _CURRENT_CALL.get(None) or CallLog("")
class Dispatcher:
@@ -91,6 +159,18 @@ class Dispatcher:
server.register(self)
# ⛔ Announced BEFORE anyone can name it. See the module docstring.
server.announce(self)
self.announced()
# And only then, as Playwright does: past the limit of its bucket the oldest are let go.
server.collect_stale(self._gc_bucket)
def announced(self) -> None:
"""The `__create__` has gone: where an object lets go of what only the
announcement needed (a leaf's headers, a POST body). Runs once, from
the constructor."""
def gc_bucket(self) -> str:
"""The bucket this object is counted in (`GC_LIMITS`): its type."""
return self.TYPE
# ── what the protocol needs ─────────────────────────────────────────────
@property
@@ -99,7 +179,11 @@ class Dispatcher:
return {"guid": self.guid}
def emit(self, method: str, params: Optional[Dict] = None) -> None:
"""Fire a protocol event on this object."""
"""Fire a protocol event on this object. One that is already disposed says
nothing: the client has dropped the guid, and naming it is an error there
(Playwright's server ignores it too, outside its own tests)."""
if self.disposed:
return
self.server.send_up({"guid": self.guid, "method": method,
"params": params or {}})
@@ -128,9 +212,17 @@ class Dispatcher:
self.server.send_up({"guid": self.guid, "method": "__dispose__",
"params": params})
self.server.unregister(self)
self.released()
for child in self.server.descendants_of(self):
child.disposed = True
self.server.unregister(child)
child.released()
def released(self) -> None:
"""The object has left the registry, by its own `dispose` or by an
ancestor's cascade (which does not call `dispose` on a descendant):
where it lets go of what OTHER objects hold of it - an index, a list,
a file. Runs once."""
# ── routing ─────────────────────────────────────────────────────────────
def call(self, method: str, params: Dict) -> Any:
@@ -170,6 +262,10 @@ class Server:
#: already in flight behind it.
self._disposed: Dict[str, None] = {}
self._counters: Dict[str, itertools.count] = {}
#: bucket -> the guids of its live objects, oldest first (a dict keeps the order).
self._buckets: Dict[str, Dict[str, None]] = {}
self.gc_limits = gc_limits_from_env()
self.gc_min_age = GC_MIN_AGE_S
self._lock = threading.Lock()
self._transport: Any = None
#: Guid "" is the Root the client creates on its own side. Nothing is
@@ -178,49 +274,11 @@ class Server:
self._on_shutdown: list = []
#: What `shutdown` runs after every hook. See `after_shutdown`.
self._after_shutdown: list = []
#: guid -> the live impl-side object for it, or None until a
#: transport binds it. See `bind_twins`.
self._twins: Optional[Dict[str, Any]] = None
#: The client's `Connection.deliver_event`, or None until bound. See
#: `bind_twins` and `deliver`.
self._deliver_event: Any = None
# ── plumbing ────────────────────────────────────────────────────────────
def attach(self, transport: Any) -> None:
self._transport = transport
def bind_twins(self, objects: Dict[str, Any], deliver_event: Any) -> None:
"""Give this server a live view of the client's guid -> object
registry, and its event-delivery entry point. See
`InProcessTransport.bind_impl_objects`, which calls this - the
docstring for WHY lives there, next to its one caller."""
self._twins = objects
self._deliver_event = deliver_event
def twin(self, guid: str) -> Any:
"""The live impl-side object for a guid this server already created,
or None if nothing is bound yet or the guid is unknown."""
return (self._twins or {}).get(guid)
def deliver(self, fn: Any, *args: Any) -> None:
"""Call `fn(*args)` as an event, under the client's own rules for
what that means (see `Connection.deliver_event`). MUST be called from
the asyncio loop thread - use `call_soon` to get there first."""
self._deliver_event(fn, *args)
def run_blocking(self, fn: Any, *args: Any) -> Any:
"""A fused dispatcher's way to run a blocking call off the loop.
Delegates to the transport, which owns the worker pool; see
`InProcessTransport.run_blocking` for why this exists and what it
guards against."""
return self._transport.run_blocking(fn, *args)
def call_soon(self, fn: Any, *args: Any) -> None:
"""A fused dispatcher's way to hand an EVENT to the asyncio loop from
the connection's read-loop thread. See
`InProcessTransport.call_soon`."""
self._transport.call_soon(fn, *args)
def send_up(self, message: Dict) -> None:
if self._transport is not None:
self._transport.emit_message(message)
@@ -231,8 +289,13 @@ class Server:
return "%s@%d" % (type_name.lower(), next(counter))
def register(self, obj: Dispatcher) -> None:
obj._born = time.monotonic()
bucket = obj._gc_bucket = getattr(obj, "TYPE", "Unknown")
if hasattr(obj, "gc_bucket"):
bucket = obj._gc_bucket = obj.gc_bucket()
with self._lock:
self._objects[obj.guid] = obj
self._buckets.setdefault(bucket, {})[obj.guid] = None
#: How many disposed guids are remembered. Large enough for any burst of
#: in-flight calls, small enough to be free.
@@ -241,6 +304,9 @@ class Server:
def unregister(self, obj: Dispatcher) -> None:
with self._lock:
self._objects.pop(obj.guid, None)
members = self._buckets.get(getattr(obj, "_gc_bucket", None))
if members is not None:
members.pop(obj.guid, None)
self._disposed[obj.guid] = None
while len(self._disposed) > self.DISPOSED_MEMORY:
self._disposed.pop(next(iter(self._disposed)))
@@ -268,6 +334,63 @@ class Server:
walker = walker.parent
return out
def gc_limit(self, bucket: str) -> int:
return self.gc_limits.get(bucket, self.gc_limits["default"])
def collect_stale(self, bucket: str) -> None:
"""Playwright's `maybeDisposeStaleDispatchers`: a bucket past its limit loses its
oldest tenth, each with `__dispose__` {reason: "gc"} and the whole subtree silently
(a client drops the children of a disposed object by itself)."""
limit = self.gc_limit(bucket)
with self._lock:
members = self._buckets.get(bucket)
if not members or len(members) <= limit:
return
oldest = list(itertools.islice(members, max(1, limit // 10)))
young = time.monotonic() - self.gc_min_age
victims = []
for guid in oldest:
obj = self._objects.get(guid)
if obj is None:
continue
if obj._born > young:
break # the bucket is in birth order: the rest are younger
victims.append(obj)
self.dispose_many(victims, "gc")
def dispose_many(self, victims: list, reason: Optional[str]) -> None:
"""Dispose objects and their subtrees with ONE walk of the registry (a walk per
object would be quadratic in a bucket of thousands). A victim under another victim
is dropped by the cascade and says nothing of its own: the client would have no
guid for it."""
ids = {id(v) for v in victims}
params = {"reason": reason} if reason else {}
for victim in victims:
walker, covered = victim.parent, False
while walker is not None:
if id(walker) in ids:
covered = True
break
walker = walker.parent
if covered or victim.disposed:
continue
victim.disposed = True
self.send_up({"guid": victim.guid, "method": "__dispose__", "params": params})
self.unregister(victim)
victim.released()
with self._lock:
everything = list(self._objects.values())
for candidate in everything:
walker, seen = candidate.parent, set()
while walker is not None and id(walker) not in seen:
if id(walker) in ids:
candidate.disposed = True
self.unregister(candidate)
candidate.released()
break
seen.add(id(walker))
walker = walker.parent
def announce(self, obj: Dispatcher) -> None:
"""Emit `__create__` for a new object, parented where the client can
already find it."""
@@ -340,7 +463,16 @@ class Server:
raise ProtocolException(
"no object %r to answer %r: it was never created"
% (guid, method))
return obj.call(method, params)
metadata = message.get("metadata") or {}
# ⛔ THE VERSIONS OF THE PROTOCOL ARE FOLDED HERE, once, before any
# operation reads a parameter: see `variants.py`. A refusal of a
# command this server does not serve is raised from there.
params = variants.to_internal(method, params, metadata)
token = _CURRENT_CALL.set(CallLog(metadata.get("title") or method or ""))
try:
return obj.call(method, params)
finally:
_CURRENT_CALL.reset(token)
def handle_root(self, method: str, params: Dict) -> Any:
raise ProtocolException("the root has no method %r" % method)
@@ -0,0 +1,175 @@
"""What the served browser does about its memory: a trim that is ON, and a probe that is OFF.
THE TRIM. On Linux with glibc the server calls `malloc_trim(0)` after each message of
TRIM_BYTES or more has been sent and after each context close. INVPW_MALLOC_TRIM=0 turns
it off. Elsewhere (not Linux, musl, a libc without the function) it calls nothing and says
nothing: the endpoint asks `trimmer_from_env` once and every hook on the hot path is a
test of the None it gets back. No `mallopt` and no MALLOC_ARENA_MAX here: those are
process-wide and must be set before threads exist, which is the launcher's business
(README: MALLOC_ARENA_MAX=2).
THE PROBE, off unless INVPW_MEM_LOG=<file> (INVPW_MEM_LOG_INTERVAL, default 2 s): one JSON
line every interval and one at each context close, at no cost when it is off.
The line of the probe (`t` is `time.monotonic()`, `event` is "tick" or
"context_closed"):
t, event, uss_mb, rss_mb null where the platform gives neither (psutil is
optional; Linux falls back to /proc/self/statm for rss)
registry_objects, contexts the guid registry, and the BrowserContext among it
clients, outbox_total_bytes, what is queued for sockets and not yet sent: the sum of
outbox_max_messages the texts, and the longest queue of one client
gc_counts {"generations": gc.get_count(), "objects": len(gc.get_objects())}
malloc glibc `mallinfo2` {arena, uordblks, fordblks, hblkhd}, else null
"""
from __future__ import annotations
import gc
import json
import os
import sys
import threading
import time
from typing import Any, Callable, Dict, Optional
#: A message of at least this many bytes is a reply with a body worth giving back to the OS.
#: WHY TRIM AT ALL: in a served browser the pages' contents (1-6 MB each) pass through the
#: process as JSON strings and die young among the long-lived registry objects; glibc keeps
#: the freed memory in its arenas. Measured by slack on a container, runs of 95 navigations:
#: the free memory held by malloc (`fordblks`) went from 13 MB to 177 MB by default. 64 KiB
#: is under any page's content and over any ordinary message.
TRIM_BYTES = 64 * 1024
DEFAULT_INTERVAL = 2.0
def _is_linux() -> bool:
return sys.platform.startswith("linux")
def _load_libc() -> Any:
import ctypes
return ctypes.CDLL("libc.so.6", use_errno=True)
def trimmer_from_env(environ: Optional[Dict[str, str]] = None) -> Optional[Callable[[], None]]:
"""`malloc_trim(0)` as a callable, or None: INVPW_MALLOC_TRIM=0, not Linux, or a libc
that has no such function (musl) - silently, in every one of them."""
environ = os.environ if environ is None else environ
if environ.get("INVPW_MALLOC_TRIM") == "0" or not _is_linux():
return None
try:
libc = _load_libc()
trim = libc.malloc_trim
except (OSError, AttributeError):
return None
return lambda: trim(0)
def _mallinfo() -> Optional[Dict[str, int]]:
if not _is_linux():
return None
try:
import ctypes
libc = _load_libc()
names = ("arena", "ordblks", "smblks", "hblks", "hblkhd",
"usmblks", "fsmblks", "uordblks", "fordblks", "keepcost")
class Info(ctypes.Structure):
_fields_ = [(n, ctypes.c_size_t) for n in names]
libc.mallinfo2.restype = Info
info = libc.mallinfo2()
return {k: int(getattr(info, k)) for k in ("arena", "uordblks", "fordblks", "hblkhd")}
except Exception:
return None
def _memory_mb() -> "tuple[Optional[float], Optional[float]]":
try:
import psutil
info = psutil.Process().memory_full_info()
return round(info.uss / 1048576, 2), round(info.rss / 1048576, 2)
except Exception:
pass
rss = None
if _is_linux():
try:
with open("/proc/self/statm") as statm:
rss = round(int(statm.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") / 1048576, 2)
except Exception:
rss = None
return None, rss
class MemProbe:
"""Writes the lines; `sample` is also what the tests read."""
def __init__(self, endpoint: Any, path: str, interval: float = DEFAULT_INTERVAL) -> None:
self.endpoint = endpoint
self.path = path
self.interval = interval
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
def start(self) -> None:
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-mem-probe")
self._thread.start()
def stop(self) -> None:
self._stop.set()
def _run(self) -> None:
while not self._stop.is_set():
self.write("tick")
self._stop.wait(self.interval)
@staticmethod
def outbox_of(client: Any) -> "tuple[int, int]":
"""(bytes, messages) queued for one client: read from the queue's own deque, so
sending costs nothing for it. The message the writer holds in `send` is not here."""
try:
queued = list(client._outbox._queue)
except Exception:
return 0, 0
return sum(len(t) for t in queued if t), len(queued)
def sample(self, event: str) -> Dict[str, Any]:
endpoint = self.endpoint
with endpoint._lock:
clients = list(endpoint.clients)
sizes = [self.outbox_of(c) for c in clients]
uss, rss = _memory_mb()
with endpoint.server._lock:
objects = list(endpoint.server._objects.values())
return {
"t": round(time.monotonic(), 3), "event": event,
"uss_mb": uss, "rss_mb": rss,
"registry_objects": len(objects),
"contexts": sum(1 for o in objects if o.TYPE == "BrowserContext"),
"clients": len(clients),
"outbox_total_bytes": sum(b for b, _ in sizes),
"outbox_max_messages": max((m for _, m in sizes), default=0),
"gc_counts": {"generations": list(gc.get_count()), "objects": len(gc.get_objects())},
"malloc": _mallinfo(),
}
def write(self, event: str) -> None:
try:
line = json.dumps(self.sample(event))
with self._lock, open(self.path, "a", encoding="utf-8") as out:
out.write(line + "\n")
except Exception:
pass # a probe never takes the server down
def probe_from_env(endpoint: Any, environ: Optional[Dict[str, str]] = None) -> Optional[MemProbe]:
environ = os.environ if environ is None else environ
path = environ.get("INVPW_MEM_LOG")
if not path:
return None
try:
interval = float(environ.get("INVPW_MEM_LOG_INTERVAL") or DEFAULT_INTERVAL)
except ValueError:
interval = DEFAULT_INTERVAL
return MemProbe(endpoint, path, interval)
@@ -156,7 +156,6 @@ COURTESY = {
#: revisit on our own: honouring them would mean inventing an answer.
NO_ENGINE_COMMAND = {
"drop",
"setOffline",
"setWebSocketInterceptionPatterns",
}
@@ -0,0 +1,866 @@
"""The page's pointer, humanised ONCE, on the server.
⛔ WHY IT LIVES HERE AND NOT IN THE CLIENT. Until this module the walk of the
pointer onto an element belonged to the in-process Playwright client
(`_cursor.py` patched `Frame._click`, `Mouse.click`, `Mouse.wheel`, ... and sent
N `mouseMove` to the page before the action). A client that is not ours - a
Go, Node or stock Python Playwright talking to `launch_server` - sends ONE
`Frame.click` and the page saw one `mousemove`: measured with humanize=True on
a served browser. The rule is that a page sees EXACTLY the same through every
client, so the walk is drawn where every client's actions arrive. The in-process
client now sends the plain action and this module does the rest, which is also
why nothing here is asked of a client: there is no copy of it on that side to
get out of step.
WHAT IS HUMANISED, and what is not (this is the list the in-process client
used to answer, carried over unchanged):
* `Frame.click / dblclick / hover / tap / check / uncheck` - the approach to the
element, the landing off its centre, the fidget that fills an idle gap;
* `Mouse.click / dblclick` - the stroke to the point, then the click;
* `Mouse.wheel` - a burst of detents with the hand creeping between them;
* NOT `Mouse.move`: an explicit move is the caller's. (The in-process client
marks its own with `humanise`, see `_cursor._wrap_mouse_move`; a client that
does not say so is answered with exactly the point it named.)
* NOT the actions of an ElementHandle (they name a node, never a selector, and
the in-process client never walked onto them either) and NOT `dragAndDrop`,
whose travel the core's `Actions` already draws.
HOW IT STAYS THE SAME AS THE CLIENT WAS. The stroke generator, the planners
(`_behaviour`) and the discipline events are delivered under (`Pacer`) are the
core's, unchanged; the page's motion seed is `_cursor.page_motion_seed(session
seed, page number)`, the budget is the session's `humanize=` cap. What changed
is only who calls them, and `tests/data/pointer_golden.json` holds what the
engine received from the client-side code of 5d9ad70 for the same seed, page
and targets: this module must reproduce it to the last coordinate and
millisecond.
⛔ NOTHING HERE MAY FAIL AN ACTION THAT WOULD HAVE SUCCEEDED. A probe that finds
the element gone, a planner that raises, a viewport that cannot be read: the
action runs exactly as the caller wrote it. Only a broken install says so, once
per process.
"""
from __future__ import annotations
import random
import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
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.juggler.connection import ReplyTimeout
from invisible_core.juggler.deadline import Deadline
from invisible_core.juggler.injected import ContextDestroyed, EvaluationError
from invisible_core.seedmix import sub_seed
from .. import _cursor
from .dispatcher import ProtocolException
# Below this much wall clock since the last event we do not fidget at all: two
# actions back to back are one continuous piece of work, and a hand does not
# stop to fiddle between them.
_IDLE_MIN_GAP_MS = 400.0
# ...and above this we stop pretending we know what happened. Half a minute of
# planned idle is plenty to draw a plausible tail from.
_IDLE_MAX_GAP_MS = 45_000.0
# Share of the movement budget an action may spend on the fidget that precedes
# it. The rest belongs to the approach, which is the part that has to work.
_IDLE_BUDGET_FRAC = 0.35
# Used only when the page will not tell us its size.
_FALLBACK_VIEWPORT = (1280.0, 720.0)
# Landing off-centre hands the automation layer a click position we chose. If
# that position turns out not to be actionable we retry with the caller's own
# arguments, so the first attempt is given a bounded slice of the time rather
# than the caller's whole timeout.
_LANDING_ATTEMPT_S = 5.0
_LANDING_MIN_BOX_PX = 12.0
# How far from the centre of a control the landing point may stray, as a
# fraction of the box: sigma of the draw and the hard clip. Tighter than the
# planner's own default because this point is also the click position.
_LANDING_SPREAD = 0.14
_LANDING_KEEP = 0.26
#: What a probe of the page can legitimately answer while we are only AIMING:
#: the element went away, the frame navigated, the page closed.
_PROBE_ERRORS = (ContextDestroyed, EvaluationError, ReplyTimeout,
ProtocolException, TimeoutError)
# ── the clock ───────────────────────────────────────────────────────────────
#
# Injectable so the delivered-vs-planned timing can be asserted without a
# browser and without a test that takes as long as the schedule it checks.
class _RealClock:
__slots__ = ()
@staticmethod
def now() -> float:
return time.perf_counter()
@staticmethod
def sleep(seconds: float) -> None:
time.sleep(seconds)
_CLOCK: Any = _RealClock()
# ── timelines ───────────────────────────────────────────────────────────────
def _timeline(steps: Iterable[Any]) -> List[_Ev]:
"""Turn a ``_behaviour`` Step list (relative delays) into absolute times."""
out: List[_Ev] = []
t = 0.0
for s in steps:
t += max(0.0, float(s.delay_ms))
if s.kind == "wait": # pure elapsed time: nothing to dispatch
continue
out.append(_Ev(t, s.x, s.y, "wheel" if s.kind == "wheel" else "move",
getattr(s, "dx", 0.0), getattr(s, "dy", 0.0)))
return out
def _normalise_waypoints(raw: Iterable[Any], max_seconds: float) -> List[Tuple[float, float, float]]:
"""Reduce whatever the generator returns to ``(x, y, delay_seconds)``.
Three shapes are accepted: a waypoint object carrying ``x`` / ``y`` /
``dt_ms``, an ``(x, y, delay_seconds)`` triple, and a bare ``(x, y)`` pair
whose pacing is then spread evenly over the cap.
The cap from ``humanize=<seconds>`` is applied through
``fit_timeline``, so a tighter cap makes the movement shorter AND coarser
rather than merely denser.
"""
points: List[Tuple[float, float, float]] = []
for p in raw:
x = getattr(p, "x", None)
if x is not None and hasattr(p, "y"):
dt_ms = getattr(p, "dt_ms", None)
delay = float(dt_ms) / 1000.0 if dt_ms is not None else 0.0
points.append((float(x), float(p.y), max(0.0, delay)))
continue
seq = tuple(p)
if len(seq) >= 3:
points.append((float(seq[0]), float(seq[1]), max(0.0, float(seq[2]))))
else:
points.append((float(seq[0]), float(seq[1]), -1.0))
if not points:
return []
if all(d <= 0.0 for _, _, d in points):
# Every waypoint at the same instant is not pacing, it is the absence
# of pacing - and dispatching it would ask for the whole movement in
# one tick. Treated exactly like the bare (x, y) case below.
points = [(x, y, -1.0) for x, y, _ in points]
if points[0][2] < 0: # bare (x, y): no pacing supplied, spread the cap
even = max_seconds / len(points)
points = [(x, y, even) for x, y, _ in points]
evs: List[_Ev] = []
t = 0.0
for x, y, d in points:
t += d * 1000.0
evs.append(_Ev(t, x, y))
evs = _fit_timeline(evs, max_seconds)
out: List[Tuple[float, float, float]] = []
prev = 0.0
for ev in evs:
out.append((ev.x, ev.y, (ev.t_ms - prev) / 1000.0))
prev = ev.t_ms
return out
def _drive(evs: Sequence[_Ev], emit_move: Callable[[float, float], Any],
emit_wheel: Optional[Callable[[float, float], Any]] = None, *,
emit_last: bool = True,
origin: Optional[Tuple[float, float]] = None) -> int:
"""The synchronous driver of `Pacer`. Returns events sent.
The rules it obeys - absolute deadlines from one ``t0``, drop rather than
send late while the drop stays within reach, never two events in one
instant - are the pacer's, the core's, and are the same ones the client's
asynchronous driver obeyed. This supplies a clock, a way of waiting and
where the pointer starts from; it makes no decision the pacer has not made.
"""
if not evs:
return 0
clock = _CLOCK
pacer = Pacer(evs, emit_last=emit_last, origin=origin)
with _fine_timer():
while True:
what, arg = pacer.step(clock.now())
if what == DONE:
break
if what == SLEEP:
clock.sleep(arg)
continue
if arg.is_wheel:
if emit_wheel is None:
pacer.dropped() # nothing here can carry a notch
continue
emit_wheel(arg.dx, arg.dy)
else:
emit_move(arg.x, arg.y)
pacer.emitted(clock.now())
return pacer.delivered
# ── one page's hand ─────────────────────────────────────────────────────────
class _Hand:
"""State of one page's pointer: where it is, and how it likes to move."""
__slots__ = ("seed", "max_seconds", "_profile", "persona", "x", "y",
"busy", "action", "last_event_at", "synced")
def __init__(self, seed: int, max_seconds: float, factory: Callable[..., Any],
synced: Any) -> None:
self.seed = int(seed)
self.max_seconds = float(max_seconds)
self._profile = _cursor._build_profile(factory, self.seed, self.max_seconds)
self.persona = PointerPersona.from_seed(self.seed)
self.x: Optional[float] = None
self.y: Optional[float] = None
self.busy = False
# Counts actions, so every draw that has to differ between two actions
# of one session (the landing point, the fidget) has something to vary
# on while staying reproducible from the seed.
self.action = 0
self.last_event_at: Optional[float] = None
#: The engine-side pointer position (`Actions.position`, the object
#: itself) as this hand last knew it. Anything else moving the pointer
#: - an explicit `mouse.move`, the click an action ends with - replaces
#: it with a new object, and the hand then stands where the pointer
#: really is.
self.synced = synced
def start_point(self, width: Optional[float], height: Optional[float]) -> Tuple[float, float]:
"""Where the pointer is before this page's first movement.
Never the origin, and never a constant: a session whose first movement
departs from (0, 0) is announcing that it had no pointer state at all
before it started, which no real navigation produces.
"""
w, h = width, height
if not w or not h:
_cursor._warn_once(
"no-viewport",
"a page reported no viewport size; the cursor start position "
"falls back to a nominal %dx%d viewport. Coordinates are still "
"seeded, but they are not derived from the real window."
% (int(_FALLBACK_VIEWPORT[0]), int(_FALLBACK_VIEWPORT[1])),
)
w, h = _FALLBACK_VIEWPORT
fn = getattr(self._profile, "start_point", None)
if callable(fn):
try:
px, py = fn(w, h)
return float(px), float(py)
except (TypeError, ValueError, ArithmeticError) as exc:
_cursor._warn_once(
"bad-start-point",
"the motion generator's start_point() failed (%s: %s); "
"using the behaviour planner's instead."
% (type(exc).__name__, exc),
)
return initial_pointer(self.seed, (float(w), float(h)))
def path(self, fx: float, fy: float, tx: float, ty: float) -> List[Tuple[float, float, float]]:
raw = self._profile.path(fx, fy, tx, ty)
return _normalise_waypoints(raw, self.max_seconds)
def renderer(self, bounds: Tuple[float, float]) -> Callable[..., List[Any]]:
"""A ``_behaviour`` renderer backed by the stroke generator.
This is what keeps ONE stroke model in the product: the macro planner
decides that a movement happens and where it goes, and every stroke it
asks for is drawn by the generator.
"""
profile = self._profile
nominal = self.persona.sample_ms
def render(start: Tuple[float, float], end: Tuple[float, float], *,
kind: str, lead_ms: float, bounds: Any = bounds,
target_w: Optional[float] = None) -> List[Any]:
try:
raw = list(profile.path(start[0], start[1], end[0], end[1],
target_w=target_w))
except TypeError:
# A generator predating the target_w argument. Accepting it and
# dropping it is better than refusing to move: pacing degrades
# to the per-seed default, everything else still works.
raw = list(profile.path(start[0], start[1], end[0], end[1]))
if raw and not any(float(getattr(p, "dt_ms", 0.0) or 0.0)
if hasattr(p, "dt_ms") else
(float(p[2]) if len(tuple(p)) > 2 else 0.0)
for p in raw):
# A generator that paces nothing has not said "instantly", it
# has said nothing. Fall back to the session's own sampling
# interval rather than asking for the whole stroke in one tick.
raw = [(float(getattr(p, "x", None) if hasattr(p, "x") else p[0]),
float(getattr(p, "y", None) if hasattr(p, "y") else p[1]),
nominal)
for p in raw]
return steps_from_waypoints(
raw, kind=kind, lead_ms=lead_ms, bounds=bounds
)
return render
def rng(self, tag: str) -> random.Random:
"""A per-(page, action, purpose) stream. Reproducible from the seed."""
return random.Random(
sub_seed(self.seed, "%s:%d" % (tag, self.action))
)
@dataclass
class _Aim:
"""Where this action is going, and how the caller must be adjusted for it.
``override`` is the position the action should run with so that it clicks
the point we walked to rather than the element's centre; None means the
action is left exactly as the caller wrote it.
"""
box: Dict[str, float]
landing: tuple
override: Optional[Dict[str, float]]
@property
def rect(self) -> tuple:
return (self.box["x"], self.box["y"],
self.box["width"], self.box["height"])
def _inside(x: float, y: float, w: Optional[float], h: Optional[float]) -> bool:
if not w or not h:
return True
return 0.0 <= x < float(w) and 0.0 <= y < float(h)
class Pointer:
"""The hand of one page: what an action does with the pointer before it
acts. Inert (`active` False) when the session did not ask for it, which
turns every method into the plain action."""
def __init__(self, actions: Any, injected: Any, number: int,
session_seed: Optional[int], budget_s: Optional[float],
viewport: Callable[[], Any], *, draws: bool = True) -> None:
self.actions = actions
self.injected = injected
self._viewport_of = viewport
self.hand: Optional[_Hand] = None
if not draws or session_seed is None or not budget_s:
return
factory = _cursor._motion_factory()
if factory is None:
return
seed = _cursor.page_motion_seed(session_seed, number)
try:
self.hand = _Hand(seed, budget_s, factory,
getattr(actions, "position", None))
except Exception as exc: # noqa: BLE001 - a broken generator must not break clicking
_cursor._warn_once(
"profile-construction",
"the cursor motion generator could not be constructed (%s: %s); "
"this session will not humanise its pointer. This is a broken "
"install, not a configuration." % (type(exc).__name__, exc),
)
@property
def active(self) -> bool:
return self.hand is not None
# -- geometry ----------------------------------------------------------
def _viewport(self) -> Tuple[Optional[float], Optional[float]]:
size = self._viewport_of()
if isinstance(size, dict):
return size.get("width"), size.get("height")
return None, None
def _bounds(self) -> Tuple[float, float]:
"""Viewport size to plan inside, falling back to a nominal one."""
w, h = self._viewport()
if not w or not h:
return _FALLBACK_VIEWPORT
return float(w) - 1.0, float(h) - 1.0
def _here(self) -> Tuple[float, float]:
"""Current pointer position, placing it first if it has never moved."""
hand = self.hand
now = getattr(self.actions, "position", None)
if now is not hand.synced:
# Something else moved the pointer since we last did.
hand.synced = now
hand.x, hand.y = float(now[0]), float(now[1])
elif hand.x is None or hand.y is None:
w, h = self._viewport()
hand.x, hand.y = hand.start_point(w, h)
return float(hand.x), float(hand.y)
def _emit_move(self, x: float, y: float) -> None:
hand = self.hand
self.actions.move(x, y)
hand.synced = getattr(self.actions, "position", None)
# -- the probes --------------------------------------------------------
def _element_box(self, frame_id: str, selector: str) -> Tuple[Optional[str], Optional[dict]]:
"""Resolve the element and its box, or (None, None). Never raises.
Deliberately non-blocking and deliberately forgiving: this is a hint
used to aim a mouse path, never a correctness step. It resolves the
element if it is already there and gives up otherwise, so it can
neither add a wait to a passing call nor invent an exception on a
failing one - the action itself still does its own waiting and raises
its own errors.
"""
try:
handle = self.injected.query_selector(frame_id, selector)
except _PROBE_ERRORS:
return None, None # gone, navigated, closed, or not a selector we know
if not handle:
return None, None
try:
box = self.injected.bounding_box(frame_id, handle)
except _PROBE_ERRORS:
box = None
if not box:
self._dispose(frame_id, handle)
return None, None
return handle, box
def _dispose(self, frame_id: str, handle: str) -> None:
try:
self.injected.dispose(frame_id, handle)
except _PROBE_ERRORS:
pass # the page or the frame is already gone; nothing to release
def _hits(self, frame_id: str, handle: str, x: float, y: float) -> bool:
"""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 ACTION'S OWN QUESTION (`Actions.hit_target`): the same frame
shift, the same shadow-aware test, so the cursor accepts exactly the
points the action itself would accept.
"""
try:
return self.actions.hit_target(frame_id, handle, (x, y)) == "done"
except _PROBE_ERRORS:
return False
def _choose_landing(self, frame_id: str, selector: str,
position: Optional[dict]) -> Optional[_Aim]:
"""Pick the point on the element this action will land on."""
hand = self.hand
handle, box = self._element_box(frame_id, selector)
if handle is None or box is None:
return None
try:
if isinstance(position, dict) and "x" in position and "y" in position:
# The caller aimed explicitly. Honour it exactly and override
# nothing: choosing our own point here would silently move a
# click the caller had every reason to think was pinned.
return _Aim(box, (box["x"] + float(position["x"]),
box["y"] + float(position["y"])), None)
landing = landing_point(
(box["x"], box["y"], box["width"], box["height"]),
hand.rng("cursor:landing"),
spread=_LANDING_SPREAD, keep=_LANDING_KEEP,
)
if (
_cursor.landing_enabled()
and box["width"] >= _LANDING_MIN_BOX_PX
and box["height"] >= _LANDING_MIN_BOX_PX
and self._hits(frame_id, handle, landing[0], landing[1])
):
return _Aim(box, landing, {"x": landing[0] - box["x"],
"y": landing[1] - box["y"]})
# The off-centre point missed the element (it is not a rectangle,
# or it is too small for the spread to be safe). Fall back to the
# centre and do NOT override: an override naming a point that
# misses would turn a working click into a failing one.
return _Aim(box, (box["x"] + box["width"] / 2.0,
box["y"] + box["height"] / 2.0), None)
finally:
self._dispose(frame_id, handle)
# -- travelling --------------------------------------------------------
def _run_steps(self, steps: Sequence[Any], emit_wheel: Optional[Callable] = None,
*, budget_s: float, emit_last: bool = True) -> None:
"""Dispatch a planned ``_behaviour`` timeline, inside a time budget."""
hand = self.hand
evs = _fit_timeline(_timeline(steps), budget_s)
if not evs:
return
def move(x: float, y: float) -> None:
self._emit_move(x, y)
hand.x, hand.y = x, y
_drive(evs, move, emit_wheel, emit_last=emit_last,
origin=(hand.x, hand.y))
if not emit_last and evs:
hand.x, hand.y = evs[-1].x, evs[-1].y
hand.last_event_at = _CLOCK.now()
def _idle_budget_ms(self) -> float:
"""How much of the movement budget this action may spend on a fidget.
Zero when the previous event was moments ago: two calls back to back
are one piece of work, and inserting a fidget between them would be
both a lie and a delay.
"""
hand = self.hand
if hand.last_event_at is None:
return 0.0
gap_ms = (_CLOCK.now() - hand.last_event_at) * 1000.0
if gap_ms < _IDLE_MIN_GAP_MS:
return 0.0
return min(hand.max_seconds * _IDLE_BUDGET_FRAC * 1000.0, gap_ms * 0.5)
def _plan_fidget(self) -> List[Any]:
"""What the hand did while the caller's script was busy elsewhere.
We cannot dispatch into the past, so the idle period is planned in full
and only its tail is kept (`tail_within`). The alternative, inventing a
short episode from scratch, would have a distribution of its own that no
amount of seeding makes match the planner's.
"""
hand = self.hand
budget = self._idle_budget_ms()
if budget <= 0.0:
return []
gap_ms = min((_CLOCK.now() - (hand.last_event_at or _CLOCK.now())) * 1000.0,
_IDLE_MAX_GAP_MS)
bounds = self._bounds()
here = self._here()
gate = hand.rng("cursor:fidget-gate")
if gate.random() < hand.persona.aimless_rate:
# 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 = plan_aimless_move(
hand.seed, hand.persona, here, bounds,
nonce=hand.action, render=hand.renderer(bounds),
)
return tail_within(steps, budget, here, bounds)
steps = plan_idle(
hand.seed, hand.persona, here, bounds, gap_ms,
nonce=hand.action, render=hand.renderer(bounds),
)
return tail_within(steps, budget, here, bounds)
def _walk_onto(self, aim: _Aim) -> None:
"""Spend the time budget getting the pointer to ``aim``."""
hand = self.hand
bounds = self._bounds()
budget = hand.max_seconds
fidget = self._plan_fidget()
if fidget:
# The fidget spends its own share of the budget and hands the rest
# to the approach, which is the part that has to work. The floor
# keeps a pathological share from leaving the approach no time.
spent = min(sum(s.delay_ms for s in fidget) / 1000.0,
budget * _IDLE_BUDGET_FRAC)
self._run_steps(fidget, budget_s=spent)
budget = max(budget - spent, 0.2)
steps = plan_approach(
hand.seed, hand.persona, self._here(), aim.rect, bounds,
nonce=hand.action, landing=aim.landing,
render=hand.renderer(bounds),
)
if steps:
# ``emit_last=False``: the final hop onto the landing point is left
# to the action itself. That is the whole hover fix restated - the
# only event inside the hit-target window is the automation layer's
# own move, and it is on target - and it also removes what would
# otherwise be a zero-displacement event immediately before every
# mousedown, since the action moves to the point we just landed on.
self._run_steps(steps, budget_s=budget, emit_last=False)
else:
# Sub-pixel approach: the pointer is already standing on the
# target. Emitting a move to where it already is would be a
# zero-displacement event, so the action's own move is left to do
# the whole of it.
hand.x, hand.y = aim.landing
# -- the entry points --------------------------------------------------
def approach(self, frame_id: str, selector: str, position: Optional[dict],
trial: bool = False) -> Optional[Dict[str, float]]:
"""Walk the pointer onto the element this action is about to touch.
Returns the `position` the action should run with, or None.
⛔ A TRIAL RUN performs the actionability checks without touching
anything, so it must not move the pointer either. It is honoured in
`Actions._retry`, where actionability lives; this only keeps the
pointer still while that happens.
"""
hand = self.hand
if hand is None or hand.busy or trial:
return None
hand.busy = True
hand.action += 1
try:
aim = self._choose_landing(frame_id, selector, position)
if aim is None:
return None
w, h = self._viewport()
if not _inside(aim.landing[0], aim.landing[1], w, h):
# The element is off-screen; the action is about to scroll it
# into view and we would be aiming at where it used to be. Let
# the action place the pointer itself this once.
return None
self._walk_onto(aim)
return aim.override
finally:
hand.busy = False
def act(self, frame_id: str, selector: str, position: Optional[dict],
timeout: Optional[float], run: Callable[[Optional[dict], Optional[float]], Any],
*, trial: bool = False) -> Any:
"""Run a pointer action on an element the way a hand would.
`run(position, timeout)` performs the plain action with those two
arguments. The approach comes first; if it chose a landing point the
action is told to click it, within a bounded slice of the caller's
time, and if that point is not actionable the caller's own call is made
with what is left of its time, so a call that would have succeeded
still does.
"""
override = None
try:
override = self.approach(frame_id, selector, position, trial)
except Exception as exc: # noqa: BLE001 - motion never fails an action
_cursor._warn_once(
"approach-failed",
"the cursor approach raised (%s: %s); the action itself is "
"unaffected and ran normally. Please report this."
% (type(exc).__name__, exc),
)
if not override:
return run(position, timeout)
deadline = Deadline(timeout)
first = (_LANDING_ATTEMPT_S if timeout is None
else min(_LANDING_ATTEMPT_S, timeout))
try:
return run(override, first)
except TimeoutError as exc:
_cursor._warn_once(
"landing-retry",
"an off-centre landing point was not actionable (%s); the "
"action was retried with its own arguments. Set %s=off to "
"disable off-centre landing."
% (type(exc).__name__, _cursor.LANDING_ENV),
)
return run(position,
None if timeout is None else deadline.left(floor=0.05))
def travel(self, x: float, y: float, what: str = "mouse.click") -> None:
"""Emit the intermediate waypoints of one plain stroke to (x, y), the
endpoint itself left to the caller.
Used before `Mouse.click`: the caller named the exact destination and
the macro layer has nothing to add. The endpoint is the caller's to
emit - it has to land on the exact coordinates it was given, unclamped -
so this returns after waiting out the last waypoint's deadline without
sending it.
"""
hand = self.hand
if hand is None or hand.busy:
return
hand.busy = True
hand.action += 1
try:
self._travel(x, y)
except Exception as exc: # noqa: BLE001
_cursor._warn_once(
"move-failed",
"the cursor path raised during %s (%s: %s); the action "
"itself is unaffected. Please report this."
% (what, type(exc).__name__, exc),
)
finally:
hand.busy = False
def _travel(self, to_x: float, to_y: float) -> None:
hand = self.hand
w, h = self._viewport()
hand.x, hand.y = self._here()
try:
waypoints = hand.path(hand.x, hand.y, to_x, to_y)
except Exception as exc: # noqa: BLE001 - never let motion break an action
_cursor._warn_once(
"path-failed",
"the cursor motion generator raised while planning a path "
"(%s: %s); this movement is not humanised. This is a broken "
"install, not a configuration." % (type(exc).__name__, exc),
)
waypoints = []
evs: List[_Ev] = []
t = 0.0
end_key = (round(to_x), round(to_y))
# ⛔ THE FIRST WAYPOINT OF A STROKE IS WHERE IT STARTS. When the engine
# has already been told the pointer is on that pixel (a move that
# stopped there, then a pause), sending it again is a zero-displacement
# `mousemove` that no mouse reports; the stroke begins at its first
# real step. A pointer the engine has never been told about (the
# page's first movement, from the seeded start point) is not "there"
# for the page, so its first waypoint is a real move and goes out.
known = getattr(self.actions, "position", None)
at_start = (None if known is None
else (round(known[0]), round(known[1])))
for px, py, delay in waypoints:
t += delay * 1000.0
cx, cy = _clamp(px, py, w, h)
if (not evs and at_start is not None
and (round(cx), round(cy)) == at_start
and (round(hand.x), round(hand.y)) == at_start):
continue # still standing on the start pixel: nothing moved
# Never pre-empt the endpoint - it is the caller's to emit, once.
#
# Nothing else here filters the stream (the start waypoint above is not
# a repeat of a shape, it is the position itself). Whether two consecutive
# events may share a device pixel is a question about the SHAPE of
# a path, and the shape belongs to the generator: a dispatcher that
# silently removed every repeat would make "the duplicate fraction
# is exactly zero" true no matter what the generator did.
if (round(cx), round(cy)) == end_key:
continue
evs.append(_Ev(t, cx, cy))
# The endpoint closes the schedule so its deadline is waited out even
# though the caller is the one that emits it.
evs.append(_Ev(max(t, evs[-1].t_ms if evs else 0.0), to_x, to_y))
def emit(x: float, y: float) -> None:
self._emit_move(x, y)
hand.x, hand.y = x, y
_drive(evs, emit, emit_last=False, origin=(hand.x, hand.y))
hand.x, hand.y = to_x, to_y
hand.last_event_at = _CLOCK.now()
def click_at(self, x: float, y: float, run: Callable[[], Any]) -> Any:
"""`Mouse.click`: the stroke, then the click `run` makes.
⛔ THE ENDPOINT IS EMITTED ONCE. The stroke stops short of it
(`travel`), and `run` is `Actions.click_at`, whose own approach is the
one `mousemove` onto the exact point before the press. This used to send
the endpoint as a move of its own first (as the client's `Mouse._click`
did), so the engine got two `mousemove` with the same coordinates at the
same instant: no mouse reports that, and a page can count it. A hand
arrives at the button in one last motion and presses; so the last
waypoint is the click's own approach, and nothing else lands on the
point before the press. Every transport comes here (`op_mouse_click`),
so the sequence is one.
"""
if self.hand is None:
return run()
self.travel(x, y)
try:
return run()
finally:
self.hand.synced = getattr(self.actions, "position", None)
def wheel(self, dx: float, dy: float) -> bool:
"""`Mouse.wheel` as a burst of detents with the hand on the mouse.
True when it was done here; False means the caller sends the plain
wheel event."""
hand = self.hand
if hand is None or hand.busy:
return False
try:
hand.busy = True
hand.action += 1
try:
plan = self._scroll_plan(float(dx), float(dy))
if plan:
self._run_steps(plan, self.actions.wheel,
budget_s=hand.max_seconds)
return True
finally:
hand.busy = False
except Exception as exc: # noqa: BLE001
_cursor._warn_once(
"wheel-failed",
"the scroll planner raised (%s: %s); the scroll itself is "
"unaffected. Please report this." % (type(exc).__name__, exc),
)
return False
def _scroll_plan(self, delta_x: float, delta_y: float) -> List[Any]:
"""A wheel burst carrying exactly (delta_x, delta_y), with the hand on it.
One protocol-level wheel event of 900 px is not a scroll a person
performs; a notched wheel produces detents. The number of detents is
bounded by the movement budget, and the deltas are rescaled so the burst
sums EXACTLY to what the caller asked for - a scroll that lands
somewhere else is a broken call, not a subtle one.
"""
hand = self.hand
total = abs(delta_x) + abs(delta_y)
if total < 1.0:
return []
notch = 100.0
max_ticks = max(1, int(hand.max_seconds * 1000.0 / 90.0))
ticks = int(max(1, min(round(total / notch), max_ticks, 24)))
if ticks < 2:
return []
bounds = self._bounds()
steps = plan_scroll(
hand.seed, hand.persona, self._here(), bounds,
ticks=ticks, tick_dy=1.0, nonce=hand.action,
render=hand.renderer(bounds),
)
shares = [s.dy for s in steps if s.kind == "wheel"]
tot = sum(shares)
if not shares or tot <= 0:
return []
out: List[Any] = []
used_x = used_y = 0.0
seen = 0
for s in steps:
if s.kind != "wheel":
out.append(s)
continue
seen += 1
if seen == len(shares): # the last notch absorbs the rounding
dx, dy = delta_x - used_x, delta_y - used_y
else:
frac = s.dy / tot
dx, dy = delta_x * frac, delta_y * frac
used_x += dx
used_y += dy
out.append(Step(x=s.x, y=s.y, delay_ms=s.delay_ms,
kind="wheel", dx=dx, dy=dy))
return out
def move(self, x: float, y: float) -> None:
"""An explicit `Mouse.move` the in-process client asked to be walked.
The endpoint is emitted by the caller, exactly."""
if self.hand is not None:
self.travel(x, y, "mouse.move")
+875
View File
@@ -0,0 +1,875 @@
"""The Playwright server of this package, on a WebSocket: `launch_server()`.
Any standard Playwright client can `connect()` to what this serves, with the
shape of Playwright's own `launchServer` / `connect`: one browser, started
once, and a WebSocket whose messages are the protocol's JSON (`transport.py`
documents the four shapes; `wire.py` is the JSON boundary).
THE DESIGN, AND WHAT IT COSTS.
* ONE BROWSER, ONE REGISTRY, MANY CONNECTIONS. `launch_server()` launches the
browser once (the same launch the in-process client does: seed, persona,
geo, prefs, env, display, all composed by `InvisiblePlaywright`'s own
methods) into a single `JugglerServer` registry, and every WebSocket
connection talks to THAT registry. The alternative - a registry per
connection over the same Juggler connection - was refused: each
`BrowserDispatcher` enables the browser itself and adopts EVERY page
target it hears about, so two of them on one connection would each build a
page for the other's tabs.
* OWNERSHIP IS THE ISOLATION. An object made while answering a call from
client C belongs to C (an object made on a thread of its own - a popup -
belongs to its parent's owner). A message about an object goes only to its
owner; an object with no owner (BrowserType, LocalUtils, the Browser) is
shared and its messages go to every client, unless they name an owned
object, which decides. A client naming an object that is not its own gets
"never created", as if it did not exist.
* A CLIENT LEAVING CLOSES ITS CONTEXTS AND NOT THE BROWSER. So does its
`Browser.close`: the browser belongs to `launch_server()` and ends with
`RemoteServer.close()` (or when the engine dies, see `on_engine_closed`).
* `initialize` IS ANSWERED HERE, not by `JugglerServer.op_initialize`: it
announces BrowserType, LocalUtils, the Browser and the Playwright root with
`preLaunchedBrowser` (the shape of `launchServer`), to that client only.
THE IDENTITY STAYS THE SERVER'S. Seed, persona, prefs and env are composed
once, at launch. The handshake reads `x-playwright-browser`, `?browser=`,
`x-playwright-launch-options`, `?launch-options=` and `x-playwright-proxy`, and
keeps them on the client record (`RemoteClient.handshake`); none of them
changes the launch. There is no version check, no 428 and no limit of ours: any
client is accepted, whatever it says it is. What a client can still choose is
what Playwright lets a client choose per context (`newContext` options); the
server fills the ones it omitted from the session's profile (viewport, screen,
locale, timezone), and `context_options_override=True` makes the server's win.
LIMITS OF THIS FIRST VERSION, said instead of hidden.
* `launchPersistentContext` and `profile_dir` are not served.
* `x-playwright-proxy` (exposeNetwork) is recorded, not honoured.
* Downloads, file choosers and other fused types follow the in-process
client's path and are not carried to a remote client.
* `RemoteServer.process` is the core's handle for the browser process
(`Connection._process`, a private attribute of the core: pid / poll / wait).
* Page numbers (`pageNumber`, which the in-process client reserves) are drawn
here from one counter for the whole browser, for clients that do not send it.
"""
from __future__ import annotations
import asyncio
import collections
import contextvars
import itertools
import json
import queue
import secrets
import sys
import threading
import time
from typing import Any, Callable, Dict, List, Optional
from urllib.parse import parse_qs, urlsplit
from . import memprobe, wire
from .dispatcher import ProtocolException
from .server import (BrowserDispatcher, BrowserTypeDispatcher, JugglerServer,
LocalUtilsDispatcher, RefusingDispatcher)
from .transport import _error_payload
#: The client whose call a worker thread is answering.
CURRENT_CLIENT: "contextvars.ContextVar[Optional[RemoteClient]]" = (
contextvars.ContextVar("invpw_remote_client", default=None))
DEFAULT_HOST = "127.0.0.1"
def _channel_guids(value: Any, depth: int = 4):
"""The guids named inside a message's params (`{"guid": g}` channels)."""
if depth < 0:
return
if isinstance(value, dict):
if set(value) == {"guid"} and isinstance(value["guid"], str):
yield value["guid"]
return
for item in value.values():
yield from _channel_guids(item, depth - 1)
elif isinstance(value, (list, tuple)):
for item in value:
yield from _channel_guids(item, depth - 1)
class RemoteClient:
"""One WebSocket connection."""
def __init__(self, endpoint: "RemoteEndpoint", ws: Any,
loop: asyncio.AbstractEventLoop, handshake: Dict) -> None:
self.endpoint = endpoint
self.ws = ws
self.loop = loop
self.handshake = handshake
self.alive = True
self.initialized = False
self._outbox: "asyncio.Queue" = asyncio.Queue()
def post(self, text: str) -> None:
"""Queue one text for the socket, from any thread. FIFO: the writer
task sends them in the order they were posted, which is what keeps
`__create__` before the reply that names it."""
if not self.alive:
return
try:
self.loop.call_soon_threadsafe(self._outbox.put_nowait, text)
except RuntimeError:
pass # the loop is closed: nobody is left to read it
def post_message(self, message: Dict) -> None:
try:
self.post(wire.dumps(message))
except wire.WireError as problem:
self.endpoint.wire_errors.append(problem)
msg_id = message.get("id") if isinstance(message, dict) else None
if msg_id is not None and "error" not in message:
self.post(json.dumps({"id": msg_id, "error": {"error": {
"name": "Error", "stack": "",
"message": "the reply is not JSON: %s" % problem}}}))
async def pump(self) -> None:
while True:
text = await self._outbox.get()
if text is None:
return
try:
await self.ws.send(text)
except Exception:
return
trim = self.endpoint.trim
if trim is not None and len(text) >= memprobe.TRIM_BYTES:
del text # the reply's text goes back to the allocator first
self._trim(trim)
@staticmethod
def _trim(trim: Callable[[], None]) -> None:
try:
trim()
except Exception:
pass
def stop_pump(self) -> None:
self.alive = False
try:
self.loop.call_soon_threadsafe(self._outbox.put_nowait, None)
except RuntimeError:
pass
class _SharedServer(JugglerServer):
"""The registry of a served browser: it knows who owns what."""
def __init__(self) -> None:
super().__init__()
self.endpoint: Optional["RemoteEndpoint"] = None
def register(self, obj: Any) -> None:
obj._owner = CURRENT_CLIENT.get(None) or getattr(
getattr(obj, "parent", None), "_owner", None)
super().register(obj)
def send_up(self, message: Dict) -> None:
if self.endpoint is not None:
self.endpoint.route(message)
def unregister(self, obj: Any) -> None:
super().unregister(obj)
if obj.TYPE == "BrowserContext" and self.endpoint is not None:
self.endpoint.context_closed()
class SharedBrowserDispatcher(BrowserDispatcher):
"""The browser of a served launch: a client's `close` ends ITS contexts."""
def op_close(self, params: Dict) -> Any:
client = CURRENT_CLIENT.get(None)
for context in list(self.contexts):
if not context.disposed and getattr(context, "_owner", None) is client:
try:
context.op_close({})
except Exception:
pass
return None
class SharedBrowserType(BrowserTypeDispatcher):
browser_class = SharedBrowserDispatcher
class UnservedBrowserType(RefusingDispatcher):
"""chromium and webkit: in the Playwright initializer because the protocol requires every
browser type there (a client's constructor reads all three and does not check for a missing
one), and every call on them refuses with the reason. Only firefox is served."""
TYPE = "BrowserType"
REASON = "this server serves one browser, the firefox engine, and not %s"
def __init__(self, server: Any, name: str) -> None:
super().__init__(server, None, {"executablePath": "", "name": name})
self.REASON = self.REASON % name
class UnservedAndroid(RefusingDispatcher):
"""Required by the 1.62 Playwright initializer; Android is outside what is served."""
TYPE = "Android"
REASON = "Android devices are not served"
def __init__(self, server: Any) -> None:
super().__init__(server, None, {})
class UnservedElectron(RefusingDispatcher):
"""Required by the 1.62 Playwright initializer; Electron is outside what is served."""
TYPE = "Electron"
REASON = "Electron is not served"
def __init__(self, server: Any) -> None:
super().__init__(server, None, {})
class RemoteEndpoint:
"""The WebSocket side: serves an already-launched browser's registry.
Knows nothing of how the browser was launched (`launch_server` does that),
so the unit tests give it a registry with a stand-in Browser.
"""
WORKERS = 8
def __init__(self, server: _SharedServer, browser_type: BrowserTypeDispatcher,
browser: Any, *, host: str = DEFAULT_HOST, port: int = 0,
path: Optional[str] = None,
context_defaults: Optional[Dict] = None,
context_options_override: bool = False) -> None:
self.server = server
self.browser_type = browser_type
self.browser = browser
self.host = host
self.requested_port = port
self.token = path or secrets.token_urlsafe(18)
self.context_defaults = dict(context_defaults or {})
self.context_options_override = context_options_override
self.clients: List[RemoteClient] = []
#: The last few: each one holds its traceback, and a client that keeps
#: asking for what is not JSON must not grow it for the life of the browser.
self.wire_errors: "collections.deque" = collections.deque(maxlen=32)
self.port: Optional[int] = None
self._pages = itertools.count(0)
self._jobs: "queue.Queue" = queue.Queue()
self._workers: List[threading.Thread] = []
self._thread: Optional[threading.Thread] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._stop: Optional[asyncio.Event] = None
self._ready = threading.Event()
self._start_error: Optional[BaseException] = None
self._lock = threading.Lock()
self._closed = False
#: The two opt-in switches (`memprobe.py`): None unless the environment asks.
self.probe = memprobe.probe_from_env(self)
self.trim = memprobe.trimmer_from_env()
#: The rest of what the Playwright initializer must name (spec 1.62: chromium,
#: firefox, webkit, android, electron are all required), created once.
self.chromium = UnservedBrowserType(server, "chromium")
self.webkit = UnservedBrowserType(server, "webkit")
self.android = UnservedAndroid(server)
self.electron = UnservedElectron(server)
server.endpoint = self
# ── where it listens ────────────────────────────────────────────────────
@property
def ws_endpoint(self) -> str:
host = self.host
if host in ("0.0.0.0", "", "::"):
host = "127.0.0.1"
if ":" in host and not host.startswith("["):
host = "[%s]" % host
return "ws://%s:%d/%s" % (host, self.port or 0, self.token)
def start(self) -> None:
for i in range(self.WORKERS):
t = threading.Thread(target=self._work, daemon=True,
name="invpw-remote-%d" % i)
t.start()
self._workers.append(t)
self._thread = threading.Thread(target=self._serve, daemon=True,
name="invpw-remote-ws")
self._thread.start()
self._ready.wait()
if self._start_error is not None:
self.close()
raise self._start_error
if self.probe is not None:
self.probe.start()
def context_closed(self) -> None:
"""A context left the registry: the probe takes a line, the allocator a trim."""
if self.probe is not None:
self.probe.write("context_closed")
if self.trim is not None:
RemoteClient._trim(self.trim)
def _serve(self) -> None:
loop = asyncio.new_event_loop()
self._loop = loop
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self._main())
except BaseException as failure: # noqa: BLE001
self._start_error = self._start_error or failure
finally:
self._ready.set()
try:
loop.close()
except Exception:
pass
async def _main(self) -> None:
try:
from websockets.asyncio.server import serve
except ImportError as failure: # pragma: no cover
# Spelled by the tool that installed this package, as `_engine.py` does.
from invisible_core.installer import install
from invisible_core.pin import format_command
raise RuntimeError(
"serving a browser needs the `websockets` package: "
+ format_command(install("invisible-playwright", "websockets"))) from failure
self._stop = asyncio.Event()
try:
async with serve(self._handler, self.host, self.requested_port,
process_request=self._process_request,
max_size=None, ping_interval=None,
compression=None) as listener:
self.port = listener.sockets[0].getsockname()[1]
self._ready.set()
await self._stop.wait()
for client in list(self.clients):
try:
await client.ws.close(1001, "the server is closing")
except Exception:
pass
except BaseException as failure: # noqa: BLE001
self._start_error = failure
raise
# ── the handshake ───────────────────────────────────────────────────────
def _process_request(self, connection: Any, request: Any) -> Any:
"""Refuse a wrong path with a readable reason, and read what a client
says about itself. Never raises: a failure is an HTTP answer."""
from http import HTTPStatus
try:
split = urlsplit(request.path)
if split.path.strip("/") != self.token:
return connection.respond(
HTTPStatus.FORBIDDEN,
"this path is not served here: the endpoint is the one "
"launch_server() returned, secret included\n")
query = parse_qs(split.query)
headers = request.headers
handshake: Dict[str, Any] = {
"browser": (headers.get("x-playwright-browser")
or (query.get("browser") or [None])[0]),
"proxy": headers.get("x-playwright-proxy"),
"launch_options": None,
}
raw = (headers.get("x-playwright-launch-options")
or (query.get("launch-options") or [None])[0])
if raw:
try:
handshake["launch_options"] = json.loads(raw)
except ValueError as bad:
return connection.respond(
HTTPStatus.BAD_REQUEST,
"launch-options is not JSON (%s); the server's launch "
"is fixed anyway, so send valid JSON or none\n" % bad)
connection.invpw_handshake = handshake
return None
except Exception as failure: # noqa: BLE001 - never crash a handshake
return connection.respond(
HTTPStatus.INTERNAL_SERVER_ERROR,
"the handshake failed: %s\n" % failure)
# ── one connection ──────────────────────────────────────────────────────
async def _handler(self, ws: Any) -> None:
loop = asyncio.get_running_loop()
client = RemoteClient(self, ws, loop,
getattr(ws, "invpw_handshake", None) or {})
with self._lock:
self.clients.append(client)
pump = asyncio.create_task(client.pump())
try:
async for raw in ws:
try:
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
message = json.loads(text)
if not isinstance(message, dict):
raise ValueError("a message is a JSON object, got %s"
% type(message).__name__)
except ValueError as bad:
await ws.close(1003, ("not a protocol message: %s" % bad)[:120])
break
self._jobs.put((client, message))
except Exception:
pass
finally:
client.stop_pump()
with self._lock:
if client in self.clients:
self.clients.remove(client)
pump.cancel()
self._jobs.put((client, None)) # the leaving, in the pool
# ── the worker side ─────────────────────────────────────────────────────
def _work(self) -> None:
while True:
item = self._jobs.get()
if item is None:
return
client, message = item
token = CURRENT_CLIENT.set(client)
try:
if message is None:
self._client_gone(client)
else:
self._answer(client, message)
except Exception:
pass
finally:
CURRENT_CLIENT.reset(token)
def _answer(self, client: RemoteClient, message: Dict) -> None:
msg_id = message.get("id")
try:
result = self._dispatch(client, message)
except Exception as failure: # noqa: BLE001
self._reply_error(client, msg_id, failure)
else:
self._reply(client, msg_id, result)
def _dispatch(self, client: RemoteClient, message: Dict) -> Any:
guid = message.get("guid")
method = message.get("method")
if guid == self.server.root_guid and method == "initialize":
return self._initialize(client)
obj = self.server._objects.get(guid)
owner = getattr(obj, "_owner", None)
if obj is not None and owner is not None and owner is not client:
raise ProtocolException(
"no object %r to answer %r: it was never created"
% (guid, method))
return self.server.handle(self._prepared(message))
def _prepared(self, message: Dict) -> Dict:
"""What a standard client does not say and this server needs: the
page's number, and the session's defaults for a context."""
method = message.get("method")
if method not in ("newPage", "newContext"):
return message
params = dict(message.get("params") or {})
if method == "newPage" and "pageNumber" not in params:
params["pageNumber"] = next(self._pages)
if message.get("guid") == self.browser.guid:
for key, value in self.context_defaults.items():
if key in ("viewport", "screen") and params.get("noDefaultViewport"):
continue
if self.context_options_override or key not in params:
params[key] = value
return dict(message, params=params)
def _initialize(self, client: RemoteClient) -> Dict:
"""The announce a launched server makes to a client, to it alone and
in the order that names nothing the client has not seen."""
client.initialized = True
for obj in (self.browser_type, self.chromium, self.webkit, self.android,
self.electron, self._utils(), self.browser):
parent = obj.parent.guid if obj.parent is not None else self.server.root_guid
client.post_message({"guid": parent, "method": "__create__",
"params": {"type": obj.TYPE, "guid": obj.guid,
"initializer": obj.initializer}})
client.post_message({"guid": self.server.root_guid, "method": "__create__",
"params": {"type": "Playwright", "guid": "Playwright",
"initializer": self._playwright_initializer()}})
return {"playwright": {"guid": "Playwright"}}
def _utils(self) -> Any:
for obj in list(self.server._objects.values()):
if isinstance(obj, LocalUtilsDispatcher):
return obj
raise ProtocolException("this server has no LocalUtils")
def _playwright_initializer(self) -> Dict:
return {"chromium": self.chromium.channel,
"firefox": self.browser_type.channel,
"webkit": self.webkit.channel,
"android": self.android.channel,
"electron": self.electron.channel,
"utils": self._utils().channel,
"preLaunchedBrowser": self.browser.channel}
def _reply(self, client: RemoteClient, msg_id: Any, result: Any) -> None:
if msg_id is None:
return
out: Dict[str, Any] = {"id": msg_id}
if result is not None:
out["result"] = result
client.post_message(out)
def _reply_error(self, client: RemoteClient, msg_id: Any,
failure: BaseException) -> None:
if msg_id is None:
return
out: Dict[str, Any] = {"id": msg_id,
"error": {"error": _error_payload(failure)}}
details = getattr(failure, "details", None)
if details is not None:
out["errorDetails"] = details
log = getattr(failure, "log", None)
if log:
out["log"] = list(log)
client.post_message(out)
# ── the server's messages, to whoever they are for ──────────────────────
def route(self, message: Dict) -> None:
for client in self._targets(message):
client.post_message(message)
def _owner_of(self, guid: Any) -> Any:
return getattr(self.server._objects.get(guid), "_owner", None)
def _targets(self, message: Dict) -> List[RemoteClient]:
params = message.get("params") or {}
subjects = [params.get("guid") if message.get("method") in
("__create__", "__adopt__") else None, message.get("guid")]
owner = None
for guid in subjects:
owner = self._owner_of(guid)
if owner is not None:
break
if owner is None:
for guid in _channel_guids(params):
owner = self._owner_of(guid)
if owner is not None:
break
if owner is not None:
return [owner] if owner.alive else []
with self._lock:
return [c for c in self.clients if c.alive and c.initialized]
def _client_gone(self, client: RemoteClient) -> None:
"""A connection ended: its contexts end with it, the browser does not."""
for obj in list(self.server._objects.values()):
if (getattr(obj, "_owner", None) is client
and obj.TYPE == "BrowserContext" and not obj.disposed):
try:
obj.op_close({})
except Exception:
pass
# ── the end ─────────────────────────────────────────────────────────────
def close(self) -> None:
with self._lock:
if self._closed:
return
self._closed = True
if self.probe is not None:
self.probe.stop()
loop, stop = self._loop, self._stop
if loop is not None and stop is not None:
try:
loop.call_soon_threadsafe(stop.set)
except RuntimeError:
pass
if self._thread is not None and self._thread is not threading.current_thread():
self._thread.join(timeout=10)
for _ in self._workers:
self._jobs.put(None)
for t in self._workers:
if t is not threading.current_thread():
t.join(timeout=5)
class RemoteServer:
"""What `launch_server()` returns: the shape of Playwright's BrowserServer
(`ws_endpoint`, `close()`, `process`) plus what the session decided."""
def __init__(self, endpoint: RemoteEndpoint, *, session: Any = None,
browser: Any = None, on_engine_closed: Optional[Callable[[], None]] = None,
notes: Optional[List[str]] = None) -> None:
self._endpoint = endpoint
self._session = session
self._browser = browser
self._on_engine_closed = on_engine_closed
self._closing = threading.Event()
self._closed = False
self._close_lock = threading.Lock()
#: Options that were asked for and could not be honoured, with why.
self.notes: List[str] = list(notes or [])
self._monitor: Optional[threading.Thread] = None
# ── BrowserServer ───────────────────────────────────────────────────────
@property
def ws_endpoint(self) -> str:
return self._endpoint.ws_endpoint
@property
def process(self) -> Any:
"""The browser process (pid / poll / wait), or None for a registry with
no process of its own."""
conn = getattr(self._browser, "conn", None)
return getattr(conn, "_process", None)
@property
def seed(self) -> Optional[int]:
return getattr(self._session, "seed", None)
@property
def exit_ip(self) -> Optional[str]:
"""The egress address measured at launch (through the proxy, if any)."""
return getattr(self._session, "_webrtc_egress_ip", None)
@property
def host(self) -> str:
return self._endpoint.host
@property
def port(self) -> Optional[int]:
return self._endpoint.port
def _watch_engine(self) -> None:
process = self.process
if process is None or self._on_engine_closed is None:
return
def watch() -> None:
while not self._closing.is_set():
try:
dead = process.poll() is not None
except Exception:
dead = True
if dead:
if not self._closing.is_set():
try:
self._on_engine_closed()
except Exception:
pass
return
time.sleep(0.25)
self._monitor = threading.Thread(target=watch, daemon=True,
name="invpw-engine-watch")
self._monitor.start()
def close(self) -> None:
"""Everything: the sockets, the browser and its tree, the hidden
display and the threads. Idempotent."""
with self._close_lock:
if self._closed:
return
self._closed = True
self._closing.set()
self._endpoint.close()
try:
self._endpoint.server.shutdown()
except Exception:
pass
if self._session is not None:
try:
self._session._teardown()
except Exception:
pass
if self._monitor is not None and self._monitor is not threading.current_thread():
self._monitor.join(timeout=5)
kill = close
def __enter__(self) -> "RemoteServer":
return self
def __exit__(self, *exc: Any) -> None:
self.close()
async def aclose(self) -> None:
await asyncio.get_running_loop().run_in_executor(None, self.close)
# ── the launch ──────────────────────────────────────────────────────────────
def _context_defaults(session: Any, downloads: Optional[str]) -> Dict:
"""The session's own defaults for a context, in the protocol's spelling:
what the wrapper's `_default_context_kwargs` gives its in-process users."""
kwargs = session._default_context_kwargs()
out: Dict[str, Any] = {}
for key, value in kwargs.items():
out["timezoneId" if key == "timezone_id" else key] = value
if downloads:
out["acceptDownloads"] = downloads
return out
def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
timeout_ms: Optional[int], notes: List[str]) -> Dict:
"""`InvisiblePlaywright.__enter__` up to the launch, as protocol params.
The same calls in the same order, so the served browser is the one the
wrapper would have launched: geo (egress, timezone, locale), the
hidden display, the prefs, the proxy, the session token and the env."""
from invisible_core import configure_proxy, prepare_session_geo
from invisible_core import make_virtual_display
from invisible_playwright._engine import resolve_executable
from invisible_playwright._reaper import SessionToken
geo = prepare_session_geo(session._timezone, session._proxy,
session._locale_requested, seed=session.seed,
udp_stun_servers=session._udp_stun_servers)
session._timezone = geo.timezone
session._locale = geo.locale
session._webrtc_egress_ip = geo.egress_ip
session._geolocation = geo.geolocation_override()
executable = resolve_executable(session._binary_path)
pw_headless = bool(headless)
if not headless and virtual_display:
if sys.platform == "win32":
notes.append("virtual_display ignored: Windows has no virtual "
"display in this server (the browser runs on the "
"caller's desktop)")
else:
vd = make_virtual_display()
if vd is None:
notes.append("virtual_display ignored: no display server found")
else:
vd.start()
session._virtual_display = vd
prefs = session._build_prefs()
playwright_proxy = configure_proxy(session._proxy, prefs)
session._session_token = SessionToken.mint()
env = session._build_env(prefs)
params: Dict[str, Any] = {
"executablePath": str(executable),
"headless": pw_headless,
"firefoxUserPrefs": prefs,
"args": list(session._extra_args),
"env": [{"name": k, "value": str(v)} for k, v in env.items()],
}
if playwright_proxy:
params["proxy"] = playwright_proxy
if timeout_ms is not None:
params["timeout"] = timeout_ms
return params
def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
path: Optional[str] = None,
seed: Optional[int] = None,
pin: Optional[Dict[str, Any]] = None,
proxy: Optional[Dict[str, str]] = None,
headless: bool = False,
virtual_display: bool = True,
humanize: Any = False,
motion_budget_s: Optional[float] = None,
show_cursor: Optional[bool] = None,
preload_newtab: Optional[bool] = None,
locale: str = "auto",
timezone: str = "",
extra_args: Optional[List[str]] = None,
extra_prefs: Optional[Dict[str, Any]] = None,
binary_path: Optional[str] = None,
downloads: Optional[str] = None,
context_options: Optional[Dict[str, Any]] = None,
context_options_override: bool = False,
launch_timeout_ms: Optional[int] = 60000,
on_engine_closed: Optional[Callable[[], None]] = None,
udp_stun_servers: Optional[List[str]] = None,
) -> RemoteServer:
"""Launch ONE browser and serve it on a WebSocket; return when it listens
and the browser is ready.
host / port / path where it listens; `127.0.0.1`, a random port and a
random secret path by default. The caller chooses an
external address.
seed None draws a new one; `server.seed` reads it back.
pin fingerprint fields forced (see docs/pinning.md).
proxy `{"server", "username", "password"}`, fixed after the
launch; the egress (exit IP -> timezone, locale
"auto"; the GeoIP database offline from
STEALTHFOX_GEOIP_MMDB) is measured here through it.
headless True = true headless; False = headed.
virtual_display with headless=False: a private virtual display (Xvfb
with its own launch env). Windows: ignored, with the
reason in `server.notes`.
humanize False (default) / True / seconds; `motion_budget_s`
gives the cap in seconds (with the seed it rides in
SESSION_SEED_PREF / MOTION_BUDGET_PREF).
downloads "deny" cancels every download of every context.
context_options protocol-spelled options (`viewport`, `locale`, ...)
applied to every context a client creates, on top of
the profile's geometry, timezone and locale; filled
where the client says nothing, unless
`context_options_override=True`.
on_engine_closed called, from another thread, when the engine dies
(not when `close()` ends it).
udp_stun_servers where a SOCKS5 proxy's UDP exit is measured from: "ip:port" IPv4 literals, None for the
two public defaults. Kept on the session, so the launch and every context proxy a client
later gives measure from the same list. Python only: nothing reaches the browser.
The engine is the sealed one (`ensure_binary`, INVISIBLE_PLAYWRIGHT_ENGINE_DIR)
and the launch FAILS if the version it reports is not the seal's.
"""
from invisible_playwright import InvisiblePlaywright
from invisible_playwright._engine import assert_wire_version
if humanize and motion_budget_s:
humanize = float(motion_budget_s)
session = InvisiblePlaywright(
seed, pin=pin, headless=headless, proxy=proxy, extra_args=extra_args,
humanize=humanize, locale=locale, timezone=timezone,
extra_prefs=extra_prefs, binary_path=binary_path,
show_cursor=show_cursor, udp_stun_servers=udp_stun_servers,
preload_newtab=preload_newtab)
notes: List[str] = []
server = _SharedServer()
endpoint: Optional[RemoteEndpoint] = None
try:
params = _launch_params(session, virtual_display=virtual_display,
headless=headless, timeout_ms=launch_timeout_ms,
notes=notes)
browser_type = SharedBrowserType(server)
LocalUtilsDispatcher(server)
browser = server.object(
browser_type.op_launch(params)["browser"]["guid"])
session._bind_process_tree()
class _Reported: # what assert_wire_version reads off a Browser
version = browser.initializer.get("version", "")
assert_wire_version(_Reported)
defaults = _context_defaults(session, downloads)
defaults.update(context_options or {})
endpoint = RemoteEndpoint(
server, browser_type, browser, host=host, port=port, path=path,
context_defaults=defaults,
context_options_override=context_options_override)
endpoint.start()
except BaseException:
if endpoint is not None:
endpoint.close()
try:
server.shutdown()
except Exception:
pass
try:
session._teardown()
except Exception:
pass
raise
result = RemoteServer(endpoint, session=session, browser=browser,
on_engine_closed=on_engine_closed, notes=notes)
result._watch_engine()
return result
async def launch_server_async(*args: Any, **options: Any) -> RemoteServer:
"""`launch_server`, off the loop: the launch blocks for seconds."""
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None, lambda: launch_server(*args, **options))
File diff suppressed because it is too large. Load diff
+49 -99
View File
@@ -53,6 +53,8 @@ from typing import Any, Dict, Optional
from invisible_playwright._pw._impl._helper import parse_error
from invisible_playwright._pw._impl._transport import Transport
from . import wire
def _error_payload(failure: BaseException) -> Dict[str, str]:
"""The `{name, message, stack}` shape both an error REPLY and a
@@ -84,19 +86,6 @@ def _translate_exception(failure: BaseException) -> BaseException:
return parse_error(_error_payload(failure))
def _settle_result(future: asyncio.Future, result: Any) -> None:
"""⛔ Guarded: a future the caller already cancelled must not be resolved
again - `asyncio.Future.set_result` on a cancelled future raises, and this
runs on the loop where that exception would have nowhere useful to go."""
if not future.done():
future.set_result(result)
def _settle_exception(future: asyncio.Future, failure: BaseException) -> None:
if not future.done():
future.set_exception(failure)
class InProcessTransport(Transport):
"""A `Transport` whose other end is a Python object, not a subprocess."""
@@ -114,85 +103,6 @@ class InProcessTransport(Transport):
self._threads: list = []
server.attach(self)
# ── the fused-type escape hatch ──────────────────────────────────────────
def bind_impl_objects(self, objects: Dict[str, Any],
deliver_event: Any) -> None:
"""Give the server a live view of the CLIENT's guid registry, and its
way to deliver an event under the correct execution context.
⛔ THE ONLY BRIDGE BETWEEN THE TWO GRAPHS. `objects` is a REFERENCE,
not a copy: the client mutates it in place as it creates and disposes
things, so this always sees the CURRENT state with nothing to go
stale. It exists because a FUSED type - one with no `__create__` and no
guid of its own - still needs to reach the live impl-side object a
SIBLING guid corresponds to (a Dialog needs its Page's twin, to find
the BrowserContext to notify).
⛔ AND `deliver_event` IS NOT OPTIONAL EITHER, found by an actual
dialog hanging rather than by the unit suite. `Connection.dispatch`
wraps every wire event in an `EventGreenlet` under the sync facade, so
a handler that calls an async method (`dialog.accept()`) can suspend
into it and resume. A fused type delivers its event directly, never
through `dispatch`, so without this it never gets that wrapping - and
the handler hangs with no exception, because it suspended into a fiber
with nobody on the other end of the switch. Dialog is the first user
of both, 2026-08-29.
"""
self._server.bind_twins(objects, deliver_event)
def run_blocking(self, fn: Any, *args: Any) -> asyncio.Future:
"""Run `fn(*args)` on this transport's OWN worker pool; return an
awaitable that resolves on the LOOP once it is done.
⛔ THE SAME POOL AS EVERY CHANNEL MESSAGE, on purpose: a fused type's
blocking call and a channel-routed call must never be able to starve
each other by running on separate pools with separate limits. `_work`
below accepts a plain callable exactly as it accepts a message dict,
from the SAME queue, serviced by the SAME four threads.
⛔ AND THE EXCEPTION IS TRANSLATED, not passed through raw. `fn` runs
`_juggler` code and can raise `_juggler.dispatcher.TargetClosedError` -
a DIFFERENT CLASS than `_pw._impl._errors.TargetClosedError` with the
SAME NAME. A fused type's own exception handling
(`is_target_closed_error`) checks the FORK's class by `isinstance`, so
a raw `_juggler` exception reaching it would look like an ordinary
error and never be swallowed - reproducing, through this new path, the
exact regression fixed on 2026-08-29 in `Page.close()`. The
translation below goes through `parse_error`, the same one the
message-envelope path already uses: not a second way of doing it, the
one way, reused.
"""
future: asyncio.Future = self._loop.create_future()
def job() -> None:
try:
result = fn(*args)
except Exception as failure:
translated = _translate_exception(failure)
self._loop.call_soon_threadsafe(_settle_exception, future,
translated)
else:
self._loop.call_soon_threadsafe(_settle_result, future, result)
self._queue.put(job)
return future
def call_soon(self, fn: Any, *args: Any) -> None:
"""Hand a call to the LOOP thread, fire-and-forget - the
construction half of what `run_blocking` does for a call whose
RESULT matters. A fused type's incoming EVENT (a dialog that just
opened, built on the connection's read-loop thread) needs this to
reach the code that must run on the asyncio loop, exactly like every
message this transport already delivers via `emit_message` below -
just carrying a real object instead of a wire message.
"""
if self._stopped.is_set():
return
try:
self._loop.call_soon_threadsafe(fn, *args)
except RuntimeError:
pass # the loop is already closed; nobody is left to receive it
# ── the five methods the seam declares ──────────────────────────────────
async def connect(self) -> None:
for i in range(self.WORKERS):
@@ -241,13 +151,6 @@ class InProcessTransport(Transport):
item = self._queue.get()
if item is None:
return
# ⛔ A PLAIN CALLABLE IS A JOB FROM `run_blocking`, and a dict is a
# channel message: the same queue, the same four threads, told
# apart by shape rather than by a second queue that would split
# the pool in two.
if callable(item):
item()
continue
message = item
try:
result = self._server.handle(message)
@@ -295,8 +198,50 @@ class InProcessTransport(Transport):
details = getattr(failure, "details", None)
if details is not None:
out["errorDetails"] = details
# And its call log, where `Connection.dispatch` reads it: the client
# prints it under "Call log:" ([B341]).
log = getattr(failure, "log", None)
if log:
out["log"] = list(log)
self.emit_message(out)
class JsonWireTransport(InProcessTransport):
"""`InProcessTransport` with the wire between the two ends: every message crosses as the
JSON text a socket would carry, in both directions.
⛔ THIS IS THE CHECK, NOT THE SOCKET. The remote transport (`remote.py`) sends the same
text over a WebSocket; this class sends it between two Python objects, so the whole
existing suite can run on it with no network and no second process, and any value that
JSON would change or lose (`wire.py`) fails here, at the line that built it, naming the
path inside the message.
A client message that is not JSON raises from `send` to its caller. A server REPLY that
is not JSON becomes an error reply for the same id (so the call that caused it fails
with the path in its message); a server EVENT that is not JSON cannot be answered, so it
is dropped and recorded in `wire_errors`, which a test asserts empty.
"""
def __init__(self, loop: asyncio.AbstractEventLoop, server: Any) -> None:
super().__init__(loop, server)
self.wire_errors: list = []
def send(self, message: Dict) -> None:
super().send(wire.round_trip(message))
def emit_message(self, message: Dict) -> None:
try:
carried = wire.round_trip(message)
except wire.WireError as problem:
self.wire_errors.append(problem)
msg_id = message.get("id") if isinstance(message, dict) else None
if msg_id is not None and "error" not in message:
super().emit_message({"id": msg_id, "error": {"error": {
"name": "Error", "message": "the reply is not JSON: %s" % problem,
"stack": ""}}})
return
super().emit_message(carried)
# ── choosing one ────────────────────────────────────────────────────────────
#
# ⛔ THIS WAS A MODULE OF ITS OWN UNTIL 2026-08-29, and what it chose between
@@ -315,6 +260,9 @@ class InProcessTransport(Transport):
# shell, and "unknown transport" would tell them nothing about what happened.
CHOICE_ENV = "INVPW_TRANSPORT"
#: `json` puts the wire between the client and the server (`JsonWireTransport`), as it is
#: for a remote client. Off by default: local use passes the dicts as it always did.
WIRE_ENV = "INVPW_WIRE"
DRIVER = "driver"
JUGGLER = "juggler"
@@ -337,4 +285,6 @@ def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
"INVPW_DRIVER_TREE at it. Both `judge_both_transports.py` and "
"`diff_protocol.py` read that variable." % CHOICE_ENV)
from .server import JugglerServer
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
return JsonWireTransport(loop, JugglerServer())
return InProcessTransport(loop, JugglerServer())
@@ -0,0 +1,97 @@
"""The shapes a message takes across Playwright's protocol versions, brought to
the one this server reads.
⛔ ONE PLACE, AT THE ENTRANCE. The client is whatever version the caller has
installed, and the protocol moved between versions: in 1.62 the `timeout` left
the parameters of nearly every command and went to the call's metadata, and a
few commands and optional fields were added. Reading each variant where the
operation uses it would put a second spelling of every timeout in a hundred
places; folding them here means `server.py` reads one shape, `_caller_timeout`
reads `params["timeout"]` as it always did, and a new version is a change to
this file.
⛔ NO VERSION IS ASKED FOR, AND NONE IS REFUSED. The two forms do not conflict
- a message carries its timeout in the parameters or in the metadata, never
meaningfully in both - so the message is read by what it contains: a timeout in
the parameters wins, one in the metadata fills the gap, and a field this
server does not know is carried along unread, as the protocol's own optional
fields are.
What each 1.62 addition becomes here:
* `metadata.timeout` (milliseconds, `0` = no limit, as in the parameters):
read into `params["timeout"]` when the parameters carry none.
* `scroll` ("auto" | "none") on click, dblclick, hover, tap, check, uncheck,
dragAndDrop: IGNORED ON PURPOSE. Every pointer action here scrolls the
target into view first, which is `auto`; `none` asks to act on the element
where it is, and honouring it needs an action path that does not scroll,
which does not exist. The action still happens, scrolled.
* `noGlobal` on exposeBinding: moot, `exposeBinding` is refused as a whole.
* `type` "webp" on screenshot: REFUSED. The engine captures PNG and JPEG, and
answering a webp request with PNG bytes would hand the caller a file that
is not the format it asked for.
* `selector` / `strict` on waitForFunction (the predicate runs against an
element): REFUSED when a selector is given. Running the predicate without
the element would answer a different question.
* `credentials` (virtual WebAuthn credentials) in storageState,
setStorageState and a context's `storageState`: REFUSED when asked for or
given; WebAuthn is outside the perimeter (see `perimeter.py`). `False`,
`None` and an empty list are not a request and pass.
* `Page.screencastFrameAck`: ACCEPTED AND DOES NOTHING (`PageDispatcher`
answers it with `op_noop`). This server acknowledges a frame to the engine
itself as soon as it has relayed it, so there is no frame held back for the
client to release; a client that acknowledges every frame, as 1.62's does,
must not be failed for that.
* `Frame.drop`: already answered by `FrameDispatcher.op_drop`, which refuses
it with its own reason (the engine has no command for it).
"""
from __future__ import annotations
from typing import Any, Dict, Optional
def _metadata_timeout(metadata: Dict) -> Optional[float]:
wanted = metadata.get("timeout")
if isinstance(wanted, bool) or not isinstance(wanted, (int, float)):
return None
return float(wanted) if wanted >= 0 else None
def _refuse(reason: str):
# Imported here: `dispatcher.py` imports this module.
from .dispatcher import ProtocolException
raise ProtocolException(reason)
def _present(value: Any) -> bool:
"""A request for something, as opposed to false, null or an empty list."""
return bool(value)
def to_internal(method: Optional[str], params: Dict, metadata: Dict) -> Dict:
"""`params` in the shape the operations read, or a refusal naming why this
one command is not served. `params` itself is never changed."""
out = dict(params)
if out.get("timeout") is None:
out.pop("timeout", None)
wanted = _metadata_timeout(metadata or {})
if wanted is not None:
out["timeout"] = wanted
if method in ("screenshot", "expectScreenshot") and out.get("type") == "webp":
_refuse("a webp screenshot is not available: the engine captures PNG "
"and JPEG only, and a PNG sent as webp would be a file that is "
"not the format asked for")
if method == "waitForFunction" and out.get("selector"):
_refuse("wait_for_function() on an element (a selector) is not "
"available: the predicate would run without the element it "
"was written for")
if method in ("storageState", "setStorageState", "newContext",
"launchPersistentContext"):
state = out.get("storageState")
if _present(out.get("credentials")) or (
isinstance(state, dict) and _present(state.get("credentials"))):
_refuse("virtual credentials in a storage state are not available: "
"WebAuthn is outside the perimeter this package covers")
return out
+86
View File
@@ -0,0 +1,86 @@
"""The wire form of a protocol message: JSON, and nothing a socket cannot carry.
Today the client and the server of this package pass each other Python dicts in the
same process (`transport.InProcessTransport`). That is why nothing has ever checked that
a message is JSON: a `bytes`, a tuple of objects, a NaN or an impl object can sit in one
and travel without a word. A message that goes through a WebSocket (`remote.py`) is a
string, so the first such value is a failure that shows up far from the line that put it
there.
`dumps` therefore refuses what JSON would change or lose, and names WHERE it is
(`$.params.payloads[0].buffer`), which is the one thing a bare `TypeError: Object of type
bytes is not JSON serializable` does not say:
- `bytes`, `bytearray`, sets and any object that is not a plain value;
- a key that is not a string (`json` would turn 1 into "1" and the reader would look
up the wrong key);
- NaN and the infinities (not JSON; Playwright's own protocol sends them as
`{"v": "NaN"}` inside serialised values, never as a bare number).
A tuple is accepted: it is a JSON array and reads back as a list, which is what a client
on the other end of a socket would see anyway.
Playwright's own protocol carries binary as a base64 string, so a server that wants to
send bytes encodes them where it builds the message; it is never this module's job to
guess that.
"""
from __future__ import annotations
import json
import math
from typing import Any, Optional
class WireError(TypeError):
"""A value in a message that JSON would change or lose. `path` says where."""
def __init__(self, path: str, reason: str) -> None:
super().__init__("%s: %s" % (path, reason))
self.path = path
self.reason = reason
def first_problem(value: Any, path: str = "$") -> Optional[WireError]:
"""The first value under `value` that is not plain JSON, or None."""
if value is None or isinstance(value, (bool, str)):
return None
if isinstance(value, int):
return None
if isinstance(value, float):
if math.isnan(value) or math.isinf(value):
return WireError(path, "%r is not JSON" % value)
return None
if isinstance(value, dict):
for key, item in value.items():
if not isinstance(key, str):
return WireError("%s[%r]" % (path, key),
"a key must be a string, not %s" % type(key).__name__)
problem = first_problem(item, "%s.%s" % (path, key))
if problem:
return problem
return None
if isinstance(value, (list, tuple)):
for index, item in enumerate(value):
problem = first_problem(item, "%s[%d]" % (path, index))
if problem:
return problem
return None
return WireError(path, "%s is not a JSON value" % type(value).__name__)
def dumps(message: Any) -> str:
"""The message as the text that crosses the wire. Raises `WireError`."""
problem = first_problem(message)
if problem:
raise problem
return json.dumps(message, separators=(",", ":"), allow_nan=False)
def loads(text: "str | bytes") -> Any:
"""The message a text carries."""
return json.loads(text)
def round_trip(message: Any) -> Any:
"""What the other end of a socket would read: `loads(dumps(message))`."""
return loads(dumps(message))
+35 -9
View File
@@ -19,11 +19,12 @@ is the whole floor, and its except branches classify the failure:
installed at all, or it is older than this check and ships no
invisible_core.pin (or no invisible_core.pin.enforce_core_pin). Those
cannot be told apart from here and do not need to be: one remedy fixes all
of them, `pip install --force-reinstall invisible-playwright`, which makes
pip resolve the core version from our own Requires-Dist. No version literal
in the message, so nothing here can drift out of step with pyproject.
of them, a force-reinstall of invisible-playwright (`reinstall_command`, spelled
by the tool that installed it), which makes the installer resolve the core
version from our own Requires-Dist. No version literal in the message, so
nothing here can drift out of step with pyproject.
* ImportError naming any other module - the core is installed and one of ITS
dependencies is missing. That is what `pip install --no-deps` leaves behind,
dependencies is missing. That is what an install with `--no-deps` leaves behind,
and reporting it as "invisible-core is not installed" sends the user to the
wrong package.
* anything else - the core is on disk and its import raised something that is
@@ -51,6 +52,31 @@ import sys as _sys
DIST_NAME = "invisible-playwright"
def reinstall_command() -> str:
"""The command that reinstalls this distribution, as the tool that
installed it spells it: the one remedy this floor hands over.
`invisible_core.installer` is where every other install command comes from,
and it cannot be asked here: the floor speaks exactly when the core does not
import. So this reads the same INSTALLER record with the standard library
and takes the same two branches, for this one command. Until 2026-10-17 it was
`pip install --force-reinstall` for everybody, and the venv the README makes
(`uv init` + `uv add`) has no pip in it.
"""
from importlib.metadata import PackageNotFoundError, distribution
try:
record = distribution(DIST_NAME).read_text("INSTALLER")
except PackageNotFoundError:
record = None
if (record or "").strip().lower() == "uv":
cmd = ["uv", "pip", "install", "--python", _sys.executable,
"--force-reinstall", DIST_NAME]
else:
cmd = [_sys.executable, "-m", "pip", "install", "--force-reinstall", DIST_NAME]
return " ".join(f'"{t}"' if " " in t else t for t in cmd)
# Captured BEFORE the core is imported, and it is the whole soundness argument
# for the in-process repair: if nothing has imported invisible_core by the time
# this package's __init__ starts, then nobody is holding an object from the
@@ -105,16 +131,16 @@ except ImportError as _e:
f"invisible-core is installed but cannot be imported: no module named "
f"{_missing!r}.\n"
f"That is one of its own dependencies, so it was installed without "
f"dependency resolution (pip install --no-deps, or a lockfile that "
f"lists the packages separately).\n"
f"Run: pip install --force-reinstall {DIST_NAME}"
f"dependency resolution (an install with --no-deps, or a lockfile "
f"that lists the packages separately).\n"
f"Run: {reinstall_command()}"
) from _e
raise ImportError(
"invisible-core is missing, or too old for this invisible-playwright: it "
"does not carry the release-pin check (invisible_core.pin), so the engine "
"it downloads cannot be matched against the configuration this package "
"ships.\n"
f"Run: pip install --force-reinstall {DIST_NAME}"
f"Run: {reinstall_command()}"
) from _e
except Exception as _e:
raise ImportError(
@@ -124,7 +150,7 @@ except Exception as _e:
f"unreadable invisible_core/seal.json is the usual cause, and it is read "
f"while invisible_core is still importing, so nothing inside the core can "
f"report it.\n"
f"Run: pip install --force-reinstall {DIST_NAME}"
f"Run: {reinstall_command()}"
) from _e
+27 -66
View File
@@ -1,75 +1,36 @@
# Il client Python di Playwright, biforcato
# Playwright's Python client, vendored
Copia modificabile di `playwright` **1.61.0** (`_impl`, `sync_api`, `async_api`),
Apache-2.0. **67 file, 2,4 MB.** La meta' Node del fork sta in `../_driver/`, e
il documento che spiega la decisione e' [quello](../_driver/README.md): qui ci
sono solo le cose che riguardano il lato Python.
A modified copy of `playwright` **1.61.0** (`_impl`, `sync_api`, `async_api`),
Apache-2.0 (`LICENSE` in this folder). The namespace is
`invisible_playwright._pw` instead of `playwright`, so it never collides with a
stock `playwright` installed alongside it. What answers this client is the
in-process server in `../_juggler/`; Playwright's Node driver is not shipped
(`../THIRD_PARTY_FORK.md` has the licence terms and the history).
## Cosa e' stato cambiato rispetto all'originale
## What differs from upstream
**Gli import, in 52 file su 67.** Il client usa **446 import assoluti**
(`from playwright...`) e **zero relativi**: copiarlo sotto un altro nome senza
riscriverli avrebbe prodotto un pacchetto che importa quello *installato*, cioe'
un fork che sembra funzionare e non e' un fork.
**The imports.** Every absolute `playwright...` import is rewritten to this
namespace, anchored at the start of the line, because the word `playwright` also
appears in docstrings, documentation URLs, examples and two local variables.
`tests/test_fork.py` keeps it that way: a new `from playwright...` line would
still run, against the installed package, and silently stop being this code.
Le riscritture sono **ancorate a inizio riga**. Non e' pignoleria: la parola
`playwright` compare 423 volte in docstring, URL della documentazione ed esempi
(`browser = playwright.chromium.launch()`), e in due punti e' una **variabile
locale** (`_impl/_browser_type.py:286`, `_impl/_fetch.py:66`). Un replace globale
le avrebbe rovinate tutte.
**The behaviour, in these files only.** Each change carries a
`# MODIFIED by invisible_playwright:` comment at the point it is made, which is
also where the repository's English gate reads it.
Cinque forme, censite invece che indovinate:
| forma | quante |
| file | what changed |
|---|---|
| `from playwright.X import ...` | 353 |
| `from playwright.{sync,async}_api import ...` | 74 |
| `import playwright.X[.Y] [as Z]` | 10 |
| `import playwright` | 2 |
| `from playwright._repo_version import ...` | 1 |
| `_impl/_browser.py` | the numbers of the pages the script asks for, 0, 1, 2, in the order of the calls, reserved before the first `await`; the only counter of them |
| `_impl/_browser_context.py` | each page the script asks for carries its number in the session, reserved on the client at the moment of the call, where the order of the calls exists |
| `_impl/_playwright.py` | asking for `chromium` or `webkit` raises a `ValueError` that says they were removed, not disabled |
| `sync_api/_generated.py`, `async_api/_generated.py` | the `chromium` and `webkit` properties raise `NotImplementedError` with the same explanation, instead of an `AttributeError` |
| `sync_api/_context_manager.py`, `async_api/_context_manager.py` | the transport comes from `make_transport` (the in-process server) |
⛔ La terza forma **era sfuggita al primo giro**, e il primo giro sembrava
riuscito. Dieci import sopravvissuti puntavano ancora al pacchetto installato.
Li ha trovati il controllo che rilegge l'albero riscritto cercando residui: e'
per quello che esiste, non per fare bella figura.
Everything else is upstream, byte for byte.
**Un effetto collaterale degli import puntati.** `import playwright._impl._X`
senza alias lasciava usabile il nome nudo `playwright`, e i due `__init__.py`
delle API se ne servono ventitre volte a testa (`playwright._impl._api_structures.Cookie`).
Dopo la riscrittura quel nome non era piu' legato da nessuno: il modulo sarebbe
esploso con `NameError` alla prima riga eseguita. Il generatore aggiunge il
legame nei file che si trovavano in quella condizione.
## Regenerating
**`_impl/_driver.py` e' l'unico file in cui e' cambiato del COMPORTAMENTO**, e
la modifica e' dichiarata in testa al file come chiede Apache-2.0: punta al
`cli.js` in `../_driver/` e prende `node` da `invisible_playwright._node`.
L'originale calcolava entrambi da `inspect.getfile(playwright)`, che dopo la
vendorizzazione punterebbe a `_pw/driver/` - una cartella che non esiste.
## Cosa NON e' stato toccato
Tutto il resto, byte per byte. Il fork esiste per poter cambiare
`../_driver/package/lib/coreBundle.js`; il client Python e' venuto dietro solo
perche' senza di lui la dipendenza da `playwright` sarebbe rimasta.
## Come rifarlo
`playwright` resta fra le dipendenze di **sviluppo** apposta: serve come
sorgente per rigenerare questa cartella, e serve a poter confrontare i due
bracci sulla stessa macchina. Un fork che non si puo' confrontare con
l'originale non si puo' nemmeno difendere.
Il generatore vive nel workbench (`C:/tmp/vendor_client.py` al momento della
prima stesura) e va rimesso in un posto stabile prima di servirne un secondo
giro.
## Verificato
- **454 test** della suite del wrapper, verdi sullo stack interamente biforcato.
- Una sessione completa del prodotto confrontata coi valori misurati **prima**
del fork: user agent, `navigator.languages`, geometria dello schermo, renderer
WebGL e **screenshot identico byte per byte** (9656). Zero differenze.
- `tests/test_fork.py` impedisce il modo silenzioso in cui questo fork
morirebbe: qualcuno che scrive `from playwright...` in un file nuovo. Quella
riga **funziona** - il pacchetto resta installato - e semplicemente esegue
codice che non e' il nostro.
`playwright==1.61.0` stays among the **development** dependencies on purpose: it is
the source this folder is regenerated from, and the reference it is compared
against. The changes above are re-applied by their markers.
Loaded 100 of 343 files, more files were not shown because too many files have changed in this diff. Show more