Skip to content

https://arxiv.org/abs/2606.28344. The end of web parsing. The beginning of scalable pixel-native search. link: https://pixelrag.ai/

36.7 KB
Raw Blame
"""The CDP backend for pixelshot — the single rendering backend.

No Playwright dependency — launches Chrome via subprocess and talks CDP over a
raw websocket. Two capture paths, selected by the Chrome binary:

- STANDARD (default, portable): standard ``Page.captureScreenshot`` (JPEG over CDP).
  Works on any stock Chrome, any OS. Used unless a turbo-capable Chrome is present.
- TURBO: delegates to ``fast_cdp`` (rawFilePath + /dev/shm + parallel JPEG), ~2x at
  batch scale. Used automatically when the pixelrag-installed patched ``headless_shell``
  is selected (``chrome.is_turbo_capable``) and the request matches its capabilities.

Selection is deterministic (by Chrome provenance), with no runtime probe — so a stock
Chrome is never sent the patched-only CDP params (which would hang).

Requirements: websockets, pillow (no playwright needed)

Usage:
    from pixelrag_render.backends.cdp import render_urls
    tile_dirs = render_urls(["https://example.com"], "./tiles", workers=4)
"""

import asyncio
import base64
import io
import json
import logging
import os
import shutil
import signal
import subprocess
import tempfile
import time
import urllib.request
from pathlib import Path

from PIL import Image

from ..chrome import sandbox_args
from .page_metrics import CONTENT_BOTTOM_JS, truncation_reason

logger = logging.getLogger("pixelrag_render.backends.cdp")

VIEWPORT_W = 875
VIEWPORT_H = 1080

# GPU rasterization: default OFF. Headless Chrome can't actually GPU-rasterize — it falls
# back to the software renderer and ignores these flags (no-op), so they never sped anything
# up (verified: enable == disable timing; the bottleneck is capture IPC, not rasterization).
# Worse, on a box that HAS a GPU device but no access to it (e.g. /dev/dri without the render
# group), Chrome tries the GPU, the GPU process crashes on init, and capture hangs. The
# `--enable-gpu-rasterization` pair was inherited from the initial release on the assumption
# it would help; it doesn't. Default to `--disable-gpu`; opt in with PIXELSHOT_ENABLE_GPU=1
# only on a real graphics-GPU box with device access.
_GPU_ARGS = (
    ["--enable-gpu-rasterization", "--force-gpu-rasterization"]
    if os.environ.get("PIXELSHOT_ENABLE_GPU")
    else ["--disable-gpu"]
)
BROWSER_ARGS = [
    "--disable-dev-shm-usage",
    *sandbox_args(),
    "--disable-renderer-backgrounding",
    "--disable-backgrounding-occluded-windows",
    "--disable-background-networking",
    "--disable-features=Translate,MediaRouter,OptimizationHints",
    *_GPU_ARGS,
]


def _find_chrome() -> str:
    from ..chrome import find_chrome

    return find_chrome()


async def _connect_cdp(port: int, retries: int = 5, delay: float = 1.0):
    """Connect to Chrome's CDP websocket endpoint."""
    import websockets

    for attempt in range(retries):
        try:
            data = urllib.request.urlopen(
                f"http://localhost:{port}/json", timeout=3
            ).read()
            targets = json.loads(data)
            # Pick a real page target — Chrome's built-in component extensions
            # (Cast/Media Router) expose background_page targets that show up
            # first in /json but never render navigations, hanging CDP capture.
            pages = [t for t in targets if t.get("type") == "page"] or targets
            ws = await websockets.connect(
                pages[0]["webSocketDebuggerUrl"],
                open_timeout=10,
                max_size=50 * 1024 * 1024,
            )
            return ws
        except Exception:
            if attempt < retries - 1:
                await asyncio.sleep(delay)
    raise ConnectionError(f"Failed to connect to Chrome on port {port}")


def _http_base_from_cdp_url(cdp_url: str) -> str:
    """Normalize a ``--cdp-url`` value to an http DevTools base ``http://host:port``.

    Accepts ``http://host:port`` (any path is ignored), ``ws://host:port/...``
    (scheme swapped to http, path dropped), or a bare ``host:port``.
    """
    from urllib.parse import urlparse

    p = urlparse(cdp_url if "//" in cdp_url else f"//{cdp_url}")
    netloc = p.netloc or p.path
    if not netloc:
        raise ValueError(f"Invalid --cdp-url: {cdp_url!r}")
    return f"http://{netloc}"


async def _connect_ws(ws_url: str):
    """Open a CDP websocket to an explicit ws URL (browser- or page-level)."""
    import websockets

    return await websockets.connect(ws_url, open_timeout=10, max_size=50 * 1024 * 1024)


def _fetch_json(url: str, cdp_url: str, timeout: float = 5):
    """GET ``url`` and parse JSON, mapping connection failures to a clear error.

    ``cdp_url`` is the user-facing endpoint, used only for the message so a bad
    or unreachable ``--cdp-url`` surfaces an actionable error instead of a raw
    URLError traceback.
    """
    try:
        data = urllib.request.urlopen(url, timeout=timeout).read()
        return json.loads(data)
    except Exception as e:
        raise RuntimeError(f"Could not reach CDP endpoint at {cdp_url}: {e}") from e


def _browser_ws_url(http_base: str, cdp_url: str) -> str:
    """Fetch the browser-level CDP websocket URL from ``/json/version``."""
    info = _fetch_json(f"{http_base}/json/version", cdp_url)
    try:
        return info["webSocketDebuggerUrl"]
    except (KeyError, TypeError) as e:
        raise RuntimeError(
            f"Could not reach CDP endpoint at {cdp_url}: "
            f"unexpected /json/version response (no webSocketDebuggerUrl)"
        ) from e


async def _page_ws_url_for_target(
    http_base: str, target_id: str, cdp_url: str, retries: int = 5, delay: float = 0.5
) -> str:
    """Resolve the page-level websocket URL for a freshly created ``targetId``.

    A freshly created target can momentarily be absent from ``/json``, so poll a
    few times (mirroring ``_connect_cdp``'s retry) before giving up. The blocking
    HTTP fetch runs in a thread so it doesn't block the event loop.
    """
    for attempt in range(retries):
        targets = await asyncio.to_thread(_fetch_json, f"{http_base}/json", cdp_url)
        for t in targets:
            if t.get("id") == target_id:
                return t["webSocketDebuggerUrl"]
        if attempt < retries - 1:
            await asyncio.sleep(delay)
    raise RuntimeError(f"Created target {target_id} not found in /json list")


async def _cdp_send(ws, msg_id_ref: list, method: str, params: dict | None = None):
    """Send a CDP command and wait for its response."""
    msg_id_ref[0] += 1
    mid = msg_id_ref[0]
    msg = {"id": mid, "method": method}
    if params:
        msg["params"] = params
    await ws.send(json.dumps(msg))
    while True:
        r = json.loads(await asyncio.wait_for(ws.recv(), timeout=180))
        if r.get("id") == mid:
            if "error" in r:
                raise RuntimeError(f"CDP error: {r['error']}")
            return r.get("result", {})


# Max time to wait for the `load` event (and for the optional network-idle wait)
# before giving up and capturing whatever is there. Keeps a hanging page from
# stalling a worker.
LOAD_TIMEOUT_MS = 12_000
# Web-font loads are allowed a short grace period, but must not stall a render:
# a server can leave a font response open indefinitely.
FONT_TIMEOUT_MS = 2_000
# The network is considered idle once at most NET_IDLE_MAX_INFLIGHT requests
# have been in flight for NET_QUIET_MS (Puppeteer's "networkidle2" semantics).
# Tolerating 2 in-flight requests is what makes this usable on arbitrary web
# pages: analytics beacons / long-polling keep 1-2 connections busy forever,
# and a strict zero-in-flight wait would sit at the hard cap on every such
# page. Content loads (SPA hydration, image sets) burst well past 2.
NET_QUIET_MS = 500
NET_IDLE_MAX_INFLIGHT = 2


class _NetIdleState:
    """networkidle2 bookkeeping over raw CDP frames.

    Feed every incoming CDP frame to :meth:`on_frame`; the state tracks the
    set of in-flight HTTP requests (``Network.requestWillBeSent`` opens one,
    ``Network.loadingFinished`` / ``Network.loadingFailed`` closes it) and
    whether the page has loaded (``Page.loadEventFired``). WebSocket traffic
    uses different CDP methods and is deliberately not counted, so persistent
    sockets never block readiness.

    The quiet clock runs whenever <= ``max_inflight`` requests are pending —
    including before load — so a page that is already quiet when `load` fires
    becomes ready immediately, with no mandatory post-load wait. Pure and
    clock-injected for testability; the async I/O lives in
    :func:`_wait_load_and_network_idle`.
    """

    _OPEN = "Network.requestWillBeSent"
    _CLOSE = ("Network.loadingFinished", "Network.loadingFailed")

    def __init__(
        self,
        now: float,
        *,
        max_inflight: int = NET_IDLE_MAX_INFLIGHT,
        quiet_ms: int = NET_QUIET_MS,
    ):
        self.max_inflight = max_inflight
        self.quiet_s = quiet_ms / 1000
        self.loaded = False
        self.inflight: set[str] = set()
        self.quiet_since: float | None = now  # nothing in flight at start

    def on_frame(self, msg: dict, now: float) -> None:
        method = msg.get("method")
        if method == "Page.loadEventFired":
            self.loaded = True
        elif method == self._OPEN:
            self.inflight.add(msg["params"]["requestId"])
        elif method in self._CLOSE:
            self.inflight.discard(msg["params"]["requestId"])
        else:
            return
        if len(self.inflight) <= self.max_inflight:
            if self.quiet_since is None:
                self.quiet_since = now
        else:
            self.quiet_since = None

    def ready(self, now: float) -> bool:
        return (
            self.loaded
            and self.quiet_since is not None
            and now - self.quiet_since >= self.quiet_s
        )

    def next_deadline(self, now: float) -> float | None:
        """Earliest future moment ready() could flip true, or None (event-bound)."""
        if self.loaded and self.quiet_since is not None:
            return self.quiet_since + self.quiet_s
        return None


async def _wait_load_and_network_idle(
    ws,
    msg_id_ref: list,
    *,
    max_inflight: int = NET_IDLE_MAX_INFLIGHT,
    quiet_ms: int = NET_QUIET_MS,
    cap_ms: int = LOAD_TIMEOUT_MS,
) -> None:
    """Wait until the page has loaded AND the network is networkidle2-quiet.

    Owns the websocket while it runs (the per-page CDP flow is sequential, so
    there is no competing reader) and feeds every frame to a
    :class:`_NetIdleState`. Returns when the state is ready or after
    ``cap_ms`` regardless, so a page that never settles (>2 permanently busy
    connections) can stall a worker for at most the cap — capture then
    proceeds with whatever is rendered, exactly like the load timeout.

    One frame race is tolerated by design: ``requestWillBeSent`` events emitted
    before this coroutine starts reading (during the ``Page.navigate``
    round-trip) are lost, which can only *under*-count in-flight requests. The
    document request itself is covered by the load gate — an initial
    ``document.readyState`` probe catches pages whose `load` fired before we
    started listening (e.g. instant file:// renders).
    """
    state = _NetIdleState(
        time.monotonic(), max_inflight=max_inflight, quiet_ms=quiet_ms
    )
    cap_deadline = time.monotonic() + cap_ms / 1000

    # readyState probe, sent raw so the frames that arrive while we wait for
    # its response are counted rather than discarded by _cdp_send's loop.
    msg_id_ref[0] += 1
    probe_id = msg_id_ref[0]
    await ws.send(
        json.dumps(
            {
                "id": probe_id,
                "method": "Runtime.evaluate",
                "params": {
                    "expression": "document.readyState",
                    "returnByValue": True,
                },
            }
        )
    )

    while True:
        now = time.monotonic()
        if state.ready(now) or now >= cap_deadline:
            return
        deadline = state.next_deadline(now)
        timeout = (
            cap_deadline if deadline is None else min(deadline, cap_deadline)
        ) - now
        try:
            frame = await asyncio.wait_for(ws.recv(), timeout=max(timeout, 0.001))
        except asyncio.TimeoutError:
            continue  # re-evaluate ready()/cap
        msg = json.loads(frame)
        if msg.get("id") == probe_id:
            try:
                if msg["result"]["result"]["value"] == "complete":
                    state.loaded = True
            except (KeyError, TypeError):
                pass
            continue
        state.on_frame(msg, time.monotonic())


def _readiness_expr() -> str:
    """Build the in-page readiness probe.

    Always waits for the `load` event before measuring (with a
    ``readyState === 'complete'`` shortcut so an already-loaded page returns
    immediately, and a hard timeout so a hanging page can't block). Without this,
    a client-rendered (SPA) page is measured/captured mid-hydration at a transient
    layout — often much taller than the settled page — producing blank tiles. SSR
    pages (e.g. Wikipedia) fire `load` almost immediately, so this adds ~no cost.

    Network-idle waiting is NOT done in-page: it runs Python-side over CDP
    Network events (see :func:`_wait_load_and_network_idle`), which can see
    in-flight requests — a PerformanceObserver only sees completions, so the
    old in-page variant reset its quiet timer on every analytics beacon and
    rode the hard cap on any page with sub-500ms background traffic.

    Returns an async-IIFE expression resolving to the page height to tile.
    """
    return f"""(async () => {{
        {CONTENT_BOTTOM_JS}
        await new Promise(res => {{
            if (document.readyState === 'complete') return res();
            const t = setTimeout(res, {LOAD_TIMEOUT_MS});
            window.addEventListener('load', () => {{ clearTimeout(t); res(); }}, {{ once: true }});
        }});
        await Promise.race([
            document.fonts.ready,
            new Promise(r => setTimeout(r, {FONT_TIMEOUT_MS})),
        ]);
        // Let layout settle over two frames — but cap it: requestAnimationFrame
        // never ticks in some headless modes (e.g. google-chrome --headless=new
        // with no compositor frames scheduled), where awaiting rAF would hang.
        await Promise.race([
            new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))),
            new Promise(r => setTimeout(r, 1000)),
        ]);
        document.documentElement.style.scrollBehavior = 'auto';
        const sh = document.documentElement.scrollHeight;
        const body = document.body;
        if (body) {{
            return Math.min(sh, Math.max(contentBottom(body), 1));
        }}
        return sh;
    }})()"""


# Before capturing a tile below the first one, scroll it into view and wait for
# its now-visible images to load. The capture clip uses absolute page coordinates,
# but Chrome only rasterizes content near the viewport — without scrolling, tiles
# past the first (e.g. on a small tile_height) come back blank. Mirrors fast_cdp.
_SCROLL_WAIT = """new Promise(resolve => {{
    window.scrollTo(0, {y});
    // Safety net: requestAnimationFrame may never tick in headless modes that
    // don't schedule frames, which would leave this promise unresolved.
    setTimeout(resolve, 1500);
    requestAnimationFrame(() => requestAnimationFrame(() => {{
        const imgs = Array.from(document.images).filter(i => {{
            if (i.complete) return false;
            const r = i.getBoundingClientRect();
            return r.bottom > 0 && r.top < window.innerHeight;
        }});
        if (imgs.length === 0) return resolve();
        const timeout = new Promise(r => setTimeout(r, 500));
        const loaded = Promise.all(imgs.map(i => new Promise(r => {{
            i.addEventListener('load', r, {{once: true}});
            i.addEventListener('error', r, {{once: true}});
        }})));
        Promise.race([loaded, timeout]).then(resolve);
    }}));
}})"""


async def capture_url(
    ws,
    msg_id_ref: list,
    url: str,
    tile_dir: Path,
    *,
    tile_h: int = 8192,
    quality: int = 85,
    viewport_w: int = VIEWPORT_W,
    image_format: str = "jpeg",
    from_surface: bool = True,
    wait_network_idle: bool = False,
    extract_text: bool = False,
) -> int:
    """Capture a URL as tiled images via direct CDP websocket.

    Returns the number of tiles written.
    """
    tile_dir.mkdir(parents=True, exist_ok=True)

    await _cdp_send(ws, msg_id_ref, "Page.navigate", {"url": url})

    # Optional networkidle2 wait, done Python-side over CDP Network events so
    # it can see in-flight requests (and therefore tolerate persistent
    # analytics/long-poll connections). Must run before the in-page probe:
    # frames arriving during a _cdp_send round-trip are discarded, so the
    # watcher has to be the socket's reader while the page settles.
    if wait_network_idle:
        await _wait_load_and_network_idle(ws, msg_id_ref)

    # Wait for load + fonts + layout to stabilize, return the page height to
    # tile in one call. See _readiness_expr.
    result = await _cdp_send(
        ws,
        msg_id_ref,
        "Runtime.evaluate",
        {
            "expression": _readiness_expr(),
            "awaitPromise": True,
            "returnByValue": True,
        },
    )
    try:
        page_height = int(result["result"]["value"])
    except (KeyError, TypeError, ValueError):
        page_height = 0
    # A zero/negative height is as much a probe failure as a missing one, and
    # would otherwise tile nothing at all while still claiming success.
    height_measured = page_height > 0
    if not height_measured:
        page_height = tile_h

    tiles = []
    y = 0
    idx = 0

    while y < page_height:
        clip_h = min(tile_h, page_height - y)
        if clip_h <= 0:
            break

        # Scroll the tile into view so Chrome rasterizes it (tiles past the first
        # are otherwise blank). The top tile is already in view after load.
        if idx > 0:
            try:
                await _cdp_send(
                    ws,
                    msg_id_ref,
                    "Runtime.evaluate",
                    {"expression": _SCROLL_WAIT.format(y=y), "awaitPromise": True},
                )
            except Exception:
                pass

        params = {
            "format": image_format,
            "fromSurface": from_surface,
            "optimizeForSpeed": True,
            "clip": {
                "x": 0,
                "y": y,
                "width": viewport_w,
                "height": clip_h,
                "scale": 1,
            },
        }
        if image_format == "jpeg":
            params["quality"] = quality

        result = await _cdp_send(ws, msg_id_ref, "Page.captureScreenshot", params)

        img_bytes = base64.b64decode(result["data"])
        tile_path = (
            tile_dir / f"tile_{idx:04d}.{'jpg' if image_format == 'jpeg' else 'png'}"
        )

        if clip_h < tile_h:
            img = Image.open(io.BytesIO(img_bytes))
            w, h = img.size
            if h > clip_h:
                img = img.crop((0, 0, w, clip_h))
            img.save(
                tile_path, "JPEG" if image_format == "jpeg" else "PNG", quality=quality
            )
        else:
            tile_path.write_bytes(img_bytes)

        tiles.append(tile_path.name)
        idx += 1
        y += tile_h

    reason = truncation_reason(page_height, tile_h, measured=height_measured)
    if reason:
        logger.warning(
            "%s: %s — capturing what is on screen and marking the manifest incomplete",
            url,
            reason,
        )

    manifest = {
        "url": url,
        "page_height": page_height,
        # The geometry the capture ran at. Recorded so a consumer reading
        # tiles.json later can redo the page_height/tile_height comparison
        # itself instead of being told the tile height out of band.
        "tile_height": tile_h,
        "viewport_width": viewport_w,
        "tiles": tiles,
        "complete": reason is None,
    }
    with open(tile_dir / "tiles.json", "w") as f:
        json.dump(manifest, f)

    # Extract page text alongside tiles (hybrid output mode)
    if extract_text:
        try:
            text_result = await _cdp_send(
                ws,
                msg_id_ref,
                "Runtime.evaluate",
                {"expression": "document.body.innerText", "returnByValue": True},
            )
            page_text = text_result.get("result", {}).get("value", "")
            if page_text:
                with open(tile_dir / "text.md", "w") as f:
                    f.write(f"# {url}\n\n{page_text}\n")
        except Exception:
            # Best-effort: the tiles are the primary output and are already
            # written, so a failed text probe must not fail the capture.
            logger.warning("%s: page text extraction failed", url, exc_info=True)

    return len(tiles)


async def _setup_page(
    ws, msg_id_ref: list, viewport_w: int, tile_height: int, wait_network_idle: bool
):
    """Enable the CDP domains and fix the viewport for a page ws before capture."""
    await _cdp_send(ws, msg_id_ref, "Page.enable")
    if wait_network_idle:
        # The networkidle2 watcher (_wait_load_and_network_idle) counts
        # Network.requestWillBeSent / loadingFinished / loadingFailed events;
        # without this domain enabled Chrome emits none of them.
        await _cdp_send(ws, msg_id_ref, "Network.enable")
    await _cdp_send(
        ws,
        msg_id_ref,
        "Emulation.setDeviceMetricsOverride",
        {
            "width": viewport_w,
            "height": tile_height,
            "deviceScaleFactor": 1,
            "mobile": False,
        },
    )


async def _drain_queue(
    ws,
    msg_id_ref: list,
    work_queue: asyncio.Queue,
    output_dir: Path,
    tile_height: int,
    quality: int,
    viewport_w: int,
    image_format: str,
    from_surface: bool,
    wait_network_idle: bool,
    extract_text: bool,
    worker_id: int,
    stats: dict,
    results: list,
):
    """Pull URLs off the queue and capture each through ``ws`` until it's empty.

    Shared by the launch (``_worker``) and attach (``_attached_worker``) paths —
    they differ only in how ``ws`` is obtained, not in how work is processed.
    """
    while True:
        try:
            item = work_queue.get_nowait()
        except asyncio.QueueEmpty:
            break

        url = item["url"]
        stem = item["stem"]
        tile_dir = output_dir / f"{stem}.png.tiles"

        t0 = time.monotonic()
        try:
            n_tiles = await capture_url(
                ws,
                msg_id_ref,
                url,
                tile_dir,
                tile_h=tile_height,
                quality=quality,
                viewport_w=viewport_w,
                image_format=image_format,
                from_surface=from_surface,
                wait_network_idle=wait_network_idle,
                extract_text=extract_text,
            )
            stats["done"] += 1
            elapsed = time.monotonic() - t0
            logger.info("[w%d] %s → %d tiles (%.1fs)", worker_id, url, n_tiles, elapsed)
            results.append(tile_dir)
        except Exception as e:
            stats["failed"] += 1
            logger.warning("[w%d] FAIL %s: %s", worker_id, url, str(e)[:200])


async def _worker(
    chrome_path: str,
    port: int,
    work_queue: asyncio.Queue,
    output_dir: Path,
    tile_height: int,
    quality: int,
    viewport_w: int,
    image_format: str,
    from_surface: bool,
    wait_network_idle: bool,
    extract_text: bool,
    worker_id: int,
    stats: dict,
    results: list,
):
    """Async worker: owns a Chrome process, pulls URLs from queue."""
    # Isolated profile per worker. Without --user-data-dir, a launch on a machine that
    # already has Chrome open forwards to the running instance (default profile) instead
    # of starting this headless renderer — navigation/screenshot then hang forever. A
    # unique dir also stops parallel workers from colliding on one profile. See issue #54.
    user_data_dir = tempfile.mkdtemp(prefix=f"pixelshot_chrome_{port}_")
    proc = subprocess.Popen(
        # `--headless=new`: the bare `--headless` is deprecated and hangs on modern
        # Chrome (e.g. google-chrome 149); `=new` works on both stock Chrome and the
        # patched headless_shell.
        [
            chrome_path,
            f"--remote-debugging-port={port}",
            "--headless=new",
            f"--user-data-dir={user_data_dir}",
        ]
        + BROWSER_ARGS
        + ["about:blank"],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )

    try:
        await asyncio.sleep(3)
        ws = await _connect_cdp(port)
        msg_id_ref = [0]

        await _setup_page(ws, msg_id_ref, viewport_w, tile_height, wait_network_idle)
        await _drain_queue(
            ws,
            msg_id_ref,
            work_queue,
            output_dir,
            tile_height,
            quality,
            viewport_w,
            image_format,
            from_surface,
            wait_network_idle,
            extract_text,
            worker_id,
            stats,
            results,
        )
        await ws.close()
    finally:
        proc.send_signal(signal.SIGTERM)
        try:
            proc.wait(timeout=5)
        except subprocess.TimeoutExpired:
            proc.kill()
        shutil.rmtree(user_data_dir, ignore_errors=True)


def _derive_stems(urls: list[str], stems: list[str] | None) -> list[str]:
    """Output-dir stem per URL (explicit stems win; else sanitize the URL).

    Shared by the standard and turbo paths so both emit identical
    ``{stem}.png.tiles`` directory names for the same inputs.
    """
    from urllib.parse import urlparse

    out: list[str] = []
    seen: dict[str, int] = {}
    for i, url in enumerate(urls):
        if stems and i < len(stems):
            out.append(str(stems[i]))
            continue
        parsed = urlparse(url)
        raw = (parsed.netloc + parsed.path).rstrip("/")
        stem = (
            raw.replace("/", "_").replace(":", "_").replace("?", "_").replace("&", "_")
        )
        stem = stem[:200] or "page"
        count = seen.get(stem, 0)
        seen[stem] = count + 1
        if count > 0:
            stem = f"{stem}_{count}"
        out.append(stem)
    return out


async def _run_batch(
    urls: list[str],
    output_dir: Path,
    num_workers: int,
    tile_height: int,
    quality: int,
    viewport_w: int,
    image_format: str,
    from_surface: bool,
    wait_network_idle: bool,
    extract_text: bool,
    stems: list[str] | None,
    chrome_path: str,
) -> list[Path]:
    work_queue: asyncio.Queue = asyncio.Queue()
    stem_list = _derive_stems(urls, stems)
    for url, stem in zip(urls, stem_list):
        work_queue.put_nowait({"url": url, "stem": stem})

    stats = {"done": 0, "failed": 0}
    results: list[Path] = []
    base_port = 9400

    actual_workers = min(num_workers, len(urls))
    workers = [
        _worker(
            chrome_path,
            base_port + wid,
            work_queue,
            output_dir,
            tile_height,
            quality,
            viewport_w,
            image_format,
            from_surface,
            wait_network_idle,
            extract_text,
            wid,
            stats,
            results,
        )
        for wid in range(actual_workers)
    ]
    await asyncio.gather(*workers, return_exceptions=True)

    logger.info("Batch complete: done=%d failed=%d", stats["done"], stats["failed"])
    return results


async def _attached_worker(
    http_base: str,
    browser_ws_url: str,
    cdp_url: str,
    work_queue: asyncio.Queue,
    output_dir: Path,
    tile_height: int,
    quality: int,
    viewport_w: int,
    image_format: str,
    from_surface: bool,
    wait_network_idle: bool,
    extract_text: bool,
    worker_id: int,
    stats: dict,
    results: list,
):
    """Async worker that attaches to an already-running browser over CDP.

    Mirrors ``_worker`` but, instead of launching a throwaway ``--headless``
    process, creates its own fresh tab (target) in the existing browser, drives
    only that tab, and closes only that tab on teardown. The browser's profile
    — cookies, logins — is whatever the running instance has, so authenticated
    pages render. Never touches the user's other tabs; never kills the browser.
    """
    browser_ws = await _connect_ws(browser_ws_url)
    bmsg = [0]
    target_id = None
    try:
        created = await _cdp_send(
            browser_ws, bmsg, "Target.createTarget", {"url": "about:blank"}
        )
        target_id = created["targetId"]
        ws = await _connect_ws(
            await _page_ws_url_for_target(http_base, target_id, cdp_url)
        )
        msg_id_ref = [0]

        await _setup_page(ws, msg_id_ref, viewport_w, tile_height, wait_network_idle)
        await _drain_queue(
            ws,
            msg_id_ref,
            work_queue,
            output_dir,
            tile_height,
            quality,
            viewport_w,
            image_format,
            from_surface,
            wait_network_idle,
            extract_text,
            worker_id,
            stats,
            results,
        )
        await ws.close()
    finally:
        # Close only the tab we created; leave the browser and its other tabs alone.
        if target_id is not None:
            try:
                await _cdp_send(
                    browser_ws, bmsg, "Target.closeTarget", {"targetId": target_id}
                )
            except Exception:
                pass
        await browser_ws.close()


async def _run_batch_attached(
    urls: list[str],
    output_dir: Path,
    num_workers: int,
    tile_height: int,
    quality: int,
    viewport_w: int,
    image_format: str,
    from_surface: bool,
    wait_network_idle: bool,
    extract_text: bool,
    stems: list[str] | None,
    cdp_url: str,
) -> list[Path]:
    http_base = _http_base_from_cdp_url(cdp_url)
    browser_ws_url = _browser_ws_url(http_base, cdp_url)

    work_queue: asyncio.Queue = asyncio.Queue()
    stem_list = _derive_stems(urls, stems)
    for url, stem in zip(urls, stem_list):
        work_queue.put_nowait({"url": url, "stem": stem})

    stats = {"done": 0, "failed": 0}
    results: list[Path] = []

    # One fresh tab per worker against the single shared browser — no extra
    # processes, no interference with the user's existing tabs.
    actual_workers = min(num_workers, len(urls))
    workers = [
        _attached_worker(
            http_base,
            browser_ws_url,
            cdp_url,
            work_queue,
            output_dir,
            tile_height,
            quality,
            viewport_w,
            image_format,
            from_surface,
            wait_network_idle,
            extract_text,
            wid,
            stats,
            results,
        )
        for wid in range(actual_workers)
    ]
    await asyncio.gather(*workers, return_exceptions=True)

    logger.info(
        "Batch complete (attached): done=%d failed=%d", stats["done"], stats["failed"]
    )
    return results


def render_urls(
    urls: list[str],
    output_dir: str | Path,
    *,
    stems: list[str] | None = None,
    tile_height: int = 8192,
    quality: int = 85,
    viewport_width: int = VIEWPORT_W,
    workers: int = 4,
    image_format: str = "jpeg",
    from_surface: bool = True,
    wait_network_idle: bool = False,
    extract_text: bool = False,
    turbo: bool | None = None,
    chrome_path: str | None = None,
    cdp_url: str | None = None,
) -> list[Path]:
    """Render URLs to tiled images via CDP.

    Uses the TURBO path (fast_cdp: rawFilePath + parallel JPEG) when a turbo-capable
    patched Chrome is present and the request matches its capture profile; otherwise
    the portable STANDARD path. Both emit ``{stem}.png.tiles/`` with a tiles.json.

    Args:
        urls: URLs to capture.
        output_dir: Output directory for tile subdirectories.
        stems: Optional output directory name per URL.
        tile_height: Max tile height in pixels (default 8192).
        quality: JPEG quality 1-100 (default 85).
        viewport_width: Browser viewport width (default 875).
        workers: Number of parallel Chrome processes (default 4).
        image_format: 'jpeg' or 'png' (default 'jpeg').
        from_surface: CDP fromSurface param. True for batch (throughput),
                      False for serve (low latency). Default True.
        wait_network_idle: After the load event, also wait until the network has
                      been quiet (~500ms) before capturing (SPAs that fetch after
                      load). Standard path only; off by default.
        turbo: None = auto (turbo when the Chrome is turbo-capable), True/False to
                      force. Turbo only applies to the default capture profile
                      (jpeg, default viewport, fromSurface, no network-idle wait);
                      other options always use the standard path.
        chrome_path: Path to Chrome binary. Auto-detected if None. Ignored when
                      ``cdp_url`` is set (no browser is launched).
        cdp_url: DevTools endpoint of an already-running browser (e.g.
                      ``http://127.0.0.1:9222``). When set (or via the
                      ``PIXELSHOT_CDP_URL`` env var), pixelshot attaches to that
                      browser and renders in a fresh tab using its existing
                      session (cookies/logins) instead of launching a throwaway
                      headless instance. Forces the standard path (no turbo) and
                      needs no local Chrome binary.

    Returns:
        List of Path objects for created tile directories.
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    if not urls:
        return []

    cdp_url = cdp_url or os.environ.get("PIXELSHOT_CDP_URL")
    if cdp_url:
        logger.info("Attaching to existing browser at %s", cdp_url)
        return asyncio.run(
            _run_batch_attached(
                urls,
                output_dir,
                workers,
                tile_height,
                quality,
                viewport_width,
                image_format,
                from_surface,
                wait_network_idle,
                extract_text,
                stems,
                cdp_url,
            )
        )

    chrome = chrome_path or _find_chrome()

    # Turbo only covers fast_cdp's capture profile; anything else → standard path.
    from ..chrome import is_turbo_capable

    use_turbo = is_turbo_capable(chrome) if turbo is None else turbo
    if use_turbo and (
        image_format != "jpeg"
        or viewport_width != VIEWPORT_W
        or wait_network_idle
        or extract_text
        or not from_surface
    ):
        if extract_text:
            # Same trade as wait_network_idle below: say so rather than
            # letting --extract-text silently produce no text.md.
            logger.info(
                "extract_text is set: using the standard capture path "
                "(the turbo path does not implement text extraction yet)"
            )
        if wait_network_idle:
            # Be loud about the trade: users with a turbo-capable Chrome would
            # otherwise silently lose ~half their capture throughput.
            logger.info(
                "wait_network_idle is set: using the standard capture path "
                "(the turbo path does not implement the idle wait yet)"
            )
        use_turbo = False

    if use_turbo:
        from .fast_cdp import render_articles

        stem_list = _derive_stems(urls, stems)

        # path "{stem}.png" makes fast_cdp emit "{stem}.png.tiles" — the same
        # layout the standard path / CLI / index pipeline expect. fast_cdp prepends
        # file:// to non-http inputs, so hand it a plain path for file:// URIs.
        def _navtarget(u: str) -> str:
            if u.startswith("http"):
                return u
            return u.removeprefix("file://")

        articles = [
            {"path": f"{stem}.png", "file": _navtarget(url)}
            for stem, url in zip(stem_list, urls)
        ]
        logger.info("Using turbo (fast_cdp) path for %d URL(s)", len(urls))
        asyncio.run(
            render_articles(
                articles,
                str(output_dir),
                chrome_path=chrome,
                n_workers=workers,
                tile_height=tile_height,
                jpeg_quality=quality,
            )
        )
        return [output_dir / f"{stem}.png.tiles" for stem in stem_list]

    return asyncio.run(
        _run_batch(
            urls,
            output_dir,
            workers,
            tile_height,
            quality,
            viewport_width,
            image_format,
            from_surface,
            wait_network_idle,
            extract_text,
            stems,
            chrome,
        )
    )