From 50fb5a50caac48e78aae4dddae0a9c23150a2347 Mon Sep 17 00:00:00 2001 From: Randy Date: Fri, 9 Oct 2026 23:03:43 +0800 Subject: [PATCH] fix(cdp): a slow link no longer drops the attached browser mid-call On a remote `--attach` over a slow, jittery link (tailnet relay, 0.3-1 s RTT), agent scripts intermittently died with `TargetClosedError: Target page, context or browser has been closed`, and the rebind then failed with `'NoneType' object has no attribute 'new_page'`. The tab stayed alive and the daemon logged nothing. Root cause: the facade bridge's upstream websocket used websockets' own keepalive (ping_interval=20, ping_timeout=20). A pong travels behind the data, so one large CDP reply (a ~1.5 MB aria snapshot) on a slow link holds it back past 20 s although bytes arrive the whole time. websockets then closed the bridge with 1011, silently; Playwright saw its whole browser disconnect. The executor then treated "my connection dropped" as "my tab died": it cleared the live tab from the ledger, re-bound on a context that no longer existed (None.new_page) and recycled itself, losing `state`. - ws_liveness: upstream CDP websockets (facade bridge and CdpUpstream) are declared dead only when no byte at all has arrived for 20 s after a ping; bytes are counted at the transport, since the big reply is one message. Idle connections are still pinged. - facade: every bridge end is logged with both sides' close frames. - executor: a TargetClosedError caused by a disconnected Browser keeps the tab binding and `state`, tells the agent to retry, and reconnects to the same tab on the next call. E2E (tests/daemon/e2e/test_cdp_attach_slow_link.py, artifact cdp-attach-slow-link.json) reproduces both halves locally with a jittery, 30 KB/s TCP forwarder in front of Chrome for Testing plus target churn on a second connection; both tests fail on main with the field signature and pass here. Co-Authored-By: Claude --- src/browserwright/_executor/process.py | 36 +- src/browserwright/daemon/server/facade.py | 37 +- src/browserwright/daemon/server/upstream.py | 13 +- .../daemon/server/ws_liveness.py | 77 +++++ tests/daemon/e2e/test_cdp_attach_slow_link.py | 319 ++++++++++++++++++ .../test_coverage_server_listener_sweep.py | 2 +- 6 files changed, 473 insertions(+), 11 deletions(-) create mode 100644 src/browserwright/daemon/server/ws_liveness.py create mode 100644 tests/daemon/e2e/test_cdp_attach_slow_link.py diff --git a/src/browserwright/_executor/process.py b/src/browserwright/_executor/process.py index 622feb7..86acffd 100644 --- a/src/browserwright/_executor/process.py +++ b/src/browserwright/_executor/process.py @@ -809,7 +809,8 @@ def _on_facade_dead(self, browser: Any | None = None) -> None: return sys.stderr.write( f"executor {self._session_id}: facade transport dropped " - "(daemon restart?); will reconnect on the next call\n") + "(daemon restart, or the link to the browser); will reconnect on " + "the next call\n") self._connected = False self._facade_death_handler = None self._facade_daemon_pid = None @@ -1003,6 +1004,20 @@ def _target_closed_response( outcomes, no loop. """ sid = self._session_id or "" + if self._transport_lost(): + # Not the tab: the executor's connection to the browser is gone, + # and with it every Page and the context. Rebinding here would run + # on no context, and forgetting the binding would abandon a tab + # that is still alive. The next call reconnects and re-binds the + # SAME tab (`_ensure_connected`), with `state` intact. + error["fix"] = ( + "the executor's connection to the browser dropped mid-call " + "(the tab itself was not closed). It reconnects to the same " + "tab on the next call and `state` is kept — RETRY the call. " + "Do not create a new session; if this repeats, check the link " + "to the browser (`browserwright-daemon` log names why the " + "connection ended).") + return self._finish(buf, error=error, exit_code=exit_code) failure: str | None = None try: if not self._rebind_dead_page(): @@ -1034,6 +1049,25 @@ def _target_closed_response( ) return self._finish(buf, error=error, exit_code=exit_code) + def _transport_lost(self) -> bool: + """Is the Playwright Browser disconnected from the cdp surface? + + A dropped connection closes every Page at once, so the call fails with + the same TargetClosedError a dead tab produces. Playwright usually + dispatched ``disconnected`` while the failing call pumped events; if it + has not yet, its ``is_connected()`` already reads False and the armed + handler is run here.""" + if not self._connected: + return True + is_connected = getattr(self._browser, "is_connected", None) + try: + alive = bool(is_connected()) if callable(is_connected) else True + except Exception: # noqa: BLE001 - a failed probe is disconnected + alive = False + if not alive: + self._on_facade_dead(self._browser) + return not alive + @staticmethod def _exec_with_return(code: str, globals_: dict[str, Any]) -> str | None: """Exec ``code``; if the LAST statement is a bare expression, return its diff --git a/src/browserwright/daemon/server/facade.py b/src/browserwright/daemon/server/facade.py index c6031bc..8b829ab 100644 --- a/src/browserwright/daemon/server/facade.py +++ b/src/browserwright/daemon/server/facade.py @@ -68,7 +68,7 @@ from ..config import (DEFAULT_FACADE_PORT, LOOPBACK_HOST, Config, needs_loopback_cobind) from .. import __version__ -from .._net import proxy_toward +from .._net import proxy_toward, redact_url from ..errors import Unavailable from ..resolver import resolve as resolve_upstream from ..._executor.protocol import _MAX_FRAME @@ -76,6 +76,7 @@ from .exec_relay import serve_exec_relay from .facade_extension import ExtensionFacadeBridge from .relay import RelayServer +from .ws_liveness import connect_kwargs as liveness_kwargs, keep_alive logger = logging.getLogger(__name__) @@ -669,31 +670,37 @@ async def _bridge(self, client: ServerConnection, upstream_url: str, Transparent: no id/sessionId rewriting (unlike the agent Router) — a Playwright client owns the whole browser-level CDP namespace on its own dedicated upstream connection, so Target.*/Browser.* responses and - events flow back unmodified.""" + events flow back unmodified. + + The upstream leg's keepalive is `ws_liveness`, not websockets' own: + on a slow remote link a pong stuck behind one big reply used to close + this bridge mid-transfer, which the Playwright client can only read as + its whole browser closing.""" upstream = await websockets.connect( upstream_url, max_size=100 * 1024 * 1024, compression=None, - ping_interval=20, - ping_timeout=20, # Exactly the session's proxy, or None for direct — never # websockets' default of reading the daemon's http_proxy/all_proxy, # which broke LAN / Tailscale / CloakBrowser upstreams (#20). The # CLI that opened the session resolved it from its own environment # (#136); per-page proxying is still Chrome's own business. proxy=proxy_toward(upstream_url, proxy), + **liveness_kwargs(), ) c2u = asyncio.create_task(self._pump(client, upstream, "c->u")) u2c = asyncio.create_task(self._pump(upstream, client, "u->c")) + alive = asyncio.create_task( + keep_alive(upstream, label="facade bridge upstream")) try: await asyncio.wait( {c2u, u2c}, return_when=asyncio.FIRST_COMPLETED) finally: - # Cancel + await BOTH pumps unconditionally. This runs on the normal + # Cancel + await every task unconditionally. This runs on the normal # FIRST_COMPLETED path AND when stop() cancels the handler task while # it's suspended in asyncio.wait above (where the `for pending` # cleanup would otherwise be skipped, orphaning the pump tasks). - for t in (c2u, u2c): + for t in (c2u, u2c, alive): t.cancel() # CancelledError is a BaseException; suppress it explicitly so a # cancelled pump doesn't escape this cleanup. @@ -703,6 +710,12 @@ async def _bridge(self, client: ServerConnection, upstream_url: str, await upstream.close() with contextlib.suppress(Exception): await client.close() + # The client sees this as its browser disconnecting, so say which + # side ended it: nothing else in the daemon log would. + logger.info( + "facade: bridge to %s ended (upstream %s, client %s)", + redact_url(upstream_url), _close_summary(upstream), + _close_summary(client)) @staticmethod async def _pump(src, dst, label: str) -> None: @@ -717,6 +730,18 @@ async def _pump(src, dst, label: str) -> None: return +def _close_summary(conn: Any) -> str: + """`sent 1011 'keepalive timeout', received none` for one ws side.""" + def frame(close: Any) -> str: + if close is None: + return "none" + return f"{int(close.code)} {close.reason!r}" + + protocol = getattr(conn, "protocol", None) + return (f"sent {frame(getattr(protocol, 'close_sent', None))}, " + f"received {frame(getattr(protocol, 'close_rcvd', None))}") + + #: ADR-0011 name for what this class now is. `PlaywrightFacade` stays as the #: class's own name (it is spelled in a lot of call sites and tests), but new #: code should read `EndpointServer` — the object serves three surfaces, only diff --git a/src/browserwright/daemon/server/upstream.py b/src/browserwright/daemon/server/upstream.py index d27d9ec..5637952 100644 --- a/src/browserwright/daemon/server/upstream.py +++ b/src/browserwright/daemon/server/upstream.py @@ -26,6 +26,7 @@ from websockets.exceptions import ConnectionClosed from .._net import proxy_hint, proxy_toward, redact_url +from .ws_liveness import connect_kwargs as liveness_kwargs, keep_alive logger = logging.getLogger(__name__) @@ -211,6 +212,7 @@ def __init__( self._ws: websockets.ClientConnection | None = None # type: ignore[name-defined] self._reader_task: asyncio.Task | None = None self._heartbeat_task: asyncio.Task | None = None + self._keepalive_task: asyncio.Task | None = None self._next_internal_id = _DAEMON_ID_BASE self._pending_internal: dict[int, asyncio.Future] = {} self._ws_url: str | None = None @@ -358,11 +360,12 @@ async def open(self, ws_url: str | None = None, *, # The CLI that opened the session resolved it from its own # environment; the facade bridge uses the same value. (#20, #136) "proxy": proxy, - # Keep the upstream alive with ws-level pings; CDP-level + # ws-level liveness is `ws_liveness.keep_alive` (started below): + # websockets' own keepalive closes a working connection when a + # pong is stuck behind a big reply on a slow link. CDP-level # Browser.getVersion heartbeat is layered on top for protocol # liveness. - "ping_interval": 20, - "ping_timeout": 20, + **liveness_kwargs(), } try: self._ws = await asyncio.wait_for( @@ -381,6 +384,8 @@ async def open(self, ws_url: str | None = None, *, self._ws_url = ws_url self._reader_task = asyncio.create_task(self._reader_loop()) self._heartbeat_task = asyncio.create_task(self._heartbeat_loop()) + self._keepalive_task = asyncio.create_task(keep_alive( + self._ws, label=f"{self.backend_name} upstream")) if lifecycle: # Tell Chrome to gossip about all targets so the router can keep # its target table without the client having to enable it. @@ -985,6 +990,8 @@ async def close(self, *, code: int = 1000, reason: str = "") -> None: self._reader_task.cancel() if self._heartbeat_task is not None: self._heartbeat_task.cancel() + if self._keepalive_task is not None: + self._keepalive_task.cancel() ws = self._ws self._ws = None for fut in self._pending_internal.values(): diff --git a/src/browserwright/daemon/server/ws_liveness.py b/src/browserwright/daemon/server/ws_liveness.py new file mode 100644 index 0000000..8f072b0 --- /dev/null +++ b/src/browserwright/daemon/server/ws_liveness.py @@ -0,0 +1,77 @@ +"""Keepalive for the daemon's upstream CDP websockets. + +websockets' built-in keepalive declares a connection dead when one pong is late +by ``ping_timeout``. A pong travels in the same TCP stream as the data, behind +it. On a slow link — an attached browser across a tailnet relay at 0.3-1 s RTT +and a few hundred KB/s — one large CDP reply (an aria snapshot of a big page, a +screenshot) can hold the pong back for longer than that, although bytes are +arriving the whole time. The built-in keepalive then closes a working +connection with 1011. On the cdp surface that is the Playwright client's whole +browser: every Page reports "Target page, context or browser has been closed" +while the tab itself is fine. + +So the verdict here is "nothing at all has arrived": any inbound byte counts as +proof of life, and the ping is only how a quiet connection gets something to +arrive. Bytes, not messages: that one big reply is a single message that takes +the whole transfer to complete. Pings still go out on idle connections, so NAT +and proxy idle timers stay fed. + +Open a connection with :func:`connect_kwargs` and run :func:`keep_alive` on it. +""" +from __future__ import annotations + +import asyncio +import logging +import time +from typing import Any + +from websockets.asyncio.client import ClientConnection +from websockets.exceptions import ConnectionClosed + +logger = logging.getLogger(__name__) + +#: Ping a connection that has been quiet this long. +KEEPALIVE_INTERVAL = 20.0 +#: Close it once it has been silent — not one byte in — this long after a ping. +KEEPALIVE_TIMEOUT = 20.0 + + +class TrackedConnection(ClientConnection): + """A client connection that records when bytes last arrived.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.last_inbound = time.monotonic() + + def data_received(self, data: bytes) -> None: + self.last_inbound = time.monotonic() + super().data_received(data) + + +def connect_kwargs() -> dict[str, Any]: + """`websockets.connect` options that hand liveness to :func:`keep_alive`.""" + return {"ping_interval": None, "create_connection": TrackedConnection} + + +async def keep_alive(ws: TrackedConnection, *, label: str, + interval: float = KEEPALIVE_INTERVAL, + timeout: float = KEEPALIVE_TIMEOUT) -> None: + """Run until ``ws`` closes, as its only keepalive.""" + try: + while True: + await asyncio.sleep(interval) + if time.monotonic() - ws.last_inbound < interval: + continue + sent = time.monotonic() + pong = await ws.ping() + while not pong.done(): + remaining = max(sent, ws.last_inbound) + timeout - time.monotonic() + if remaining <= 0: + logger.warning( + "%s: nothing received for %.0fs after a ping; " + "closing the connection", label, timeout) + await ws.close(code=1011, reason="keepalive timeout") + return + await asyncio.wait({pong}, timeout=remaining) + except (ConnectionClosed, asyncio.CancelledError): + return diff --git a/tests/daemon/e2e/test_cdp_attach_slow_link.py b/tests/daemon/e2e/test_cdp_attach_slow_link.py new file mode 100644 index 0000000..80545df --- /dev/null +++ b/tests/daemon/e2e/test_cdp_attach_slow_link.py @@ -0,0 +1,319 @@ +"""cdp --attach to a browser across a slow, jittery link. + +Field symptom (an attached browser over a tailnet relay, 0.3-1 s RTT): a fixed +`goto -> snapshot -> fill -> click` script intermittently died with +`TargetClosedError: ... Target page, context or browser has been closed`, and +the in-place rebind then failed with `'NoneType' object has no attribute +'new_page'`. The tab stayed alive and the daemon logged nothing. + +Two defects, one scenario each: + +1. The facade bridge's upstream websocket ran websockets' own keepalive: one + pong late by 20 s closed it with 1011. A pong travels behind the data, so a + large reply on a slow link (here a ~1.5 MB aria snapshot at 30 KB/s) delays + it past that although frames arrive the whole time. Playwright saw its + browser disconnect. +2. The executor then treated "my connection dropped" as "my tab died": it + cleared the session's (live) tab from the ledger and re-bound on a context + that no longer existed, then recycled itself and lost `state`. + +The rig, all on this machine: the test Chrome reached through a TCP forwarder +that delays every chunk by a random 100-500 ms and caps throughput, plus a +client on its own direct CDP connection that keeps creating, activating and +closing a background target while the agent script runs (the shape of the +field's probe / popups). Artifact: `cdp-attach-slow-link.json`. +""" +from __future__ import annotations + +import asyncio +import json +import os +import random +import subprocess +import sys +import threading +import time +from pathlib import Path + +import websockets + +from .conftest import TEST_CDP_PORT, published_endpoint, scrubbed_env + +_BS_HOME = Path(__file__).resolve().parent / "_bs_home" / "cdp" +_PROXY_VARS = ("http_proxy", "https_proxy", "all_proxy", "no_proxy", + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY") + + +class _SlowLink: + """127.0.0.1: -> the test Chrome. Every chunk is delayed by a random + ``lo``-``hi`` seconds (order kept per direction) and, with ``rate``, + throughput is capped at that many bytes/s per direction.""" + + def __init__(self, lo: float = 0.0, hi: float = 0.0, rate: float = 0.0): + self.lo, self.hi, self.rate = lo, hi, rate + self.bytes = 0 + self._conns: list[tuple[asyncio.StreamWriter, asyncio.StreamWriter]] = [] + self.loop = asyncio.new_event_loop() + self._thread = threading.Thread(target=self.loop.run_forever, daemon=True) + self._thread.start() + + async def _serve(): + self._srv = await asyncio.start_server(self._forward, "127.0.0.1", 0) + return self._srv.sockets[0].getsockname()[1] + self.port = asyncio.run_coroutine_threadsafe(_serve(), self.loop).result(5) + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.port}" + + def drop_newest(self) -> None: + """Reset the most recently opened live connection — the facade + bridge, which the executor opens after the session's own upstream.""" + def _drop(): + live = [c for c in self._conns if not c[0].is_closing()] + for w in live[-1]: + w.transport.abort() + self.loop.call_soon_threadsafe(_drop) + + def close(self) -> None: + def _close(): + self._srv.close() + for pair in self._conns: + for w in pair: + w.transport.abort() + self.loop.call_soon_threadsafe(_close) + time.sleep(0.2) + self.loop.call_soon_threadsafe(self.loop.stop) + self._thread.join(5) + + async def _pipe(self, reader, writer): + q: asyncio.Queue = asyncio.Queue() + + async def deliver(): + while (item := await q.get()) is not None: + due, data = item + await asyncio.sleep(max(0.0, due - time.monotonic())) + writer.write(data) + await writer.drain() + + sender = asyncio.create_task(deliver()) + due = 0.0 + try: + while data := await reader.read(16384): + self.bytes += len(data) + # Monotone due times keep each direction's bytes in order. + due = max(due, time.monotonic() + random.uniform(self.lo, self.hi)) + if self.rate: + due += len(data) / self.rate + q.put_nowait((due, data)) + except (ConnectionError, OSError): + pass + finally: + q.put_nowait(None) + try: + await sender + except (ConnectionError, OSError): + pass + writer.close() + + async def _forward(self, reader, writer): + ur, uw = await asyncio.open_connection("127.0.0.1", TEST_CDP_PORT) + self._conns.append((writer, uw)) + await asyncio.gather(self._pipe(reader, uw), self._pipe(ur, writer), + return_exceptions=True) + + +class _TargetChurn: + """create(background) -> activate -> close, in a loop, on a direct CDP ws.""" + + def __init__(self, browser_ws: str): + self.browser_ws = browser_ws + self.cycles = 0 + self.errors: list[str] = [] + self._stop = threading.Event() + self._thread = threading.Thread(target=lambda: asyncio.run(self._run()), + daemon=True) + + def __enter__(self): + self._thread.start() + return self + + def __exit__(self, *exc): + self._stop.set() + self._thread.join(15) + + async def _run(self): + async with websockets.connect(self.browser_ws, max_size=None) as ws: + n = 0 + + async def call(method, **params): + nonlocal n + n += 1 + await ws.send(json.dumps({"id": n, "method": method, "params": params})) + while True: + msg = json.loads(await ws.recv()) + if msg.get("id") == n: + if "error" in msg: + raise RuntimeError(f"{method}: {msg['error']}") + return msg.get("result", {}) + + while not self._stop.is_set(): + try: + tid = (await call("Target.createTarget", url="about:blank", + background=True))["targetId"] + await call("Target.activateTarget", targetId=tid) + await asyncio.sleep(0.2) + await call("Target.closeTarget", targetId=tid) + self.cycles += 1 + except Exception as e: # noqa: BLE001 - recorded, keep churning + self.errors.append(repr(e)[:200]) + await asyncio.sleep(0.3) + + +def _cli(args: list[str], runtime_dir: str, stdin: str | None = None, + timeout: float = 300.0): + env = {k: v for k, v in scrubbed_env().items() if k not in _PROXY_VARS} + env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env.get("PATH", "") + env["XDG_RUNTIME_DIR"] = runtime_dir + env["TMPDIR"] = runtime_dir + env["BW_DAEMON_URL"] = published_endpoint(runtime_dir) or "" + env["BS_HOME"] = str(_BS_HOME) + assert env["BW_DAEMON_URL"], "test cdp daemon did not publish its endpoint" + binary = Path(sys.executable).with_name("browserwright") + return subprocess.run([str(binary), *args], input=stdin, capture_output=True, + text=True, env=env, timeout=timeout) + + +def _run(sid: str, runtime_dir: str, code: str, timeout: int = 240): + return _cli(["-s", sid, "--timeout", str(timeout), "--code-stdin"], + runtime_dir, stdin=code, timeout=timeout + 60) + + +def _record(artifacts: Path, key: str, value: dict) -> None: + path = artifacts / "cdp-attach-slow-link.json" + try: + report = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + report = {} + report[key] = value + path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + +def _summary(proc) -> dict: + return {"exit_code": proc.returncode, "stdout_tail": proc.stdout[-800:], + "stderr_tail": proc.stderr[-1500:]} + + +_FORM = ("data:text/html,slow-link" + "") + +#: ~1.5 MB of aria snapshot on the wire: at 30 KB/s that is ~50 s, so at +#: least one 20 s keepalive ping is answered more than 20 s late. +_BIG_DOM_ITEMS = 12000 + +# `human=False`: human input costs many sequential round trips, which on this +# link alone outlasts the 30 s action timeout; that is not what is under test. +_HEAVY_SCRIPT = f""" +import time +page.goto({_FORM!r}) +page.evaluate('''n => {{ + const ul = document.createElement('ul'); + for (let i = 0; i < n; i++) {{ + const li = document.createElement('li'); + li.innerHTML = 'item ' + i + ' lorem ipsum dolor sit amet'; + ul.appendChild(li); + }} + document.body.appendChild(ul); +}}''', {_BIG_DOM_ITEMS}) +t = time.monotonic() +tree = page.aria_snapshot(mode="ai", timeout=180_000) +print("SNAPSHOT", len(tree), "chars in", round(time.monotonic() - t), "s") +page.get_by_role("textbox", name="Name").fill("ok", human=False) +page.get_by_role("button", name="Go").click(human=False) +print("TITLE", page.title()) +""" + + +def test_large_reply_on_a_slow_link_keeps_the_browser_connected( + e2e_cdp_daemon, e2e_chrome_cdp, e2e_artifacts_dir): + link = _SlowLink(lo=0.1, hi=0.5, rate=30_000) + try: + new = _cli(["session", "new", "--backend=cdp", f"--attach={link.url}", + "--name=slow-link"], e2e_cdp_daemon) + assert new.returncode == 0, new.stderr + sid = new.stdout.strip().splitlines()[-1] + try: + with _TargetChurn(e2e_chrome_cdp.ws_url) as churn: + t0 = time.monotonic() + ran = _run(sid, e2e_cdp_daemon, _HEAVY_SCRIPT) + elapsed = round(time.monotonic() - t0, 1) + finally: + _cli(["session", "end", sid], e2e_cdp_daemon) + finally: + link.close() + _record(e2e_artifacts_dir, "large_reply_on_slow_link", { + "link": {"jitter_s": [link.lo, link.hi], "bytes_per_s": link.rate}, + "bytes_forwarded": link.bytes, "elapsed_s": elapsed, + "churn_cycles": churn.cycles, "churn_errors": churn.errors[:5], + **_summary(ran)}) + assert churn.cycles > 0 + assert ran.returncode == 0, ran.stderr + assert "TITLE clicked-ok" in ran.stdout, ran.stdout + + +def test_dropped_bridge_reconnects_to_the_same_tab_with_state( + e2e_cdp_daemon, e2e_chrome_cdp, e2e_artifacts_dir): + link = _SlowLink() + try: + new = _cli(["session", "new", "--backend=cdp", f"--attach={link.url}", + "--name=dropped-bridge"], e2e_cdp_daemon) + assert new.returncode == 0, new.stderr + sid = new.stdout.strip().splitlines()[-1] + try: + first = _run(sid, e2e_cdp_daemon, ( + f"page.goto({_FORM!r})\n" + "state['marker'] = 'kept'\n" + "page.evaluate('window.__tab_marker = 42')\n" + "print('BOUND', page.title())\n" + "print('TABS', len(context.pages))\n")) + assert first.returncode == 0, first.stderr + + # Drop the bridge while a call is running on it; the session's own + # upstream (an older connection) stays up, as in the field. + timer = threading.Timer(3.0, link.drop_newest) + timer.start() + try: + dropped = _run(sid, e2e_cdp_daemon, ( + "import time\n" + "end = time.monotonic() + 15\n" + "while time.monotonic() < end:\n" + " page.title()\n" + " time.sleep(0.1)\n")) + finally: + timer.cancel() + + after = _run(sid, e2e_cdp_daemon, ( + "print('STATE', state.get('marker'))\n" + "print('TAB', page.evaluate('window.__tab_marker'))\n" + "print('TABS', len(context.pages))\n")) + finally: + _cli(["session", "end", sid], e2e_cdp_daemon) + finally: + link.close() + _record(e2e_artifacts_dir, "dropped_bridge", { + "first": _summary(first), "dropped": _summary(dropped), + "after": _summary(after)}) + + # The drop surfaces as the connection, not as a dead tab ... + assert dropped.returncode != 0, dropped.stdout + assert "connection to the browser dropped" in dropped.stderr, dropped.stderr + assert "new_page" not in dropped.stderr, dropped.stderr + # ... and the next call is back on the SAME tab, with `state` kept. + assert after.returncode == 0, after.stderr + assert "STATE kept" in after.stdout, after.stdout + assert "TAB 42" in after.stdout, after.stdout + # No replacement tab was opened. + tabs = next(line for line in first.stdout.splitlines() + if line.startswith("TABS")) + assert tabs in after.stdout, (first.stdout, after.stdout) diff --git a/tests/daemon/test_coverage_server_listener_sweep.py b/tests/daemon/test_coverage_server_listener_sweep.py index 2a8a363..70e1f58 100644 --- a/tests/daemon/test_coverage_server_listener_sweep.py +++ b/tests/daemon/test_coverage_server_listener_sweep.py @@ -506,7 +506,7 @@ def fake_create_task(coro): assert conn.is_open is True assert conn.ws_url == "ws://localhost:9222/devtools/browser/x" - assert len(created) == 2 + assert len(created) == 3 # reader, CDP heartbeat, ws keepalive assert connect_calls[0][0] == "ws://localhost:9222/devtools/browser/x" kwargs = connect_calls[0][1] assert kwargs["compression"] is None