engine-test: WebKit tuning runs (base, cache-viewer, mem500, no-page-cache, related, hw-never, gsk-gl partial); refshot.py (S029 WIP); S039 R5-14 caret box

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 23:36:57 -06:00
commit aabbd00a5e
4 changed files with 1353 additions and 4 deletions

View file

@ -10,6 +10,7 @@
# The run focuses an empty workspace on ENGINE_MONITOR (default DP-1), samples ENGINE_BASELINE seconds (default 15)
# with no browser, starts the browser, maximizes its column (the same window size for all three), then goes through
# sites.txt (settle per site), idles ENGINE_IDLE seconds (default 60) with every tab open and quits.
# ENGINE_ARGS adds arguments to webkit_shell.py (its tuning flags).
# Ad blocking is off and tab freezing/unloading is off in both Nacres, so all three load the same pages and keep
# every tab live. Proxies are unset; the real runtime dir is kept for the Wayland and audio sockets only.
set -u
@ -62,7 +63,7 @@ chromium)
;;
webkit)
"${envs[@]}" python3 "$here/webkit_shell.py" --plan "$sites" --out "$out" --idle "$idle" \
--output "$monitor" >"$out/browser.log" 2>&1 &
--output "$monitor" ${ENGINE_ARGS:-} >"$out/browser.log" 2>&1 &
;;
*) echo "run: unknown engine $engine" >&2; exit 2 ;;
esac

View file

@ -0,0 +1,7 @@
# short plan for WebKit tuning checks: the four tabs that went blank in the first run plus two that worked
01-yt-home https://www.youtube.com/ 15
02-yt-watch https://www.youtube.com/watch?v=aqz-KE-bpKQ 25 play
03-yt-search https://www.youtube.com/results?search_query=big+buck+bunny 15
04-discord https://discord.com/login 15
05-reddit https://www.reddit.com/ 15
09-ddg https://duckduckgo.com/?q=web+browser+engine 15

View file

@ -6,7 +6,10 @@ Usage:
webkit_shell.py --plan sites.txt --out DIR open the plan's sites one by one (driver mode, see run.sh)
Window 1556x815 (a maximized niri column on the 1600x900 monitor, the size the Nacre windows get), ephemeral
network session (no profile on disk), default hardware acceleration policy. In driver mode, for each line of
network session (no profile on disk), default hardware acceleration policy. Tuning flags (each off by default):
--related (tabs share the first tab's web process), --mem-limit MB (memory pressure settings on the web context and
the network session), --cache-model viewer|browser|docbrowser, --no-page-cache, --hw always|never, --ua chrome
(a Chrome 140 Linux user agent); GSK_RENDERER in the environment picks GTK's renderer. In driver mode, for each line of
the plan (`label url settle_seconds`) it writes the label to DIR/mark, opens the URL in a new tab, waits the settle
time (with `play`: 10 s in, saves check-<label>-pre.json and starts the first video if it is paused), saves a check (title, readiness, video state) to DIR/check-<label>.json, pauses any video and takes a screenshot
of the screen output with grim (DIR/<label>.png); after the last site it writes `idle`, waits IDLE seconds
@ -29,6 +32,10 @@ CHECK_JS = """JSON.stringify({title: document.title, ready: document.readyState,
videos: [...document.querySelectorAll('video')].map(v => ({t: v.currentTime, paused: v.paused,
rs: v.readyState, err: v.error && v.error.code, w: v.videoWidth}))})"""
PLAY_JS = "var v = document.querySelector('video'); if (v && v.paused) { v.muted = true; v.play(); } 0"
CACHE_MODELS = {"viewer": WebKit.CacheModel.DOCUMENT_VIEWER, "browser": WebKit.CacheModel.WEB_BROWSER,
"docbrowser": WebKit.CacheModel.DOCUMENT_BROWSER}
CHROME_UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 "
"Safari/537.36")
PAUSE_JS = "document.querySelectorAll('video').forEach(v => v.pause()); 0"
@ -39,15 +46,38 @@ def main():
ap.add_argument("--out")
ap.add_argument("--idle", type=int, default=60)
ap.add_argument("--output", default="DP-1", help="monitor grim captures")
ap.add_argument("--related", action="store_true")
ap.add_argument("--mem-limit", type=int)
ap.add_argument("--cache-model", choices=list(CACHE_MODELS))
ap.add_argument("--no-page-cache", action="store_true")
ap.add_argument("--hw", choices=["always", "never"])
ap.add_argument("--ua", choices=["chrome"])
a = ap.parse_args()
app = Gtk.Application(application_id=None)
pressure = None
if a.mem_limit:
pressure = WebKit.MemoryPressureSettings.new()
pressure.set_memory_limit(a.mem_limit)
WebKit.NetworkSession.set_memory_pressure_settings(pressure) # before the session is made
session = WebKit.NetworkSession.new_ephemeral()
context = WebKit.WebContext(memory_pressure_settings=pressure) if pressure else WebKit.WebContext.get_default()
if a.cache_model:
context.set_cache_model(CACHE_MODELS[a.cache_model])
settings = WebKit.Settings(enable_developer_extras=True)
if a.no_page_cache:
settings.set_enable_page_cache(False)
if a.hw:
settings.set_hardware_acceleration_policy(getattr(WebKit.HardwareAccelerationPolicy, a.hw.upper()))
if a.ua:
settings.set_user_agent(CHROME_UA)
views = []
def new_tab(notebook, url):
view = WebKit.WebView(network_session=session)
view.get_settings().set_enable_developer_extras(True)
if a.related and views:
view = WebKit.WebView(related_view=views[0], settings=settings)
else:
view = WebKit.WebView(network_session=session, web_context=context, settings=settings)
label = Gtk.Label(label=url[:30])
view.connect("notify::title", lambda v, _p: label.set_label((v.get_title() or url)[:30]))
i = notebook.append_page(view, label)

135
tools/refshot.py Executable file
View file

@ -0,0 +1,135 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = "==3.12.*"
# dependencies = ["PyQt6==6.9.1", "PyQt6-WebEngine==6.9.0"]
# ///
"""Reference shot (D-030): load a URL in Chromium (QtWebEngine) and save the page as a PNG at a given size.
Usage: tools/refshot.py <url> <out.png> [--size 1280x720] [--wait 5] [--waitfor <js expr> [--timeout 60]]
[--js <expr>] [--scroll <px>] [--light] [--ua <string>]
--size the page's viewport in CSS pixels (match Nacre's page area, not its whole window)
--wait seconds to let the page run after it loaded (and after --waitfor gave true)
--waitfor poll this expression until it is truthy; a timeout is reported, the shot is still taken
--js run this after the wait; its result (JSON) is printed and written next to the shot as <out>.json
--scroll scroll the page by this many pixels before the shot
--light prefer-color-scheme light (default dark, like Nacre's default theme)
--ua user agent (default: QtWebEngine's, without the QtWebEngine token, so sites see plain Chrome)
Runs offscreen (no window) with an off-the-record profile (nothing kept) and software GL; uv makes a cached
venv with PyQt6 + PyQt6-WebEngine on first use, no system packages needed. Direct connections only (no proxy).
Exit 0 when the shot was written, 1 on load failure or timeout (the shot is still written when possible).
"""
import argparse
import json
import os
import re
import sys
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS",
"--disable-gpu --autoplay-policy=no-user-gesture-required --no-proxy-server")
os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1")
from PyQt6.QtCore import QSize, Qt, QTimer, QUrl # noqa: E402
from PyQt6.QtGui import QGuiApplication # noqa: E402
from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineSettings # noqa: E402
from PyQt6.QtWebEngineWidgets import QWebEngineView # noqa: E402
from PyQt6.QtWidgets import QApplication # noqa: E402
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("url")
ap.add_argument("out")
ap.add_argument("--size", default="1280x720")
ap.add_argument("--wait", type=float, default=5)
ap.add_argument("--waitfor")
ap.add_argument("--timeout", type=float, default=60)
ap.add_argument("--js")
ap.add_argument("--scroll", type=int, default=0)
ap.add_argument("--light", action="store_true")
ap.add_argument("--ua")
a = ap.parse_args()
w, h = (int(n) for n in a.size.lower().split("x"))
app = QApplication(sys.argv[:1])
hints = QGuiApplication.styleHints()
if hasattr(hints, "setColorScheme"):
hints.setColorScheme(Qt.ColorScheme.Light if a.light else Qt.ColorScheme.Dark)
profile = QWebEngineProfile(app) # no storage name: off the record, nothing written
profile.setHttpUserAgent(a.ua or re.sub(r" ?QtWebEngine/\S+", "", profile.httpUserAgent()))
page = QWebEnginePage(profile, app)
s = page.settings()
s.setAttribute(QWebEngineSettings.WebAttribute.PlaybackRequiresUserGesture, False)
s.setAttribute(QWebEngineSettings.WebAttribute.ScreenCaptureEnabled, False)
view = QWebEngineView()
view.setPage(page)
view.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen)
view.resize(QSize(w, h))
view.show()
state = {"rc": 0, "loaded": False}
def log(msg: str) -> None:
print(f"refshot: {msg}", flush=True)
def finish() -> None:
def shot(result=None) -> None:
if a.js is not None:
print(json.dumps(result), flush=True)
with open(os.path.splitext(a.out)[0] + ".json", "w") as f:
json.dump(result, f)
img = view.grab()
if img.isNull() or not img.save(a.out):
log("could not save the shot")
state["rc"] = 1
else:
log(f"wrote {a.out} ({img.width()}x{img.height()})")
app.quit()
def after_wait() -> None:
if a.js is not None:
page.runJavaScript(a.js, 0, shot)
else:
shot()
if a.scroll:
page.runJavaScript(f"window.scrollBy(0, {a.scroll})")
QTimer.singleShot(int(a.wait * 1000), after_wait)
def poll(left: float) -> None:
def got(v) -> None:
if v:
finish()
elif left <= 0:
log(f"waitfor timed out: {a.waitfor}")
state["rc"] = 1
finish()
else:
QTimer.singleShot(500, lambda: poll(left - 0.5))
page.runJavaScript(a.waitfor, 0, got)
def loaded(ok: bool) -> None:
if state["loaded"]:
return # later loads (in-page navigations, redirects) are part of the same visit
state["loaded"] = True
if not ok:
log("load failed")
state["rc"] = 1
if a.waitfor:
poll(a.timeout)
else:
finish()
page.loadFinished.connect(loaded)
# A page that never finishes loading is shot anyway.
QTimer.singleShot(int((a.timeout + 60) * 1000), lambda: (log("load timed out"), state.update(rc=1), loaded(True)))
page.load(QUrl(a.url))
app.exec()
return state["rc"]
if __name__ == "__main__":
sys.exit(main())