diff --git a/AGENTS.md b/AGENTS.md index 71353a1..6deba16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1537,7 +1537,13 @@ CLI, unit tests (24) + integration tests (2). `check_requirements()` deliberately **always returns ok**: `run_bridges()` aborts *all* bridges when one's requirements fail and this dependency is optional, so a missing Playwright/browser must be a per-call `503` (with an - install hint), never take down simplex/llm/nextcloud. Playwright's sync API is + install hint), never take down simplex/llm/nextcloud. Install is + `scripts/bootstrap.sh --browser`; when `playwright install` fails (notably on a + host with an IPv6 address but no global IPv6 route — Playwright's downloader + forces `autoSelectFamily` + a dual-stack resolver that prefers IPv6 and hangs + instead of falling back to IPv4), bootstrap falls back to + `scripts/playwright-browsers.py`, which fetches the same pinned artifacts over + IPv4 and lays them out where Playwright expects. Playwright's sync API is bound to its creating thread and the bridge serves each request on a new one, so the driver runs the **async** API on one dedicated event-loop thread and serializes whole operations behind an `asyncio.Lock`, submitting coroutines diff --git a/README.md b/README.md index a754ccc..8140657 100644 --- a/README.md +++ b/README.md @@ -854,6 +854,10 @@ screenshot, and click/fill/press/select to complete a flow. It is the first bridge with a heavy optional dependency, so it is **disabled by default** and installed with `scripts/bootstrap.sh --browser` (Playwright + Chromium land under `.runtime/browser`; the bridge sets `PLAYWRIGHT_BROWSERS_PATH` there at launch). +If `playwright install` fails — notably on a host with an IPv6 address but no +global IPv6 route, where Playwright's downloader prefers IPv6 and hangs — +bootstrap falls back to `scripts/playwright-browsers.py`, which downloads the +same pinned artifacts over IPv4. Unlike the others it owns a browser and keeps a **persistent profile** (`.runtime/browser/profile`) so a login you do once survives across calls and restarts — the browser analog of the SimpleX bridge owning its own daemon diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 2af1736..55f79ea 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -384,8 +384,22 @@ PY )" case "$BROWSER_ENGINE" in chromium|firefox|webkit) ;; *) BROWSER_ENGINE=chromium ;; esac echo "== downloading Playwright browser '$BROWSER_ENGINE' into $BROWSERS" - PLAYWRIGHT_BROWSERS_PATH="$BROWSERS" "$PYTHON" -m playwright install "$BROWSER_ENGINE" \ - || echo "WARN: playwright browser download failed; re-run: PLAYWRIGHT_BROWSERS_PATH=$BROWSERS $PYTHON -m playwright install $BROWSER_ENGINE" >&2 + if ! PLAYWRIGHT_BROWSERS_PATH="$BROWSERS" "$PYTHON" -m playwright install "$BROWSER_ENGINE"; then + echo "WARN: 'playwright install' failed" >&2 + if [[ "$BROWSER_ENGINE" = chromium ]]; then + # Playwright's own downloader prefers IPv6 (autoSelectFamily + a custom + # dual-stack resolver) and can hang on a host that has an IPv6 address but + # no working global IPv6 route, even though the CDN serves over IPv4. The + # helper fetches the same pinned artifacts over IPv4 and lays them out + # where Playwright expects them, so the install becomes a no-op. + echo "== retrying over IPv4 (scripts/playwright-browsers.py)" >&2 + PLAYWRIGHT_BROWSERS_PATH="$BROWSERS" "$PYTHON" "$REPO_ROOT/scripts/playwright-browsers.py" \ + --browsers-path "$BROWSERS" --engine "$BROWSER_ENGINE" \ + || echo "WARN: browser priming failed; re-run: $PYTHON scripts/playwright-browsers.py --browsers-path $BROWSERS" >&2 + else + echo "WARN: re-run: PLAYWRIGHT_BROWSERS_PATH=$BROWSERS $PYTHON -m playwright install $BROWSER_ENGINE" >&2 + fi + fi fi # --- stage 4: GGUF -------------------------------------------------------------- diff --git a/scripts/playwright-browsers.py b/scripts/playwright-browsers.py new file mode 100755 index 0000000..3b8b745 --- /dev/null +++ b/scripts/playwright-browsers.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Prime Playwright's browser cache over IPv4 (a fallback for `playwright install`). + +`playwright install` downloads through Playwright's own Node fetcher, which +forces `autoSelectFamily` with a custom dual-stack resolver that prefers IPv6. +On a host that has an IPv6 address (often a ULA) but no working global IPv6 +route, that first IPv6 connection hangs instead of falling back to IPv4, so the +download stalls until the socket timeout and `playwright install` fails even +though the CDN is reachable over IPv4. + +This helper downloads the exact pinned artifacts Playwright expects, forcing +IPv4, and lays them out under `PLAYWRIGHT_BROWSERS_PATH` with the +`INSTALLATION_COMPLETE` marker Playwright checks, so the normal install (and the +browser bridge) then works. It reads revisions/versions from the installed +Playwright's own `browsers.json`, so it tracks version bumps automatically. + +Idempotent: an artifact with its marker present is skipped. Only Chromium (plus +its headless shell and ffmpeg) is handled; Firefox/WebKit have no such helper. + +Usage: + scripts/playwright-browsers.py --browsers-path .runtime/browser + scripts/playwright-browsers.py --browsers-path .runtime/browser --engine chromium +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import shutil +import stat +import subprocess +import sys +import tempfile +import urllib.request +import zipfile +from pathlib import Path + +#: The CDN mirror Playwright's fetcher falls back to and that serves the exact +#: Chrome-for-Testing layout over a redirect (IPv4 works). +CDN = "https://cdn.playwright.dev" + +#: Executables that must stay executable after a pure-Python unzip (which does +#: not preserve permissions). Relative to each browser's directory. +_EXECUTABLES = { + "chromium": ("chrome-linux64/chrome",), + "chromium_headless_shell": ("chrome-headless-shell-linux64/chrome-headless-shell",), + "ffmpeg": ("ffmpeg-linux",), +} + + +def _arch_suffix() -> str: + machine = platform.machine().lower() + return "arm64" if machine in ("aarch64", "arm64") else "x64" + + +def _cft_paths(arch: str) -> dict[str, str]: + if arch == "arm64": + return { + "chromium": "linux-arm64/chrome-linux-arm64.zip", + "chromium_headless_shell": "linux-arm64/chrome-headless-shell-linux-arm64.zip", + "ffmpeg": "ffmpeg-linux-arm64.zip", + } + return { + "chromium": "linux64/chrome-linux64.zip", + "chromium_headless_shell": "linux64/chrome-headless-shell-linux64.zip", + "ffmpeg": "ffmpeg-linux.zip", + } + + +def _browsers_json() -> dict: + import playwright # the package the venv already has + + path = Path(playwright.__file__).resolve().parent / "driver" / "package" / "browsers.json" + with open(path) as handle: + return json.load(handle) + + +def _artifacts(browsers_json: dict, arch: str) -> list[tuple[str, str]]: + """List of `(directory_name, download_path)` Playwright expects.""" + suffixes = _cft_paths(arch) + wanted = { + "chromium": ("chromium", "chromium"), + "chromium-headless-shell": ("chromium_headless_shell", "chromium_headless_shell"), + "ffmpeg": ("ffmpeg", "ffmpeg"), + } + out: list[tuple[str, str]] = [] + for browser in browsers_json.get("browsers", []): + name = browser.get("name") + if name not in wanted or not browser.get("installByDefault", True): + continue + slug, key = wanted[name] + revision = browser["revision"] + if key == "ffmpeg": + path = f"builds/ffmpeg/{revision}/{suffixes['ffmpeg']}" + else: + path = f"builds/cft/{browser['browserVersion']}/{suffixes[key]}" + out.append((f"{slug}-{revision}", path)) + return out + + +def _download(url: str, dest: str) -> None: + if shutil.which("curl"): + subprocess.run( + ["curl", "-4", "-fL", "--retry", "3", "-m", "600", "-o", dest, url], + check=True, + ) + return + # No curl: urllib may pick IPv6 on a broken host, but it is the best we have. + print(f" (curl not found; using urllib for {url})", flush=True) + request = urllib.request.Request(url, headers={"User-Agent": "semif-bootstrap"}) + with urllib.request.urlopen(request, timeout=600) as response, open(dest, "wb") as handle: + shutil.copyfileobj(response, handle) + + +def _extract(archive: str, target: Path, directory_name: str) -> None: + if shutil.which("unzip"): + subprocess.run(["unzip", "-q", "-o", archive, "-d", str(target)], check=True) + else: + with zipfile.ZipFile(archive) as zf: + zf.extractall(target) + for relative in _EXECUTABLES.get(directory_name.split("-")[0], ()): + candidate = target / relative + if candidate.is_file(): + candidate.chmod(candidate.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def _install_one(browsers_path: Path, directory_name: str, download_path: str) -> bool: + target = browsers_path / directory_name + marker = target / "INSTALLATION_COMPLETE" + if marker.is_file(): + print(f" = {directory_name} already installed") + return True + url = f"{CDN}/{download_path}" + print(f" + {directory_name} <- {url}") + target.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="semif-browser-") as tmp: + archive = os.path.join(tmp, "download.zip") + _download(url, archive) + _extract(archive, target, directory_name) + marker.write_text("") + return True + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Prime Playwright's browser cache over IPv4.") + parser.add_argument("--browsers-path", required=True, help="PLAYWRIGHT_BROWSERS_PATH to populate") + parser.add_argument("--engine", default="chromium", help="only 'chromium' is supported by this helper") + args = parser.parse_args(argv) + + if args.engine != "chromium": + print(f"helper only primes chromium, not {args.engine!r}; nothing to do", file=sys.stderr) + return 0 + + browsers_path = Path(args.browsers_path).expanduser().resolve() + browsers_path.mkdir(parents=True, exist_ok=True) + arch = _arch_suffix() + artifacts = _artifacts(_browsers_json(), arch) + if not artifacts: + print("no chromium artifacts found in playwright's browsers.json", file=sys.stderr) + return 1 + + print(f"priming Playwright browsers into {browsers_path} ({arch}, IPv4)") + for directory_name, download_path in artifacts: + _install_one(browsers_path, directory_name, download_path) + print("done; 'playwright install chromium' should now be a no-op") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())