Compare commits
310
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ea36371f5 | ||
|
|
9b0f474bc8 | ||
|
|
97ba055d77 | ||
|
|
54b2f26c69 | ||
|
|
6d23f75229 | ||
|
|
beff30e822 | ||
|
|
1382a83540 | ||
|
|
299fc9f5da | ||
|
|
fe5cb50ed3 | ||
|
|
2d1bc68b26 | ||
|
|
3b594b85ed | ||
|
|
8d1356cb69 | ||
|
|
0a5961270a | ||
|
|
07b7b74e08 | ||
|
|
710ee498ba | ||
|
|
9883d3f455 | ||
|
|
7c79ba1ed4 | ||
|
|
fc10e257ca | ||
|
|
78277565f5 | ||
|
|
0a0d0d689d | ||
|
|
ff02f112fe | ||
|
|
016eccab9e | ||
|
|
db5c7ef565 | ||
|
|
5459a6b59e | ||
|
|
483f9af50a | ||
|
|
1d33f56100 | ||
|
|
285e3ba93e | ||
|
|
966e2d6a8b | ||
|
|
d13a9442c5 | ||
|
|
2effeb1594 | ||
|
|
15d7608867 | ||
|
|
2d9cf3a82f | ||
|
|
05420d83ce | ||
|
|
03d18c853d | ||
|
|
23b17c33ef | ||
|
|
fb888c09cf | ||
|
|
3f56ac2e69 | ||
|
|
8621f0a5d6 | ||
|
|
9956adc386 | ||
|
|
72997c957c | ||
|
|
bd853bc040 | ||
|
|
7a0d55f4ce | ||
|
|
d867282c99 | ||
|
|
302af97575 | ||
|
|
47725170de | ||
|
|
d56ea298b4 | ||
|
|
b46e5a32d3 | ||
|
|
e88e664a50 | ||
|
|
bacf03ad21 | ||
|
|
9357e790b3 | ||
|
|
1466ac6433 | ||
|
|
bf5c6dabb3 | ||
|
|
e992255d38 | ||
|
|
8049df3c33 | ||
|
|
e4edf5f81f | ||
|
|
7a094c3bbc | ||
|
|
7272ea8f64 | ||
|
|
a70f2fecaf | ||
|
|
65f7580182 | ||
|
|
4933f8cdba | ||
|
|
bfb67e0c2c | ||
|
|
2022ecf32a | ||
|
|
5ae6833299 | ||
|
|
a90dadc204 | ||
|
|
210161d9b6 | ||
|
|
1542fede01 | ||
|
|
5426744bc6 | ||
|
|
973927fdb7 | ||
|
|
071cf8d697 | ||
|
|
7af5b84954 | ||
|
|
a18e967675 | ||
|
|
64dc8d3476 | ||
|
|
bd46760313 | ||
|
|
2283d40198 | ||
|
|
012fc862ef | ||
|
|
8c7e413b68 | ||
|
|
bbf4019940 | ||
|
|
4e1f2ecf40 | ||
|
|
6f9b87c860 | ||
|
|
a072aa22b8 | ||
|
|
328ed0738e | ||
|
|
6200bc29ed | ||
|
|
b05741f538 | ||
|
|
95c7e156ac | ||
|
|
620f969655 | ||
|
|
adf96a2b15 | ||
|
|
2167538130 | ||
|
|
440bbb36e6 | ||
|
|
2f153c76ff | ||
|
|
fbceeafb65 | ||
|
|
b09d620930 | ||
|
|
776c00afe2 | ||
|
|
ba5b51cf91 | ||
|
|
14c24347c5 | ||
|
|
99c7fc93aa | ||
|
|
a61465b2be | ||
|
|
47536b5e64 | ||
|
|
4f95aa3797 | ||
|
|
6a60dcebb7 | ||
|
|
7927e30679 | ||
|
|
bf2a3c33b0 | ||
|
|
03d96a7baa | ||
|
|
7db28e4611 | ||
|
|
f76240893e | ||
|
|
d5c0e410de | ||
|
|
422e675b86 | ||
|
|
1c7bcf9dee | ||
|
|
84fd375562 | ||
|
|
d596ee81c8 | ||
|
|
66d5090a0b | ||
|
|
3a1dc8df9b | ||
|
|
5b87926543 | ||
|
|
b396e055ce | ||
|
|
68bb2b8e8f | ||
|
|
c14f2b1e9a | ||
|
|
bfedd53850 | ||
|
|
e868714339 | ||
|
|
36ecd11e99 | ||
|
|
80672c69a3 | ||
|
|
a21e1decb9 | ||
|
|
ecf384a923 | ||
|
|
a8cc2c842e | ||
|
|
5da874d67f | ||
|
|
f3e3ce164d | ||
|
|
2329dc6c1c | ||
|
|
52e520dd92 | ||
|
|
73c070ebb1 | ||
|
|
1d564f5732 | ||
|
|
6f25adc2e5 | ||
|
|
cd062e2c59 | ||
|
|
5a617dd899 | ||
|
|
793ea3d191 | ||
|
|
154a9de475 | ||
|
|
8c92c764b7 | ||
|
|
000fa7a3ad | ||
|
|
6a5b7e014a | ||
|
|
b78c5bb67c | ||
|
|
228576009b | ||
|
|
bc816cb1ae | ||
|
|
7ef736ca73 | ||
|
|
d6f5c884b4 | ||
|
|
cbd9f5db5b | ||
|
|
183219ce18 | ||
|
|
5c66186464 | ||
|
|
7ddb451af7 | ||
|
|
98d9a799f6 | ||
|
|
f9221ae3c2 | ||
|
|
41f7bec7a7 | ||
|
|
56b33a7740 | ||
|
|
b6d32402f2 | ||
|
|
fef0bc5ea7 | ||
|
|
2bc12eb80b | ||
|
|
ff2123ef58 | ||
|
|
5402da4d80 | ||
|
|
82d88c848f | ||
|
|
e2a006d1c9 | ||
|
|
c33b9dd8f2 | ||
|
|
ebaed54e0e | ||
|
|
8de4cd2c9f | ||
|
|
087117dfc6 | ||
|
|
b85c8f49a1 | ||
|
|
e82ae18bac | ||
|
|
b1887220a3 | ||
|
|
f3d083aa85 | ||
|
|
8f86007065 | ||
|
|
1ff8ed5785 | ||
|
|
0eee28d093 | ||
|
|
ccb0ff051f | ||
|
|
0321737429 | ||
|
|
e8b57121e1 | ||
|
|
fa0d19cca3 | ||
|
|
1e23d20e0c | ||
|
|
3481f419c7 | ||
|
|
5c0de53221 | ||
|
|
c7c7285557 | ||
|
|
da503f254a | ||
|
|
43a3197d89 | ||
|
|
ce79a51417 | ||
|
|
d9c21dd67b | ||
|
|
64f76b2d94 | ||
|
|
808c8f8c97 | ||
|
|
a42d863e48 | ||
|
|
f62bf3f6dc | ||
|
|
eadf95b90a | ||
|
|
b81f1561c5 | ||
|
|
61d2ee29d5 | ||
|
|
882c0f3a0e | ||
|
|
dde60415d7 | ||
|
|
be60e4d7e4 | ||
|
|
8c2dcbf570 | ||
|
|
4fddee2d46 | ||
|
|
87f48c9b8a | ||
|
|
7d702fb188 | ||
|
|
42cbc45da2 | ||
|
|
97faaa84f2 | ||
|
|
e5cb8934a2 | ||
|
|
16abec2c09 | ||
|
|
742281ec3a | ||
|
|
c5e89a85d2 | ||
|
|
a8da4b117f | ||
|
|
4ba1cefcdd | ||
|
|
3378b8f3e2 | ||
|
|
07a03e41e9 | ||
|
|
22a098843a | ||
|
|
e76c63a6cb | ||
|
|
caae1ea0aa | ||
|
|
acb073dda7 | ||
|
|
081b3a1aa0 | ||
|
|
9460e8eb86 | ||
|
|
3abd710393 | ||
|
|
80034c9c84 | ||
|
|
820d88e8eb | ||
|
|
558a402fa9 | ||
|
|
2b3cbe0795 | ||
|
|
3dd1424a0a | ||
|
|
5847dfe87a | ||
|
|
622b6e82a7 | ||
|
|
4355274838 | ||
|
|
97f8663ec6 | ||
|
|
ce68aea668 | ||
|
|
dab71bd637 | ||
|
|
0c043d580e | ||
|
|
0421f95adf | ||
|
|
284a840ebe | ||
|
|
eb8b415635 | ||
|
|
e508c10e9d | ||
|
|
7a4e7c4d0a | ||
|
|
3824a2e03e | ||
|
|
fb5c3a403c | ||
|
|
eb2be0e88d | ||
|
|
621a396def | ||
|
|
2afb1cc349 | ||
|
|
b0dc24031c | ||
|
|
d87cc4e3b6 | ||
|
|
8eb28c2ada | ||
|
|
09eeb004d1 | ||
|
|
c23612e295 | ||
|
|
11b9e08b1a | ||
|
|
632490aa50 | ||
|
|
6c0cfdb610 | ||
|
|
9a98c0060b | ||
|
|
4b9e28a879 | ||
|
|
6383f21dbb | ||
|
|
6080c06bd9 | ||
|
|
ae947139d8 | ||
|
|
e1f1659776 | ||
|
|
02bd688896 | ||
|
|
c6dca80401 | ||
|
|
f03164e7e0 | ||
|
|
0236afb11d | ||
|
|
af932640b8 | ||
|
|
fd22249b65 | ||
|
|
c84c8c32a5 | ||
|
|
a5ad308e4a | ||
|
|
c30e07ee9f | ||
|
|
85cc5d10e6 | ||
|
|
7c23e4377d | ||
|
|
0418f37dbb | ||
|
|
0dc42b6380 | ||
|
|
f4381155bd | ||
|
|
bec6e5f835 | ||
|
|
d9dca5b498 | ||
|
|
469e1692a7 | ||
|
|
44a3eed971 | ||
|
|
77b192eba5 | ||
|
|
49e4e3a133 | ||
|
|
4a0bd76768 | ||
|
|
6de45423d1 | ||
|
|
20f8a43693 | ||
|
|
00d8154ef8 | ||
|
|
12d1cc7308 | ||
|
|
2e1b91b196 | ||
|
|
c11c04b30e | ||
|
|
29a5c7a516 | ||
|
|
00ad6d702f | ||
|
|
9fb0f20dbc | ||
|
|
254b2dce1d | ||
|
|
2ee9f100bf | ||
|
|
d5a50275ea | ||
|
|
b02c79f279 | ||
|
|
4a69d25254 | ||
|
|
7b783cf892 | ||
|
|
455f0cf0e1 | ||
|
|
655d99020a | ||
|
|
4b61bea3fa | ||
|
|
ffad787af9 | ||
|
|
cc3bce2f58 | ||
|
|
33940459f7 | ||
|
|
dc9ff53e78 | ||
|
|
4ad30e5079 | ||
|
|
e94863c79d | ||
|
|
151c314c05 | ||
|
|
8bbc41162b | ||
|
|
58fd0c8d93 | ||
|
|
edaf224417 | ||
|
|
07a55bfc85 | ||
|
|
1bac4b6f8b | ||
|
|
47dabed289 | ||
|
|
a1312941eb | ||
|
|
5b762bab65 | ||
|
|
920292760a | ||
|
|
0afe5737fa | ||
|
|
9a1501af7a | ||
|
|
fb56fde88d | ||
|
|
88d3f7a513 | ||
|
|
1504d95ed3 | ||
|
|
9927c974da | ||
|
|
632f023b8c | ||
|
|
0dd99b7638 | ||
|
|
0433b18aa7 |
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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 }})
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -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>
|
||||
@@ -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)."}
|
||||
]
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 |
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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"
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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}"
|
||||
|
||||
@@ -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]))
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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))
|
||||
@@ -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"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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.",
|
||||
]
|
||||
|
||||
@@ -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"}
|
||||
]
|
||||
}
|
||||
@@ -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>
|
||||
Binary file not shown.
Binary file not shown.
@@ -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())
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
@@ -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:]))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
+66
-1188
File diff suppressed because it is too large.
Load diff
@@ -98,11 +98,17 @@ def assert_playwright_range() -> None:
|
||||
|
||||
if t(seal.playwright_min) <= t(have) <= t(seal.playwright_max):
|
||||
return
|
||||
# Spelled by the tool that installed this package (`invisible_core.installer`):
|
||||
# a written `pip install` is a command the venv the README makes does not have.
|
||||
from invisible_core.installer import install
|
||||
from invisible_core.pin import format_command
|
||||
|
||||
fix = format_command(install("invisible-playwright", f"playwright=={seal.playwright_max}"))
|
||||
msg = (f"playwright {have} is outside the range this engine was tested with "
|
||||
f"({seal.playwright_min} .. {seal.playwright_max}, from the seal for {seal.tag}).\n"
|
||||
f"The Juggler protocol schema is closed-world: an untested client can kill every "
|
||||
f"session at context creation.\n"
|
||||
f'Run: pip install "playwright=={seal.playwright_max}" '
|
||||
f"Run: {fix} "
|
||||
f"(or set INVISIBLE_PLAYWRIGHT_SKEW=allow to proceed anyway)")
|
||||
if os.environ.get("INVISIBLE_PLAYWRIGHT_SKEW") == "allow":
|
||||
warnings.warn(msg, RuntimeWarning, stacklevel=2)
|
||||
|
||||
@@ -15,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)
|
||||
@@ -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")
|
||||
@@ -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
@@ -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
|
||||
@@ -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))
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
Reference in new issue
Block a user