A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does

The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
feder-crandClaude Sonnet 5.5 committed 2026-11-12 04:10:00 +01:00
1 parent b05741f538
commit 6200bc29ed
4 files changed
+67 -3

No files matched your search

+24 -3
View File
@@ -2560,6 +2560,14 @@ class RouteDispatcher(Dispatcher):
# ── page ────────────────────────────────────────────────────────────────────
def _target_is_gone(error: BaseException) -> bool:
"""Whether a failed command failed because the target or its session no longer exists (the engine closed the tab under it)."""
if isinstance(error, juggler.TargetClosedError):
return True
text = str(error).lower()
return "cannot find session" in text or "target closed" in text or "session closed" in text
class PageDispatcher(Dispatcher):
TYPE = "Page"
#: No hand until `_build` gives it one: a page without it acts as the
@@ -2692,7 +2700,16 @@ class PageDispatcher(Dispatcher):
def _build(self, server, context: "BrowserContextDispatcher",
session: str, conn, opener: Optional["PageDispatcher"]) -> None:
"""The rest of the construction, under `__init__`'s cleanup."""
self.injected.install()
# ⛔ A TARGET THAT GOES AWAY WHILE ITS PAGE IS BEING INITIALIZED (a download's empty tab, closed by the engine within milliseconds)
# makes the engine answer "cannot find session" to the command. That is the detach-before-ready case again, caught a step later:
# the page is still built, flagged gone, and announced and closed as Playwright's is - not discarded with a warning.
self.gone_while_building = False
try:
self.injected.install()
except Exception as failure:
if not _target_is_gone(failure):
raise
self.gone_while_building = True
self.actions = context.browser.actions_for_page(
session, self.lifecycle, self.injected, self.number)
#: The viewport as the client was told it (the initializer's, then
@@ -2747,7 +2764,11 @@ class PageDispatcher(Dispatcher):
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
self._dialogs_open: Dict[str, Any] = {}
self._dialogs_seen = 0
self.main_frame_id = self.lifecycle.wait_for_main_frame(timeout=20.0)
if self.gone_while_building and self.lifecycle.main_frame is None:
# gone before it even announced a frame: a frame of its own name keeps the object whole until it is closed
self.main_frame_id = "gone-" + str(self.target_id)
else:
self.main_frame_id = self.lifecycle.wait_for_main_frame(timeout=20.0)
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
# initializer has to name a mainFrame the client can already resolve.
# ⛔ WITH WHAT THE LIFECYCLE ALREADY KNOWS OF IT, as every other frame is made (`frame_for`): the initializer is a snapshot, and
@@ -4821,7 +4842,7 @@ class BrowserDispatcher(Dispatcher):
# ⛔ A DETACH THAT CAME WHILE THE PAGE WAS BEING BUILT is recorded as early and went by `_handle_detach` with nobody to tell
# (the page was not in `_building` yet): waiting for a ready now would wait for ever for a tab that is already gone (a
# download's empty tab closes within milliseconds, and a loaded machine builds slowly).
detached_already = target_id in self._detached_early
detached_already = target_id in self._detached_early or page.gone_while_building
gone = False
try:
if detached_already:
@@ -56,6 +56,8 @@ class _Page:
self.number = number
self.channel = {"guid": "page-" + target_id}
gone_while_building = False
def wait_until_ready(self, timeout=20.0):
pass # the engine of this test says Page.ready at once
@@ -401,3 +401,42 @@ def test_a_popup_whose_target_goes_away_while_its_page_is_being_built_is_announc
while "page" not in announced and time.monotonic() < deadline:
time.sleep(0.01)
assert "page" in announced, "the popup that went away while its page was being built was never announced"
@pytest.mark.parametrize("command", ["Page.setInitScripts", "Browser.getInfo"])
def test_a_command_of_the_adoption_that_finds_the_session_gone_announces_and_closes_the_popup(late_browser, command, monkeypatch):
"""The tab goes away WHILE the adoption initializes it: the engine answers 'cannot find session' to a command of the adoption. Like a
detach before the ready, that ends in the page announced and closed (Playwright's does), never in a discard with a warning: the
download of a link into a new tab was lost one time in a hundred (independent run, quiet machine)."""
import warnings
from invisible_core.juggler.connection import ProtocolError
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
original_send = conn.send
def send(method, params=None, session=None, timeout=30):
if method == command and session not in (None, "s1"):
raise ProtocolError('%s: ERROR: cannot find session with id "%s"' % (method, session))
return original_send(method, params, session, timeout)
monkeypatch.setattr(conn, "send", send)
announced = []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
target, session = conn.popup_born(opener_target, context.context_id, 1)
if command == "Browser.getInfo":
conn.say_ready(session) # this one is asked once the page is ready
else:
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
deadline = time.monotonic() + 5
while "page" not in announced and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert "page" in announced, "the popup whose session was gone was discarded instead of announced"
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
@@ -237,6 +237,8 @@ class _Page:
self.popups_opened = 0
self.channel = {"guid": "page-" + target_id}
gone_while_building = False
def wait_until_ready(self, timeout=20.0):
pass # the engine of this test says Page.ready at once