A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it

- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
feder-crandClaude Sonnet 5.5 committed 2026-11-12 02:42:32 +01:00
1 parent fbceeafb65
commit 2f153c76ff
4 files changed
+408 -6

No files matched your search

+24 -6
View File
@@ -4519,6 +4519,9 @@ class BrowserDispatcher(Dispatcher):
#: Targets whose adoption thread is still building. `op_new_page`
#: waits on these instead of building a second dispatcher.
self._adopting: set = set()
#: The page that opened each target being adopted (None if it has no announced opener): a download started by a popup that
#: is not announced yet belongs to its opener (Playwright's ffBrowser._onDownloadCreated).
self._openers: Dict[str, Optional[PageDispatcher]] = {}
#: Pages built and waiting for their Page.ready, by target (announced to the client after it).
self._building: Dict[str, PageDispatcher] = {}
#: Adoption failures, by target. The `newPage` waiter re-raises (and
@@ -4740,6 +4743,7 @@ class BrowserDispatcher(Dispatcher):
return
self._adopting.add(target_id)
opener = self._page_targets.get(opener_id) if opener_id else None
self._openers[target_id] = opener
if opener is not None:
opener.popups_opened += 1
number: Optional[int] = popup_number(opener.number,
@@ -4800,6 +4804,7 @@ class BrowserDispatcher(Dispatcher):
with self._targets_lock:
self._adopting.discard(target_id)
self._detached_early.discard(target_id)
self._openers.pop(target_id, None)
self._pages_ready.notify_all()
return
# ⛔ THE EVENTS THAT COME WITH THE READY ARE APPLIED FIRST. The engine says Page.ready and, in the same turn, the commit of
@@ -4814,6 +4819,7 @@ class BrowserDispatcher(Dispatcher):
context.emit("page", {"page": page.channel})
with self._targets_lock:
self._adopting.discard(target_id)
self._openers.pop(target_id, None)
self._page_targets[target_id] = page
context.pages.append(page)
early = target_id in self._detached_early
@@ -4832,6 +4838,7 @@ class BrowserDispatcher(Dispatcher):
with self._targets_lock:
self._adopting.discard(target_id)
self._detached_early.discard(target_id)
self._openers.pop(target_id, None)
self._adopt_errors[target_id] = failure
while len(self._adopt_errors) > 64:
self._adopt_errors.pop(next(iter(self._adopt_errors)))
@@ -5209,7 +5216,17 @@ class BrowserDispatcher(Dispatcher):
def _on_download_created(self, params: Dict) -> None:
context = next((c for c in self.contexts
if c.context_id == params.get("browserContextId")), None)
page = self._page_targets.get(params.get("pageTargetId"))
target = params.get("pageTargetId")
with self._targets_lock:
announced = self._page_targets.get(target)
# The page whose frame the download came from: announced, or built and waiting for its Page.ready.
page = announced or self._building.get(target)
# ⛔ THE PAGE THE DOWNLOAD IS REPORTED ON. A download that starts in a new tab (a `target=_blank` link or a `window.open` to a
# `Content-Disposition: attachment`) comes from a tab the client has not been told of: the tab waits for a Page.ready that never
# comes and is closed by the engine at once. Playwright reports it on the OPENER in that case (ffBrowser._onDownloadCreated:
# "if it's a new window download, report it on the pop-up's opener"); looking only among the announced pages, as this did,
# lost the download altogether.
origin = announced or self._openers.get(target)
if context is None:
return
directory = self._downloads_dir(params.get("browserContextId"))
@@ -5217,7 +5234,7 @@ class BrowserDispatcher(Dispatcher):
os.path.join(directory, params["uuid"]))
self._artifacts[params["uuid"]] = artifact
early = self._finished_early.pop(params["uuid"], None)
if page is not None:
if page is not None or origin is not None:
# ⛔ THE ENGINE ENDS A NAVIGATION THAT BECAME A DOWNLOAD WITH NO
# EVENT AT ALL (no navigationCommitted, no navigationAborted), so
# a `goto` or a click waiting on it waited out its timeout.
@@ -5226,7 +5243,7 @@ class BrowserDispatcher(Dispatcher):
# starting')); the lifecycle is fed the same abort. A frame whose
# current navigation already committed is left alone: the
# download came from a click or a script, not from a load.
frame = page.lifecycle.frame(params.get("frameId"))
frame = page.lifecycle.frame(params.get("frameId")) if page is not None else None
if (frame is not None and frame.navigation
and frame.navigation not in frame.aborted
and not any(c[1] == frame.navigation
@@ -5234,9 +5251,10 @@ class BrowserDispatcher(Dispatcher):
page.lifecycle._on_event("Page.navigationAborted", {
"frameId": frame.id, "navigationId": frame.navigation,
"errorText": "Download is starting"})
page.emit("download", {"url": params.get("url") or "",
"suggestedFilename": params.get("suggestedFileName") or "",
"artifact": artifact.channel})
if origin is not None:
origin.emit("download", {"url": params.get("url") or "",
"suggestedFilename": params.get("suggestedFileName") or "",
"artifact": artifact.channel})
if early is not None:
artifact.report_finished(early)
@@ -303,3 +303,28 @@ def test_a_popup_is_announced_with_the_address_of_the_commit_that_came_with_its_
while not urls and time.monotonic() < deadline:
time.sleep(0.01)
assert urls == [url], "the popup was announced with %r, not with the address of the commit that came with its ready" % (urls,)
def test_a_download_started_by_a_popup_that_is_not_announced_is_reported_on_its_opener(late_browser):
"""`<a target=_blank href=file>` with `Content-Disposition: attachment`: the new tab never gets a Page.ready and the engine closes it
at once. Playwright reports the download on the OPENER (ffBrowser._onDownloadCreated); looking only among the announced pages
lost it (no `download` event anywhere)."""
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))
opener = next(o for o in server._objects.values() if o.TYPE == "Page" and o.target_id == opener_target)
said = []
original = opener.emit
opener.emit = lambda event, params=None: (said.append((event, params)), original(event, params))[1]
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while target not in late_browser._building and time.monotonic() < deadline:
time.sleep(0.01)
conn.dispatch_event("Browser.downloadCreated", {
"uuid": "u1", "browserContextId": context.context_id, "pageTargetId": target, "frameId": "f" + target,
"url": "http://127.0.0.1/file", "suggestedFileName": "f.bin"}, None)
downloads = [p for e, p in said if e == "download"]
assert len(downloads) == 1, "the download of the popup was not reported on its opener: %r" % (said,)
assert downloads[0]["suggestedFilename"] == "f.bin"
+173
View File
@@ -0,0 +1,173 @@
"""What a popup does depends on what its destination answers; the client must see what stock Firefox makes it see.
Reference: Playwright 1.62 with its own Firefox, measured (a `window.open(url)` from a click, and a clicked
`<a target=_blank>`, destination on the opener's site, two repetitions each, 30 s observed unless said; the destination on
another site gave the same):
* 204 No Content: NO `page` event at all (observed for 30 s). The popup is never announced.
* a destination that never answers: NO `page` event (observed for 30 s).
* a destination that answers a normal HTML page after N seconds: the `page` event arrives when the answer comes, N s after
the click, with the destination as its url, and the load follows at once. There is no ceiling: with N = 25 the event
came at about 25 s (checked by hand, the 25 s case is not run here; this file uses 4 s).
* `Content-Disposition: attachment`: the `page` event arrives at once (url empty), a `download` event arrives on the
OPENER (not on the popup) and the popup closes within about 10 ms.
Why it matters here: the page dispatcher announces a popup when the engine says it is ready (`Page.ready`), and gives up on
one that never does after 20 s. A destination that answers late must still be announced when it answers, one that never
becomes a page must not be announced, and a download started by a popup must reach the client on the opener like on stock.
The waits for "no event" are bounded to 8 s here (stock was observed for 30 s).
Transports: the client of this wheel in the same process, and the stock Playwright client over `launch_server`.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from test_popups_reach_the_client_e2e import browser # noqa: F401 (the two-transport fixture of the sibling file)
pytestmark = pytest.mark.e2e
SLOW_SECONDS = 4
NO_EVENT_SECONDS = 8
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def _send(self, code, ctype, body=b"", extra=()):
self.send_response(code)
if ctype:
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
for key, value in extra:
self.send_header(key, value)
self.end_headers()
self.wfile.write(body)
def do_GET(self):
port = self.server.server_address[1]
try:
if self.path.startswith("/main"):
body = ""
for d in "1234":
url = "http://127.0.0.1:%d/d%s" % (port, d)
body += ("<a id=link%s target=_blank href='%s'>a</a> "
"<button id=open%s onclick=\"window.open('%s')\">w</button><br>") % (d, url, d, url)
self._send(200, "text/html", ("<!doctype html><title>opener</title>" + body).encode())
elif self.path.startswith("/d1"):
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
elif self.path.startswith("/d2"):
time.sleep(SLOW_SECONDS)
self._send(200, "text/html", b"<!doctype html><title>slow</title><p>slow page</p>")
elif self.path.startswith("/d3"):
time.sleep(NO_EVENT_SECONDS + 6) # longer than any wait of a test: it never answers in time
self._send(200, "text/html", b"<!doctype html><title>late</title>")
elif self.path.startswith("/d4"):
self._send(200, "text/plain", b"hello attachment\n",
[("Content-Disposition", 'attachment; filename="a.txt"')])
else:
self._send(404, "text/plain", b"not found")
except (ConnectionError, TimeoutError, OSError):
self.close_connection = True
class _Server(ThreadingHTTPServer):
daemon_threads = True
@pytest.fixture(scope="module")
def site():
srv = _Server(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield srv.server_address[1]
srv.shutdown()
srv.server_close()
class _Run:
"""One popup attempt: the opener page, what the context announced, what the opener downloaded."""
def __init__(self, browser, port, how, dest):
self.context = browser.new_context(accept_downloads=True)
self.opener = self.context.new_page()
self.popups, self.downloads, self.arrived_at = [], [], None
self.context.on("page", self._on_page)
self.opener.on("download", lambda download: self.downloads.append(download))
self.opener.goto("http://127.0.0.1:%d/main" % port)
self.clicked = time.time()
self.opener.click("#%s%s" % (how, dest))
def _on_page(self, page):
self.popups.append(page)
self.arrived_at = time.time() - self.clicked
def wait_until(self, predicate, seconds):
end = time.time() + seconds
while time.time() < end and not predicate():
self.opener.wait_for_timeout(100) # the sync client reads the engine's events inside its calls
return predicate()
def close(self):
try:
self.context.close()
except Exception:
pass
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_a_204_is_never_announced(browser, site, how): # noqa: F811
run = _Run(browser, site, how, "1")
try:
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
"a 204 destination was announced as a page after %.1fs (stock gives no page event)" % run.arrived_at
assert len(run.context.pages) == 1
finally:
run.close()
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_a_server_that_never_answers_is_never_announced(browser, site, how): # noqa: F811
run = _Run(browser, site, how, "3")
try:
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
"an unanswered destination was announced as a page after %.1fs (stock gives no page event)" % run.arrived_at
assert len(run.context.pages) == 1
finally:
run.close()
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_a_slow_page_is_announced_when_it_answers(browser, site, how): # noqa: F811
run = _Run(browser, site, how, "2")
try:
assert run.wait_until(lambda: run.popups, SLOW_SECONDS + 6), "the slow popup never arrived"
assert run.arrived_at >= SLOW_SECONDS - 0.5, "announced after %.1fs, before the page answered" % run.arrived_at
popup = run.popups[0]
popup.wait_for_load_state("load", timeout=10000)
assert popup.url == "http://127.0.0.1:%d/d2" % site
assert popup.evaluate("document.title") == "slow"
assert len(run.context.pages) == 2
finally:
run.close()
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_an_attachment_reports_the_download_on_the_opener_and_closes(browser, site, how): # noqa: F811
run = _Run(browser, site, how, "4")
try:
assert run.wait_until(lambda: run.downloads, 10), "no `download` event on the opener (stock gives one)"
assert run.downloads[0].suggested_filename == "a.txt"
assert run.popups, "stock announces the popup (its url is empty) before it closes"
assert run.wait_until(lambda: run.popups[0].is_closed(), 10), "the popup of a download stays open"
assert len(run.context.pages) == 1
finally:
run.close()
+186
View File
@@ -0,0 +1,186 @@
"""A popup reaches the client: the `page` event arrives, the new page is at its address and answers.
Why this file exists: the page dispatcher once waited for the engine's ready signal (`Page.ready`) before it handed a new
page over. A popup whose first request goes through a context route (the shape of every production client: abort the
images, continue the rest) was held behind a page that did not exist yet, the engine never said ready for it, the wait gave
up after 20 s and the popup vanished: the client never got the `page` event. That was found by a user journey (a
`target=_blank` link) and it is the same for a link and for `window.open`, to the page's own site and to another one.
The matrix: four ways to open a popup (a `target=_blank` link, the same link with `rel=noopener`, `window.open(url)` from a
click, `window.open(url, '_blank', 'noopener')`) x the target on the opener's site (`127.0.0.1`) or on another site
(`localhost`: another site for the engine, no pref needed) x with and without a context route x two transports: the client
of this wheel in the same process, and the stock Playwright client over `launch_server` (the way the fake web does it).
Each case: the `page` event arrives within 10 s, the page ends at the target address, answers an `evaluate`, and has an
opener (`page.opener()`). Stock Firefox (Playwright 1.62) gives an opener in all four kinds, `noopener` included, so this is
asserted for all four; if the engine ever returns None for a noopener kind the test says so.
One extra case proves that the other-site target is really in another process, so that the matrix cannot quietly become a
same-site test: opening it adds a content process below the test; the same-site target does not.
"""
from __future__ import annotations
import importlib
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
pytestmark = pytest.mark.e2e
OWN, OTHER = "127.0.0.1", "localhost"
KINDS = {
"a-blank": "a1",
"a-noopener": "a2",
"open": "w1",
"open-noopener": "w2",
}
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
port = self.server.server_address[1]
if self.path.startswith("/main"):
body = ""
for tag, host in (("s", OWN), ("o", OTHER)):
url = "http://%s:%d/p" % (host, port)
body += (
"<a id=a1%s target=_blank href='%s'>a</a> "
"<a id=a2%s target=_blank rel=noopener href='%s'>a</a> "
"<button id=w1%s onclick=\"window.open('%s')\">w</button> "
"<button id=w2%s onclick=\"window.open('%s','_blank','noopener')\">w</button><br>"
) % (tag, url, tag, url, tag, url, tag, url)
else:
body = "<p>popup</p>"
data = ("<!doctype html><title>t</title>" + body).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
@pytest.fixture(scope="module")
def site():
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield srv.server_address[1]
srv.shutdown()
srv.server_close()
@pytest.fixture(scope="module", params=["in-process", "stock-client"])
def browser(request, firefox_binary):
"""One browser per transport for the whole file."""
if request.param == "in-process":
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(binary_path=firefox_binary, headless=True) as b:
yield b
return
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
except ImportError as exc:
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
pytrace=False)
from invisible_playwright._juggler.remote import launch_server
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
try:
with sync_playwright() as p:
b = p.firefox.connect(server.ws_endpoint)
try:
yield b
finally:
b.close()
finally:
server.close()
def _route(context):
context.route("**/*", lambda route: route.abort() if route.request.resource_type in ("image", "media")
else route.continue_())
@pytest.mark.parametrize("routed", [False, True], ids=["no-route", "route"])
@pytest.mark.parametrize("target", ["same-site", "other-site"])
@pytest.mark.parametrize("kind", sorted(KINDS))
def test_a_popup_reaches_the_client(browser, site, kind, target, routed):
host, tag = (OWN, "s") if target == "same-site" else (OTHER, "o")
context = browser.new_context()
try:
if routed:
_route(context)
page = context.new_page()
page.goto("http://%s:%d/main" % (OWN, site))
t0 = time.time()
with context.expect_page(timeout=10000) as info:
page.click("#%s%s" % (KINDS[kind], tag))
popup = info.value
arrived = time.time() - t0
popup.wait_for_load_state("load", timeout=10000)
assert popup.url == "http://%s:%d/p" % (host, site), "the popup is at %s" % popup.url
assert popup.evaluate("document.title") == "t"
assert popup.opener() is not None, "no opener (stock Firefox gives one for every kind)"
assert arrived < 10
finally:
context.close()
def _content_processes(engine_dir):
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
import psutil
pids = set()
for child in psutil.Process(os.getpid()).children(recursive=True):
try:
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
continue
cmd = child.cmdline()
except psutil.Error:
continue
if "-contentproc" in cmd and cmd[-1] == "tab":
pids.add(child.pid)
return pids
def _quiet(engine_dir, seconds=3.0, limit=30.0):
"""The set of content processes once it has not changed for `seconds` (the engine keeps a spare one)."""
end = time.time() + limit
last, since = _content_processes(engine_dir), time.time()
while time.time() < end:
time.sleep(0.25)
now = _content_processes(engine_dir)
if now != last:
last, since = now, time.time()
elif time.time() - since >= seconds:
break
return last
def test_the_other_site_popup_runs_in_another_process(browser, firefox_binary, site):
"""The control of the matrix above: the popup to `localhost` adds a content process, the one to `127.0.0.1` does not."""
engine_dir = str(Path(firefox_binary).resolve().parent)
context = browser.new_context()
page = context.new_page()
page.goto("http://%s:%d/main" % (OWN, site))
before = _quiet(engine_dir)
with context.expect_page(timeout=10000) as info:
page.click("#a1s")
info.value.wait_for_load_state("load")
same = _quiet(engine_dir)
info.value.close()
page.goto("http://%s:%d/main" % (OWN, site))
base = _quiet(engine_dir)
with context.expect_page(timeout=10000) as info:
page.click("#a1o")
info.value.wait_for_load_state("load")
other = _quiet(engine_dir)
assert not (same - before), "a popup to the opener's own site started a process: %s" % sorted(same - before)
assert len(other - base) >= 1, "the other-site popup added no content process: %s -> %s" % (
sorted(base), sorted(other))