From b840bc991798ae3899f0ebd02420811790f736ae Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Sun, 15 Nov 2026 16:50:46 +0300 Subject: [PATCH] browser: add page.wait_for_change for canvas apps Signed-off-by: dawn <90008@klbr.net> --- priv/python/albedo_plugins/browser/page.py | 82 +++++++++++- priv/python/albedo_plugins/browser/pixels.py | 105 +++++++++++++++ .../extensions/browser/extension.gleam | 5 +- test/e2e/browser_test.py | 120 +++++++++++++++++- test/harness/browser_pixels_test.py | 39 ++++++ 5 files changed, 346 insertions(+), 5 deletions(-) create mode 100644 priv/python/albedo_plugins/browser/pixels.py create mode 100644 test/harness/browser_pixels_test.py diff --git a/priv/python/albedo_plugins/browser/page.py b/priv/python/albedo_plugins/browser/page.py index a98fb7474..73d74a954 100644 --- a/priv/python/albedo_plugins/browser/page.py +++ b/priv/python/albedo_plugins/browser/page.py @@ -20,7 +20,7 @@ from typing import Any, TYPE_CHECKING from albedo_plugins.hook import reported -from . import hooks, javascript as js, paths +from . import hooks, javascript as js, paths, pixels from .capture import CaptureLimits, FrameSession, Reference, capture_frames from .errors import ( ActionOutcomeUnknown, @@ -50,6 +50,12 @@ if TYPE_CHECKING: from .transport import CDPSession, JSON, positive +# CALIBRATION frames learn how much each block moves on its own, then FLOOR frames measure the noise floor. +CALIBRATION = 4 +FLOOR = 3 +CALIBRATION_STEP = 0.2 + + def now() -> str: return datetime.now(timezone.utc).isoformat() @@ -873,6 +879,80 @@ class Page: last_coverage=last_coverage, ) from exc + async def wait_for_change( + self, + region: tuple[float, float, float, float] | None = None, + *, + min_change: float = 0.02, + timeout: float = 30, + interval: float = 0.5, + tolerance: float = 24, + ) -> JSON: + """Wait until min_change of region, a fraction of its area, looks different. + + region is (x, y, width, height) in viewport coordinates, default the + whole viewport. The region is compared in blocks of 8 page pixels or + more, so dither and one-pixel shimmer average out. The first two + seconds measure how much of it moves on its own, and that noise floor is + added to min_change. Choose a region larger than what you wait for, so + the fraction is steady. Returns the seconds waited and the fraction + changed. + """ + positive(timeout, "timeout") + positive(interval, "interval") + if not 0 < min_change < 1: + raise ValueError("min_change must be a fraction between 0 and 1") + if not 0 <= tolerance < 255: + raise ValueError("tolerance must be from 0 to 255") + self._check() + started = time.monotonic() + metrics = await self.cdp.send("Page.getLayoutMetrics") + viewport = metrics.get("cssLayoutViewport", metrics["layoutViewport"]) + clip = self._region(region, viewport, 1) + clip["scale"] = pixels.scale(clip["width"], clip["height"]) + params: JSON = {"format": "png", "fromSurface": True, "clip": clip} + + async def capture() -> list[tuple[float, ...]]: + shot = await self.cdp.send("Page.captureScreenshot", params) + return pixels.blocks(base64.b64decode(shot["data"])) + + def changed(blocks: list[tuple[float, ...]]) -> float: + moved = pixels.difference(first, blocks) + return sum(m > limit for m, limit in zip(moved, limits)) / len(moved) + + most, floor = 0.0, None + try: + async with asyncio.timeout(timeout): + first = await capture() + noise = [0.0] * len(first) + for _ in range(CALIBRATION): + await asyncio.sleep(CALIBRATION_STEP) + moved = pixels.difference(first, await capture()) + noise = list(map(max, noise, moved)) + limits = [n + tolerance for n in noise] + floor = 0.0 + for _ in range(FLOOR): + await asyncio.sleep(CALIBRATION_STEP) + floor = max(floor, changed(await capture())) + while True: + await asyncio.sleep(interval) + fraction = changed(await capture()) + most = max(most, fraction) + if fraction >= floor + min_change: + return { + "waited": round(time.monotonic() - started, 2), + "changed": round(fraction, 4), + "noise_floor": round(floor, 4), + } + except TimeoutError as exc: + measured = "unmeasured" if floor is None else f"{floor:.1%}" + raise WaitTimeout( + f"Region did not change enough: max change {most:.1%}," + f" noise floor {measured}, wanted {min_change:.1%}.", + region=region, + timeout=timeout, + ) from exc + async def _hit(self, cdp: CDPSession, x: float, y: float, viewport: JSON) -> JSON: # DOM hit testing uses document coordinates; Input uses viewport coordinates. try: diff --git a/priv/python/albedo_plugins/browser/pixels.py b/priv/python/albedo_plugins/browser/pixels.py new file mode 100644 index 000000000..4a08b3e4a --- /dev/null +++ b/priv/python/albedo_plugins/browser/pixels.py @@ -0,0 +1,105 @@ +"""Coarse pixel comparison of screenshots, with the standard library only. + +Decodes 8-bit, non-interlaced gray, gray+alpha, RGB and RGBA PNGs, which is +what Chrome captures; palette, 16-bit and interlaced images raise ValueError. +""" + +from __future__ import annotations + +import math +import struct +import zlib + +CHANNELS = {0: 1, 2: 3, 4: 2, 6: 4} +# Pixels per block side. At half scale Chrome averages each 2x2 itself, so a +# block covers 8 page pixels or more and dither inside it cancels out. +BLOCK = 4 +# Most pixels one comparison captures: about 10 ms to decode and average. +SAMPLES = 40_000 + + +def scale(width: float, height: float) -> float: + return min(0.5, math.sqrt(SAMPLES / (width * height))) + + +def decode(png: bytes) -> tuple[int, int, int, bytes]: + """Width, height, channels per pixel and raw rows of an 8-bit PNG.""" + if png[:8] != b"\x89PNG\r\n\x1a\n" or png[12:16] != b"IHDR": + raise ValueError("not a PNG") + width, height, depth, colour, _, _, interlace = struct.unpack( + ">IIBBBBB", png[16:29] + ) + if depth != 8 or colour not in CHANNELS or interlace: + raise ValueError("only 8-bit, non-interlaced, non-palette PNGs decode here") + at, data = 8, bytearray() + while at + 8 <= len(png): + size, chunk = struct.unpack(">I4s", png[at : at + 8]) + if chunk == b"IDAT": + data += png[at + 8 : at + 8 + size] + at += 12 + size + raw = zlib.decompress(data) + step = CHANNELS[colour] + stride = width * step + out = bytearray(stride * height) + prior = bytearray(stride) + for y in range(height): + start = y * (stride + 1) + method = raw[start] + row = bytearray(raw[start + 1 : start + 1 + stride]) + if method == 1: + for i in range(step, stride): + row[i] = (row[i] + row[i - step]) & 255 + elif method == 2: + for i in range(stride): + row[i] = (row[i] + prior[i]) & 255 + elif method == 3: + for i in range(stride): + left = row[i - step] if i >= step else 0 + row[i] = (row[i] + ((left + prior[i]) >> 1)) & 255 + elif method == 4: + for i in range(stride): + a = row[i - step] if i >= step else 0 + b = prior[i] + c = prior[i - step] if i >= step else 0 + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + row[i] = ( + row[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c) + ) & 255 + out[y * stride : (y + 1) * stride] = row + prior = row + return width, height, step, bytes(out) + + +def blocks(png: bytes) -> list[tuple[float, ...]]: + """Mean colour of each BLOCK x BLOCK square, row by row, alpha ignored.""" + width, height, step, pixels = decode(png) + colours = 3 if step >= 3 else 1 + stride = width * step + means = [] + for top in range(0, height, BLOCK): + rows = range(top, min(top + BLOCK, height)) + for left in range(0, width, BLOCK): + right = min(left + BLOCK, width) + count = len(rows) * (right - left) + means.append( + tuple( + sum( + sum( + pixels[ + y * stride + left * step + c : y * stride + + right * step : step + ] + ) + for y in rows + ) + / count + for c in range(colours) + ) + ) + return means + + +def difference(a: list[tuple[float, ...]], b: list[tuple[float, ...]]) -> list[float]: + """How far each block's colour moved, in 0-255 channel units.""" + return [max(abs(x - y) for x, y in zip(p, q)) for p, q in zip(a, b)] diff --git a/src/albedo/harness/extensions/browser/extension.gleam b/src/albedo/harness/extensions/browser/extension.gleam index e9f506d67..6f55e21b0 100644 --- a/src/albedo/harness/extensions/browser/extension.gleam +++ b/src/albedo/harness/extensions/browser/extension.gleam @@ -13,7 +13,10 @@ pub fn extension() -> extension.Extension { <> " await page.click(node), await page.fill(node, text)," <> " await page.type(text, ref=node) inserts at the caret of node, or without ref of whatever has focus (a canvas app's hidden text box, say)," <> " await page.select(node, value), await page.hover(node or (x, y)), await page.press(key, count=1)," - <> " await page.wait_for(...), and await page.screenshot(clip=(x, y, width, height), scale=1) (clip in viewport coordinates; scale=3 enlarges small text)." + <> " await page.wait_for(role=..., name=...) for the accessibility tree," + <> " await page.wait_for_change((x, y, width, height), min_change=0.02, timeout=30) until that fraction of a viewport region looks different (canvas apps), returning {waited, changed, noise_floor};" + <> " shimmer and dither seen in its first two seconds are discounted. Pick a region larger than what you wait for (a small one makes the fraction jumpy) and estimate min_change from a screenshot: a bus entering is ~10% of the frame, a changed text line under 1%;" + <> " and await page.screenshot(clip=(x, y, width, height), scale=1) (clip in viewport coordinates; scale=3 enlarges small text)." <> " browser.find(snapshot, ...) and browser.one(snapshot, ...) locate nodes in an observation." <> " Use await page.click((x, y)) for coordinates, await page.drag(start, end, steps=20) for drags (observed nodes or viewport points)," <> " and await page.click_text(text) for a unique button/link whose accessible name contains text; none or several raises SelectionError." diff --git a/test/e2e/browser_test.py b/test/e2e/browser_test.py index 1e213cd65..d1a97304d 100644 --- a/test/e2e/browser_test.py +++ b/test/e2e/browser_test.py @@ -277,16 +277,87 @@ document.querySelector('canvas').onmousemove = e => { window.pointer = [e.offset """ +# Every frame redraws random black and white noise, and the bus is a solid block. +NOISE = """
""" + +# A retro shader: a slowly swaying scene in 1-bit Bayer dither, so dither +# crawls along every edge, and the bus is a dark patch of the same dither. +DITHER = """""" + +# Each frame lights a fresh 10% of the blocks, so some always flicker that +# calibration never saw: a noise floor of about 6%. +TWINKLE = """""" + +# The bus covers 8% of the region (16% on TWINKLE). The wait must outlast the +# noise, then end. Calibration is 8 captures, and a loaded machine can take +# 0.4 s for each, so every change below waits 8 s to land after it. +BUS_ARRIVES = """ +waiting = asyncio.create_task(page.wait_for_change((0, 0, 400, 300), timeout=30)) +await asyncio.sleep(8) +assert not waiting.done(), waiting +await page.evaluate('window.bus = true; return true') +result = await waiting +""" + + class BrowserCanvasTests(unittest.TestCase): - def browse(self, code): - """Run code against a fresh page on CANVAS; it prints 'passed' when done.""" + def browse(self, code, html=CANVAS): + """Run code against a fresh page on html; it prints 'passed' when done.""" require_chrome(self) cell = f""" import urllib.parse b = await browser.spawn() try: page = await b.new_page() - await page.goto('data:text/html,' + urllib.parse.quote({CANVAS!r})) + await page.goto('data:text/html,' + urllib.parse.quote({html!r})) {textwrap.indent(code, " ")} print('passed') finally: @@ -353,4 +424,47 @@ centre = await page.evaluate( " pen.drawImage(image, 0, 0); return [...pen.getImageData(20, 20, 1, 1).data]; })()" ) assert centre == [255, 0, 0, 255], centre +""") + + def test_wait_for_change_waits_through_random_noise_for_the_bus(self): + self.browse(BUS_ARRIVES, NOISE) + + def test_wait_for_change_waits_through_ordered_dither_for_the_bus(self): + self.browse(BUS_ARRIVES, DITHER) + + def test_wait_for_change_counts_min_change_above_the_noise_floor(self): + self.browse( + BUS_ARRIVES + "assert result['noise_floor'] >= 0.03, result\n", TWINKLE + ) + + def test_wait_for_change_sees_a_small_change_in_a_quiet_region(self): + self.browse(""" +waiting = asyncio.create_task(page.wait_for_change((0, 0, 120, 80), timeout=30)) +await asyncio.sleep(8) +await page.evaluate("pen.fillStyle = 'blue'; pen.fillRect(40, 24, 16, 16); return true") +result = await waiting +assert 0.02 <= result['changed'] < 0.1, result +""") + + def test_wait_for_change_holds_to_min_change_and_says_what_it_saw(self): + self.browse(""" +import re +from albedo_plugins.browser import WaitTimeout +async def half(min_change, timeout): + waiting = asyncio.create_task(page.wait_for_change((0, 0, 160, 80), min_change=min_change, timeout=timeout)) + await asyncio.sleep(8) + await page.evaluate("pen.fillStyle = 'blue'; pen.fillRect(0, 0, 80, 80); return true") + try: + return await waiting + finally: + await page.evaluate('pen.clearRect(0, 0, 160, 80); return true') +try: + await half(0.6, 11) +except WaitTimeout as error: + message = 'max change 50.0%, noise floor 0.0%, wanted 60.0%' + assert message in str(error), error +else: + raise AssertionError('half the region met min_change=0.6') +result = await half(0.4, 30) +assert result['changed'] == 0.5, result """) diff --git a/test/harness/browser_pixels_test.py b/test/harness/browser_pixels_test.py new file mode 100644 index 000000000..9fb3260fd --- /dev/null +++ b/test/harness/browser_pixels_test.py @@ -0,0 +1,39 @@ +"""Screenshot pixels for wait_for_change: a channel Chrome rarely emits.""" + +import struct +import sys +import unittest +import zlib +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "priv" / "python")) + +from albedo_plugins.browser import pixels # noqa: E402 + + +def png(colour, rows): + def chunk(kind, data): + body = kind + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) + + header = struct.pack(">IIBBBBB", len(rows[0]) // 2, len(rows), 8, colour, 0, 0, 0) + data = b"".join(b"\x00" + bytes(row) for row in rows) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(data)) + + chunk(b"IEND", b"") + ) + + +class PixelsTest(unittest.TestCase): + def test_gray_alpha_blocks_compare_gray_only(self): + # One gray level under two alphas: the same colour, seen twice. + opaque = png(4, [[90, 255] * 4] * 4) + clear = png(4, [[90, 0] * 4] * 4) + self.assertEqual(pixels.blocks(opaque), [(90.0,)]) + self.assertEqual(pixels.blocks(opaque), pixels.blocks(clear)) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1