Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(target): own stable pages in target hosts

ldm0fff356767fac
diff --git a/moli-cdp-smoke/moli_cdp_smoke/fixture.py b/moli-cdp-smoke/moli_cdp_smoke/fixture.py
index c43af2c60..af1e12ae2 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/fixture.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/fixture.py
@@ -1735,16 +1735,18 @@ class FixtureServer:
)
def _send_slow_download(self) -> None:
- body = b"slow download contents"
+ body = b"slow download contents\n" * (256 * 1024)
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Disposition", 'attachment; filename="slow-smoke-download.txt"')
+ self.send_header("Content-Length", str(len(body)))
self.end_headers()
- self.wfile.write(body[:4])
+ split = 64 * 1024
+ self.wfile.write(body[:split])
self.wfile.flush()
time.sleep(5)
- self.wfile.write(body[4:])
+ self.wfile.write(body[split:])
def _handle_websocket(self) -> None:
key = self.headers.get("Sec-WebSocket-Key")
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py
index ac463b6f3..c31b57c4f 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_context.py
@@ -14,6 +14,7 @@ RESPONSE_STAGE_BODY_BASE64 = "cmVzcG9uc2Utc3RhZ2UgYm9keQ=="
async def run_multi_context_group(browser: Any, fixture: str, results: list[dict[str, Any]]) -> None:
+ await run_multi_page_after_startup_target_close_smoke(browser, fixture, results)
await run_multi_context_blob_uuid_partition_smoke(browser, fixture, results)
await run_multi_context_dialog_owner_state_smoke(browser, fixture, results)
await run_multi_context_route_owner_state_smoke(browser, fixture, results)
@@ -30,6 +31,144 @@ async def run_multi_context_group(browser: Any, fixture: str, results: list[dict
await run_multi_context_held_response_stage_resume_smoke(browser, fixture, results)
+async def run_multi_page_after_startup_target_close_smoke(
+ browser: Any, fixture: str, results: list[dict[str, Any]]
+) -> None:
+ closed_startup_target = await _close_startup_target_if_present(browser)
+
+ context_a = await browser.new_context()
+ context_b = await browser.new_context()
+ try:
+ page_a, page_a_peer, page_b = await asyncio.gather(
+ context_a.new_page(),
+ context_a.new_page(),
+ context_b.new_page(),
+ )
+ await asyncio.gather(
+ page_a.goto(
+ f"{fixture}/plain?multi-page=a", wait_until="load", timeout=10_000
+ ),
+ page_a_peer.goto(
+ f"{fixture}/plain?multi-page=a-peer",
+ wait_until="load",
+ timeout=10_000,
+ ),
+ page_b.goto(
+ f"{fixture}/plain?multi-page=b", wait_until="load", timeout=10_000
+ ),
+ )
+
+ cdp_a, cdp_a_peer, cdp_b = await asyncio.gather(
+ _new_cdp_session(context_a, page_a, "multi-page A"),
+ _new_cdp_session(context_a, page_a_peer, "multi-page A peer"),
+ _new_cdp_session(context_b, page_b, "multi-page B"),
+ )
+ evaluations = await asyncio.gather(
+ _send_cdp(
+ cdp_a,
+ "Runtime.evaluate",
+ {
+ "expression": "globalThis.__moliMultiPage = 'a'; __moliMultiPage",
+ "returnByValue": True,
+ },
+ ),
+ _send_cdp(
+ cdp_a_peer,
+ "Runtime.evaluate",
+ {
+ "expression": "globalThis.__moliMultiPage = 'a-peer'; __moliMultiPage",
+ "returnByValue": True,
+ },
+ ),
+ _send_cdp(
+ cdp_b,
+ "Runtime.evaluate",
+ {
+ "expression": "globalThis.__moliMultiPage = 'b'; __moliMultiPage",
+ "returnByValue": True,
+ },
+ ),
+ )
+ assert_equal(
+ [evaluation.get("result", {}).get("value") for evaluation in evaluations],
+ ["a", "a-peer", "b"],
+ "three target-local Runtime evaluations",
+ )
+
+ await page_a_peer.close()
+ survivor_values = await asyncio.gather(
+ page_a.evaluate(
+ "() => `${globalThis.__moliMultiPage}:${document.querySelector('main')?.textContent}`"
+ ),
+ page_b.evaluate(
+ "() => `${globalThis.__moliMultiPage}:${document.querySelector('main')?.textContent}`"
+ ),
+ )
+ assert_equal(
+ survivor_values,
+ ["a:plain ok", "b:plain ok"],
+ "surviving pages after peer close",
+ )
+ await asyncio.gather(
+ page_a.goto(
+ f"{fixture}/plain?multi-page=a-final",
+ wait_until="load",
+ timeout=10_000,
+ ),
+ page_b.goto(
+ f"{fixture}/plain?multi-page=b-final",
+ wait_until="load",
+ timeout=10_000,
+ ),
+ )
+ assert_equal(
+ await asyncio.gather(page_a.text_content("main"), page_b.text_content("main")),
+ ["plain ok", "plain ok"],
+ "surviving pages after concurrent renavigation",
+ )
+ record(
+ results,
+ "multi_page_after_startup_target_close",
+ {"closedStartupTarget": closed_startup_target, "pageCount": 3},
+ )
+ finally:
+ await _close_context_best_effort(context_a)
+ await _close_context_best_effort(context_b)
+
+
+async def _close_startup_target_if_present(browser: Any) -> bool:
+ browser_cdp = await browser.new_browser_cdp_session()
+ try:
+ targets = await _send_cdp(browser_cdp, "Target.getTargets")
+ startup_targets = [
+ target
+ for target in targets.get("targetInfos", [])
+ if target.get("type") == "page" and target.get("targetId") == "moli-default"
+ ]
+ if len(startup_targets) > 1:
+ raise SmokeError(f"multiple startup targets were published: {startup_targets!r}")
+ if startup_targets:
+ close_result = await _send_cdp(
+ browser_cdp,
+ "Target.closeTarget",
+ {"targetId": "moli-default"},
+ )
+ assert_equal(close_result.get("success"), True, "close startup Page target")
+
+ async def startup_target_is_absent() -> bool:
+ current = await _send_cdp(browser_cdp, "Target.getTargets")
+ return all(
+ target.get("targetId") != "moli-default"
+ for target in current.get("targetInfos", [])
+ )
+
+ await wait_until(startup_target_is_absent, "closed startup Page target")
+ return True
+ return False
+ finally:
+ await browser_cdp.detach()
+
+
async def run_multi_context_blob_uuid_partition_smoke(
browser: Any, fixture: str, results: list[dict[str, Any]]
) -> None:
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.py
new file mode 100644
index 000000000..e1f31717b
--- /dev/null
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.py
@@ -0,0 +1,1123 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+from contextlib import suppress
+from pathlib import Path
+from typing import Any
+
+from ..assertions import SmokeError, assert_equal, record, wait_until
+from ..helpers import attach_cdp_event_collector, run_worker_command
+from .multi_page_contracts import run_multi_page_contracts
+
+
+async def run_multi_page_group(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ await _close_startup_target(browser)
+ await _page_churn_and_session_reattach(browser, fixture, results)
+ await _same_context_storage_and_history(browser, fixture, results)
+ await _mixed_navigation_outcomes_and_recovery(browser, fixture, results)
+ await _concurrent_route_outcomes(browser, fixture, results)
+ await _inflight_navigation_close_and_peer_recovery(browser, fixture, results)
+ await _target_local_session_events(browser, fixture, results)
+ await _target_local_dialogs(browser, fixture, results)
+ await _concurrent_downloads_and_peer(browser, fixture, results)
+ await _popup_tree_survives_middle_close(browser, fixture, results)
+ await _background_tasks_workers_and_screenshots(browser, fixture, results)
+ await _context_teardown_with_pending_commands(browser, fixture, results)
+ await run_multi_page_contracts(browser, fixture, results)
+
+
+async def _page_churn_and_session_reattach(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ browser_cdp = await browser.new_browser_cdp_session()
+ sessions: list[Any] = []
+ try:
+ pages = await asyncio.gather(*(context.new_page() for _ in range(6)))
+ urls = [f"{fixture}/plain?multi-page-churn={index}" for index in range(6)]
+ await asyncio.gather(
+ *(
+ page.goto(url, wait_until="load", timeout=10_000)
+ for page, url in zip(pages, urls, strict=True)
+ )
+ )
+
+ sessions = await asyncio.gather(
+ *(context.new_cdp_session(page) for page in pages)
+ )
+ writes = await asyncio.gather(
+ *(
+ _send_cdp(
+ session,
+ "Runtime.evaluate",
+ {
+ "expression": (
+ f"globalThis.__moliMultiPageChurn = 'page-{index}'; "
+ "globalThis.__moliMultiPageChurn"
+ ),
+ "returnByValue": True,
+ },
+ )
+ for index, session in enumerate(sessions)
+ )
+ )
+ assert_equal(
+ [_runtime_value(write) for write in writes],
+ [f"page-{index}" for index in range(6)],
+ "six target-local Runtime writes",
+ )
+
+ for index in (1, 3, 5):
+ await sessions[index].detach()
+ sessions[index] = await context.new_cdp_session(pages[index])
+ reads = await asyncio.gather(
+ *(
+ _send_cdp(
+ session,
+ "Runtime.evaluate",
+ {
+ "expression": "globalThis.__moliMultiPageChurn",
+ "returnByValue": True,
+ },
+ )
+ for session in sessions
+ )
+ )
+ assert_equal(
+ [_runtime_value(read) for read in reads],
+ [f"page-{index}" for index in range(6)],
+ "Runtime state after alternating session reattach",
+ )
+
+ retired_indexes = (1, 3, 4)
+ await asyncio.gather(*(pages[index].close() for index in retired_indexes))
+ survivors = [pages[index] for index in (0, 2, 5)]
+ assert_equal(
+ await asyncio.gather(
+ *(page.evaluate("globalThis.__moliMultiPageChurn") for page in survivors)
+ ),
+ ["page-0", "page-2", "page-5"],
+ "surviving page state after non-tail target close",
+ )
+
+ replacements = await asyncio.gather(*(context.new_page() for _ in range(3)))
+ replacement_urls = [
+ f"{fixture}/plain?multi-page-replacement={index}" for index in range(3)
+ ]
+ await asyncio.gather(
+ *(
+ page.goto(url, wait_until="load", timeout=10_000)
+ for page, url in zip(replacements, replacement_urls, strict=True)
+ )
+ )
+ expected_urls = set(urls[index] for index in (0, 2, 5)) | set(
+ replacement_urls
+ )
+ retired_urls = {urls[index] for index in retired_indexes}
+
+ async def target_registry_matches_live_pages() -> bool:
+ infos = (await _send_cdp(browser_cdp, "Target.getTargets")).get(
+ "targetInfos", []
+ )
+ page_urls = {
+ info.get("url") for info in infos if info.get("type") == "page"
+ }
+ return expected_urls <= page_urls and not (retired_urls & page_urls)
+
+ await wait_until(
+ target_registry_matches_live_pages,
+ "target registry after middle-page churn",
+ )
+ record(
+ results,
+ "multi_page_churn_and_session_reattach",
+ {"createdPages": 9, "closedMiddlePages": len(retired_indexes)},
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ with suppress(Exception):
+ await browser_cdp.detach()
+ await _close_context(context)
+
+
+async def _same_context_storage_and_history(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context_a = await browser.new_context()
+ context_b = await browser.new_context()
+ context_a_closed = False
+ try:
+ page_a, page_a_peer, page_b = await asyncio.gather(
+ context_a.new_page(),
+ context_a.new_page(),
+ context_b.new_page(),
+ )
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/plain?storage=a", wait_until="load"),
+ page_a_peer.goto(f"{fixture}/plain?storage=a-peer", wait_until="load"),
+ page_b.goto(f"{fixture}/plain?storage=b", wait_until="load"),
+ )
+ await page_a.evaluate(
+ """() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ localStorage.setItem('multi-page-local', 'context-a');
+ sessionStorage.setItem('multi-page-session', 'page-a');
+ document.cookie = 'multiPageCookie=context-a; Path=/';
+ }"""
+ )
+ same_context = await page_a_peer.evaluate(
+ """() => ({
+ local: localStorage.getItem('multi-page-local'),
+ session: sessionStorage.getItem('multi-page-session'),
+ cookie: document.cookie,
+ })"""
+ )
+ assert_equal(same_context.get("local"), "context-a", "same-context localStorage")
+ assert_equal(same_context.get("session"), None, "target-local sessionStorage")
+ if "multiPageCookie=context-a" not in same_context.get("cookie", ""):
+ raise SmokeError(f"same-context cookie was not shared: {same_context}")
+
+ isolated_context = await page_b.evaluate(
+ """() => ({
+ local: localStorage.getItem('multi-page-local'),
+ session: sessionStorage.getItem('multi-page-session'),
+ cookie: document.cookie,
+ })"""
+ )
+ assert_equal(
+ isolated_context,
+ {"local": None, "session": None, "cookie": ""},
+ "cross-context storage isolation",
+ )
+
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/history-a?owner=a", wait_until="load"),
+ page_a_peer.goto(f"{fixture}/history-b?owner=a-peer", wait_until="load"),
+ )
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/history-b?owner=a", wait_until="load"),
+ page_a_peer.goto(f"{fixture}/history-a?owner=a-peer", wait_until="load"),
+ )
+ await asyncio.gather(
+ page_a.go_back(wait_until="commit", timeout=10_000),
+ page_a_peer.go_back(wait_until="commit", timeout=10_000),
+ )
+ assert_equal(
+ await asyncio.gather(
+ page_a.text_content("main"), page_a_peer.text_content("main")
+ ),
+ ["history a", "history b"],
+ "independent same-context target history",
+ )
+
+ await asyncio.wait_for(context_a.close(), timeout=5)
+ context_a_closed = True
+ assert_equal(
+ await page_b.evaluate("() => document.querySelector('main')?.textContent"),
+ "plain ok",
+ "other context after peer context disposal",
+ )
+ await page_b.goto(f"{fixture}/plain?storage=b-final", wait_until="load")
+ record(results, "multi_page_storage_history_and_context_disposal")
+ finally:
+ if not context_a_closed:
+ await _close_context(context_a)
+ await _close_context(context_b)
+
+
+async def _mixed_navigation_outcomes_and_recovery(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ pages = await asyncio.gather(*(context.new_page() for _ in range(5)))
+ sessions = await asyncio.gather(
+ *(context.new_cdp_session(page) for page in pages)
+ )
+ responses = await asyncio.gather(
+ pages[0].goto(f"{fixture}/redirect-start", wait_until="load"),
+ pages[1].goto(f"{fixture}/navigation-http-error", wait_until="load"),
+ pages[2].goto(f"{fixture}/missing-multi-page", wait_until="load"),
+ pages[3].goto(
+ "data:text/html,<main>multi-page-data</main>", wait_until="load"
+ ),
+ pages[4].goto(f"{fixture}/iframe", wait_until="load"),
+ )
+ assert_equal(
+ [
+ responses[0].status if responses[0] else None,
+ responses[1].status if responses[1] else None,
+ responses[2].status if responses[2] else None,
+ responses[3].status if responses[3] else None,
+ responses[4].status if responses[4] else None,
+ ],
+ [200, 502, 404, None, 200],
+ "parallel mixed navigation statuses",
+ )
+ assert_equal(
+ await asyncio.gather(
+ pages[0].text_content("main"),
+ pages[1].text_content("main"),
+ pages[2].text_content("body"),
+ pages[3].text_content("main"),
+ pages[4].text_content("main"),
+ ),
+ [
+ "redirect final",
+ "gateway error",
+ "not found: /missing-multi-page",
+ "multi-page-data",
+ "parent",
+ ],
+ "parallel mixed navigation Documents",
+ )
+
+ frame_trees = await asyncio.gather(
+ *(_send_cdp(session, "Page.getFrameTree") for session in sessions)
+ )
+ frame_ids = [_collect_frame_ids(tree.get("frameTree", {})) for tree in frame_trees]
+ for index, ids in enumerate(frame_ids):
+ for other_index, other_ids in enumerate(frame_ids):
+ if index != other_index and ids & other_ids:
+ raise SmokeError(
+ "frame ids crossed target ownership: "
+ f"target={index}, other={other_index}, ids={ids & other_ids}"
+ )
+ assert_equal(len(frame_ids[4]), 2, "iframe target frame count")
+
+ transport_failure: BaseException | None = None
+ document_before_transport_failure = pages[2].url
+ try:
+ await pages[2].goto(
+ "http://127.0.0.1:1/multi-page-transport-failure",
+ wait_until="load",
+ timeout=5_000,
+ )
+ except BaseException as error:
+ transport_failure = error
+ if transport_failure is None:
+ raise SmokeError("transport-failure navigation unexpectedly succeeded")
+ await wait_until(
+ lambda: pages[2].url != document_before_transport_failure,
+ "transport-failure error Document replacement",
+ )
+ await pages[2].wait_for_load_state("load", timeout=5_000)
+ assert_equal(
+ await pages[0].text_content("main"),
+ "redirect final",
+ "peer target after transport failure",
+ )
+
+ await asyncio.gather(
+ *(
+ page.goto(
+ f"{fixture}/plain?mixed-recovery={index}",
+ wait_until="load",
+ timeout=10_000,
+ )
+ for index, page in enumerate(pages)
+ )
+ )
+ assert_equal(
+ await asyncio.gather(*(page.text_content("main") for page in pages)),
+ ["plain ok"] * len(pages),
+ "all mixed-navigation targets recover",
+ )
+ record(
+ results,
+ "multi_page_mixed_navigation_outcomes_and_recovery",
+ {"pages": len(pages), "iframeFrames": len(frame_ids[4])},
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _concurrent_route_outcomes(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context_a = await browser.new_context()
+ context_b = await browser.new_context()
+
+ async def route_a(route: Any) -> None:
+ if route.request.url.endswith("/abort"):
+ await route.abort("failed")
+ return
+ marker = route.request.url.rsplit("/", 1)[-1]
+ await route.fulfill(
+ status=200,
+ content_type="text/html",
+ body=f"<!doctype html><main>context-a:{marker}</main>",
+ )
+
+ async def route_b(route: Any) -> None:
+ marker = route.request.url.rsplit("/", 1)[-1]
+ await route.fulfill(
+ status=201,
+ content_type="text/html",
+ body=f"<!doctype html><main>context-b:{marker}</main>",
+ )
+
+ try:
+ await context_a.route("**/multi-page-route/**", route_a)
+ await context_b.route("**/multi-page-route/**", route_b)
+ page_a, page_a_abort, page_b, page_b_peer = await asyncio.gather(
+ context_a.new_page(),
+ context_a.new_page(),
+ context_b.new_page(),
+ context_b.new_page(),
+ )
+ outcomes = await asyncio.gather(
+ page_a.goto(f"{fixture}/multi-page-route/fulfilled-a", wait_until="load"),
+ page_a_abort.goto(f"{fixture}/multi-page-route/abort", wait_until="load"),
+ page_b.goto(f"{fixture}/multi-page-route/fulfilled-b", wait_until="load"),
+ page_b_peer.goto(
+ f"{fixture}/multi-page-route/fulfilled-b-peer", wait_until="load"
+ ),
+ return_exceptions=True,
+ )
+ if not isinstance(outcomes[1], BaseException):
+ raise SmokeError(f"aborted target navigation did not fail: {outcomes[1]!r}")
+ assert_equal(
+ [
+ outcomes[0].status if not isinstance(outcomes[0], BaseException) else None,
+ outcomes[2].status if not isinstance(outcomes[2], BaseException) else None,
+ outcomes[3].status if not isinstance(outcomes[3], BaseException) else None,
+ ],
+ [200, 201, 201],
+ "concurrent fulfilled route statuses",
+ )
+ assert_equal(
+ await asyncio.gather(
+ page_a.text_content("main"),
+ page_b.text_content("main"),
+ page_b_peer.text_content("main"),
+ ),
+ [
+ "context-a:fulfilled-a",
+ "context-b:fulfilled-b",
+ "context-b:fulfilled-b-peer",
+ ],
+ "concurrent route target ownership",
+ )
+ await page_a_abort.goto(
+ f"{fixture}/plain?route-abort-recovery", wait_until="load"
+ )
+ assert_equal(
+ await page_a_abort.text_content("main"),
+ "plain ok",
+ "aborted target recovery",
+ )
+ record(results, "multi_page_concurrent_fulfill_abort_and_recovery")
+ finally:
+ with suppress(Exception):
+ await context_a.unroute("**/multi-page-route/**")
+ with suppress(Exception):
+ await context_b.unroute("**/multi-page-route/**")
+ await _close_context(context_a)
+ await _close_context(context_b)
+
+
+async def _inflight_navigation_close_and_peer_recovery(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ route_started = asyncio.Event()
+ release_route = asyncio.Event()
+
+ async def hold_navigation(route: Any) -> None:
+ route_started.set()
+ await release_route.wait()
+ with suppress(Exception):
+ await route.abort("aborted")
+
+ victim_navigation: asyncio.Task[Any] | None = None
+ victim_close: asyncio.Task[Any] | None = None
+ try:
+ victim, peer = await asyncio.gather(context.new_page(), context.new_page())
+ await peer.goto(f"{fixture}/plain?inflight-peer=initial", wait_until="load")
+ await victim.route("**/multi-page-inflight/blocked", hold_navigation)
+ victim_navigation = asyncio.create_task(
+ victim.goto(
+ f"{fixture}/multi-page-inflight/blocked",
+ wait_until="load",
+ timeout=10_000,
+ )
+ )
+ await asyncio.wait_for(route_started.wait(), timeout=5)
+
+ await peer.goto(f"{fixture}/plain?inflight-peer=while-blocked", wait_until="load")
+ assert_equal(
+ await peer.evaluate("() => location.search"),
+ "?inflight-peer=while-blocked",
+ "peer navigation while another target request is paused",
+ )
+
+ victim_close = asyncio.create_task(victim.close())
+ await asyncio.sleep(0)
+ release_route.set()
+ close_result, navigation_result = await asyncio.wait_for(
+ asyncio.gather(
+ victim_close,
+ victim_navigation,
+ return_exceptions=True,
+ ),
+ timeout=5,
+ )
+ if isinstance(close_result, BaseException):
+ raise SmokeError(
+ f"closing a target with a paused navigation failed: {close_result!r}"
+ )
+ if not isinstance(navigation_result, BaseException):
+ raise SmokeError(
+ "closing a target did not reject its paused navigation: "
+ f"{navigation_result!r}"
+ )
+
+ replacement = await context.new_page()
+ await asyncio.gather(
+ peer.goto(f"{fixture}/plain?inflight-peer=final", wait_until="load"),
+ replacement.goto(
+ f"{fixture}/plain?inflight-replacement", wait_until="load"
+ ),
+ )
+ assert_equal(
+ await asyncio.gather(
+ peer.evaluate("() => location.search"),
+ replacement.evaluate("() => location.search"),
+ ),
+ ["?inflight-peer=final", "?inflight-replacement"],
+ "peer and replacement after paused target close",
+ )
+ record(results, "multi_page_inflight_navigation_close_and_peer_recovery")
+ finally:
+ release_route.set()
+ for task in (victim_navigation, victim_close):
+ if task is not None and not task.done():
+ task.cancel()
+ await _close_context(context)
+
+
+async def _target_local_session_events(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ pages = await asyncio.gather(*(context.new_page() for _ in range(3)))
+ await asyncio.gather(
+ *(
+ page.goto(
+ f"{fixture}/plain?session-events={index}", wait_until="load"
+ )
+ for index, page in enumerate(pages)
+ )
+ )
+ primaries = await asyncio.gather(
+ *(context.new_cdp_session(page) for page in pages)
+ )
+ auxiliaries = await asyncio.gather(
+ *(context.new_cdp_session(page) for page in pages)
+ )
+ sessions = [*primaries, *auxiliaries]
+ collectors = [
+ attach_cdp_event_collector(
+ session,
+ ["Runtime.consoleAPICalled", "Network.requestWillBeSent"],
+ )
+ for session in sessions
+ ]
+ await asyncio.gather(
+ *(_send_cdp(session, "Runtime.enable") for session in sessions),
+ *(_send_cdp(session, "Network.enable") for session in sessions),
+ )
+
+ network_tokens = [f"session-network={index}" for index in range(3)]
+ await asyncio.gather(
+ *(
+ page.goto(
+ f"{fixture}/plain?{network_tokens[index]}",
+ wait_until="load",
+ )
+ for index, page in enumerate(pages)
+ )
+ )
+ for index, token in enumerate(network_tokens):
+ for collector_index in (index, index + len(pages)):
+ await wait_until(
+ lambda collector_index=collector_index, token=token: any(
+ token in url
+ for url in _document_request_urls(collectors[collector_index])
+ ),
+ f"Document request event for target {index} session {collector_index}",
+ )
+ peer_tokens = set(network_tokens) - {token}
+ leaked = {
+ peer_token
+ for peer_token in peer_tokens
+ if any(
+ peer_token in url
+ for url in _document_request_urls(collectors[collector_index])
+ )
+ }
+ if leaked:
+ raise SmokeError(
+ f"target {index} Network sessions received peer events: {leaked}"
+ )
+
+ tokens = [f"multi-page-console-{index}" for index in range(3)]
+ await asyncio.gather(
+ *(
+ _send_cdp(
+ primaries[index],
+ "Runtime.evaluate",
+ {
+ "expression": f"console.log('{token}')",
+ "returnByValue": True,
+ },
+ )
+ for index, token in enumerate(tokens)
+ )
+ )
+
+ for index, token in enumerate(tokens):
+ await wait_until(
+ lambda index=index, token=token: token
+ in _console_values(collectors[index]),
+ f"primary console event for target {index}",
+ )
+ await wait_until(
+ lambda index=index, token=token: token
+ in _console_values(collectors[index + len(pages)]),
+ f"auxiliary console event for target {index}",
+ )
+ for index, token in enumerate(tokens):
+ other_tokens = set(tokens) - {token}
+ for collector_index in (index, index + len(pages)):
+ leaked = other_tokens & set(_console_values(collectors[collector_index]))
+ if leaked:
+ raise SmokeError(
+ f"target {index} console sessions received peer events: {leaked}"
+ )
+
+ await primaries[1].detach()
+ sessions.remove(primaries[1])
+ surviving = await _send_cdp(
+ auxiliaries[1],
+ "Runtime.evaluate",
+ {"expression": "21 * 2", "returnByValue": True},
+ )
+ assert_equal(_runtime_value(surviving), 42, "auxiliary after primary detach")
+ replacement = await context.new_cdp_session(pages[1])
+ sessions.append(replacement)
+ replacement_read = await _send_cdp(
+ replacement,
+ "Runtime.evaluate",
+ {"expression": "location.search", "returnByValue": True},
+ )
+ assert_equal(
+ _runtime_value(replacement_read),
+ "?session-network=1",
+ "reattached target session route",
+ )
+ record(
+ results,
+ "multi_page_target_local_multi_session_events",
+ {"pages": len(pages), "sessions": 6},
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _popup_tree_survives_middle_close(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ try:
+ root, peer = await asyncio.gather(context.new_page(), context.new_page())
+ await asyncio.gather(
+ root.goto(f"{fixture}/plain?popup-tree=root", wait_until="load"),
+ peer.goto(f"{fixture}/plain?popup-tree=peer", wait_until="load"),
+ )
+ popup = await _open_popup(
+ root,
+ f"{fixture}/plain?popup-tree=middle",
+ "multi-page-middle",
+ )
+ child = await _open_popup(
+ popup,
+ f"{fixture}/plain?popup-tree=child",
+ "multi-page-child",
+ )
+ sibling = await _open_popup(
+ root,
+ f"{fixture}/plain?popup-tree=sibling",
+ "multi-page-sibling",
+ )
+ await asyncio.gather(
+ root.evaluate("globalThis.__popupTreeToken = 'root'"),
+ popup.evaluate("globalThis.__popupTreeToken = 'middle'"),
+ child.evaluate("globalThis.__popupTreeToken = 'child'"),
+ sibling.evaluate("globalThis.__popupTreeToken = 'sibling'"),
+ peer.evaluate("globalThis.__popupTreeToken = 'peer'"),
+ )
+
+ await popup.close()
+ assert_equal(
+ await asyncio.gather(
+ root.evaluate("globalThis.__popupTreeToken"),
+ child.evaluate("globalThis.__popupTreeToken"),
+ sibling.evaluate("globalThis.__popupTreeToken"),
+ peer.evaluate("globalThis.__popupTreeToken"),
+ ),
+ ["root", "child", "sibling", "peer"],
+ "popup-tree survivors after middle target close",
+ )
+ assert_equal(
+ await child.evaluate("() => window.opener?.closed ?? null"),
+ None,
+ "child clears its retired middle opener",
+ )
+
+ named = await _open_popup(
+ root,
+ f"{fixture}/plain?popup-tree=named-first",
+ "multi-page-named",
+ )
+ page_count = len(context.pages)
+ await root.evaluate(
+ "url => window.open(url, 'multi-page-named')",
+ f"{fixture}/plain?popup-tree=named-second",
+ )
+ await named.wait_for_url("**/plain?popup-tree=named-second", timeout=5_000)
+ assert_equal(len(context.pages), page_count, "named popup target reuse")
+ assert_equal(
+ await sibling.evaluate("globalThis.__popupTreeToken"),
+ "sibling",
+ "sibling popup after named-target reuse",
+ )
+ record(
+ results,
+ "multi_page_popup_tree_middle_close_and_named_reuse",
+ {"survivingPages": len(context.pages)},
+ )
+ finally:
+ await _close_context(context)
+
+
+async def _target_local_dialogs(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ try:
+ prompt_page, confirm_page, peer = await asyncio.gather(
+ context.new_page(),
+ context.new_page(),
+ context.new_page(),
+ )
+ await asyncio.gather(
+ prompt_page.goto(f"{fixture}/dialog?target=prompt", wait_until="load"),
+ confirm_page.goto(f"{fixture}/dialog?target=confirm", wait_until="load"),
+ peer.goto(f"{fixture}/plain?target=dialog-peer", wait_until="load"),
+ )
+
+ async with (
+ prompt_page.expect_event("dialog", timeout=5_000) as prompt_info,
+ confirm_page.expect_event("dialog", timeout=5_000) as confirm_info,
+ ):
+ prompt_task = asyncio.create_task(
+ prompt_page.evaluate(
+ "() => prompt('multi-page prompt', 'target-local default')"
+ )
+ )
+ confirm_task = asyncio.create_task(
+ confirm_page.evaluate("() => confirm('multi-page confirm')")
+ )
+ prompt, confirm = await asyncio.gather(prompt_info.value, confirm_info.value)
+ assert_equal(prompt.type, "prompt", "target-local prompt type")
+ assert_equal(prompt.message, "multi-page prompt", "target-local prompt message")
+ assert_equal(
+ prompt.default_value,
+ "target-local default",
+ "target-local prompt default",
+ )
+ assert_equal(confirm.type, "confirm", "target-local confirm type")
+ assert_equal(confirm.message, "multi-page confirm", "target-local confirm message")
+ assert_equal(
+ await peer.evaluate("() => location.search"),
+ "?target=dialog-peer",
+ "peer target while two dialogs are open",
+ )
+
+ await confirm.accept()
+ assert_equal(await confirm_task, True, "target-local confirm accept result")
+ assert_equal(
+ prompt_page.url,
+ f"{fixture}/dialog?target=prompt",
+ "accepting peer dialog does not disturb prompt owner",
+ )
+ await prompt.dismiss()
+ assert_equal(await prompt_task, None, "target-local prompt dismiss result")
+ assert_equal(
+ await asyncio.gather(
+ prompt_page.text_content("#alert"),
+ confirm_page.text_content("#alert"),
+ peer.text_content("main"),
+ ),
+ ["alert", "alert", "plain ok"],
+ "all targets after reverse-order dialog handling",
+ )
+ record(results, "multi_page_target_local_concurrent_dialogs")
+ finally:
+ await _close_context(context)
+
+
+async def _concurrent_downloads_and_peer(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ try:
+ download_a, download_b, peer = await asyncio.gather(
+ context.new_page(),
+ context.new_page(),
+ context.new_page(),
+ )
+ await asyncio.gather(
+ download_a.goto(f"{fixture}/download-page", wait_until="load"),
+ download_b.goto(f"{fixture}/download-page", wait_until="load"),
+ peer.goto(f"{fixture}/plain?target=download-peer", wait_until="load"),
+ )
+
+ async with (
+ download_a.expect_download(timeout=10_000) as first_info,
+ download_b.expect_download(timeout=10_000) as second_info,
+ ):
+ await asyncio.gather(
+ download_a.locator("#download").evaluate("anchor => anchor.click()"),
+ download_b.locator("#download").evaluate("anchor => anchor.click()"),
+ )
+ first, second = await asyncio.gather(first_info.value, second_info.value)
+ assert_equal(
+ [first.suggested_filename, second.suggested_filename],
+ ["smoke-download.txt", "smoke-download.txt"],
+ "concurrent target-local download filenames",
+ )
+ first_path, second_path = await asyncio.gather(first.path(), second.path())
+ assert_equal(
+ [
+ Path(first_path).read_text(encoding="utf-8"),
+ Path(second_path).read_text(encoding="utf-8"),
+ ],
+ ["download contents", "download contents"],
+ "concurrent target-local download artifacts",
+ )
+
+ async with download_a.expect_download(timeout=10_000) as slow_info:
+ await download_a.locator("#slow-download").evaluate(
+ "anchor => anchor.click()"
+ )
+ slow = await slow_info.value
+ assert_equal(
+ await peer.evaluate("() => location.search"),
+ "?target=download-peer",
+ "peer target during slow download",
+ )
+ await slow.cancel()
+ assert_equal(await slow.failure(), "canceled", "target-local download cancel")
+ assert_equal(
+ await download_b.text_content("#download"),
+ "download",
+ "peer download page after other target cancellation",
+ )
+ record(results, "multi_page_concurrent_downloads_and_peer_cancel")
+ finally:
+ await _close_context(context)
+
+
+async def _background_tasks_workers_and_screenshots(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context(viewport={"width": 320, "height": 200})
+ try:
+ pages = await asyncio.gather(*(context.new_page() for _ in range(4)))
+ await asyncio.gather(
+ *(
+ page.goto(
+ f"{fixture}/plain?background-page={index}", wait_until="load"
+ )
+ for index, page in enumerate(pages)
+ )
+ )
+ colors = ("#ff0000", "#00ff00", "#0000ff", "#ffff00")
+ await asyncio.gather(
+ *(
+ page.set_content(
+ "<!doctype html>"
+ f"<style>html,body{{margin:0;background:{color}}}</style>"
+ f"<main>background-page-{index}</main>",
+ wait_until="load",
+ )
+ for index, (page, color) in enumerate(
+ zip(pages, colors, strict=True)
+ )
+ )
+ )
+ screenshots = await asyncio.gather(*(page.screenshot() for page in pages))
+ if any(not screenshot.startswith(b"\x89PNG\r\n\x1a\n") for screenshot in screenshots):
+ raise SmokeError("concurrent page screenshot returned a non-PNG payload")
+ screenshot_hashes = {hashlib.sha256(screenshot).hexdigest() for screenshot in screenshots}
+ assert_equal(len(screenshot_hashes), 4, "target-local concurrent screenshots")
+
+ worker_results = await asyncio.gather(
+ *(
+ run_worker_command(page, {"page": index})
+ for index, page in enumerate(pages[:3])
+ )
+ )
+ assert_equal(
+ [result.get("echoed", {}).get("page") for result in worker_results],
+ [0, 1, 2],
+ "target-local dedicated workers",
+ )
+
+ timer_tasks = [
+ asyncio.create_task(
+ page.evaluate(
+ """token => new Promise(resolve => {
+ setTimeout(() => resolve(`${token}:${document.querySelector('main').textContent}`), 120);
+ })""",
+ f"timer-{index}",
+ )
+ )
+ for index, page in enumerate(pages)
+ ]
+ for page in reversed(pages):
+ await page.bring_to_front()
+ assert_equal(
+ await asyncio.gather(*timer_tasks),
+ [f"timer-{index}:background-page-{index}" for index in range(4)],
+ "background timers across foreground activation churn",
+ )
+
+ pending = asyncio.create_task(
+ pages[2].evaluate("() => new Promise(resolve => setTimeout(resolve, 10_000))")
+ )
+ await asyncio.sleep(0.05)
+ await pages[2].close()
+ pending_result = (await asyncio.gather(pending, return_exceptions=True))[0]
+ if not isinstance(pending_result, BaseException):
+ raise SmokeError("closing a page did not reject its pending Runtime evaluation")
+ assert_equal(
+ await asyncio.gather(
+ pages[0].text_content("main"),
+ pages[1].text_content("main"),
+ pages[3].text_content("main"),
+ ),
+ ["background-page-0", "background-page-1", "background-page-3"],
+ "peer pages after pending-evaluate target close",
+ )
+ record(
+ results,
+ "multi_page_background_timer_worker_screenshot_and_close",
+ {"screenshots": 4, "workers": 3},
+ )
+ finally:
+ await _close_context(context)
+
+
+async def _context_teardown_with_pending_commands(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context_a = await browser.new_context()
+ context_b = await browser.new_context()
+ context_a_closed = False
+ try:
+ page_a, page_a_peer, survivor = await asyncio.gather(
+ context_a.new_page(),
+ context_a.new_page(),
+ context_b.new_page(),
+ )
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/plain?teardown=a", wait_until="load"),
+ page_a_peer.goto(f"{fixture}/plain?teardown=a-peer", wait_until="load"),
+ survivor.goto(f"{fixture}/plain?teardown=survivor", wait_until="load"),
+ )
+ pending = [
+ asyncio.create_task(
+ page.evaluate("() => new Promise(() => {})")
+ )
+ for page in (page_a, page_a_peer)
+ ]
+ await asyncio.sleep(0.05)
+ await asyncio.wait_for(context_a.close(), timeout=5)
+ context_a_closed = True
+ pending_results = await asyncio.wait_for(
+ asyncio.gather(*pending, return_exceptions=True),
+ timeout=5,
+ )
+ if not all(isinstance(result, BaseException) for result in pending_results):
+ raise SmokeError(
+ f"disposed context did not reject every pending command: {pending_results!r}"
+ )
+ assert_equal(
+ await survivor.evaluate("() => location.search"),
+ "?teardown=survivor",
+ "survivor target after pending-command context disposal",
+ )
+ replacement = await context_b.new_page()
+ await replacement.goto(
+ f"{fixture}/plain?teardown=replacement", wait_until="load"
+ )
+ assert_equal(
+ await asyncio.gather(
+ survivor.text_content("main"), replacement.text_content("main")
+ ),
+ ["plain ok", "plain ok"],
+ "new and existing pages after peer context disposal",
+ )
+ record(
+ results,
+ "multi_page_context_teardown_with_pending_commands",
+ {"pendingCommands": len(pending)},
+ )
+ finally:
+ if not context_a_closed:
+ await _close_context(context_a)
+ await _close_context(context_b)
+
+
+async def _open_popup(page: Any, url: str, name: str) -> Any:
+ async with page.expect_popup(timeout=5_000) as popup_info:
+ opened = await page.evaluate(
+ "({url, name}) => Boolean(window.open(url, name))",
+ {"url": url, "name": name},
+ )
+ assert_equal(opened, True, f"window.open returned a WindowProxy for {name}")
+ popup = await popup_info.value
+ await popup.wait_for_load_state("load", timeout=10_000)
+ return popup
+
+
+async def _close_startup_target(browser: Any) -> None:
+ session = await browser.new_browser_cdp_session()
+ try:
+ targets = await _send_cdp(session, "Target.getTargets")
+ startup = [
+ info
+ for info in targets.get("targetInfos", [])
+ if info.get("type") == "page" and info.get("targetId") == "moli-default"
+ ]
+ if not startup:
+ startup = [
+ info
+ for info in targets.get("targetInfos", [])
+ if info.get("type") == "page" and info.get("url") == "about:blank"
+ ]
+ if len(startup) != 1:
+ raise SmokeError(f"expected one startup Page target, got: {startup!r}")
+ startup_target_id = startup[0].get("targetId")
+ if not isinstance(startup_target_id, str) or not startup_target_id:
+ raise SmokeError(f"startup Page target has no targetId: {startup[0]!r}")
+ result = await _send_cdp(
+ session,
+ "Target.closeTarget",
+ {"targetId": startup_target_id},
+ )
+ assert_equal(result.get("success"), True, "close startup Page target")
+
+ async def startup_is_absent() -> bool:
+ current = await _send_cdp(session, "Target.getTargets")
+ return all(
+ info.get("targetId") != startup_target_id
+ for info in current.get("targetInfos", [])
+ )
+
+ await wait_until(startup_is_absent, "startup Page target retirement")
+ finally:
+ await session.detach()
+
+
+async def _send_cdp(
+ session: Any,
+ method: str,
+ params: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ return await asyncio.wait_for(session.send(method, params or {}), timeout=5)
+
+
+async def _close_context(context: Any) -> None:
+ try:
+ await asyncio.wait_for(context.close(), timeout=5)
+ except Exception as error:
+ raise SmokeError(f"BrowserContext.close failed: {type(error).__name__}: {error}") from error
+
+
+def _runtime_value(response: dict[str, Any]) -> Any:
+ return response.get("result", {}).get("value")
+
+
+def _collect_frame_ids(frame_tree: dict[str, Any]) -> set[str]:
+ ids: set[str] = set()
+ frame_id = frame_tree.get("frame", {}).get("id")
+ if isinstance(frame_id, str):
+ ids.add(frame_id)
+ for child in frame_tree.get("childFrames", []):
+ ids.update(_collect_frame_ids(child))
+ return ids
+
+
+def _console_values(events: list[dict[str, Any]]) -> list[Any]:
+ values: list[Any] = []
+ for event in events:
+ for argument in event.get("params", {}).get("args", []):
+ if "value" in argument:
+ values.append(argument["value"])
+ return values
+
+
+def _document_request_urls(events: list[dict[str, Any]]) -> list[str]:
+ return [
+ event.get("params", {}).get("request", {}).get("url", "")
+ for event in events
+ if event.get("method") == "Network.requestWillBeSent"
+ and event.get("params", {}).get("type") == "Document"
+ ]
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py
new file mode 100644
index 000000000..9777868e9
--- /dev/null
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py
@@ -0,0 +1,3226 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import urllib.request
+from contextlib import suppress
+from typing import Any, Awaitable
+
+from ..assertions import SmokeError, assert_equal, record_contract, wait_until
+from ..helpers import attach_cdp_event_collector
+from ..progress import await_with_progress
+
+
+async def run_multi_page_contracts(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ """Run Chromium-calibrated ownership contracts across live Page targets."""
+
+ contracts = (
+ _remote_object_and_execution_context_ownership,
+ _target_local_device_metrics,
+ _new_document_script_session_lifecycle,
+ _same_target_new_document_script_session_ownership,
+ _isolated_world_script_detach_lifecycle,
+ _same_name_isolated_worlds_are_session_local,
+ _runtime_binding_session_lifecycle,
+ _same_target_remote_objects_are_session_local,
+ _same_target_dom_node_and_backend_node_ownership,
+ _same_source_scripts_keep_session_authority,
+ _network_enablement_is_session_local,
+ _page_lifecycle_enablement_is_session_local,
+ _runtime_enablement_and_context_replay_are_session_local,
+ _same_name_runtime_bindings_keep_session_authority,
+ _session_detach_cancels_only_its_pending_await,
+ _fetch_interception_is_session_local,
+ _network_and_emulation_profiles_are_target_local,
+ _closed_target_new_document_script_does_not_leak,
+ _broadcast_channel_context_partition,
+ _same_target_navigation_supersession,
+ _target_destroy_event_cardinality,
+ _network_response_body_target_ownership,
+ _websocket_survives_peer_target_close,
+ )
+ for contract in contracts:
+ await await_with_progress(
+ f"multi-page/{contract.__name__.removeprefix('_')}",
+ contract(browser, fixture, results),
+ timeout_seconds=20,
+ )
+
+
+async def _remote_object_and_execution_context_ownership(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page_a, page_b = await asyncio.gather(context.new_page(), context.new_page())
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/plain?multi-page-object=a", wait_until="load"),
+ page_b.goto(f"{fixture}/plain?multi-page-object=b", wait_until="load"),
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page_a),
+ context.new_cdp_session(page_b),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("Runtime.enable"),
+ session_b.send("Runtime.enable"),
+ )
+
+ remote = (
+ await session_a.send(
+ "Runtime.evaluate",
+ {"expression": "({owner: 'page-a', value: 7})"},
+ )
+ ).get("result", {})
+ object_id = remote.get("objectId")
+ if not isinstance(object_id, str) or not object_id:
+ raise SmokeError(f"page A evaluation returned no objectId: {remote!r}")
+
+ frame_tree = await session_a.send("Page.getFrameTree")
+ frame_id = frame_tree.get("frameTree", {}).get("frame", {}).get("id")
+ if not isinstance(frame_id, str) or not frame_id:
+ raise SmokeError(f"page A frame tree returned no frame id: {frame_tree!r}")
+ isolated = await session_a.send(
+ "Page.createIsolatedWorld",
+ {"frameId": frame_id, "worldName": "multi-page-owner-a"},
+ )
+ execution_context_id = isolated.get("executionContextId")
+ if not isinstance(execution_context_id, int):
+ raise SmokeError(
+ f"page A isolated world returned no executionContextId: {isolated!r}"
+ )
+
+ foreign_object_error = await _expect_protocol_error(
+ session_b.send("Runtime.getProperties", {"objectId": object_id}),
+ "page B resolving page A objectId",
+ )
+ foreign_context_error = await _expect_protocol_error(
+ session_b.send(
+ "Runtime.evaluate",
+ {
+ "expression": "1",
+ "contextId": execution_context_id,
+ "returnByValue": True,
+ },
+ ),
+ "page B evaluating in page A executionContextId",
+ )
+
+ own_properties = await session_a.send(
+ "Runtime.getProperties",
+ {"objectId": object_id, "ownProperties": True},
+ )
+ enumerable_names = {
+ prop.get("name")
+ for prop in own_properties.get("result", [])
+ if prop.get("enumerable")
+ }
+ assert_equal(
+ enumerable_names,
+ {"owner", "value"},
+ "owner session resolves its own remote object",
+ )
+ peer_value = await session_b.send(
+ "Runtime.evaluate",
+ {"expression": "6 * 7", "returnByValue": True},
+ )
+ assert_equal(
+ peer_value.get("result", {}).get("value"),
+ 42,
+ "peer session after rejected foreign identifiers",
+ )
+
+ await page_a.goto(
+ f"{fixture}/plain?multi-page-object=a-replaced",
+ wait_until="load",
+ )
+ stale_object_error = await _expect_protocol_error(
+ session_a.send("Runtime.getProperties", {"objectId": object_id}),
+ "old objectId after its owning Document was replaced",
+ )
+ assert_equal(
+ await page_b.evaluate("() => location.search"),
+ "?multi-page-object=b",
+ "peer target after owner Document replacement",
+ )
+ record_contract(
+ results,
+ "multi_page_remote_object_and_execution_context_ownership",
+ contract=(
+ "RemoteObject and executionContext identifiers are target-local; "
+ "foreign and stale identifiers fail without poisoning either session."
+ ),
+ source="Chromium CDP oracle",
+ commands=[
+ "Runtime.evaluate",
+ "Runtime.getProperties",
+ "Page.createIsolatedWorld",
+ ],
+ observed={
+ "foreignObjectRejected": bool(foreign_object_error),
+ "foreignContextRejected": bool(foreign_context_error),
+ "staleObjectRejected": bool(stale_object_error),
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _target_local_device_metrics(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context(viewport={"width": 800, "height": 600})
+ sessions: list[Any] = []
+ try:
+ page_a, page_b = await asyncio.gather(context.new_page(), context.new_page())
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/plain?multi-page-metrics=a", wait_until="load"),
+ page_b.goto(f"{fixture}/plain?multi-page-metrics=b", wait_until="load"),
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page_a),
+ context.new_cdp_session(page_b),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send(
+ "Emulation.setDeviceMetricsOverride",
+ {
+ "width": 420,
+ "height": 310,
+ "deviceScaleFactor": 2,
+ "mobile": False,
+ },
+ ),
+ session_b.send(
+ "Emulation.setDeviceMetricsOverride",
+ {
+ "width": 530,
+ "height": 390,
+ "deviceScaleFactor": 1.5,
+ "mobile": False,
+ },
+ ),
+ )
+ expected = [[420, 310, 2], [530, 390, 1.5]]
+ before_navigation = await asyncio.gather(
+ _viewport_metrics(page_a),
+ _viewport_metrics(page_b),
+ )
+ assert_equal(before_navigation, expected, "target-local device metrics")
+
+ await asyncio.gather(
+ page_a.goto(
+ f"{fixture}/plain?multi-page-metrics=a-replaced",
+ wait_until="load",
+ ),
+ page_b.goto(
+ f"{fixture}/plain?multi-page-metrics=b-replaced",
+ wait_until="load",
+ ),
+ )
+ after_navigation = await asyncio.gather(
+ _viewport_metrics(page_a),
+ _viewport_metrics(page_b),
+ )
+ assert_equal(
+ after_navigation,
+ expected,
+ "target-local device metrics after concurrent Document replacement",
+ )
+
+ await session_a.send("Emulation.clearDeviceMetricsOverride")
+ cleared_a, unchanged_b = await asyncio.gather(
+ _viewport_metrics(page_a),
+ _viewport_metrics(page_b),
+ )
+ if cleared_a[:2] == expected[0][:2] or cleared_a[2] != 1:
+ raise SmokeError(
+ "clearing page A metrics did not restore its unscaled viewport: "
+ f"{cleared_a!r}"
+ )
+ assert_equal(
+ unchanged_b,
+ expected[1],
+ "clearing page A metrics does not mutate page B",
+ )
+ record_contract(
+ results,
+ "multi_page_target_local_device_metrics",
+ contract=(
+ "Device metrics are target-local, survive cross-Document navigation, "
+ "and clearing one target does not mutate a peer."
+ ),
+ source="Chromium CDP oracle",
+ commands=[
+ "Emulation.setDeviceMetricsOverride",
+ "Emulation.clearDeviceMetricsOverride",
+ ],
+ observed={"before": before_navigation, "after": after_navigation},
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _new_document_script_session_lifecycle(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page_a, page_b = await asyncio.gather(context.new_page(), context.new_page())
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page_a),
+ context.new_cdp_session(page_b),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("Page.enable"),
+ session_b.send("Page.enable"),
+ )
+ script_a, script_b = await asyncio.gather(
+ session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__multiPageInit = 'page-a';"},
+ ),
+ session_b.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__multiPageInit = 'page-b';"},
+ ),
+ )
+ identifier_b = script_b.get("identifier")
+ if not isinstance(script_a.get("identifier"), str) or not isinstance(
+ identifier_b, str
+ ):
+ raise SmokeError(
+ "new-Document script registration returned invalid identifiers: "
+ f"{script_a!r}, {script_b!r}"
+ )
+
+ await asyncio.gather(
+ page_a.goto(f"{fixture}/plain?multi-page-init=a", wait_until="load"),
+ page_b.goto(f"{fixture}/plain?multi-page-init=b", wait_until="load"),
+ )
+ assert_equal(
+ await asyncio.gather(
+ page_a.evaluate("globalThis.__multiPageInit"),
+ page_b.evaluate("globalThis.__multiPageInit"),
+ ),
+ ["page-a", "page-b"],
+ "target-local new-Document scripts",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ detached_live_child_value = await page_a.evaluate(
+ """() => new Promise(resolve => {
+ const frame = document.createElement('iframe');
+ frame.srcdoc = '<!doctype html><body>detached-session-child</body>';
+ frame.onload = () => resolve(
+ frame.contentWindow.__multiPageInit ?? null
+ );
+ document.body.append(frame);
+ })"""
+ )
+ assert_equal(
+ detached_live_child_value,
+ None,
+ "detaching owner session removes script from the live Page registry",
+ )
+ await asyncio.gather(
+ page_a.goto(
+ f"{fixture}/plain?multi-page-init=a-after-detach",
+ wait_until="load",
+ ),
+ page_b.goto(
+ f"{fixture}/plain?multi-page-init=b-next",
+ wait_until="load",
+ ),
+ )
+ assert_equal(
+ await page_a.evaluate("globalThis.__multiPageInit"),
+ None,
+ "detaching owner session removes its new-Document script",
+ )
+ assert_equal(
+ await page_b.evaluate("globalThis.__multiPageInit"),
+ "page-b",
+ "peer session script survives owner detach",
+ )
+
+ await session_b.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": identifier_b},
+ )
+ await page_b.goto(
+ f"{fixture}/plain?multi-page-init=b-removed",
+ wait_until="load",
+ )
+ assert_equal(
+ await page_b.evaluate("globalThis.__multiPageInit"),
+ None,
+ "explicitly removed new-Document script",
+ )
+
+ replacement_session = await context.new_cdp_session(page_a)
+ sessions.append(replacement_session)
+ replacement_value = await replacement_session.send(
+ "Runtime.evaluate",
+ {"expression": "40 + 2", "returnByValue": True},
+ )
+ assert_equal(
+ replacement_value.get("result", {}).get("value"),
+ 42,
+ "replacement session after script-owner detach",
+ )
+ record_contract(
+ results,
+ "multi_page_new_document_script_session_lifecycle",
+ contract=(
+ "Page.addScriptToEvaluateOnNewDocument is session- and target-local; "
+ "it persists across navigation until removed or its owner detaches."
+ ),
+ source="Chromium CDP oracle",
+ commands=[
+ "Page.addScriptToEvaluateOnNewDocument",
+ "Page.removeScriptToEvaluateOnNewDocument",
+ ],
+ observed={
+ "targetValues": ["page-a", "page-b"],
+ "removedFromLivePage": True,
+ "removedOnDetach": True,
+ "removedExplicitly": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _same_target_new_document_script_session_ownership(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("Page.enable"),
+ session_b.send("Page.enable"),
+ )
+ script_a, script_b = await asyncio.gather(
+ session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__multiPageSessionA = 'session-a';"},
+ ),
+ session_b.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__multiPageSessionB = 'session-b';"},
+ ),
+ )
+ identifier_a = script_a.get("identifier")
+ identifier_b = script_b.get("identifier")
+ if not isinstance(identifier_a, str) or not isinstance(identifier_b, str):
+ raise SmokeError(
+ "same-target new-Document script registration returned invalid "
+ f"identifiers: {script_a!r}, {script_b!r}"
+ )
+
+ await page.goto(
+ f"{fixture}/plain?multi-page-session-scripts=both",
+ wait_until="load",
+ )
+ assert_equal(
+ await _same_target_session_script_values(page),
+ ["session-a", "session-b"],
+ "same-target scripts from two CDP sessions",
+ )
+
+ await session_a.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": identifier_a},
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-session-scripts=a-removed",
+ wait_until="load",
+ )
+ assert_equal(
+ await _same_target_session_script_values(page),
+ [None, "session-b"],
+ "removing one session's script preserves its same-target peer",
+ )
+
+ await session_b.detach()
+ sessions.remove(session_b)
+ detached_live_child_value = await page.evaluate(
+ """() => new Promise(resolve => {
+ const frame = document.createElement('iframe');
+ frame.srcdoc = '<!doctype html><body>same-target-detached-child</body>';
+ frame.onload = () => resolve(
+ frame.contentWindow.__multiPageSessionB ?? null
+ );
+ document.body.append(frame);
+ })"""
+ )
+ assert_equal(
+ detached_live_child_value,
+ None,
+ "detaching one same-target session updates the live Page registry",
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-session-scripts=both-gone",
+ wait_until="load",
+ )
+ assert_equal(
+ await _same_target_session_script_values(page),
+ [None, None],
+ "same-target session-owned scripts after remove and detach",
+ )
+
+ replacement_session = await context.new_cdp_session(page)
+ sessions.append(replacement_session)
+ replacement_value = await replacement_session.send(
+ "Runtime.evaluate",
+ {"expression": "21 * 2", "returnByValue": True},
+ )
+ assert_equal(
+ replacement_value.get("result", {}).get("value"),
+ 42,
+ "replacement session after same-target script cleanup",
+ )
+ record_contract(
+ results,
+ "multi_page_same_target_new_document_script_session_ownership",
+ contract=(
+ "Multiple CDP sessions on one Page own independent new-Document "
+ "scripts; remove and detach clean only the calling session's script."
+ ),
+ source="Chromium CDP oracle",
+ commands=[
+ "Page.addScriptToEvaluateOnNewDocument",
+ "Page.removeScriptToEvaluateOnNewDocument",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "bothInitiallyInjected": True,
+ "peerSurvivedRemove": True,
+ "detachedScriptRemovedFromLivePage": True,
+ "bothEventuallyRemoved": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _isolated_world_script_detach_lifecycle(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ owner_session = await context.new_cdp_session(page)
+ sessions = [owner_session]
+ await owner_session.send("Page.enable")
+ registration = await owner_session.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {
+ "source": "globalThis.__multiPageUtilityInit = 'utility-ready';",
+ "worldName": "multi-page-utility",
+ },
+ )
+ if not isinstance(registration.get("identifier"), str):
+ raise SmokeError(
+ "isolated-world script registration returned no identifier: "
+ f"{registration!r}"
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-utility-script=owner",
+ wait_until="load",
+ )
+ owner_context_id = await _create_isolated_world(
+ owner_session,
+ "multi-page-utility",
+ )
+ await owner_session.send(
+ "Runtime.addBinding",
+ {
+ "name": "multiPageUtilityBinding",
+ "executionContextId": owner_context_id,
+ },
+ )
+ assert_equal(
+ await _evaluate_context_value(
+ owner_session,
+ owner_context_id,
+ "[globalThis.__multiPageUtilityInit ?? null, "
+ "typeof globalThis.multiPageUtilityBinding]",
+ ),
+ ["utility-ready", "function"],
+ "isolated-world session state before owner detach",
+ )
+
+ await owner_session.detach()
+ sessions.remove(owner_session)
+ replacement_session = await context.new_cdp_session(page)
+ sessions.append(replacement_session)
+ await replacement_session.send("Page.enable")
+ live_context_id = await _create_isolated_world(
+ replacement_session,
+ "multi-page-utility",
+ )
+ assert_equal(
+ await _evaluate_context_value(
+ replacement_session,
+ live_context_id,
+ "[globalThis.__multiPageUtilityInit ?? null, "
+ "typeof globalThis.multiPageUtilityBinding]",
+ ),
+ [None, "undefined"],
+ "detach retires the prior session's live isolated world and binding",
+ )
+
+ await page.goto(
+ f"{fixture}/plain?multi-page-utility-script=after-detach",
+ wait_until="load",
+ )
+ future_context_id = await _create_isolated_world(
+ replacement_session,
+ "multi-page-utility",
+ )
+ assert_equal(
+ await _evaluate_context_value(
+ replacement_session,
+ future_context_id,
+ "[globalThis.__multiPageUtilityInit ?? null, "
+ "typeof globalThis.multiPageUtilityBinding]",
+ ),
+ [None, "undefined"],
+ "detached session's isolated-world state is absent from a future Document",
+ )
+ record_contract(
+ results,
+ "multi_page_isolated_world_script_detach_lifecycle",
+ contract=(
+ "Detaching a CDP session retires its named isolated world, binding, and "
+ "future-Document script without contaminating a replacement session."
+ ),
+ source="Chromium CDP oracle",
+ commands=[
+ "Page.addScriptToEvaluateOnNewDocument",
+ "Page.createIsolatedWorld",
+ "Runtime.addBinding",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "replacementLiveWorldState": [None, "undefined"],
+ "replacementFutureDocumentState": [None, "undefined"],
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _same_name_isolated_worlds_are_session_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("Page.enable"),
+ session_b.send("Page.enable"),
+ )
+ await asyncio.gather(
+ session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {
+ "source": "globalThis.__multiPageWorldA = 'session-a';",
+ "worldName": "multi-page-shared-name",
+ },
+ ),
+ session_b.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {
+ "source": "globalThis.__multiPageWorldB = 'session-b';",
+ "worldName": "multi-page-shared-name",
+ },
+ ),
+ )
+ await page.goto(
+ f"{fixture}/iframe?multi-page-worlds=initial",
+ wait_until="load",
+ )
+ frame_ids = await _root_and_child_frame_ids(session_a)
+ contexts_a = await _create_isolated_worlds_for_frames(
+ session_a,
+ frame_ids,
+ "multi-page-shared-name",
+ )
+ contexts_b = await _create_isolated_worlds_for_frames(
+ session_b,
+ frame_ids,
+ "multi-page-shared-name",
+ )
+ if any(left == right for left, right in zip(contexts_a, contexts_b, strict=True)):
+ raise SmokeError(
+ "same-name isolated worlds reused an execution context across sessions: "
+ f"{contexts_a!r} vs {contexts_b!r}"
+ )
+ expression = (
+ "[globalThis.__multiPageWorldA ?? null, "
+ "globalThis.__multiPageWorldB ?? null]"
+ )
+ assert_equal(
+ await asyncio.gather(
+ *(
+ _evaluate_context_value(session_a, context_id, expression)
+ for context_id in contexts_a
+ )
+ ),
+ [["session-a", None], ["session-a", None]],
+ "session A owns distinct root and child worlds",
+ )
+ assert_equal(
+ await asyncio.gather(
+ *(
+ _evaluate_context_value(session_b, context_id, expression)
+ for context_id in contexts_b
+ )
+ ),
+ [[None, "session-b"], [None, "session-b"]],
+ "session B owns distinct root and child worlds",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ replacement_session = await context.new_cdp_session(page)
+ sessions.append(replacement_session)
+ await replacement_session.send("Page.enable")
+ replacement_contexts = await _create_isolated_worlds_for_frames(
+ replacement_session,
+ frame_ids,
+ "multi-page-shared-name",
+ )
+ assert_equal(
+ await asyncio.gather(
+ *(
+ _evaluate_context_value(
+ replacement_session,
+ context_id,
+ expression,
+ )
+ for context_id in replacement_contexts
+ )
+ ),
+ [[None, None], [None, None]],
+ "replacement session receives clean same-name root and child worlds",
+ )
+ assert_equal(
+ await asyncio.gather(
+ *(
+ _evaluate_context_value(session_b, context_id, expression)
+ for context_id in contexts_b
+ )
+ ),
+ [[None, "session-b"], [None, "session-b"]],
+ "detaching session A does not retire session B worlds",
+ )
+
+ await page.goto(
+ f"{fixture}/iframe?multi-page-worlds=future",
+ wait_until="load",
+ )
+ future_frame_ids = await _root_and_child_frame_ids(session_b)
+ future_b_contexts = await _create_isolated_worlds_for_frames(
+ session_b,
+ future_frame_ids,
+ "multi-page-shared-name",
+ )
+ future_replacement_contexts = await _create_isolated_worlds_for_frames(
+ replacement_session,
+ future_frame_ids,
+ "multi-page-shared-name",
+ )
+ assert_equal(
+ await asyncio.gather(
+ *(
+ _evaluate_context_value(session_b, context_id, expression)
+ for context_id in future_b_contexts
+ )
+ ),
+ [[None, "session-b"], [None, "session-b"]],
+ "surviving session script owns future root and child worlds",
+ )
+ assert_equal(
+ await asyncio.gather(
+ *(
+ _evaluate_context_value(
+ replacement_session,
+ context_id,
+ expression,
+ )
+ for context_id in future_replacement_contexts
+ )
+ ),
+ [[None, None], [None, None]],
+ "replacement session remains clean in a future Document",
+ )
+ record_contract(
+ results,
+ "multi_page_same_name_isolated_world_session_ownership",
+ contract=(
+ "Named isolated worlds are keyed by CDP session, frame, and Document; "
+ "same-name preload scripts never share a realm across sessions."
+ ),
+ source="Chromium InspectorPageAgent oracle",
+ commands=[
+ "Page.addScriptToEvaluateOnNewDocument",
+ "Page.createIsolatedWorld",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "rootAndChildContextsDistinct": True,
+ "replacementWorldsClean": True,
+ "peerWorldsSurvivedDetach": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _runtime_binding_session_lifecycle(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ await page.goto(
+ f"{fixture}/plain?multi-page-bindings=initial",
+ wait_until="load",
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ events_a = attach_cdp_event_collector(session_a, ["Runtime.bindingCalled"])
+ events_b = attach_cdp_event_collector(session_b, ["Runtime.bindingCalled"])
+ await asyncio.gather(
+ session_a.send("Runtime.enable"),
+ session_b.send("Runtime.enable"),
+ )
+ await asyncio.gather(
+ session_a.send("Runtime.addBinding", {"name": "multiPageBindingA"}),
+ session_b.send("Runtime.addBinding", {"name": "multiPageBindingB"}),
+ )
+ assert_equal(
+ await page.evaluate(
+ "() => [typeof multiPageBindingA, typeof multiPageBindingB]"
+ ),
+ ["function", "function"],
+ "both session bindings share the current default world",
+ )
+ await page.evaluate(
+ "() => { multiPageBindingA('a-before'); multiPageBindingB('b-before'); }"
+ )
+ await wait_until(
+ lambda: _binding_payloads(events_a, "multiPageBindingA") == ["a-before"]
+ and _binding_payloads(events_b, "multiPageBindingB") == ["b-before"],
+ "session-local Runtime.bindingCalled delivery",
+ )
+ assert_equal(
+ _binding_payloads(events_a, "multiPageBindingB"),
+ [],
+ "session A does not receive session B binding events",
+ )
+ assert_equal(
+ _binding_payloads(events_b, "multiPageBindingA"),
+ [],
+ "session B does not receive session A binding events",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ events_b.clear()
+ assert_equal(
+ await page.evaluate(
+ "() => [typeof multiPageBindingA, typeof multiPageBindingB]"
+ ),
+ ["function", "function"],
+ "detach does not delete an already-installed global binding function",
+ )
+ await page.evaluate(
+ "() => { multiPageBindingA('a-detached'); multiPageBindingB('b-live'); }"
+ )
+ await wait_until(
+ lambda: _binding_payloads(events_b, "multiPageBindingB") == ["b-live"],
+ "surviving binding event after peer detach",
+ )
+ assert_equal(
+ _binding_payloads(events_b, "multiPageBindingA"),
+ [],
+ "detached binding function has no surviving session subscriber",
+ )
+
+ detached_child_bindings = await page.evaluate(
+ """() => new Promise(resolve => {
+ const frame = document.createElement('iframe');
+ frame.srcdoc = '<!doctype html><body>binding-child</body>';
+ frame.onload = () => resolve([
+ typeof frame.contentWindow.multiPageBindingA,
+ typeof frame.contentWindow.multiPageBindingB,
+ ]);
+ document.body.append(frame);
+ })"""
+ )
+ assert_equal(
+ detached_child_bindings,
+ ["undefined", "function"],
+ "a child realm created after detach receives only live-session bindings",
+ )
+
+ await page.goto(
+ f"{fixture}/plain?multi-page-bindings=future",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate(
+ "() => [typeof multiPageBindingA, typeof multiPageBindingB]"
+ ),
+ ["undefined", "function"],
+ "only the surviving session binding is installed in a future Document",
+ )
+ events_b.clear()
+ await page.evaluate("() => multiPageBindingB('b-future')")
+ await wait_until(
+ lambda: _binding_payloads(events_b, "multiPageBindingB") == ["b-future"],
+ "surviving binding event in a future Document",
+ )
+ record_contract(
+ results,
+ "multi_page_runtime_binding_session_lifecycle",
+ contract=(
+ "Runtime bindings share a live default-world property but keep session-local "
+ "event authority; detach drops future registration without deleting the "
+ "already-installed function."
+ ),
+ source="Chromium V8RuntimeAgentImpl oracle",
+ commands=[
+ "Runtime.addBinding",
+ "Runtime.bindingCalled",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "currentGlobalAfterDetach": ["function", "function"],
+ "newChildAfterDetach": ["undefined", "function"],
+ "futureGlobalAfterDetach": ["undefined", "function"],
+ "bindingEventsSessionLocal": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _same_target_remote_objects_are_session_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ await page.goto(
+ f"{fixture}/plain?multi-page-session-objects",
+ wait_until="load",
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ contexts_a = attach_cdp_event_collector(
+ session_a, ["Runtime.executionContextCreated"]
+ )
+ contexts_b = attach_cdp_event_collector(
+ session_b, ["Runtime.executionContextCreated"]
+ )
+ await asyncio.gather(
+ session_a.send("Runtime.enable"),
+ session_b.send("Runtime.enable"),
+ )
+ await asyncio.gather(
+ wait_until(
+ lambda: _default_execution_context_id(contexts_a) is not None,
+ "session A default execution context",
+ ),
+ wait_until(
+ lambda: _default_execution_context_id(contexts_b) is not None,
+ "session B default execution context",
+ ),
+ )
+ context_id_a = _default_execution_context_id(contexts_a)
+ context_id_b = _default_execution_context_id(contexts_b)
+ assert_equal(
+ context_id_a,
+ context_id_b,
+ "same-target execution context IDs are shared across Runtime sessions",
+ )
+ cross_session_context = await session_b.send(
+ "Runtime.evaluate",
+ {
+ "expression": "6 * 7",
+ "contextId": context_id_a,
+ "returnByValue": True,
+ },
+ )
+ assert_equal(
+ cross_session_context.get("result", {}).get("value"),
+ 42,
+ "peer session evaluates in the target-scoped execution context",
+ )
+ remote_a = (
+ await session_a.send(
+ "Runtime.evaluate",
+ {"expression": "({session: 'a', value: 21})"},
+ )
+ ).get("result", {})
+ object_a = remote_a.get("objectId")
+ if not isinstance(object_a, str) or not object_a:
+ raise SmokeError(f"session A returned no objectId: {remote_a!r}")
+
+ foreign_error = await _expect_protocol_error(
+ session_b.send("Runtime.getProperties", {"objectId": object_a}),
+ "same-target session B resolving session A objectId",
+ )
+ own_properties = await session_a.send(
+ "Runtime.getProperties",
+ {"objectId": object_a, "ownProperties": True},
+ )
+ assert_equal(
+ {
+ prop.get("name")
+ for prop in own_properties.get("result", [])
+ if prop.get("enumerable")
+ },
+ {"session", "value"},
+ "same-target object owner resolves its handle",
+ )
+ await session_a.send("Runtime.releaseObject", {"objectId": object_a})
+ released_error = await _expect_protocol_error(
+ session_a.send("Runtime.getProperties", {"objectId": object_a}),
+ "released same-target objectId",
+ )
+
+ grouped_a, grouped_b = await asyncio.gather(
+ session_a.send(
+ "Runtime.evaluate",
+ {
+ "expression": "({groupOwner: 'a'})",
+ "objectGroup": "shared-name-group",
+ },
+ ),
+ session_b.send(
+ "Runtime.evaluate",
+ {
+ "expression": "({groupOwner: 'b'})",
+ "objectGroup": "shared-name-group",
+ },
+ ),
+ )
+ grouped_object_a = grouped_a.get("result", {}).get("objectId")
+ grouped_object_b = grouped_b.get("result", {}).get("objectId")
+ if not isinstance(grouped_object_a, str) or not isinstance(grouped_object_b, str):
+ raise SmokeError(
+ "same-name object groups returned invalid handles: "
+ f"{grouped_a!r}, {grouped_b!r}"
+ )
+ await session_a.send(
+ "Runtime.releaseObjectGroup",
+ {"objectGroup": "shared-name-group"},
+ )
+ released_group_error = await _expect_protocol_error(
+ session_a.send("Runtime.getProperties", {"objectId": grouped_object_a}),
+ "released owner object group",
+ )
+ peer_group_properties = await session_b.send(
+ "Runtime.getProperties",
+ {"objectId": grouped_object_b, "ownProperties": True},
+ )
+ assert_equal(
+ next(
+ prop.get("value", {}).get("value")
+ for prop in peer_group_properties.get("result", [])
+ if prop.get("name") == "groupOwner"
+ ),
+ "b",
+ "same-name peer object group survives owner release",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ peer = await session_b.send(
+ "Runtime.evaluate",
+ {"expression": "6 * 7", "returnByValue": True},
+ )
+ assert_equal(
+ peer.get("result", {}).get("value"),
+ 42,
+ "peer Runtime session after object owner detach",
+ )
+ record_contract(
+ results,
+ "multi_page_same_target_remote_object_session_ownership",
+ contract=(
+ "Execution context IDs are target-scoped, while remote objects and object "
+ "groups are Runtime-session scoped; release and detach cannot damage a peer."
+ ),
+ source="Chromium V8 Inspector oracle",
+ commands=[
+ "Runtime.evaluate",
+ "Runtime.getProperties",
+ "Runtime.releaseObject",
+ "Runtime.releaseObjectGroup",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "sharedExecutionContextId": context_id_a,
+ "crossSessionContextEvaluation": 42,
+ "foreignObjectRejected": bool(foreign_error),
+ "releasedObjectRejected": bool(released_error),
+ "releasedGroupRejected": bool(released_group_error),
+ "peerSameNameGroupSurvived": True,
+ "peerValueAfterDetach": 42,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _same_target_dom_node_and_backend_node_ownership(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ await page.goto(
+ f"{fixture}/plain?multi-page-dom-session-ownership",
+ wait_until="load",
+ )
+ await page.evaluate(
+ """() => {
+ document.body.innerHTML =
+ '<main><div id="owner-node">owner</div><div id="peer-node">peer</div></main>';
+ }"""
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("DOM.enable"),
+ session_b.send("DOM.enable"),
+ session_a.send("Runtime.enable"),
+ session_b.send("Runtime.enable"),
+ )
+ document_a, document_b = await asyncio.gather(
+ session_a.send("DOM.getDocument", {"depth": -1}),
+ session_b.send("DOM.getDocument", {"depth": 0}),
+ )
+ root_a = document_a.get("root", {}).get("nodeId")
+ root_b = document_b.get("root", {}).get("nodeId")
+ if not isinstance(root_a, int) or not isinstance(root_b, int):
+ raise SmokeError(
+ f"DOM.getDocument returned invalid roots: {document_a!r}, {document_b!r}"
+ )
+ owner_query = await session_a.send(
+ "DOM.querySelector",
+ {"nodeId": root_a, "selector": "#owner-node"},
+ )
+ owner_node_id = owner_query.get("nodeId")
+ if not isinstance(owner_node_id, int) or owner_node_id <= 0:
+ raise SmokeError(f"DOM.querySelector returned no owner node: {owner_query!r}")
+ owner_description = await session_a.send(
+ "DOM.describeNode",
+ {"nodeId": owner_node_id},
+ )
+ backend_node_id = owner_description.get("node", {}).get("backendNodeId")
+ if not isinstance(backend_node_id, int) or backend_node_id <= 0:
+ raise SmokeError(
+ f"DOM.describeNode returned no backendNodeId: {owner_description!r}"
+ )
+
+ foreign_node_error = await _expect_protocol_error(
+ session_b.send("DOM.describeNode", {"nodeId": owner_node_id}),
+ "unpublished DOM nodeId in peer session",
+ )
+ resolved = await session_b.send(
+ "DOM.resolveNode",
+ {"backendNodeId": backend_node_id},
+ )
+ peer_object_id = resolved.get("object", {}).get("objectId")
+ if not isinstance(peer_object_id, str):
+ raise SmokeError(f"DOM.resolveNode returned no objectId: {resolved!r}")
+ text_value = await session_b.send(
+ "Runtime.callFunctionOn",
+ {
+ "objectId": peer_object_id,
+ "functionDeclaration": "function() { return this.textContent; }",
+ "returnByValue": True,
+ },
+ )
+ assert_equal(
+ text_value.get("result", {}).get("value"),
+ "owner",
+ "peer resolves target-scoped backendNodeId",
+ )
+ foreign_object_error = await _expect_protocol_error(
+ session_a.send("Runtime.getProperties", {"objectId": peer_object_id}),
+ "DOM-resolved peer Runtime objectId",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ peer_after_detach = await session_b.send(
+ "Runtime.callFunctionOn",
+ {
+ "objectId": peer_object_id,
+ "functionDeclaration": "function() { return this.id; }",
+ "returnByValue": True,
+ },
+ )
+ assert_equal(
+ peer_after_detach.get("result", {}).get("value"),
+ "owner-node",
+ "peer DOM-resolved object after other DOM session detaches",
+ )
+ record_contract(
+ results,
+ "multi_page_same_target_dom_node_session_ownership",
+ contract=(
+ "DOM nodeId mappings and resolved Runtime handles are session-local, while "
+ "backendNodeId identifies a live node across sessions on the same target."
+ ),
+ source="Chromium InspectorDOMAgent oracle",
+ commands=[
+ "DOM.getDocument",
+ "DOM.querySelector",
+ "DOM.describeNode",
+ "DOM.resolveNode",
+ "Runtime.callFunctionOn",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "unpublishedForeignNodeRejected": bool(foreign_node_error),
+ "backendNodeResolvedByPeer": True,
+ "resolvedObjectRejectedByForeignSession": bool(foreign_object_error),
+ "peerObjectSurvivedDetach": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _same_source_scripts_keep_session_authority(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("Page.enable"),
+ session_b.send("Page.enable"),
+ )
+ source = "globalThis.__sameSourceRuns = (globalThis.__sameSourceRuns || 0) + 1;"
+ registration_a, registration_b = await asyncio.gather(
+ session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": source},
+ ),
+ session_b.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": source},
+ ),
+ )
+ identifier_a = registration_a.get("identifier")
+ identifier_b = registration_b.get("identifier")
+ if not isinstance(identifier_a, str) or not isinstance(identifier_b, str):
+ raise SmokeError(
+ "same-source registrations returned invalid identifiers: "
+ f"{registration_a!r}, {registration_b!r}"
+ )
+ assert_equal(
+ identifier_a,
+ identifier_b,
+ "Page script identifiers use a session-local namespace",
+ )
+
+ await page.goto(
+ f"{fixture}/plain?multi-page-same-source=both",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate("globalThis.__sameSourceRuns ?? 0"),
+ 2,
+ "identical scripts from two sessions both execute",
+ )
+ await session_b.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": identifier_a},
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-same-source=b-remove",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate("globalThis.__sameSourceRuns ?? 0"),
+ 1,
+ "colliding identifier removes only session B's registration",
+ )
+ repeated_remove_error = await _expect_protocol_error(
+ session_b.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": identifier_a},
+ ),
+ "session B removing its already-removed script identifier",
+ )
+
+ await session_a.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": identifier_a},
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-same-source=owner-remove",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate("globalThis.__sameSourceRuns ?? 0"),
+ 0,
+ "session A can still remove its colliding identifier",
+ )
+
+ duplicate_source = (
+ "globalThis.__sameSessionRuns = (globalThis.__sameSessionRuns || 0) + 1;"
+ )
+ duplicate_a, duplicate_b = await asyncio.gather(
+ session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": duplicate_source},
+ ),
+ session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": duplicate_source},
+ ),
+ )
+ assert_equal(
+ [duplicate_a.get("identifier"), duplicate_b.get("identifier")],
+ ["1", "2"],
+ "same-session duplicate sources keep distinct identifiers",
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-same-source=same-session",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate("globalThis.__sameSessionRuns ?? 0"),
+ 2,
+ "same-session duplicate registrations both execute",
+ )
+ await asyncio.gather(
+ *(
+ session_a.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": identifier},
+ )
+ for identifier in ("1", "2")
+ )
+ )
+ reused = await session_a.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__reusedScriptIdentifier = true;"},
+ )
+ assert_equal(
+ reused.get("identifier"),
+ "1",
+ "empty session script registry reuses identifier one",
+ )
+ await session_a.send(
+ "Page.removeScriptToEvaluateOnNewDocument",
+ {"identifier": "1"},
+ )
+ await session_b.detach()
+ sessions.remove(session_b)
+ await page.goto(
+ f"{fixture}/plain?multi-page-same-source=detached",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate("globalThis.__sameSourceRuns ?? 0"),
+ 0,
+ "detaching the final owner removes its identical script",
+ )
+ record_contract(
+ results,
+ "multi_page_same_source_script_session_authority",
+ contract=(
+ "Page script identifiers are session-local and may collide; removing an "
+ "identifier affects only the registration owned by that session."
+ ),
+ source="Chromium InspectorPageAgent oracle",
+ commands=[
+ "Page.addScriptToEvaluateOnNewDocument",
+ "Page.removeScriptToEvaluateOnNewDocument",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "identifierCollision": identifier_a,
+ "repeatedRemoveRejected": bool(repeated_remove_error),
+ "executionCounts": [2, 1, 0, 0],
+ "sameSessionDuplicateIdentifiers": ["1", "2"],
+ "identifierAfterEmptyRegistry": "1",
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _network_enablement_is_session_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ events_a = attach_cdp_event_collector(
+ session_a,
+ ["Network.responseReceived", "Network.loadingFinished"],
+ )
+ events_b = attach_cdp_event_collector(
+ session_b,
+ ["Network.responseReceived", "Network.loadingFinished"],
+ )
+ await asyncio.gather(
+ session_a.send("Network.enable"),
+ session_b.send("Network.enable"),
+ )
+ first_url = f"{fixture}/plain?multi-page-network-sessions=both"
+ await page.goto(first_url, wait_until="load")
+ request_a = _document_request_id(events_a, first_url)
+ request_b = _document_request_id(events_b, first_url)
+
+ events_a.clear()
+ events_b.clear()
+ await session_a.send("Network.disable")
+ disabled_cache_error = await _expect_protocol_error(
+ session_a.send("Network.getResponseBody", {"requestId": request_a}),
+ "disabled Network session response-body cache",
+ )
+ retained_body_b = await session_b.send(
+ "Network.getResponseBody",
+ {"requestId": request_b},
+ )
+ if "plain ok" not in retained_body_b.get("body", ""):
+ raise SmokeError(
+ "peer Network response-body cache was cleared by another session: "
+ f"{retained_body_b!r}"
+ )
+ second_url = f"{fixture}/plain?multi-page-network-sessions=b-only"
+ await page.goto(second_url, wait_until="load")
+ await wait_until(
+ lambda: _has_document_response(events_b, second_url),
+ "surviving Network session after peer disable",
+ )
+ await asyncio.sleep(0.1)
+ assert_equal(
+ _has_document_response(events_a, second_url),
+ False,
+ "Network.disable silences only its own session",
+ )
+ request_b_only = _document_request_id(events_b, second_url)
+ body_b = await session_b.send(
+ "Network.getResponseBody",
+ {"requestId": request_b_only},
+ )
+ if "plain ok" not in body_b.get("body", ""):
+ raise SmokeError(f"surviving Network session returned wrong body: {body_b!r}")
+
+ await session_a.send("Network.enable")
+ events_a.clear()
+ events_b.clear()
+ third_url = f"{fixture}/plain?multi-page-network-sessions=reenabled"
+ await page.goto(third_url, wait_until="load")
+ await asyncio.gather(
+ wait_until(
+ lambda: _has_document_response(events_a, third_url),
+ "re-enabled Network session",
+ ),
+ wait_until(
+ lambda: _has_document_response(events_b, third_url),
+ "continuously enabled Network session",
+ ),
+ )
+ record_contract(
+ results,
+ "multi_page_same_target_network_enablement_isolation",
+ contract=(
+ "Network.enable and Network.disable are per DevTools session on one Page; "
+ "disabling one observer neither silences nor invalidates the peer observer."
+ ),
+ source="Chromium InspectorNetworkAgent oracle",
+ commands=["Network.enable", "Network.disable", "Network.getResponseBody"],
+ observed={
+ "initialRequestIds": [request_a, request_b],
+ "disabledSessionSilent": True,
+ "disabledSessionCacheCleared": bool(disabled_cache_error),
+ "peerBodyRetained": True,
+ "reenabledFanout": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _page_lifecycle_enablement_is_session_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ events_a = attach_cdp_event_collector(session_a, ["Page.lifecycleEvent"])
+ events_b = attach_cdp_event_collector(session_b, ["Page.lifecycleEvent"])
+ await asyncio.gather(
+ session_a.send("Page.enable"),
+ session_b.send("Page.enable"),
+ )
+ await asyncio.gather(
+ session_a.send("Page.setLifecycleEventsEnabled", {"enabled": True}),
+ session_b.send("Page.setLifecycleEventsEnabled", {"enabled": True}),
+ )
+ events_a.clear()
+ events_b.clear()
+ await page.goto(
+ f"{fixture}/plain?multi-page-lifecycle=both",
+ wait_until="load",
+ )
+ await asyncio.gather(
+ wait_until(
+ lambda: _has_lifecycle_event(events_a, "load"),
+ "session A Page.lifecycleEvent load",
+ ),
+ wait_until(
+ lambda: _has_lifecycle_event(events_b, "load"),
+ "session B Page.lifecycleEvent load",
+ ),
+ )
+
+ await session_a.send(
+ "Page.setLifecycleEventsEnabled",
+ {"enabled": False},
+ )
+ events_a.clear()
+ events_b.clear()
+ await page.goto(
+ f"{fixture}/plain?multi-page-lifecycle=b-only",
+ wait_until="load",
+ )
+ await wait_until(
+ lambda: _has_lifecycle_event(events_b, "load"),
+ "surviving Page lifecycle observer",
+ )
+ await asyncio.sleep(0.1)
+ assert_equal(
+ _has_lifecycle_event(events_a, "load"),
+ False,
+ "disabling lifecycle events silences only one session",
+ )
+
+ await session_a.send(
+ "Page.setLifecycleEventsEnabled",
+ {"enabled": True},
+ )
+ await wait_until(
+ lambda: _has_lifecycle_event(events_a, "load"),
+ "re-enabled session current lifecycle snapshot",
+ )
+ events_a.clear()
+ events_b.clear()
+ await page.goto(
+ f"{fixture}/plain?multi-page-lifecycle=reenabled",
+ wait_until="load",
+ )
+ await asyncio.gather(
+ wait_until(
+ lambda: _has_lifecycle_event(events_a, "load"),
+ "re-enabled Page lifecycle observer",
+ ),
+ wait_until(
+ lambda: _has_lifecycle_event(events_b, "load"),
+ "continuous Page lifecycle observer",
+ ),
+ )
+ record_contract(
+ results,
+ "multi_page_same_target_lifecycle_event_enablement_isolation",
+ contract=(
+ "Page lifecycle event enablement is scoped to one DevTools session on a "
+ "shared target; disable and re-enable do not alter a peer observer."
+ ),
+ source="Chromium InspectorPageAgent oracle",
+ commands=["Page.enable", "Page.setLifecycleEventsEnabled", "Page.lifecycleEvent"],
+ observed={
+ "initialFanout": True,
+ "disabledSessionSilent": True,
+ "reenabledFanout": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _same_name_runtime_bindings_keep_session_authority(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ await page.goto(
+ f"{fixture}/plain?multi-page-shared-binding=initial",
+ wait_until="load",
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ events_a = attach_cdp_event_collector(session_a, ["Runtime.bindingCalled"])
+ events_b = attach_cdp_event_collector(session_b, ["Runtime.bindingCalled"])
+ await asyncio.gather(
+ session_a.send("Runtime.enable"),
+ session_b.send("Runtime.enable"),
+ )
+ await asyncio.gather(
+ session_a.send(
+ "Runtime.addBinding",
+ {"name": "multiPageSharedBinding"},
+ ),
+ session_b.send(
+ "Runtime.addBinding",
+ {"name": "multiPageSharedBinding"},
+ ),
+ )
+ await page.evaluate("() => multiPageSharedBinding('both-live')")
+ await wait_until(
+ lambda: _binding_payloads(events_a, "multiPageSharedBinding")
+ == ["both-live"]
+ and _binding_payloads(events_b, "multiPageSharedBinding") == ["both-live"],
+ "same-name binding fanout to both owners",
+ )
+
+ await session_a.send(
+ "Runtime.removeBinding",
+ {"name": "multiPageSharedBinding"},
+ )
+ events_a.clear()
+ events_b.clear()
+ await page.evaluate("() => multiPageSharedBinding('b-after-a-remove')")
+ await wait_until(
+ lambda: _binding_payloads(events_b, "multiPageSharedBinding")
+ == ["b-after-a-remove"],
+ "same-name binding surviving peer removeBinding",
+ )
+ await asyncio.sleep(0.1)
+ assert_equal(
+ _binding_payloads(events_a, "multiPageSharedBinding"),
+ [],
+ "Runtime.removeBinding silences only its owning session",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ events_b.clear()
+ await page.evaluate("() => multiPageSharedBinding('b-survives')")
+ await wait_until(
+ lambda: _binding_payloads(events_b, "multiPageSharedBinding")
+ == ["b-survives"],
+ "same-name binding surviving owner after peer detach",
+ )
+ await page.goto(
+ f"{fixture}/plain?multi-page-shared-binding=future",
+ wait_until="load",
+ )
+ assert_equal(
+ await page.evaluate("typeof multiPageSharedBinding"),
+ "function",
+ "surviving same-name binding in a future Document",
+ )
+ events_b.clear()
+ await page.evaluate("() => multiPageSharedBinding('b-future')")
+ await wait_until(
+ lambda: _binding_payloads(events_b, "multiPageSharedBinding")
+ == ["b-future"],
+ "same-name binding surviving owner in a future Document",
+ )
+ record_contract(
+ results,
+ "multi_page_same_name_runtime_binding_session_authority",
+ contract=(
+ "Two Runtime sessions may own the same binding name; removeBinding and detach "
+ "retire only one owner's events while the peer remains authoritative."
+ ),
+ source="Chromium V8RuntimeAgentImpl oracle",
+ commands=[
+ "Runtime.addBinding",
+ "Runtime.removeBinding",
+ "Runtime.bindingCalled",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "initialOwnersNotified": 2,
+ "removedOwnerSilent": True,
+ "survivingOwnerNotified": True,
+ "futureDocumentBinding": "function",
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _runtime_enablement_and_context_replay_are_session_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ await page.goto(
+ f"{fixture}/plain?multi-page-runtime-enablement",
+ wait_until="load",
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ events_a = attach_cdp_event_collector(
+ session_a,
+ ["Runtime.executionContextCreated"],
+ )
+ events_b = attach_cdp_event_collector(
+ session_b,
+ ["Runtime.executionContextCreated"],
+ )
+
+ await session_a.send("Runtime.enable")
+ events_a.clear()
+ events_b.clear()
+ await page.evaluate(
+ """() => new Promise(resolve => {
+ const frame = document.createElement('iframe');
+ frame.id = 'runtime-enabled-a';
+ frame.srcdoc = '<!doctype html><body>runtime-a</body>';
+ frame.onload = resolve;
+ document.body.append(frame);
+ })"""
+ )
+ await wait_until(
+ lambda: bool(events_a),
+ "Runtime-enabled session receives a new child context",
+ )
+ await asyncio.sleep(0.05)
+ assert_equal(
+ events_b,
+ [],
+ "Runtime-disabled peer receives no child context event",
+ )
+
+ await session_b.send("Runtime.enable")
+ await wait_until(
+ lambda: len(events_b) >= 2,
+ "newly Runtime-enabled peer receives existing context replay",
+ )
+ replayed_context_count = len(events_b)
+ events_a.clear()
+ events_b.clear()
+
+ await session_a.send("Runtime.disable")
+ await page.evaluate(
+ """() => new Promise(resolve => {
+ const frame = document.createElement('iframe');
+ frame.id = 'runtime-enabled-b';
+ frame.srcdoc = '<!doctype html><body>runtime-b</body>';
+ frame.onload = resolve;
+ document.body.append(frame);
+ })"""
+ )
+ await wait_until(
+ lambda: bool(events_b),
+ "surviving Runtime-enabled session receives the second child context",
+ )
+ await asyncio.sleep(0.05)
+ assert_equal(
+ events_a,
+ [],
+ "Runtime.disable silences only its owning session",
+ )
+ record_contract(
+ results,
+ "multi_page_runtime_enablement_and_context_replay",
+ contract=(
+ "Runtime domain enablement is session-local; enabling replays existing "
+ "contexts, and disabling one session does not silence a peer."
+ ),
+ source="Chromium V8RuntimeAgentImpl oracle",
+ commands=["Runtime.enable", "Runtime.disable"],
+ observed={
+ "disabledPeerInitiallySilent": True,
+ "replayedContextCount": replayed_context_count,
+ "disabledOwnerFinallySilent": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _session_detach_cancels_only_its_pending_await(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page = await context.new_page()
+ await page.goto(
+ f"{fixture}/plain?multi-page-pending-await",
+ wait_until="load",
+ )
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [session_a, session_b]
+ pending = asyncio.create_task(
+ session_a.send(
+ "Runtime.evaluate",
+ {
+ "expression": "new Promise(resolve => setTimeout(() => resolve('late'), 1000))",
+ "awaitPromise": True,
+ "returnByValue": True,
+ },
+ )
+ )
+ await asyncio.sleep(0.05)
+ await session_a.detach()
+ sessions.remove(session_a)
+ canceled = (await asyncio.gather(pending, return_exceptions=True))[0]
+ if not isinstance(canceled, BaseException):
+ raise SmokeError(
+ "detached Runtime session unexpectedly completed its pending await: "
+ f"{canceled!r}"
+ )
+ peer = await asyncio.wait_for(
+ session_b.send(
+ "Runtime.evaluate",
+ {"expression": "21 * 2", "returnByValue": True},
+ ),
+ timeout=2,
+ )
+ assert_equal(
+ peer.get("result", {}).get("value"),
+ 42,
+ "peer Runtime session after pending owner detach",
+ )
+ replacement = await context.new_cdp_session(page)
+ sessions.append(replacement)
+ replacement_value = await replacement.send(
+ "Runtime.evaluate",
+ {"expression": "40 + 2", "returnByValue": True},
+ )
+ assert_equal(
+ replacement_value.get("result", {}).get("value"),
+ 42,
+ "replacement Runtime session after pending owner detach",
+ )
+ record_contract(
+ results,
+ "multi_page_pending_runtime_await_session_detach",
+ contract=(
+ "Detaching a session cancels only that session's pending awaitPromise command; "
+ "peer and replacement sessions remain immediately usable."
+ ),
+ source="Chromium DevToolsSession oracle",
+ commands=["Runtime.evaluate", "Target.detachFromTarget"],
+ observed={
+ "pendingOwnerCanceled": True,
+ "peerValue": 42,
+ "replacementValue": 42,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _fetch_interception_is_session_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ navigation: asyncio.Task[Any] | None = None
+ try:
+ page = await context.new_page()
+ interceptor, peer = await asyncio.gather(
+ context.new_cdp_session(page),
+ context.new_cdp_session(page),
+ )
+ sessions = [interceptor, peer]
+ paused = attach_cdp_event_collector(interceptor, ["Fetch.requestPaused"])
+ await interceptor.send(
+ "Fetch.enable",
+ {
+ "patterns": [
+ {
+ "urlPattern": "*multi-page-fetch-detach*",
+ "requestStage": "Request",
+ }
+ ]
+ },
+ )
+ url = f"{fixture}/plain?multi-page-fetch-detach"
+ navigation = asyncio.create_task(page.goto(url, wait_until="load", timeout=5000))
+ await wait_until(
+ lambda: any(
+ event.get("method") == "Fetch.requestPaused"
+ and event.get("params", {}).get("request", {}).get("url") == url
+ for event in paused
+ ),
+ "Fetch.requestPaused before interceptor detach",
+ )
+ paused_request = next(
+ event
+ for event in paused
+ if event.get("method") == "Fetch.requestPaused"
+ and event.get("params", {}).get("request", {}).get("url") == url
+ )
+ request_id = paused_request.get("params", {}).get("requestId")
+ if not isinstance(request_id, str):
+ raise SmokeError(f"Fetch.requestPaused returned no requestId: {paused_request!r}")
+
+ await peer.send("Fetch.disable")
+ await asyncio.sleep(0.1)
+ assert_equal(
+ navigation.done(),
+ False,
+ "peer Fetch.disable cannot release another session's paused request",
+ )
+ await interceptor.send(
+ "Fetch.continueRequest",
+ {"requestId": request_id},
+ )
+ response = await asyncio.wait_for(navigation, timeout=5)
+ assert_equal(
+ response.status if response is not None else None,
+ 200,
+ "Fetch owner continues its paused navigation",
+ )
+ await asyncio.wait_for(interceptor.detach(), timeout=2)
+ sessions.remove(interceptor)
+ recovery = await page.goto(
+ f"{fixture}/plain?multi-page-fetch-detach=recovery",
+ wait_until="load",
+ timeout=5_000,
+ )
+ assert_equal(
+ recovery.status if recovery is not None else None,
+ 200,
+ "future navigation after detached Fetch owner",
+ )
+ record_contract(
+ results,
+ "multi_page_fetch_interceptor_session_detach_recovery",
+ contract=(
+ "Fetch interception is session-owned: a peer cannot disable or release its "
+ "paused request, while owner detach removes interception from future requests."
+ ),
+ source="Chromium Fetch domain oracle",
+ commands=[
+ "Fetch.enable",
+ "Fetch.disable",
+ "Fetch.requestPaused",
+ "Fetch.continueRequest",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "pausedBeforeDetach": True,
+ "peerDisableDidNotRelease": True,
+ "ownerContinuedNavigationStatus": 200,
+ "recoveryNavigationStatus": 200,
+ },
+ )
+ finally:
+ if navigation is not None and not navigation.done():
+ navigation.cancel()
+ if navigation is not None:
+ await asyncio.gather(navigation, return_exceptions=True)
+ with suppress(Exception):
+ await asyncio.wait_for(page.close(), timeout=2)
+ with suppress(Exception):
+ await asyncio.wait_for(
+ asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ ),
+ timeout=2,
+ )
+ await _close_context(context)
+
+
+async def _network_and_emulation_profiles_are_target_local(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page_a, page_b = await asyncio.gather(context.new_page(), context.new_page())
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page_a),
+ context.new_cdp_session(page_b),
+ )
+ sessions = [session_a, session_b]
+ await asyncio.gather(
+ session_a.send("Page.enable"),
+ session_b.send("Page.enable"),
+ session_a.send("Network.enable"),
+ session_b.send("Network.enable"),
+ )
+ profiles = (
+ (
+ session_a,
+ "target-a",
+ "MultiPageAgentA/1.0",
+ "fr-FR",
+ "Europe/Paris",
+ ),
+ (
+ session_b,
+ "target-b",
+ "MultiPageAgentB/1.0",
+ "ja-JP",
+ "Asia/Tokyo",
+ ),
+ )
+ await asyncio.gather(
+ *(
+ asyncio.gather(
+ session.send(
+ "Network.setExtraHTTPHeaders",
+ {"headers": {"x-moli-profile-smoke": marker}},
+ ),
+ session.send(
+ "Emulation.setUserAgentOverride",
+ {
+ "userAgent": user_agent,
+ "acceptLanguage": language,
+ },
+ ),
+ session.send(
+ "Emulation.setLocaleOverride",
+ {"locale": language},
+ ),
+ session.send(
+ "Emulation.setTimezoneOverride",
+ {"timezoneId": timezone},
+ ),
+ )
+ for session, marker, user_agent, language, timezone in profiles
+ )
+ )
+
+ tokens = ("multi-page-profile-a", "multi-page-profile-b")
+ navigation_results = await asyncio.gather(
+ session_a.send(
+ "Page.navigate",
+ {"url": f"{fixture}/profile-headers?token={tokens[0]}"},
+ ),
+ session_b.send(
+ "Page.navigate",
+ {"url": f"{fixture}/profile-headers?token={tokens[1]}"},
+ ),
+ )
+ if any(result.get("errorText") for result in navigation_results):
+ raise SmokeError(f"profile navigation failed: {navigation_results!r}")
+ wire_profiles: list[Any] = [None, None]
+
+ async def collect_wire_profile(index: int, token: str) -> None:
+ async def read_profile() -> bool:
+ try:
+ profile = await asyncio.to_thread(
+ _read_fixture_json,
+ f"{fixture}/profile-result?token={token}",
+ )
+ except Exception:
+ return False
+ if profile is None:
+ return False
+ wire_profiles[index] = profile
+ return True
+
+ await wait_until(read_profile, f"profile target {index} request")
+
+ await asyncio.gather(
+ *(
+ collect_wire_profile(
+ index,
+ token,
+ )
+ for index, token in enumerate(tokens)
+ )
+ )
+ runtime_profiles: list[Any] = [None, None]
+
+ async def collect_runtime_profile(index: int, session: Any) -> None:
+ last_observation: Any = None
+ for _ in range(100):
+ try:
+ response = await session.send(
+ "Runtime.evaluate",
+ {
+ "expression": """({
+ userAgent: navigator.userAgent,
+ language: navigator.language,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ })""",
+ "returnByValue": True,
+ },
+ )
+ except Exception as error:
+ last_observation = f"{type(error).__name__}: {error}"
+ await asyncio.sleep(0.05)
+ continue
+ last_observation = response
+ profile = response.get("result", {}).get("value")
+ if not isinstance(profile, dict):
+ await asyncio.sleep(0.05)
+ continue
+ runtime_profiles[index] = profile
+ return
+ raise SmokeError(
+ f"profile target {index} runtime unavailable: {last_observation!r}"
+ )
+
+ await asyncio.gather(
+ *(
+ collect_runtime_profile(
+ index,
+ session,
+ )
+ for index, session in enumerate((session_a, session_b))
+ )
+ )
+ expected_runtime_profiles = [
+ {
+ "userAgent": "MultiPageAgentA/1.0",
+ "language": "fr-FR",
+ "timezone": "Europe/Paris",
+ },
+ {
+ "userAgent": "MultiPageAgentB/1.0",
+ "language": "ja-JP",
+ "timezone": "Asia/Tokyo",
+ },
+ ]
+ assert_equal(
+ runtime_profiles,
+ expected_runtime_profiles,
+ "target-local Runtime emulation profiles",
+ )
+ assert_equal(
+ [
+ {
+ "userAgent": profile.get("userAgent"),
+ "acceptLanguage": profile.get("acceptLanguage"),
+ "extraHeader": profile.get("extraHeader"),
+ }
+ for profile in wire_profiles
+ ],
+ [
+ {
+ "userAgent": "MultiPageAgentA/1.0",
+ "acceptLanguage": "fr-FR",
+ "extraHeader": "target-a",
+ },
+ {
+ "userAgent": "MultiPageAgentB/1.0",
+ "acceptLanguage": "ja-JP",
+ "extraHeader": "target-b",
+ },
+ ],
+ "target-local navigation request profiles",
+ )
+
+ await session_a.detach()
+ sessions.remove(session_a)
+ detached_token = "multi-page-profile-a-detached"
+ await page_a.goto(
+ f"{fixture}/profile-headers?token={detached_token}",
+ wait_until="load",
+ )
+ detached_wire_profile = await asyncio.to_thread(
+ _read_fixture_json,
+ f"{fixture}/profile-result?token={detached_token}",
+ )
+ detached_runtime_profile, surviving_runtime_profile = await asyncio.gather(
+ page_a.evaluate(
+ """() => ({
+ userAgent: navigator.userAgent,
+ language: navigator.language,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ })"""
+ ),
+ page_b.evaluate(
+ """() => ({
+ userAgent: navigator.userAgent,
+ language: navigator.language,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ })"""
+ ),
+ )
+ if detached_wire_profile.get("extraHeader") is not None:
+ raise SmokeError(
+ "detached target retained its session-owned extra header: "
+ f"{detached_wire_profile!r}"
+ )
+ if detached_runtime_profile == expected_runtime_profiles[0]:
+ raise SmokeError(
+ "detached target retained every session-owned emulation override: "
+ f"{detached_runtime_profile!r}"
+ )
+ assert_equal(
+ surviving_runtime_profile,
+ expected_runtime_profiles[1],
+ "peer target emulation profile after owner detach",
+ )
+ record_contract(
+ results,
+ "multi_page_network_and_emulation_profile_ownership",
+ contract=(
+ "Headers, user agent, locale, and timezone overrides are target-local; "
+ "detaching their owning session clears that target without mutating a peer."
+ ),
+ source="Chromium Network and Emulation agent oracle",
+ commands=[
+ "Network.setExtraHTTPHeaders",
+ "Emulation.setUserAgentOverride",
+ "Emulation.setLocaleOverride",
+ "Emulation.setTimezoneOverride",
+ "Target.detachFromTarget",
+ ],
+ observed={
+ "initialRuntimeProfiles": runtime_profiles,
+ "initialWireProfiles": wire_profiles,
+ "detachedRuntimeProfile": detached_runtime_profile,
+ "detachedWireProfile": detached_wire_profile,
+ "peerProfileSurvived": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _closed_target_new_document_script_does_not_leak(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ owner, peer = await asyncio.gather(context.new_page(), context.new_page())
+ owner_session, peer_session = await asyncio.gather(
+ context.new_cdp_session(owner),
+ context.new_cdp_session(peer),
+ )
+ sessions = [owner_session, peer_session]
+ await asyncio.gather(
+ owner_session.send("Page.enable"),
+ peer_session.send("Page.enable"),
+ )
+ await asyncio.gather(
+ owner_session.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__multiPageClosedOwner = 'owner';"},
+ ),
+ peer_session.send(
+ "Page.addScriptToEvaluateOnNewDocument",
+ {"source": "globalThis.__multiPageSurvivingPeer = 'peer';"},
+ ),
+ )
+ await asyncio.gather(
+ owner.goto(
+ f"{fixture}/plain?multi-page-close-script=owner",
+ wait_until="load",
+ ),
+ peer.goto(
+ f"{fixture}/plain?multi-page-close-script=peer",
+ wait_until="load",
+ ),
+ )
+ assert_equal(
+ await asyncio.gather(
+ owner.evaluate("globalThis.__multiPageClosedOwner"),
+ peer.evaluate("globalThis.__multiPageSurvivingPeer"),
+ ),
+ ["owner", "peer"],
+ "target-local scripts before owner target close",
+ )
+
+ await owner.close()
+ replacement = await context.new_page()
+ await replacement.goto(
+ f"{fixture}/plain?multi-page-close-script=replacement",
+ wait_until="load",
+ )
+ replacement_owner_value, surviving_peer_value = await asyncio.gather(
+ replacement.evaluate("globalThis.__multiPageClosedOwner ?? null"),
+ peer.evaluate("globalThis.__multiPageSurvivingPeer ?? null"),
+ )
+ assert_equal(
+ replacement_owner_value,
+ None,
+ "closed target script does not leak into a replacement target",
+ )
+ assert_equal(
+ surviving_peer_value,
+ "peer",
+ "closing a scripted target preserves a peer target's script state",
+ )
+ replacement_session = await context.new_cdp_session(replacement)
+ sessions.append(replacement_session)
+ replacement_result = await replacement_session.send(
+ "Runtime.evaluate",
+ {"expression": "7 * 6", "returnByValue": True},
+ )
+ assert_equal(
+ replacement_result.get("result", {}).get("value"),
+ 42,
+ "replacement target session after scripted owner close",
+ )
+ record_contract(
+ results,
+ "multi_page_closed_target_new_document_script_does_not_leak",
+ contract=(
+ "Closing a Page discards that target's session-owned new-Document "
+ "scripts; a new target starts clean while a live peer remains unchanged."
+ ),
+ source="Chromium CDP oracle",
+ commands=[
+ "Page.addScriptToEvaluateOnNewDocument",
+ "Target.closeTarget",
+ "Target.createTarget",
+ ],
+ observed={
+ "replacementInheritedClosedTargetScript": False,
+ "survivingPeerRetainedScript": True,
+ "replacementSessionUsable": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _broadcast_channel_context_partition(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context_a = await browser.new_context()
+ context_b = await browser.new_context()
+ try:
+ page_a_sender, page_a_receiver = await asyncio.gather(
+ context_a.new_page(),
+ context_a.new_page(),
+ )
+ page_b_sender, page_b_receiver = await asyncio.gather(
+ context_b.new_page(),
+ context_b.new_page(),
+ )
+ pages = [page_a_sender, page_a_receiver, page_b_sender, page_b_receiver]
+ await asyncio.gather(
+ *(
+ page.goto(
+ f"{fixture}/plain?multi-page-channel={index}",
+ wait_until="load",
+ )
+ for index, page in enumerate(pages)
+ )
+ )
+ await asyncio.gather(*(_install_broadcast_channel(page) for page in pages))
+
+ await asyncio.gather(
+ page_a_sender.evaluate(
+ "__multiPageChannel.postMessage({owner: 'a', sequence: 1})"
+ ),
+ page_b_sender.evaluate(
+ "__multiPageChannel.postMessage({owner: 'b', sequence: 1})"
+ ),
+ )
+ await asyncio.gather(
+ page_a_receiver.wait_for_function(
+ "() => __multiPageMessages.length === 1", timeout=5_000
+ ),
+ page_b_receiver.wait_for_function(
+ "() => __multiPageMessages.length === 1", timeout=5_000
+ ),
+ )
+ initial_messages = await asyncio.gather(
+ *(page.evaluate("globalThis.__multiPageMessages") for page in pages)
+ )
+ assert_equal(
+ initial_messages,
+ [
+ [],
+ [{"owner": "a", "sequence": 1}],
+ [],
+ [{"owner": "b", "sequence": 1}],
+ ],
+ "BroadcastChannel sender exclusion and BrowserContext partition",
+ )
+
+ await asyncio.gather(page_a_receiver.close(), page_b_receiver.close())
+ replacement_receiver = await context_a.new_page()
+ await replacement_receiver.goto(
+ f"{fixture}/plain?multi-page-channel=replacement",
+ wait_until="load",
+ )
+ await _install_broadcast_channel(replacement_receiver)
+ await page_a_sender.evaluate(
+ "__multiPageChannel.postMessage({owner: 'a', sequence: 2})"
+ )
+ await replacement_receiver.wait_for_function(
+ "() => __multiPageMessages.length === 1", timeout=5_000
+ )
+ assert_equal(
+ await replacement_receiver.evaluate("globalThis.__multiPageMessages"),
+ [{"owner": "a", "sequence": 2}],
+ "replacement same-context BroadcastChannel receiver",
+ )
+ assert_equal(
+ await page_b_sender.evaluate("globalThis.__multiPageMessages"),
+ [],
+ "replacement delivery does not cross BrowserContext",
+ )
+ record_contract(
+ results,
+ "multi_page_broadcast_channel_context_partition",
+ contract=(
+ "BroadcastChannel fans out to peer Pages in the same BrowserContext and "
+ "origin, excludes the sender, and never crosses BrowserContext partitions."
+ ),
+ source="Chromium DOM oracle",
+ commands=["Runtime.evaluate", "Target.closeTarget"],
+ observed={
+ "sameContextDelivered": True,
+ "senderExcluded": True,
+ "crossContextDelivered": False,
+ "replacementReceiverDelivered": True,
+ },
+ )
+ finally:
+ await _close_context(context_a)
+ await _close_context(context_b)
+
+
+async def _same_target_navigation_supersession(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ route_started = asyncio.Event()
+ release_route = asyncio.Event()
+ first_navigation: asyncio.Task[Any] | None = None
+
+ async def hold_first_navigation(route: Any) -> None:
+ route_started.set()
+ await release_route.wait()
+ with suppress(Exception):
+ await route.continue_()
+
+ try:
+ victim, peer = await asyncio.gather(context.new_page(), context.new_page())
+ await peer.goto(
+ f"{fixture}/plain?multi-page-supersession=peer-initial",
+ wait_until="load",
+ )
+ await victim.route("**/multi-page-supersession-held", hold_first_navigation)
+ first_navigation = asyncio.create_task(
+ victim.goto(
+ f"{fixture}/multi-page-supersession-held",
+ wait_until="load",
+ timeout=10_000,
+ )
+ )
+ await asyncio.wait_for(route_started.wait(), timeout=5)
+
+ peer_navigation = asyncio.create_task(
+ peer.goto(
+ f"{fixture}/plain?multi-page-supersession=peer-winner",
+ wait_until="load",
+ timeout=10_000,
+ )
+ )
+ winning_navigation = asyncio.create_task(
+ victim.goto(
+ f"{fixture}/plain?multi-page-supersession=victim-winner",
+ wait_until="load",
+ timeout=10_000,
+ )
+ )
+ release_route.set()
+ first_result = (
+ await asyncio.gather(first_navigation, return_exceptions=True)
+ )[0]
+ if not isinstance(first_result, BaseException):
+ raise SmokeError(
+ "a newer same-target navigation did not reject the held predecessor: "
+ f"{first_result!r}"
+ )
+ await asyncio.gather(peer_navigation, winning_navigation)
+ assert_equal(
+ [victim.url, peer.url],
+ [
+ f"{fixture}/plain?multi-page-supersession=victim-winner",
+ f"{fixture}/plain?multi-page-supersession=peer-winner",
+ ],
+ "same-target navigation winner and independent peer",
+ )
+ assert_equal(
+ await asyncio.gather(
+ victim.text_content("main"),
+ peer.text_content("main"),
+ ),
+ ["plain ok", "plain ok"],
+ "Documents after same-target navigation supersession",
+ )
+ record_contract(
+ results,
+ "multi_page_same_target_navigation_supersession",
+ contract=(
+ "A newer navigation aborts an older held navigation on the same target "
+ "without delaying or canceling a peer target's navigation."
+ ),
+ source="Chromium navigation oracle",
+ commands=["Fetch.enable", "Page.navigate"],
+ observed={
+ "predecessorRejected": True,
+ "winner": victim.url,
+ "peer": peer.url,
+ },
+ )
+ finally:
+ release_route.set()
+ if first_navigation is not None and not first_navigation.done():
+ first_navigation.cancel()
+ with suppress(Exception):
+ await context.unroute("**/multi-page-supersession-held")
+ await _close_context(context)
+
+
+async def _target_destroy_event_cardinality(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ context_closed = False
+ browser_cdp = await browser.new_browser_cdp_session()
+ destroyed: list[str] = []
+ browser_cdp.on(
+ "Target.targetDestroyed",
+ lambda event: destroyed.append(event.get("targetId", "")),
+ )
+ try:
+ await browser_cdp.send("Target.setDiscoverTargets", {"discover": True})
+ pages = await asyncio.gather(*(context.new_page() for _ in range(5)))
+ urls = [f"{fixture}/plain?multi-page-destroy={index}" for index in range(5)]
+ await asyncio.gather(
+ *(
+ page.goto(url, wait_until="load")
+ for page, url in zip(pages, urls, strict=True)
+ )
+ )
+ target_infos = (await browser_cdp.send("Target.getTargets")).get(
+ "targetInfos", []
+ )
+ target_by_url = {
+ info.get("url"): info.get("targetId")
+ for info in target_infos
+ if info.get("type") == "page"
+ }
+ target_ids = {target_by_url.get(url) for url in urls}
+ if None in target_ids or len(target_ids) != len(urls):
+ raise SmokeError(
+ "Target.getTargets did not expose every multi-page target: "
+ f"urls={urls!r}, infos={target_infos!r}"
+ )
+ live_target_ids = {str(target_id) for target_id in target_ids}
+ closing_indexes = (0, 2, 4)
+ first_closed_ids = {
+ str(target_by_url[urls[index]]) for index in closing_indexes
+ }
+ await asyncio.gather(*(pages[index].close() for index in closing_indexes))
+ await wait_until(
+ lambda: first_closed_ids <= set(destroyed),
+ "Target.targetDestroyed for non-tail target closes",
+ )
+ await browser_cdp.send("Target.getTargets")
+ first_destroyed = [
+ target_id for target_id in destroyed if target_id in first_closed_ids
+ ]
+ assert_equal(
+ len(first_destroyed),
+ len(first_closed_ids),
+ "one targetDestroyed event per explicitly closed target",
+ )
+ assert_equal(
+ {page.url for page in context.pages},
+ {urls[1], urls[3]},
+ "surviving Pages after alternating target closes",
+ )
+
+ await asyncio.wait_for(context.close(), timeout=5)
+ context_closed = True
+ await wait_until(
+ lambda: live_target_ids <= set(destroyed),
+ "Target.targetDestroyed for BrowserContext disposal",
+ )
+ await browser_cdp.send("Target.getTargets")
+ all_destroyed = [
+ target_id for target_id in destroyed if target_id in live_target_ids
+ ]
+ assert_equal(
+ len(all_destroyed),
+ len(live_target_ids),
+ "one targetDestroyed event per disposed-context target",
+ )
+ assert_equal(
+ len(set(all_destroyed)),
+ len(live_target_ids),
+ "unique targetDestroyed ownership",
+ )
+ record_contract(
+ results,
+ "multi_page_target_destroy_event_cardinality",
+ contract=(
+ "Each Page target emits exactly one Target.targetDestroyed event, both "
+ "for individual close and for BrowserContext disposal."
+ ),
+ source="Chromium Target domain oracle",
+ commands=[
+ "Target.setDiscoverTargets",
+ "Target.getTargets",
+ "Target.closeTarget",
+ "Target.disposeBrowserContext",
+ ],
+ observed={
+ "targets": len(live_target_ids),
+ "destroyedEvents": len(all_destroyed),
+ "uniqueTargetIds": len(set(all_destroyed)),
+ },
+ )
+ finally:
+ with suppress(Exception):
+ await browser_cdp.send("Target.setDiscoverTargets", {"discover": False})
+ with suppress(Exception):
+ await browser_cdp.detach()
+ if not context_closed:
+ await _close_context(context)
+
+
+async def _network_response_body_target_ownership(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ page_a, page_b = await asyncio.gather(context.new_page(), context.new_page())
+ session_a, session_b = await asyncio.gather(
+ context.new_cdp_session(page_a),
+ context.new_cdp_session(page_b),
+ )
+ sessions = [session_a, session_b]
+ events_a = attach_cdp_event_collector(
+ session_a,
+ ["Network.responseReceived", "Network.loadingFinished"],
+ )
+ events_b = attach_cdp_event_collector(
+ session_b,
+ ["Network.responseReceived", "Network.loadingFinished"],
+ )
+ await asyncio.gather(
+ session_a.send("Network.enable"),
+ session_b.send("Network.enable"),
+ )
+ url_a = f"{fixture}/plain?multi-page-network-body=a"
+ url_b = f"{fixture}/plain?multi-page-network-body=b"
+ await asyncio.gather(
+ page_a.goto(url_a, wait_until="load"),
+ page_b.goto(url_b, wait_until="load"),
+ )
+ request_a = _document_request_id(events_a, url_a)
+ request_b = _document_request_id(events_b, url_b)
+ if request_a == request_b:
+ raise SmokeError(
+ "concurrent Page targets reused a Document requestId: "
+ f"{request_a!r}"
+ )
+ body_a = await session_a.send(
+ "Network.getResponseBody",
+ {"requestId": request_a},
+ )
+ body_b = await session_b.send(
+ "Network.getResponseBody",
+ {"requestId": request_b},
+ )
+ assert_equal(
+ ["plain ok" in body_a.get("body", ""), "plain ok" in body_b.get("body", "")],
+ [True, True],
+ "target sessions resolve their own response bodies",
+ )
+ foreign_a = await _expect_protocol_error(
+ session_a.send("Network.getResponseBody", {"requestId": request_b}),
+ "page A resolving page B requestId",
+ )
+ foreign_b = await _expect_protocol_error(
+ session_b.send("Network.getResponseBody", {"requestId": request_a}),
+ "page B resolving page A requestId",
+ )
+
+ await page_b.close()
+ sessions.remove(session_b)
+ body_a_after_peer_close = await session_a.send(
+ "Network.getResponseBody",
+ {"requestId": request_a},
+ )
+ assert_equal(
+ body_a_after_peer_close.get("body"),
+ body_a.get("body"),
+ "peer target close does not evict the surviving target response body",
+ )
+ record_contract(
+ results,
+ "multi_page_network_response_body_target_ownership",
+ contract=(
+ "Document request identifiers and response-body caches are target-local; "
+ "foreign ids fail and peer close cannot evict a surviving cache entry."
+ ),
+ source="Chromium Network domain oracle",
+ commands=["Network.enable", "Network.getResponseBody", "Target.closeTarget"],
+ observed={
+ "requestIdsDistinct": True,
+ "foreignARejected": bool(foreign_a),
+ "foreignBRejected": bool(foreign_b),
+ "survivingBodyRetained": True,
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _websocket_survives_peer_target_close(
+ browser: Any,
+ fixture: str,
+ results: list[dict[str, Any]],
+) -> None:
+ context = await browser.new_context()
+ sessions: list[Any] = []
+ try:
+ owner, peer = await asyncio.gather(context.new_page(), context.new_page())
+ await asyncio.gather(
+ owner.goto(f"{fixture}/plain?multi-page-websocket=owner", wait_until="load"),
+ peer.goto(f"{fixture}/plain?multi-page-websocket=peer", wait_until="load"),
+ )
+ owner_session, peer_session = await asyncio.gather(
+ context.new_cdp_session(owner),
+ context.new_cdp_session(peer),
+ )
+ sessions = [owner_session, peer_session]
+ event_methods = [
+ "Network.webSocketCreated",
+ "Network.webSocketHandshakeResponseReceived",
+ "Network.webSocketFrameSent",
+ "Network.webSocketFrameReceived",
+ "Network.webSocketClosed",
+ ]
+ owner_events = attach_cdp_event_collector(owner_session, event_methods)
+ peer_events = attach_cdp_event_collector(peer_session, event_methods)
+ await asyncio.gather(
+ owner_session.send("Network.enable"),
+ peer_session.send("Network.enable"),
+ )
+
+ owner_payload = "owner-websocket-payload-is-deliberately-long"
+ peer_payload = "peer-short"
+ owner_echo, peer_echo = await asyncio.gather(
+ _open_persistent_websocket(owner, owner_payload),
+ _open_persistent_websocket(peer, peer_payload),
+ )
+ assert_equal(owner_echo, f"echo:{owner_payload}", "owner WebSocket echo")
+ assert_equal(peer_echo, f"echo:{peer_payload}", "peer WebSocket echo")
+ await asyncio.gather(
+ wait_until(
+ lambda: _has_received_websocket_payload_length(
+ owner_events, len(owner_echo)
+ ),
+ "owner WebSocket frame",
+ ),
+ wait_until(
+ lambda: _has_received_websocket_payload_length(
+ peer_events, len(peer_echo)
+ ),
+ "peer WebSocket frame",
+ ),
+ )
+ if _has_received_websocket_payload_length(peer_events, len(owner_echo)):
+ raise SmokeError("peer Network session received owner WebSocket frame")
+ if _has_received_websocket_payload_length(owner_events, len(peer_echo)):
+ raise SmokeError("owner Network session received peer WebSocket frame")
+
+ await owner.close()
+ peer_after_close_payload = "peer-after-owner-target-close"
+ peer_after_close_echo = await _send_persistent_websocket(
+ peer,
+ peer_after_close_payload,
+ )
+ assert_equal(
+ peer_after_close_echo,
+ f"echo:{peer_after_close_payload}",
+ "peer WebSocket after owner target close",
+ )
+ await wait_until(
+ lambda: _has_received_websocket_payload_length(
+ peer_events, len(peer_after_close_echo)
+ ),
+ "peer WebSocket frame after owner target close",
+ )
+ assert_equal(
+ await peer.evaluate("() => location.search"),
+ "?multi-page-websocket=peer",
+ "peer Document after owner WebSocket target close",
+ )
+ await peer.evaluate(
+ """() => new Promise(resolve => {
+ const socket = globalThis.__multiPageSocket;
+ if (!socket || socket.readyState === WebSocket.CLOSED) {
+ resolve();
+ return;
+ }
+ socket.addEventListener('close', () => resolve(), {once: true});
+ socket.close(1000, 'done');
+ })"""
+ )
+ await wait_until(
+ lambda: any(
+ event.get("method") == "Network.webSocketClosed"
+ for event in peer_events
+ ),
+ "peer Network.webSocketClosed",
+ )
+ record_contract(
+ results,
+ "multi_page_websocket_survives_peer_target_close",
+ contract=(
+ "WebSocket state and Network events belong to one Page target; closing "
+ "a peer target does not close or reroute a surviving Page's socket."
+ ),
+ source="Chromium Network domain oracle",
+ commands=["Network.enable", "Target.closeTarget"],
+ observed={
+ "ownerEchoLength": len(owner_echo),
+ "peerEchoLength": len(peer_echo),
+ "peerAfterCloseEchoLength": len(peer_after_close_echo),
+ },
+ )
+ finally:
+ await asyncio.gather(
+ *(session.detach() for session in sessions),
+ return_exceptions=True,
+ )
+ await _close_context(context)
+
+
+async def _expect_protocol_error(awaitable: Awaitable[Any], label: str) -> str:
+ try:
+ result = await awaitable
+ except Exception as error:
+ return str(error)
+ raise SmokeError(f"{label} unexpectedly succeeded: {result!r}")
+
+
+def _default_execution_context_id(events: list[dict[str, Any]]) -> int | None:
+ for event in events:
+ if event.get("method") != "Runtime.executionContextCreated":
+ continue
+ context = event.get("params", {}).get("context", {})
+ if context.get("auxData", {}).get("isDefault") is not True:
+ continue
+ context_id = context.get("id")
+ if isinstance(context_id, int):
+ return context_id
+ return None
+
+
+def _has_lifecycle_event(events: list[dict[str, Any]], name: str) -> bool:
+ return any(
+ event.get("method") == "Page.lifecycleEvent"
+ and event.get("params", {}).get("name") == name
+ for event in events
+ )
+
+
+async def _viewport_metrics(page: Any) -> list[float]:
+ return await page.evaluate(
+ "() => [innerWidth, innerHeight, devicePixelRatio]"
+ )
+
+
+async def _same_target_session_script_values(page: Any) -> list[str | None]:
+ return await page.evaluate(
+ """() => [
+ globalThis.__multiPageSessionA ?? null,
+ globalThis.__multiPageSessionB ?? null,
+ ]"""
+ )
+
+
+async def _create_isolated_world(session: Any, world_name: str) -> int:
+ frame_tree = await session.send("Page.getFrameTree")
+ frame_id = frame_tree.get("frameTree", {}).get("frame", {}).get("id")
+ if not isinstance(frame_id, str) or not frame_id:
+ raise SmokeError(f"Page.getFrameTree returned no main frame id: {frame_tree!r}")
+ world = await session.send(
+ "Page.createIsolatedWorld",
+ {"frameId": frame_id, "worldName": world_name},
+ )
+ context_id = world.get("executionContextId")
+ if not isinstance(context_id, int):
+ raise SmokeError(f"Page.createIsolatedWorld returned no context id: {world!r}")
+ return context_id
+
+
+async def _root_and_child_frame_ids(session: Any) -> list[str]:
+ frame_tree = (await session.send("Page.getFrameTree")).get("frameTree", {})
+ root_id = frame_tree.get("frame", {}).get("id")
+ children = frame_tree.get("childFrames", [])
+ child_id = children[0].get("frame", {}).get("id") if children else None
+ if not isinstance(root_id, str) or not isinstance(child_id, str):
+ raise SmokeError(
+ "Page.getFrameTree returned no root/child frame pair: "
+ f"{frame_tree!r}"
+ )
+ return [root_id, child_id]
+
+
+async def _create_isolated_worlds_for_frames(
+ session: Any,
+ frame_ids: list[str],
+ world_name: str,
+) -> list[int]:
+ context_ids: list[int] = []
+ for frame_id in frame_ids:
+ world = await session.send(
+ "Page.createIsolatedWorld",
+ {"frameId": frame_id, "worldName": world_name},
+ )
+ context_id = world.get("executionContextId")
+ if not isinstance(context_id, int):
+ raise SmokeError(
+ "Page.createIsolatedWorld returned no context id for frame "
+ f"{frame_id!r}: {world!r}"
+ )
+ context_ids.append(context_id)
+ return context_ids
+
+
+async def _evaluate_context_value(
+ session: Any,
+ context_id: int,
+ expression: str,
+) -> Any:
+ evaluation = await session.send(
+ "Runtime.evaluate",
+ {
+ "contextId": context_id,
+ "expression": expression,
+ "returnByValue": True,
+ },
+ )
+ return evaluation.get("result", {}).get("value")
+
+
+def _binding_payloads(events: list[dict[str, Any]], name: str) -> list[str]:
+ return [
+ str(event.get("params", {}).get("payload"))
+ for event in events
+ if event.get("method") == "Runtime.bindingCalled"
+ and event.get("params", {}).get("name") == name
+ ]
+
+
+def _document_request_id(events: list[dict[str, Any]], url: str) -> str:
+ for event in events:
+ if event.get("method") != "Network.responseReceived":
+ continue
+ params = event.get("params", {})
+ if params.get("type") != "Document":
+ continue
+ if params.get("response", {}).get("url") != url:
+ continue
+ request_id = params.get("requestId")
+ if isinstance(request_id, str) and request_id:
+ return request_id
+ raise SmokeError(
+ f"Network.responseReceived exposed no Document requestId for {url!r}: {events!r}"
+ )
+
+
+def _has_document_response(events: list[dict[str, Any]], url: str) -> bool:
+ return any(
+ event.get("method") == "Network.responseReceived"
+ and event.get("params", {}).get("type") == "Document"
+ and event.get("params", {}).get("response", {}).get("url") == url
+ for event in events
+ )
+
+
+async def _install_broadcast_channel(page: Any) -> None:
+ await page.evaluate(
+ """() => {
+ globalThis.__multiPageMessages = [];
+ globalThis.__multiPageChannel = new BroadcastChannel('multi-page-contract');
+ globalThis.__multiPageChannel.onmessage = event => {
+ globalThis.__multiPageMessages.push(event.data);
+ };
+ }"""
+ )
+
+
+async def _open_persistent_websocket(page: Any, payload: str) -> str:
+ return await page.evaluate(
+ """payload => new Promise((resolve, reject) => {
+ const url = new URL('/ws-echo', location.href);
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
+ const socket = new WebSocket(url.href, 'smoke');
+ globalThis.__multiPageSocket = socket;
+ const timer = setTimeout(() => {
+ socket.close();
+ reject(new Error(`WebSocket open timed out at ${socket.readyState}`));
+ }, 5000);
+ socket.onopen = () => socket.send(payload);
+ socket.onmessage = event => {
+ clearTimeout(timer);
+ resolve(event.data);
+ };
+ socket.onerror = () => {
+ clearTimeout(timer);
+ reject(new Error(`WebSocket failed at ${socket.readyState}`));
+ };
+ })""",
+ payload,
+ )
+
+
+async def _send_persistent_websocket(page: Any, payload: str) -> str:
+ return await page.evaluate(
+ """payload => new Promise((resolve, reject) => {
+ const socket = globalThis.__multiPageSocket;
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
+ reject(new Error(`WebSocket is not open: ${socket?.readyState}`));
+ return;
+ }
+ const timer = setTimeout(() => {
+ reject(new Error(`WebSocket reply timed out at ${socket.readyState}`));
+ }, 5000);
+ const receive = event => {
+ clearTimeout(timer);
+ resolve(event.data);
+ };
+ socket.addEventListener('message', receive, {once: true});
+ socket.send(payload);
+ })""",
+ payload,
+ )
+
+
+def _has_received_websocket_payload_length(
+ events: list[dict[str, Any]],
+ payload_length: int,
+) -> bool:
+ for event in events:
+ if event.get("method") != "Network.webSocketFrameReceived":
+ continue
+ response = event.get("params", {}).get("response", {})
+ observed_length = response.get("payloadLength")
+ if not isinstance(observed_length, int):
+ payload_data = response.get("payloadData")
+ if isinstance(payload_data, str):
+ observed_length = len(payload_data.encode("utf-8"))
+ if observed_length == payload_length:
+ return True
+ return False
+
+
+async def _close_context(context: Any) -> None:
+ try:
+ await asyncio.wait_for(context.close(), timeout=5)
+ except Exception as error:
+ raise SmokeError(
+ f"BrowserContext.close failed: {type(error).__name__}: {error}"
+ ) from error
+
+
+def _read_fixture_json(url: str) -> Any:
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ with opener.open(url, timeout=2) as response:
+ return json.load(response)
diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.py
index ac45161ee..596d41cc0 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py
@@ -41,6 +41,7 @@ from .groups.iframe_input import run_iframe_input_group
from .groups.layout_screenshot import run_layout_screenshot_group
from .groups.multi_client import run_multi_client_group
from .groups.multi_context import run_multi_context_group
+from .groups.multi_page import run_multi_page_group
from .groups.network import (
run_download_group,
run_network_body_cache_group,
@@ -348,6 +349,13 @@ BROWSER_GROUPS: tuple[SmokeGroup, ...] = (
"browser",
run_multi_context_group,
),
+ SmokeGroup(
+ "multi-page",
+ "Multi-target churn, navigation, interception, popup, session, worker, "
+ "screenshot, and teardown regression matrix.",
+ "browser",
+ run_multi_page_group,
+ ),
)
MANAGED_EXTERNAL_GROUPS: tuple[SmokeGroup, ...] = (
diff --git a/moli-cdp-smoke/tests/test_group_selection.py b/moli-cdp-smoke/tests/test_group_selection.py
index b6b6b1e0d..a44597539 100644
--- a/moli-cdp-smoke/tests/test_group_selection.py
+++ b/moli-cdp-smoke/tests/test_group_selection.py
@@ -31,6 +31,7 @@ class GroupSelectionTests(unittest.TestCase):
self.assertIn("file-chooser", DEFAULT_GROUP_NAMES)
self.assertIn("inspector-routing", DEFAULT_GROUP_NAMES)
self.assertIn("navigation-outcomes", DEFAULT_GROUP_NAMES)
+ self.assertIn("multi-page", DEFAULT_GROUP_NAMES)
self.assertIn("puppeteer", DEFAULT_GROUP_NAMES)
self.assertEqual(
tuple(group.name for group in MANAGED_EXTERNAL_GROUPS),
diff --git a/moli-core/src/page/command_dispatch.rs b/moli-core/src/page/command_dispatch.rs
index e2bb78ff8..245cd57df 100644
--- a/moli-core/src/page/command_dispatch.rs
+++ b/moli-core/src/page/command_dispatch.rs
@@ -108,6 +108,21 @@ impl CompletedPageCommand {
}
Ok(self.output)
}
+
+ /// Consumes a unit-reply command that settled on an attachment which is
+ /// no longer current.
+ ///
+ /// The caller deliberately does not install the frozen Page state on the
+ /// replacement attachment. Target-scoped browser state must instead be
+ /// replayed while that replacement Page is installed.
+ pub fn into_unit_page_command_turn(self) -> Result<RendererCommandTurnOutput> {
+ if !matches!(self.output.completion().reply(), RendererPageReply::Unit) {
+ return Err(anyhow::anyhow!(
+ "unit page command returned an unexpected renderer reply"
+ ));
+ }
+ Ok(self.output)
+ }
}
impl Page {
diff --git a/moli-core/src/runtime/mod.rs b/moli-core/src/runtime/mod.rs
index 0df1a3e78..753de7a1b 100644
--- a/moli-core/src/runtime/mod.rs
+++ b/moli-core/src/runtime/mod.rs
@@ -1099,6 +1099,7 @@ impl Browser {
.cloned()
.map(|source| DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source,
world_name: None,
has_bidi_channel_argument: false,
@@ -1227,6 +1228,7 @@ impl Browser {
.cloned()
.map(|source| DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source,
world_name: None,
has_bidi_channel_argument: false,
diff --git a/moli-core/src/runtime/navigation_engine.rs b/moli-core/src/runtime/navigation_engine.rs
index 6bb9cfd68..c570373a0 100644
--- a/moli-core/src/runtime/navigation_engine.rs
+++ b/moli-core/src/runtime/navigation_engine.rs
@@ -345,8 +345,7 @@ impl PendingBuiltDocumentPage {
}
}
-/// Browser-owner configuration that must survive every NavigationEngine
-/// replacement and BrowserContext handoff.
+/// Configuration copied into each Page-owned or standalone NavigationEngine.
#[derive(Debug, Clone)]
pub struct NavigationRuntimeConfig {
fetch_config: FetchConfig,
@@ -767,8 +766,8 @@ impl NavigationEngine {
expected_final_url: &Url,
source: CommittedDocumentResourceSource,
) -> Result<ResourceRequestClient> {
- let expected_runtime = self.ensure_resource_runtime(cookie_store)?;
let CommittedDocumentResourceSource::Navigation(seed) = source else {
+ let expected_runtime = self.ensure_resource_runtime(cookie_store)?;
return Ok(
ResourceRequestClient::from_browser_resource_runtime_with_page_network_policy(
expected_runtime,
@@ -783,11 +782,23 @@ impl NavigationEngine {
);
}
let committed_runtime = seed.browser_resource_runtime();
- if !expected_runtime.shares_state_with(&committed_runtime) {
+ if self
+ .browser_context_access
+ .validate_registered(&committed_runtime)
+ .is_err()
+ || !Arc::ptr_eq(&committed_runtime.cookie_store(), &cookie_store)
+ || !committed_runtime.matches_fetch_config(&self.fetch_config)
+ {
anyhow::bail!(
"navigation commit seed does not belong to the NavigationEngine browser resource runtime"
);
}
+ // Another target sharing this BrowserContext may replace the ambient
+ // transport binding while this request is in flight. The immutable
+ // navigation seed remains the exact authority for the committed
+ // Document as long as its runtime is still registered under this
+ // owner and matches the target's captured policy.
+ self.resource_runtime = Some(committed_runtime.clone());
Ok(
ResourceRequestClient::from_browser_resource_runtime_with_page_network_policy(
committed_runtime,
@@ -2737,4 +2748,53 @@ mod tests {
.contains("does not belong to the NavigationEngine browser resource runtime")
);
}
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn navigation_commit_keeps_its_registered_runtime_after_peer_target_replacement() {
+ let mut target_a = NavigationEngine::new();
+ let mut target_b = target_a.clone();
+ let cookie_store = target_a
+ .resource_request_client()
+ .expect("target A initial request client")
+ .browser_resource_runtime()
+ .cookie_store();
+ target_a.set_user_agent_override("Moli/Target-A");
+ let target_a_client = target_a
+ .rebuild_resource_request_client(cookie_store.clone())
+ .expect("target A runtime");
+ let start_url = Url::parse("https://example.test/start").expect("navigation start URL");
+ let final_url = Url::parse("https://example.test/final").expect("navigation final URL");
+ let navigation = moli_renderer_v8::network::navigation::NavigationResourceLoader::new(
+ target_a_client.clone(),
+ start_url,
+ moli_renderer_v8::network::RendererResourceTaskRunner::from_current_tokio()
+ .expect("test must own a Tokio runtime"),
+ );
+ navigation
+ .note_service_worker_response_ready()
+ .expect("target A navigation response ready");
+ let seed = navigation
+ .commit(final_url.clone())
+ .expect("target A navigation seed");
+
+ target_b.set_user_agent_override("Moli/Target-B");
+ let target_b_client = target_b
+ .rebuild_resource_request_client(cookie_store.clone())
+ .expect("target B must replace the ambient BrowserContext runtime");
+ assert!(!target_a_client.shares_resource_runtime_with(&target_b_client));
+
+ let committed_client = target_a
+ .resource_request_client_for_committed_document(
+ cookie_store,
+ &final_url,
+ CommittedDocumentResourceSource::Navigation(Box::new(seed)),
+ )
+ .expect("target A must commit with the runtime that fetched its response");
+
+ assert!(committed_client.shares_resource_runtime_with(&target_a_client));
+ assert_eq!(
+ committed_client.browser_identity().user_agent(),
+ "Moli/Target-A"
+ );
+ }
}
diff --git a/moli-page-types/src/inspector_state.rs b/moli-page-types/src/inspector_state.rs
index 9ff29fc70..a8d8f3c0e 100644
--- a/moli-page-types/src/inspector_state.rs
+++ b/moli-page-types/src/inspector_state.rs
@@ -278,6 +278,7 @@ mod tests {
protocol_configuration: RendererInspectorProtocolConfiguration {
runtime_frontend_enabled: true,
runtime_bindings: vec![RuntimeBindingRegistration {
+ devtools_session: None,
name: "binding".to_owned(),
execution_context_name: None,
}],
@@ -299,6 +300,7 @@ mod tests {
let restore = RendererInspectorSessionRestoreSnapshot {
protocol_configuration: RendererInspectorProtocolConfiguration {
runtime_bindings: vec![RuntimeBindingRegistration {
+ devtools_session: None,
name: "binding".to_owned(),
execution_context_name: Some("utility".to_owned()),
}],
diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rs
index 9b272fccc..017982347 100644
--- a/moli-page-types/src/lib.rs
+++ b/moli-page-types/src/lib.rs
@@ -1030,6 +1030,13 @@ pub struct BidiPreloadChannelHandoff {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentStartScript {
pub registry_key: Option<String>,
+ /// DevTools session whose Page agent owns a named-world script.
+ ///
+ /// Blink keeps `InspectorPageAgent` state per DevTools session, so equal
+ /// `worldName` values from two sessions must materialize different worlds.
+ /// `None` is reserved for non-CDP registrations such as configured and
+ /// WebDriver BiDi preloads.
+ pub devtools_session: Option<DevToolsSessionKey>,
pub source: String,
pub world_name: Option<String>,
pub has_bidi_channel_argument: bool,
@@ -1042,6 +1049,12 @@ impl DocumentStartScript {
script.registry_key = Some(registry_key.into());
script
}
+
+ pub fn with_devtools_session(&self, devtools_session: DevToolsSessionKey) -> Self {
+ let mut script = self.clone();
+ script.devtools_session = Some(devtools_session);
+ script
+ }
}
#[derive(Debug, Clone)]
@@ -3071,10 +3084,22 @@ pub struct PendingRuntimeBindingCall {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeBindingRegistration {
+ /// Renderer DevTools session that owns this binding when it is part of an
+ /// aggregate Page snapshot. Session-local Inspector configuration leaves
+ /// this as `None` because the containing session is already authoritative.
+ pub devtools_session: Option<DevToolsSessionKey>,
pub name: String,
pub execution_context_name: Option<String>,
}
+impl RuntimeBindingRegistration {
+ pub fn with_devtools_session(&self, devtools_session: DevToolsSessionKey) -> Self {
+ let mut binding = self.clone();
+ binding.devtools_session = Some(devtools_session);
+ binding
+ }
+}
+
#[derive(Debug, Clone, PartialEq)]
pub enum RuntimeContextRestoreEvent {
Created(RuntimeExecutionContextRestoreEvent),
diff --git a/moli-protocol-server/src/protocol_server/tests/bidi.rs b/moli-protocol-server/src/protocol_server/tests/bidi.rs
index 6054051d0..723d9cb7f 100644
--- a/moli-protocol-server/src/protocol_server/tests/bidi.rs
+++ b/moli-protocol-server/src/protocol_server/tests/bidi.rs
@@ -11879,6 +11879,16 @@ async fn websocket_bidi_emulation_user_context_overrides_apply_to_later_http_nav
);
assert_eq!(
bidi_string_script_value(&mut socket, 9, &context_id, "navigator.language").await,
+ "en-US"
+ );
+ assert_eq!(
+ bidi_string_script_value(
+ &mut socket,
+ 91,
+ &context_id,
+ "Intl.DateTimeFormat().resolvedOptions().locale"
+ )
+ .await,
locale
);
let profile = bidi_string_script_value(
@@ -11891,7 +11901,7 @@ async fn websocket_bidi_emulation_user_context_overrides_apply_to_later_http_nav
let profile: serde_json::Value =
serde_json::from_str(&profile).expect("profile echo should be JSON");
assert_eq!(profile["userAgent"], json!(user_agent));
- assert_eq!(profile["acceptLanguage"], json!(locale));
+ assert_eq!(profile["acceptLanguage"], json!("en-US,en;q=0.9"));
let _ = socket.close(None).await;
protocol_server.abort();
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
index 8143dd3f5..195051df9 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
@@ -2598,7 +2598,7 @@ async fn websocket_cdp_shared_owner_survives_idle_browser_reconnect() {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn websocket_cdp_puppeteer_reconnect_replays_existing_runtime_context() {
+async fn websocket_cdp_puppeteer_reconnect_recreates_session_owned_runtime_context() {
let (addr, server) = spawn_test_protocol_server().await;
let (status, body) = fetch_server_response(addr, "PUT", "/json/new?about%3Ablank").await;
assert_eq!(status, 200);
@@ -2649,12 +2649,10 @@ async fn websocket_cdp_puppeteer_reconnect_replays_existing_runtime_context() {
}),
)
.await;
- assert!(
+ let first_utility_context_id =
response_by_id(&utility_world, 6)["result"]["executionContextId"]
.as_i64()
- .is_some(),
- "failed to create the persistent Puppeteer utility world: {utility_world:#?}"
- );
+ .unwrap_or_else(|| panic!("failed to create the utility world: {utility_world:#?}"));
browser
.close(None)
@@ -2687,25 +2685,48 @@ async fn websocket_cdp_puppeteer_reconnect_replays_existing_runtime_context() {
)
.await;
assert!(
- replay.iter().any(|message| {
- message["sessionId"] == json!(replacement_page_session_id)
- && message["method"] == json!("Runtime.executionContextCreated")
- && message["params"]["context"]["name"]
- == json!("__puppeteer_utility_world__moli_reconnect")
+ replay.iter().all(|message| {
+ message["sessionId"] != json!(replacement_page_session_id)
+ || message["method"] != json!("Runtime.executionContextCreated")
+ || message["params"]["context"]["name"]
+ != json!("__puppeteer_utility_world__moli_reconnect")
}),
- "replacement Runtime.enable did not replay the existing Puppeteer utility world: {replay:#?}"
+ "replacement Runtime.enable inherited a detached session's utility world: {replay:#?}"
);
- let evaluated = send_cdp_command(
+ let replacement_utility_world = send_cdp_command(
&mut replacement,
6,
+ "Page.createIsolatedWorld",
+ Some(&replacement_page_session_id),
+ json!({
+ "frameId": target_id,
+ "worldName": "__puppeteer_utility_world__moli_reconnect",
+ "grantUniveralAccess": true
+ }),
+ )
+ .await;
+ let replacement_utility_context_id =
+ response_by_id(&replacement_utility_world, 6)["result"]["executionContextId"]
+ .as_i64()
+ .unwrap_or_else(|| {
+ panic!(
+ "replacement session failed to recreate its utility world: \
+ {replacement_utility_world:#?}"
+ )
+ });
+ assert_ne!(replacement_utility_context_id, first_utility_context_id);
+
+ let evaluated = send_cdp_command(
+ &mut replacement,
+ 7,
"Runtime.evaluate",
Some(&replacement_page_session_id),
json!({ "expression": "6 * 7", "returnByValue": true }),
)
.await;
assert_eq!(
- response_by_id(&evaluated, 6)["result"]["result"]["value"],
+ response_by_id(&evaluated, 7)["result"]["result"]["value"],
json!(42)
);
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index 8b65be72e..751d67540 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -542,12 +542,12 @@ pub(crate) use site_data_manager_surface::{
BrowserContextReservedSiteDataOwnerState, BrowserContextSiteDataManagerOwnerState,
};
pub use state::{
- BackgroundTarget, BrowserContext, BrowserWindowBounds, DevToolsPageResidenceIdentity,
- DocumentStartScript, DownloadNavigation, EmulatedDeviceMetrics, EmulatedGeolocationOverride,
+ BrowserContext, BrowserWindowBounds, DevToolsPageResidenceIdentity, DocumentStartScript,
+ DownloadNavigation, EmulatedDeviceMetrics, EmulatedGeolocationOverride,
EmulatedGeolocationOverrideState, EmulatedMediaOverrides, IsolatedWorldDefinition,
LoadedNavigation, NavigationDispatchState, NavigationLoadOutcome, NavigationRequestLoadPolicy,
- PageNavigationHistoryEntry, ParkedFetchState, ParkedNetworkArtifacts, ParkedPageSessionState,
- PendingNavigationHistoryUpdate, RuntimeBindingDefinition, TargetInfo, URL_BASE,
+ PageNavigationHistoryEntry, PageTargetHost, PendingNavigationHistoryUpdate,
+ RuntimeBindingDefinition, TargetInfo, TargetPageState, URL_BASE,
};
pub(crate) use state::{
BrowserContextPageStorageHandles, BrowserContextResourceStorageHandles,
@@ -558,11 +558,11 @@ pub(crate) use state::{
DocumentNavigationToken, DuplicatePendingRendererCommand, EmulatedNetworkConditions,
EmulatedViewportSurface, InspectorCommandDispatch, NETWORK_ERROR_PAGE_URL,
NavigationResultProjection, NavigationSourceDocumentSecurityContext,
- NetworkErrorPageNavigation, PageScreencastConfig, PageScreencastFormat, ParkedTargetAuxState,
- ParkedTargetOwnerState, PendingBidiChannelListener, PendingInspectorAwait,
- PendingRendererCommandKey, PerformanceTimeDomain, PreparedRendererCallDispatch, ProfilerAction,
- ProfilerInspectorCommand, RendererCommandCorrelation, RendererCommandDescriptor,
- RendererCommandReplay, RendererDocumentLifecycleObservation, RendererDocumentLifecycleObserver,
+ NetworkErrorPageNavigation, PageScreencastConfig, PageScreencastFormat, ParkedTargetOwnerState,
+ PendingBidiChannelListener, PendingInspectorAwait, PendingRendererCommandKey,
+ PerformanceTimeDomain, PreparedRendererCallDispatch, ProfilerAction, ProfilerInspectorCommand,
+ RendererCommandCorrelation, RendererCommandDescriptor, RendererCommandReplay,
+ RendererDocumentLifecycleObservation, RendererDocumentLifecycleObserver,
RendererMainDocumentCommitSeed, RendererPageResidenceIdentity,
ServiceWorkerRuntimeExceptionSnapshot, ServiceWorkerTargetState, SharedWorkerTargetState,
SiteDataClearOptions, TargetIdentityState, TargetInitialEmptyDocumentCreator, TargetOwnerState,
@@ -574,7 +574,7 @@ pub(crate) use state::{
TargetServiceWorkerRunIdentity, TargetServiceWorkerRunRetirement,
TargetServiceWorkerRuntimeAttachmentIdentity, TargetServiceWorkerVersionIdentity,
TargetServiceWorkerVersionRetirement, TargetSharedWorkerProtocolAttachmentIdentity,
- TargetSharedWorkerProtocolAttachmentRetirement, TargetSlotState, TargetWindowSurfaceState,
+ TargetSharedWorkerProtocolAttachmentRetirement, TargetWindowSurfaceState,
viewport_surface_install_script,
};
#[cfg(test)]
@@ -672,7 +672,6 @@ pub(crate) struct IdleNavigationEngineReleaseResult {
pub(crate) reason: &'static str,
pub(crate) loaded_browser_context_count: usize,
pub(crate) live_target_browser_context_count: usize,
- pub(crate) retained_background_navigation_engine_count: usize,
}
impl IdleNavigationEngineReleaseResult {
@@ -682,7 +681,6 @@ impl IdleNavigationEngineReleaseResult {
"reason": self.reason,
"loadedBrowserContextCount": self.loaded_browser_context_count,
"liveTargetBrowserContextCount": self.live_target_browser_context_count,
- "retainedBackgroundNavigationEngineCount": self.retained_background_navigation_engine_count,
})
}
}
@@ -1043,18 +1041,18 @@ pub(crate) struct ServiceWorkerAutoAttachRelatedOwnerSession {
pub(crate) wait_for_debugger_on_start: bool,
}
-/// Drop-addressable slot for the connection's active renderer owner.
+/// Drop-addressable fallback engine for commands without a concrete Page host.
///
/// `CdpConnection::drop` must release this engine before joining its extracted
/// BrowserContext network roots. A plain field would only be dropped after the
/// Drop implementation returned, which reverses that order.
-struct NavigationEngineOwnerSlot {
+struct StandaloneNavigationEngineSlot {
engine: OnceCell<NavigationEngine>,
runtime_config: NavigationRuntimeConfig,
renderer_publication_sender: Option<moli_core::RendererOutputTransportSender>,
}
-impl NavigationEngineOwnerSlot {
+impl StandaloneNavigationEngineSlot {
fn materialized(engine: NavigationEngine) -> Self {
let runtime_config = engine.runtime_config();
let slot = Self {
@@ -1064,7 +1062,7 @@ impl NavigationEngineOwnerSlot {
};
slot.engine
.set(engine)
- .expect("fresh navigation engine slot must be empty");
+ .expect("fresh standalone navigation engine slot must be empty");
slot
}
@@ -1120,7 +1118,7 @@ impl NavigationEngineOwnerSlot {
let previous = self.engine.take();
self.engine
.set(engine)
- .expect("navigation engine slot must be empty after take");
+ .expect("standalone navigation engine slot must be empty after take");
previous
}
@@ -1142,7 +1140,7 @@ impl NavigationEngineOwnerSlot {
self.ensure();
self.engine
.get_mut()
- .expect("navigation engine was just materialized")
+ .expect("standalone navigation engine was just materialized")
}
}
@@ -1216,16 +1214,9 @@ pub struct CdpConnection {
// source-specific queue ownership is being migrated outward.
scheduler_state: CdpConnectionSchedulerState,
- // Renderer/page owner state. This must remain single-owner and current
- // thread affine while V8/DOM/Page state still lives inside NavigationEngine.
- engine: NavigationEngineOwnerSlot,
- // Background or inactive navigations run on fresh NavigationEngine
- // instances so they do not block the active page owner. A loaded Page only
- // keeps a weak renderer handle; the engine is the strong owner of that
- // renderer runtime. Keep engines keyed by browser-context/target while the
- // page is parked in the background or in an inactive browser context, and
- // swap them back into `engine` when that owner becomes active.
- retained_background_navigation_engines: HashMap<(String, String), NavigationEngine>,
+ // Standalone navigation state for commands that have no concrete Page
+ // owner. Every page-owned engine lives in its stable PageTargetHost.
+ standalone_navigation_engine: StandaloneNavigationEngineSlot,
}
impl Default for CdpConnection {
@@ -1254,17 +1245,16 @@ impl Drop for CdpConnection {
root.terminate_renderer_producers_for_owner_shutdown();
}
- // Dropping contexts releases active/background target and Page state.
+ // Dropping contexts releases every PageTargetHost and its Page state.
drop(contexts);
// RenderRuntimeOwner joins happen when the last JsRuntime-backed
// NavigationEngine handle is released. Do that explicitly here rather
// than relying on field drop after this method returns.
- self.retained_background_navigation_engines.clear();
- drop(self.engine.take());
+ drop(self.standalone_navigation_engine.take());
- // Only after active and retained renderer owners are gone may the
- // context roots close fetch admission and join semantic/curl owners.
+ // Only after every Page engine and the standalone fallback are gone
+ // may the context roots close fetch admission and join network owners.
for root in &mut roots {
root.shutdown_network_and_join();
}
@@ -1278,7 +1268,56 @@ impl CdpConnection {
}
pub(crate) fn layout_policy(&self) -> LayoutPolicy {
- self.engine.layout_policy()
+ self.browser_context
+ .as_ref()
+ .and_then(|context| context.page_targets.active())
+ .and_then(PageTargetHost::navigation_engine)
+ .map(NavigationEngine::layout_policy)
+ .unwrap_or_else(|| self.standalone_navigation_engine.layout_policy())
+ }
+
+ pub(crate) fn active_navigation_engine(&self) -> &NavigationEngine {
+ if let Some(engine) = self
+ .browser_context
+ .as_ref()
+ .and_then(|context| context.page_targets.active())
+ .and_then(PageTargetHost::navigation_engine)
+ {
+ return engine;
+ }
+ self.standalone_navigation_engine.ensure()
+ }
+
+ pub(crate) fn active_navigation_engine_mut(&mut self) -> &mut NavigationEngine {
+ let active_owner = self
+ .browser_context
+ .as_ref()
+ .and_then(|context| Some((context.id.clone(), context.active_target_id()?.to_owned())));
+ if let Some((browser_context_id, target_id)) = active_owner {
+ return self
+ .ensure_page_navigation_engine_for_target(&browser_context_id, &target_id)
+ .expect("active PageTargetHost navigation engine disappeared");
+ }
+ self.standalone_navigation_engine.ensure_mut()
+ }
+
+ pub(crate) fn ensure_page_navigation_engine_for_target(
+ &mut self,
+ browser_context_id: &str,
+ target_id: &str,
+ ) -> Option<&mut NavigationEngine> {
+ let needs_engine = self
+ .browser_context_by_id(browser_context_id)?
+ .page_navigation_engine(target_id)
+ .is_none();
+ if needs_engine {
+ let config = self.standalone_navigation_engine.runtime_config();
+ let sender = self.scheduler_hooks.renderer_publication_sender();
+ self.browser_context_by_id_mut(browser_context_id)?
+ .bind_page_navigation_engines(config, sender);
+ }
+ self.browser_context_by_id_mut(browser_context_id)?
+ .page_navigation_engine_mut(target_id)
}
pub fn has_pending_javascript_dialog(&self) -> bool {
@@ -1402,7 +1441,7 @@ impl CdpConnection {
);
Self::new_with_initial_storage_partition_owner_and_engine(
initial_storage_partition,
- NavigationEngineOwnerSlot::deferred(navigation_runtime_config),
+ StandaloneNavigationEngineSlot::deferred(navigation_runtime_config),
)
}
@@ -1412,17 +1451,17 @@ impl CdpConnection {
) -> Self {
Self::new_with_initial_storage_partition_owner_and_engine(
initial_storage_partition,
- NavigationEngineOwnerSlot::materialized(NavigationEngine::new_with_runtime_config(
- navigation_runtime_config,
- )),
+ StandaloneNavigationEngineSlot::materialized(
+ NavigationEngine::new_with_runtime_config(navigation_runtime_config),
+ ),
)
}
fn new_with_initial_storage_partition_owner_and_engine(
initial_storage_partition: CdpInitialStoragePartitionOwner,
- engine: NavigationEngineOwnerSlot,
+ standalone_navigation_engine: StandaloneNavigationEngineSlot,
) -> Self {
- let fetch_config = engine.fetch_config();
+ let fetch_config = standalone_navigation_engine.fetch_config();
let base_browser_identity = fetch_config.browser_identity().clone();
let base_http_proxy = fetch_config.http_proxy().map(str::to_owned);
let base_http_no_proxy = fetch_config.http_no_proxy().map(str::to_owned);
@@ -1476,8 +1515,7 @@ impl CdpConnection {
target_host_lifecycle_observer: None,
scheduler_state: CdpConnectionSchedulerState::default(),
none_session_owner_route_override: None,
- engine,
- retained_background_navigation_engines: HashMap::new(),
+ standalone_navigation_engine,
}
}
@@ -1521,10 +1559,14 @@ impl CdpConnection {
) {
self.scheduler_hooks
.set_renderer_publication_sender(sender.clone());
- self.engine
+ self.standalone_navigation_engine
.set_renderer_output_transport_sender(sender.clone());
- for engine in self.retained_background_navigation_engines.values() {
- engine.set_renderer_output_transport_sender(sender.clone());
+ for context in self
+ .browser_context
+ .iter_mut()
+ .chain(self.inactive_browser_contexts.iter_mut())
+ {
+ context.set_renderer_output_transport_sender(sender.clone());
}
}
@@ -2434,7 +2476,7 @@ impl CdpConnection {
}
self.browser_context
.as_ref()
- .is_some_and(|browser_context| browser_context.background_targets.is_empty())
+ .is_some_and(|browser_context| browser_context.has_no_background_targets())
}
pub(crate) fn can_defer_initial_document_page_build(&self) -> bool {
@@ -2533,10 +2575,10 @@ impl CdpConnection {
protocol_events
}
- pub(crate) fn replace_navigation_engine(&mut self, engine: NavigationEngine) {
+ pub(crate) fn replace_standalone_navigation_engine(&mut self, engine: NavigationEngine) {
let engine = engine;
self.apply_scheduler_senders_to_navigation_engine(&engine);
- drop(self.engine.replace(engine));
+ drop(self.standalone_navigation_engine.replace(engine));
}
pub(crate) fn apply_scheduler_senders_to_navigation_engine(&self, engine: &NavigationEngine) {
@@ -2545,17 +2587,17 @@ impl CdpConnection {
}
}
- fn retain_background_navigation_engine(
+ fn install_page_navigation_engine(
&mut self,
- browser_context_id: String,
- target_id: String,
+ browser_context_id: &str,
+ target_id: &str,
engine: NavigationEngine,
) -> Result<(), String> {
let owner_access = self
- .browser_context_by_id(&browser_context_id)
+ .browser_context_by_id(browser_context_id)
.ok_or_else(|| {
format!(
- "cannot retain navigation engine for missing BrowserContext `{browser_context_id}`"
+ "cannot install navigation engine for missing BrowserContext `{browser_context_id}`"
)
})?
.renderer_runtime_owner_access();
@@ -2569,22 +2611,17 @@ impl CdpConnection {
}
self.apply_scheduler_senders_to_navigation_engine(&engine);
let replaced = self
- .retained_background_navigation_engines
- .insert((browser_context_id, target_id), engine);
- // The replaced wrapper may carry the last ambient (non-Document)
- // lease for a retired fetch runtime. Drop it before asking the exact
- // BrowserContext root to reap; doing this at the one retained-engine
- // transition avoids route-specific finish hooks.
+ .browser_context_by_id_mut(browser_context_id)
+ .and_then(|context| context.page_target_mut(target_id))
+ .ok_or_else(|| {
+ format!("cannot install navigation engine for missing Page target `{target_id}`")
+ })?
+ .replace_navigation_engine(engine);
drop(replaced);
owner_access.reap_retired_resource_runtimes();
Ok(())
}
- pub(crate) fn forget_retained_navigation_engine_for_target(&mut self, target_id: &str) {
- self.retained_background_navigation_engines
- .retain(|(_, retained_target_id), _| retained_target_id != target_id);
- }
-
pub(crate) fn adopt_loaded_navigation_engine_for_session_owner(
&mut self,
session_id: Option<&str>,
@@ -2595,70 +2632,41 @@ impl CdpConnection {
None => self.none_session_owner_route_override(),
};
let Some(route) = route else {
- self.replace_navigation_engine(engine);
+ self.replace_standalone_navigation_engine(engine);
return;
};
- match route {
- CdpSessionRoute::BackgroundTarget {
+ let page_owner = match route {
+ CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
- } => self
- .retain_background_navigation_engine(browser_context_id, target_id, engine)
- .expect("background route must retain its exact BrowserContext engine"),
- CdpSessionRoute::ActiveTarget {
+ }
+ | CdpSessionRoute::ActiveTarget {
browser_context_id,
target_id: Some(target_id),
- } if self
- .browser_context
- .as_ref()
- .is_none_or(|browser_context| browser_context.id != browser_context_id) =>
- {
- self.retain_background_navigation_engine(browser_context_id, target_id, engine)
- .expect(
- "inactive active-target route must retain its exact BrowserContext engine",
- )
}
+ | CdpSessionRoute::AuxiliaryTarget {
+ browser_context_id,
+ target_id,
+ } => Some((browser_context_id, target_id)),
CdpSessionRoute::ActiveTarget {
browser_context_id,
target_id: None,
- } if self
- .browser_context
- .as_ref()
- .is_none_or(|browser_context| browser_context.id != browser_context_id) =>
- {
- if let Some(target_id) = self
- .browser_context_by_id(&browser_context_id)
- .and_then(|browser_context| browser_context.active_target_id())
- .map(str::to_owned)
- {
- self.retain_background_navigation_engine(browser_context_id, target_id, engine)
- .expect("inactive active-target route must retain its exact BrowserContext engine");
- } else {
- self.replace_navigation_engine(engine);
- }
- }
- CdpSessionRoute::AuxiliaryTarget {
- browser_context_id,
- target_id,
- } if self
+ } => self
.browser_context_by_id(&browser_context_id)
- .and_then(|browser_context| browser_context.background_target(&target_id))
- .is_some()
- || self
- .browser_context
- .as_ref()
- .is_none_or(|browser_context| browser_context.id != browser_context_id) =>
- {
- self.retain_background_navigation_engine(browser_context_id, target_id, engine)
- .expect("auxiliary route must retain its exact BrowserContext engine")
- }
+ .and_then(|browser_context| browser_context.active_target_id())
+ .map(str::to_owned)
+ .map(|target_id| (browser_context_id, target_id)),
CdpSessionRoute::Browser
| CdpSessionRoute::TabTarget { .. }
- | CdpSessionRoute::ActiveTarget { .. }
- | CdpSessionRoute::AuxiliaryTarget { .. }
| CdpSessionRoute::SharedWorkerTarget { .. }
| CdpSessionRoute::DedicatedWorkerTarget { .. }
- | CdpSessionRoute::ServiceWorkerTarget { .. } => self.replace_navigation_engine(engine),
+ | CdpSessionRoute::ServiceWorkerTarget { .. } => None,
+ };
+ if let Some((browser_context_id, target_id)) = page_owner {
+ self.install_page_navigation_engine(&browser_context_id, &target_id, engine)
+ .expect("page route must install its exact PageTargetHost engine");
+ } else {
+ self.replace_standalone_navigation_engine(engine);
}
}
@@ -2667,23 +2675,8 @@ impl CdpConnection {
owner: &InitialDocumentPageOwner,
engine: NavigationEngine,
) {
- let owner_is_current_active_target =
- self.browser_context
- .as_ref()
- .is_some_and(|browser_context| {
- browser_context.id == owner.browser_context_id
- && browser_context.active_target_id() == Some(owner.target_id.as_str())
- });
- if owner_is_current_active_target {
- self.replace_navigation_engine(engine);
- return;
- }
- self.retain_background_navigation_engine(
- owner.browser_context_id.clone(),
- owner.target_id.clone(),
- engine,
- )
- .expect("page owner must retain its exact BrowserContext engine");
+ self.install_page_navigation_engine(&owner.browser_context_id, &owner.target_id, engine)
+ .expect("page owner must install its exact PageTargetHost engine");
}
pub(crate) fn enqueue_deferred_main_document_load_completion(
@@ -2999,8 +2992,7 @@ impl CdpConnection {
}
pub(crate) fn response_body_materialize_limit(&self) -> usize {
- self.engine
- .fetch_config()
+ self.fetch_config()
.http_max_response_size()
.unwrap_or(body_spool::DEFAULT_BODY_MATERIALIZE_LIMIT)
}
@@ -3015,14 +3007,19 @@ impl CdpConnection {
.iter()
.map(BrowserContext::moli_memory_diagnostics)
.collect::<Vec<_>>();
- let retained_engine_keys = self
- .retained_background_navigation_engines
- .keys()
- .map(|(browser_context_id, target_id)| {
- json!({
- "browserContextId": browser_context_id,
- "targetId": target_id,
- })
+ let page_engine_keys = self
+ .browser_contexts()
+ .flat_map(|browser_context| {
+ browser_context
+ .page_targets
+ .iter()
+ .filter(|host| host.navigation_engine().is_some())
+ .map(|host| {
+ json!({
+ "browserContextId": browser_context.id,
+ "targetId": host.target_id(),
+ })
+ })
})
.collect::<Vec<_>>();
let browser_context_count = self.browser_contexts().count();
@@ -3111,23 +3108,27 @@ impl CdpConnection {
shared_worker_pending_service_lane_event_count +=
shared_worker_diagnostics.pending_service_lane_event_count;
}
- let retained_background_navigation_engine_count =
- self.retained_background_navigation_engines.len();
- let active_engine = self.engine.ensure();
+ let page_navigation_engine_count = page_engine_keys.len();
+ let active_engine = self.active_navigation_engine();
let active_renderer_owner_id = active_engine.renderer_owner_id_for_diagnostics();
- let mut retained_background_navigation_engine_renderer_owner_ids = HashSet::new();
+ let mut page_navigation_engine_renderer_owner_ids = HashSet::new();
let mut estimated_renderer_owner_ids = HashSet::new();
estimated_renderer_owner_ids.insert(active_renderer_owner_id);
estimated_renderer_owner_ids.extend(document_renderer_owner_ids.iter().copied());
- for engine in self.retained_background_navigation_engines.values() {
+ for engine in self.browser_contexts().flat_map(|browser_context| {
+ browser_context
+ .page_targets
+ .iter()
+ .filter_map(PageTargetHost::navigation_engine)
+ }) {
let renderer_owner_id = engine.renderer_owner_id_for_diagnostics();
if renderer_owner_id != active_renderer_owner_id {
- retained_background_navigation_engine_renderer_owner_ids.insert(renderer_owner_id);
+ page_navigation_engine_renderer_owner_ids.insert(renderer_owner_id);
}
estimated_renderer_owner_ids.insert(renderer_owner_id);
}
- let retained_background_navigation_engine_renderer_owner_count =
- retained_background_navigation_engine_renderer_owner_ids.len();
+ let page_navigation_engine_renderer_owner_count =
+ page_navigation_engine_renderer_owner_ids.len();
let estimated_renderer_owner_count = estimated_renderer_owner_ids.len();
let document_isolate_model = active_engine.document_isolate_model_for_diagnostics();
let estimated_document_isolate_count =
@@ -3162,8 +3163,8 @@ impl CdpConnection {
"globalIoStreamCount": self.global_io_streams.len(),
"tracing": self.tracing_state.diagnostics(),
"permissionOverrideCount": self.permission_overrides.len(),
- "retainedBackgroundNavigationEngineCount": retained_background_navigation_engine_count,
- "retainedBackgroundNavigationEngineKeys": retained_engine_keys,
+ "pageNavigationEngineCount": page_navigation_engine_count,
+ "pageNavigationEngineKeys": page_engine_keys,
"autoAttach": self.auto_attach,
"targetDiscoveryEnabled": self.target_discovery_enabled,
"targetInfoChangeEventsEnabled": self.target_info_change_events_enabled,
@@ -3182,7 +3183,7 @@ impl CdpConnection {
"documentIsolateModel": document_isolate_model,
"workerIsolateModel": "per-worker-thread",
"activeNavigationEngineRendererOwnerCount": 1,
- "retainedBackgroundNavigationEngineRendererOwnerCount": retained_background_navigation_engine_renderer_owner_count,
+ "pageNavigationEngineRendererOwnerCount": page_navigation_engine_renderer_owner_count,
"estimatedRendererOwnerCount": estimated_renderer_owner_count,
"browserContextCount": browser_context_count,
"loadedDocumentPageCount": loaded_document_page_count,
@@ -3224,62 +3225,54 @@ impl CdpConnection {
})
}
- fn idle_navigation_engine_release_counts(&self) -> (usize, usize, usize) {
+ fn idle_navigation_engine_release_counts(&self) -> (usize, usize) {
let loaded_browser_context_count = self
.browser_contexts()
.filter(|browser_context| {
browser_context.has_loaded_page()
|| browser_context
- .background_targets
- .iter()
- .any(BackgroundTarget::has_loaded_page)
+ .background_targets()
+ .any(PageTargetHost::has_loaded_page)
})
.count();
let live_target_browser_context_count = self
.browser_contexts()
.filter(|browser_context| {
- browser_context.has_active_target()
- || !browser_context.background_targets.is_empty()
+ browser_context.has_active_target() || !browser_context.has_no_background_targets()
})
.count();
(
loaded_browser_context_count,
live_target_browser_context_count,
- self.retained_background_navigation_engines.len(),
)
}
pub(crate) fn release_idle_navigation_engine_memory_if_idle(
&mut self,
) -> IdleNavigationEngineReleaseResult {
- let (
- loaded_browser_context_count,
- live_target_browser_context_count,
- retained_background_navigation_engine_count,
- ) = self.idle_navigation_engine_release_counts();
- let eligible = loaded_browser_context_count == 0
- && live_target_browser_context_count == 0
- && retained_background_navigation_engine_count == 0;
+ let (loaded_browser_context_count, live_target_browser_context_count) =
+ self.idle_navigation_engine_release_counts();
+ let eligible = loaded_browser_context_count == 0 && live_target_browser_context_count == 0;
if !eligible {
return IdleNavigationEngineReleaseResult {
reset: false,
reason: "not-idle",
loaded_browser_context_count,
live_target_browser_context_count,
- retained_background_navigation_engine_count,
};
}
- let replacement = NavigationEngine::new_with_runtime_config(self.engine.runtime_config());
- self.replace_navigation_engine(replacement);
+ let replacement = NavigationEngine::new_with_runtime_config(
+ self.standalone_navigation_engine.runtime_config(),
+ );
+ self.replace_standalone_navigation_engine(replacement);
IdleNavigationEngineReleaseResult {
reset: true,
reason: "idle-engine-replaced",
loaded_browser_context_count,
live_target_browser_context_count,
- retained_background_navigation_engine_count,
}
}
@@ -3324,9 +3317,7 @@ impl CdpConnection {
}
fn apply_global_browser_context_state(&self, browser_context: &mut BrowserContext) {
- browser_context
- .network_policy
- .set_cache_disabled(self.global_cache_disabled);
+ browser_context.global_cache_disabled = self.global_cache_disabled;
browser_context.global_extra_headers = self.global_extra_headers.clone();
browser_context.global_network_conditions = self.global_network_conditions;
browser_context.global_geolocation_override = self.global_geolocation_override.clone();
@@ -3475,7 +3466,7 @@ impl CdpConnection {
.is_placeholder_target(target_id)
&& self.browser_contexts().all(|browser_context| {
!browser_context.has_active_target()
- && browser_context.background_targets.is_empty()
+ && browser_context.background_targets().next().is_none()
})
}
diff --git a/moli-protocol/src/conn/activity_source.rs b/moli-protocol/src/conn/activity_source.rs
index 92de9ecdc..f55087898 100644
--- a/moli-protocol/src/conn/activity_source.rs
+++ b/moli-protocol/src/conn/activity_source.rs
@@ -30,71 +30,6 @@ impl PendingChildFrameLifecycleWork {
}
}
-fn browser_context_by_id_mut_from_parts<'a>(
- browser_context: &'a mut Option<BrowserContext>,
- inactive_browser_contexts: &'a mut [BrowserContext],
- browser_context_id: &str,
-) -> Option<&'a mut BrowserContext> {
- if browser_context
- .as_ref()
- .is_some_and(|bc| bc.id == browser_context_id)
- {
- return browser_context.as_mut();
- }
- inactive_browser_contexts
- .iter_mut()
- .find(|bc| bc.id == browser_context_id)
-}
-
-fn runtime_slot_for_route_mut_from_parts<'a>(
- browser_context: &'a mut Option<BrowserContext>,
- inactive_browser_contexts: &'a mut [BrowserContext],
- route: &CdpSessionRoute,
-) -> Option<&'a mut TargetRuntimeSlot> {
- let context = match route {
- CdpSessionRoute::Browser => browser_context.as_mut()?,
- CdpSessionRoute::ActiveTarget {
- browser_context_id, ..
- }
- | CdpSessionRoute::AuxiliaryTarget {
- browser_context_id, ..
- }
- | CdpSessionRoute::BackgroundTarget {
- browser_context_id, ..
- } => browser_context_by_id_mut_from_parts(
- browser_context,
- inactive_browser_contexts,
- browser_context_id,
- )?,
- CdpSessionRoute::TabTarget { .. }
- | CdpSessionRoute::SharedWorkerTarget { .. }
- | CdpSessionRoute::DedicatedWorkerTarget { .. }
- | CdpSessionRoute::ServiceWorkerTarget { .. } => return None,
- };
- match route {
- CdpSessionRoute::AuxiliaryTarget { target_id, .. } => {
- if let Some(index) = context
- .background_targets
- .iter()
- .position(|target| target.is_target(target_id))
- {
- return Some(&mut context.background_targets[index].runtime_slot);
- }
- Some(&mut context.active_target.runtime_slot)
- }
- CdpSessionRoute::BackgroundTarget { target_id, .. } => {
- Some(&mut context.background_target_mut(target_id)?.runtime_slot)
- }
- CdpSessionRoute::Browser | CdpSessionRoute::ActiveTarget { .. } => {
- Some(&mut context.active_target.runtime_slot)
- }
- CdpSessionRoute::TabTarget { .. }
- | CdpSessionRoute::SharedWorkerTarget { .. }
- | CdpSessionRoute::DedicatedWorkerTarget { .. }
- | CdpSessionRoute::ServiceWorkerTarget { .. } => None,
- }
-}
-
impl CdpConnection {
fn activity_source_engine_and_runtime_slot_mut(
&mut self,
@@ -106,46 +41,6 @@ impl CdpConnection {
.none_session_owner_route_override()
.unwrap_or(CdpSessionRoute::Browser),
};
- let primary_engine = match &route {
- CdpSessionRoute::Browser => true,
- CdpSessionRoute::ActiveTarget {
- browser_context_id,
- target_id,
- } => self.browser_context.as_ref().is_some_and(|context| {
- context.id == *browser_context_id
- && target_id
- .as_deref()
- .is_none_or(|target_id| context.active_target_id() == Some(target_id))
- }),
- CdpSessionRoute::AuxiliaryTarget {
- browser_context_id,
- target_id,
- } => self.browser_context.as_ref().is_some_and(|context| {
- context.id == *browser_context_id
- && context.background_target(target_id).is_none()
- && context.active_target_id() == Some(target_id)
- }),
- CdpSessionRoute::BackgroundTarget { .. }
- | CdpSessionRoute::TabTarget { .. }
- | CdpSessionRoute::SharedWorkerTarget { .. }
- | CdpSessionRoute::DedicatedWorkerTarget { .. }
- | CdpSessionRoute::ServiceWorkerTarget { .. } => false,
- };
- if primary_engine {
- let CdpConnection {
- engine,
- browser_context,
- inactive_browser_contexts,
- ..
- } = self;
- let slot = runtime_slot_for_route_mut_from_parts(
- browser_context,
- inactive_browser_contexts,
- &route,
- )?;
- return Some((engine.ensure_mut(), slot));
- }
-
let (browser_context_id, target_id) = match &route {
CdpSessionRoute::ActiveTarget {
browser_context_id,
@@ -162,30 +57,23 @@ impl CdpConnection {
browser_context_id,
target_id,
}
- | CdpSessionRoute::BackgroundTarget {
+ | CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
} => (browser_context_id.clone(), target_id.clone()),
- CdpSessionRoute::Browser
- | CdpSessionRoute::TabTarget { .. }
+ CdpSessionRoute::Browser => {
+ let context = self.browser_context.as_ref()?;
+ (context.id.clone(), context.active_target_id()?.to_owned())
+ }
+ CdpSessionRoute::TabTarget { .. }
| CdpSessionRoute::SharedWorkerTarget { .. }
| CdpSessionRoute::DedicatedWorkerTarget { .. }
| CdpSessionRoute::ServiceWorkerTarget { .. } => return None,
};
- let CdpConnection {
- retained_background_navigation_engines,
- browser_context,
- inactive_browser_contexts,
- ..
- } = self;
- let engine =
- retained_background_navigation_engines.get_mut(&(browser_context_id, target_id))?;
- let slot = runtime_slot_for_route_mut_from_parts(
- browser_context,
- inactive_browser_contexts,
- &route,
- )?;
- Some((engine, slot))
+ self.ensure_page_navigation_engine_for_target(&browser_context_id, &target_id)?;
+ self.browser_context_by_id_mut(&browser_context_id)?
+ .page_target_mut(&target_id)?
+ .navigation_engine_and_runtime_slot_mut()
}
pub(crate) fn start_child_frame_lifecycle_work_for_session_owner(
diff --git a/moli-protocol/src/conn/browser_context/emulation_owner.rs b/moli-protocol/src/conn/browser_context/emulation_owner.rs
index 6dcfcd503..ff86fdc58 100644
--- a/moli-protocol/src/conn/browser_context/emulation_owner.rs
+++ b/moli-protocol/src/conn/browser_context/emulation_owner.rs
@@ -1,13 +1,17 @@
use super::target_session_owner::{TargetSessionOwnerMut, TargetSessionOwnerRef};
use super::*;
+use crate::conn::state::TargetSessionOverrideStack;
use crate::conn::{
EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedMediaOverrides,
EmulatedNetworkConditions,
};
pub(crate) struct TargetEmulationSessionStateMut<'a> {
+ session_id: Option<String>,
pub(crate) locale_override: &'a mut Option<String>,
pub(crate) timezone_override: &'a mut Option<String>,
+ locale_overrides: &'a mut TargetSessionOverrideStack<String>,
+ timezone_overrides: &'a mut TargetSessionOverrideStack<String>,
pub(crate) network_conditions: &'a mut Option<EmulatedNetworkConditions>,
pub(crate) geolocation_override: &'a mut Option<EmulatedGeolocationOverrideState>,
pub(crate) emulated_media: &'a mut EmulatedMediaOverrides,
@@ -19,6 +23,20 @@ pub(crate) struct TargetEmulationSessionStateMut<'a> {
pub(crate) script_execution_disabled: &'a mut bool,
}
+impl TargetEmulationSessionStateMut<'_> {
+ pub(crate) fn set_locale_override(&mut self, locale: Option<String>) {
+ self.locale_overrides
+ .replace(self.session_id.as_deref(), locale);
+ *self.locale_override = self.locale_overrides.effective().cloned();
+ }
+
+ pub(crate) fn set_timezone_override(&mut self, timezone: Option<String>) {
+ self.timezone_overrides
+ .replace(self.session_id.as_deref(), timezone);
+ *self.timezone_override = self.timezone_overrides.effective().cloned();
+ }
+}
+
impl TargetSessionOwnerMut<'_> {
fn mutate_emulation_session_state(
mut self,
@@ -26,28 +44,40 @@ impl TargetSessionOwnerMut<'_> {
) -> bool {
match &mut self {
Self::ActiveTarget {
- browser_context, ..
- } => f(Some(TargetEmulationSessionStateMut {
- locale_override: &mut browser_context.locale_override,
- timezone_override: &mut browser_context.timezone_override,
- network_conditions: &mut browser_context.network_conditions,
- geolocation_override: &mut browser_context.geolocation_override,
- emulated_media: &mut browser_context.emulated_media,
- emulated_device_metrics: &mut browser_context.emulated_device_metrics,
- cpu_throttling_rate: &mut browser_context.cpu_throttling_rate,
- touch_emulation_enabled: &mut browser_context.touch_emulation_enabled,
- emit_touch_events_for_mouse: &mut browser_context.emit_touch_events_for_mouse,
- focus_emulation_enabled: &mut browser_context.focus_emulation_enabled,
- script_execution_disabled: &mut browser_context.script_execution_disabled,
- })),
- Self::BackgroundTarget {
+ browser_context,
+ session_id,
+ ..
+ } => {
+ let state = browser_context.active_page_state_mut();
+ f(Some(TargetEmulationSessionStateMut {
+ session_id: session_id.clone(),
+ locale_override: &mut state.locale_override,
+ timezone_override: &mut state.timezone_override,
+ locale_overrides: &mut state.locale_overrides,
+ timezone_overrides: &mut state.timezone_overrides,
+ network_conditions: &mut state.network_conditions,
+ geolocation_override: &mut state.geolocation_override,
+ emulated_media: &mut state.emulated_media,
+ emulated_device_metrics: &mut state.emulated_device_metrics,
+ cpu_throttling_rate: &mut state.cpu_throttling_rate,
+ touch_emulation_enabled: &mut state.touch_emulation_enabled,
+ emit_touch_events_for_mouse: &mut state.emit_touch_events_for_mouse,
+ focus_emulation_enabled: &mut state.focus_emulation_enabled,
+ script_execution_disabled: &mut state.script_execution_disabled,
+ }))
+ }
+ Self::PageTargetHost {
browser_context,
target_id,
+ session_id,
..
} => browser_context.mutate_parked_page_session_state(target_id, |state| {
f(Some(TargetEmulationSessionStateMut {
+ session_id: session_id.clone(),
locale_override: &mut state.locale_override,
timezone_override: &mut state.timezone_override,
+ locale_overrides: &mut state.locale_overrides,
+ timezone_overrides: &mut state.timezone_overrides,
network_conditions: &mut state.network_conditions,
geolocation_override: &mut state.geolocation_override,
emulated_media: &mut state.emulated_media,
@@ -74,7 +104,7 @@ impl TargetSessionOwnerRef<'_> {
Self::ActiveTarget {
browser_context, ..
} => Some(browser_context.emit_touch_events_for_mouse),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
diff --git a/moli-protocol/src/conn/browser_context/fetch_owner.rs b/moli-protocol/src/conn/browser_context/fetch_owner.rs
index 32da82a23..3b9076fe2 100644
--- a/moli-protocol/src/conn/browser_context/fetch_owner.rs
+++ b/moli-protocol/src/conn/browser_context/fetch_owner.rs
@@ -1,8 +1,7 @@
use super::target_session_owner::TargetSessionOwnerMut;
use super::*;
use crate::conn::state::{
- TargetFetchConfig, TargetFetchOwner, TargetFetchState,
- TargetFetchSubresourceInterceptionSnapshot,
+ TargetFetchConfig, TargetFetchOwner, TargetFetchSubresourceInterceptionSnapshot,
};
use crate::conn::{
CapturedBody, CompletedFetchResponseBodyStreamReadDispatch, FetchInterceptionPattern,
@@ -23,142 +22,56 @@ pub(crate) type SessionOwnerPendingFetchState = (
Vec<(String, PendingSubresourceFetchResponseRequest)>,
);
-struct ParkedFetchStateGuard<'a> {
- browser_context: &'a mut BrowserContext,
- target_id: String,
- fetch_state: Option<TargetFetchState>,
-}
-
-impl<'a> ParkedFetchStateGuard<'a> {
- fn take(browser_context: &'a mut BrowserContext, target_id: &str) -> Self {
- Self {
- fetch_state: Some(browser_context.take_parked_fetch_state(target_id)),
- browser_context,
- target_id: target_id.to_owned(),
- }
- }
-
- fn fetch_state_mut(&mut self) -> &mut TargetFetchState {
- self.fetch_state
- .as_mut()
- .expect("parked fetch state should be restored exactly once")
- }
-
- fn fetch_state(&self) -> &TargetFetchState {
- self.fetch_state
- .as_ref()
- .expect("parked fetch state should be restored exactly once")
- }
-
- fn open_pending_fetch_response_body_stream(
- &mut self,
- request_id: &str,
- ) -> Result<Option<String>, String> {
- let Some(fetch_state) = self.fetch_state.as_mut() else {
- return Ok(None);
- };
- let owner_key = fetch_stream_owner_key(&self.browser_context.id, &self.target_id);
- let Some(target) = self.browser_context.background_target_mut(&self.target_id) else {
- return Ok(None);
- };
- let handle = target_scoped_stream_handle(
- &owner_key,
- target.runtime_slot.allocate_io_stream_handle(),
- );
- fetch_state.open_pending_fetch_response_body_stream(
- &mut target.runtime_slot,
- request_id,
- handle,
- )
- }
-
- fn start_pending_fetch_response_body_stream_read(
- &mut self,
- handle: &str,
- offset: Option<usize>,
- size: Option<usize>,
- ) -> PendingFetchResponseBodyStreamReadStart {
- let Some(fetch_state) = self.fetch_state.as_mut() else {
- return PendingFetchResponseBodyStreamReadStart::NotFound;
- };
- fetch_state.start_pending_fetch_response_body_stream_read(handle, offset, size)
- }
+struct SessionPendingFetchOwner<'a>(&'a mut TargetFetchOwner);
- fn finish_pending_fetch_response_body_stream_read(
- &mut self,
- completed: CompletedFetchResponseBodyStreamReadDispatch,
- ) -> PendingFetchResponseBodyStreamRead {
- let Some(fetch_state) = self.fetch_state.as_mut() else {
- return PendingFetchResponseBodyStreamRead::NotFound;
- };
- let Some(target) = self.browser_context.background_target_mut(&self.target_id) else {
- return PendingFetchResponseBodyStreamRead::NotFound;
- };
- fetch_state
- .finish_pending_fetch_response_body_stream_read(&mut target.runtime_slot, completed)
- }
+impl std::ops::Deref for SessionPendingFetchOwner<'_> {
+ type Target = TargetFetchOwner;
- fn close_pending_fetch_response_body_stream(&mut self, handle: &str) -> bool {
- let Some(fetch_state) = self.fetch_state.as_mut() else {
- return false;
- };
- if self
- .browser_context
- .background_target(&self.target_id)
- .is_none()
- {
- return false;
- }
- fetch_state.close_pending_fetch_response_body_stream(handle)
+ fn deref(&self) -> &Self::Target {
+ self.0
}
}
-impl Drop for ParkedFetchStateGuard<'_> {
- fn drop(&mut self) {
- if let Some(fetch_state) = self.fetch_state.take() {
- self.browser_context
- .replace_parked_fetch_state(self.target_id.clone(), fetch_state);
- }
+impl std::ops::DerefMut for SessionPendingFetchOwner<'_> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.0
}
}
-struct ParkedPendingFetchOwner<'a> {
- fetch_state: ParkedFetchStateGuard<'a>,
-}
-
-impl<'a> ParkedPendingFetchOwner<'a> {
- fn take(browser_context: &'a mut BrowserContext, target_id: &str) -> Self {
- Self {
- fetch_state: ParkedFetchStateGuard::take(browser_context, target_id),
- }
- }
-
- fn fetch_state_mut(&mut self) -> &mut TargetFetchState {
- self.fetch_state.fetch_state_mut()
- }
-
- fn fetch_state(&self) -> &TargetFetchState {
- self.fetch_state.fetch_state()
+impl SessionPendingFetchOwner<'_> {
+ fn in_flight_subresource_fetch_request_identity(
+ &self,
+ internal_id: u64,
+ ) -> Option<(String, crate::conn::TargetPageResidenceIdentity)> {
+ Some((
+ self.in_flight_subresource_fetch_request_id(internal_id)?
+ .to_owned(),
+ self.in_flight_subresource_fetch_request_page_owner(internal_id)?
+ .clone(),
+ ))
}
}
-struct ParkedFetchBodyStreamOwner<'a> {
- fetch_state: ParkedFetchStateGuard<'a>,
+struct SessionFetchBodyStreamOwner<'a> {
+ owner_key: String,
+ fetch_owner: &'a mut TargetFetchOwner,
+ runtime_slot: &'a mut TargetRuntimeSlot,
}
-impl<'a> ParkedFetchBodyStreamOwner<'a> {
- fn take(browser_context: &'a mut BrowserContext, target_id: &str) -> Self {
- Self {
- fetch_state: ParkedFetchStateGuard::take(browser_context, target_id),
- }
- }
-
+impl SessionFetchBodyStreamOwner<'_> {
fn open_pending_fetch_response_body_stream(
&mut self,
request_id: &str,
) -> Result<Option<String>, String> {
- self.fetch_state
- .open_pending_fetch_response_body_stream(request_id)
+ let handle = target_scoped_stream_handle(
+ &self.owner_key,
+ self.runtime_slot.allocate_io_stream_handle(),
+ );
+ self.fetch_owner.open_pending_fetch_response_body_stream(
+ self.runtime_slot,
+ request_id,
+ handle,
+ )
}
fn start_pending_fetch_response_body_stream_read(
@@ -167,7 +80,7 @@ impl<'a> ParkedFetchBodyStreamOwner<'a> {
offset: Option<usize>,
size: Option<usize>,
) -> PendingFetchResponseBodyStreamReadStart {
- self.fetch_state
+ self.fetch_owner
.start_pending_fetch_response_body_stream_read(handle, offset, size)
}
@@ -175,116 +88,38 @@ impl<'a> ParkedFetchBodyStreamOwner<'a> {
&mut self,
completed: CompletedFetchResponseBodyStreamReadDispatch,
) -> PendingFetchResponseBodyStreamRead {
- self.fetch_state
- .finish_pending_fetch_response_body_stream_read(completed)
+ self.fetch_owner
+ .finish_pending_fetch_response_body_stream_read(self.runtime_slot, completed)
}
fn close_pending_fetch_response_body_stream(&mut self, handle: &str) -> bool {
- self.fetch_state
+ self.fetch_owner
.close_pending_fetch_response_body_stream(handle)
}
}
-enum SessionPendingFetchOwner<'a> {
- Active(&'a mut TargetFetchOwner),
- Parked(Box<ParkedPendingFetchOwner<'a>>),
-}
-
-enum SessionFetchBodyStreamOwner<'a> {
- Active {
- owner_key: String,
- fetch_owner: &'a mut TargetFetchOwner,
- runtime_slot: &'a mut TargetRuntimeSlot,
- },
- Parked(Box<ParkedFetchBodyStreamOwner<'a>>),
-}
-
-impl SessionFetchBodyStreamOwner<'_> {
- fn open_pending_fetch_response_body_stream(
- &mut self,
- request_id: &str,
- ) -> Result<Option<String>, String> {
- match self {
- Self::Active {
- owner_key,
- fetch_owner,
- runtime_slot,
- } => {
- let handle = target_scoped_stream_handle(
- owner_key,
- runtime_slot.allocate_io_stream_handle(),
- );
- fetch_owner.open_pending_fetch_response_body_stream(
- runtime_slot,
- request_id,
- handle,
- )
- }
- Self::Parked(owner) => owner.open_pending_fetch_response_body_stream(request_id),
- }
- }
-
- fn start_pending_fetch_response_body_stream_read(
- &mut self,
- handle: &str,
- offset: Option<usize>,
- size: Option<usize>,
- ) -> PendingFetchResponseBodyStreamReadStart {
- match self {
- Self::Active { fetch_owner, .. } => {
- fetch_owner.start_pending_fetch_response_body_stream_read(handle, offset, size)
- }
- Self::Parked(owner) => {
- owner.start_pending_fetch_response_body_stream_read(handle, offset, size)
- }
- }
- }
-
- fn finish_pending_fetch_response_body_stream_read(
- &mut self,
- completed: CompletedFetchResponseBodyStreamReadDispatch,
- ) -> PendingFetchResponseBodyStreamRead {
- match self {
- Self::Active {
- fetch_owner,
- runtime_slot,
- ..
- } => {
- fetch_owner.finish_pending_fetch_response_body_stream_read(runtime_slot, completed)
- }
- Self::Parked(owner) => owner.finish_pending_fetch_response_body_stream_read(completed),
- }
- }
-
- fn close_pending_fetch_response_body_stream(&mut self, handle: &str) -> bool {
- match self {
- Self::Active { fetch_owner, .. } => {
- fetch_owner.close_pending_fetch_response_body_stream(handle)
- }
- Self::Parked(owner) => owner.close_pending_fetch_response_body_stream(handle),
- }
- }
-}
-
fn fetch_body_stream_owner_for_target_mut<'a>(
browser_context: &'a mut BrowserContext,
target_id: &str,
) -> Option<SessionFetchBodyStreamOwner<'a>> {
- let is_active_target = browser_context.active_target_id() == Some(target_id)
- || (target_id == "active" && browser_context.active_target_id().is_none());
+ let is_active_target = browser_context.active_target_id() == Some(target_id);
if is_active_target {
let owner_key = fetch_stream_owner_key(&browser_context.id, target_id);
let active_target = &mut browser_context.active_target;
- return Some(SessionFetchBodyStreamOwner::Active {
+ return Some(SessionFetchBodyStreamOwner {
owner_key,
fetch_owner: &mut active_target.fetch_owner,
runtime_slot: &mut active_target.runtime_slot,
});
}
- browser_context.background_target(target_id)?;
- Some(SessionFetchBodyStreamOwner::Parked(Box::new(
- ParkedFetchBodyStreamOwner::take(browser_context, target_id),
- )))
+ let owner_key = fetch_stream_owner_key(&browser_context.id, target_id);
+ let target = browser_context.background_target_mut(target_id)?;
+ let active_target = &mut target.state_mut().active_target;
+ Some(SessionFetchBodyStreamOwner {
+ owner_key,
+ fetch_owner: &mut active_target.fetch_owner,
+ runtime_slot: &mut active_target.runtime_slot,
+ })
}
fn runtime_slot_for_target_scoped_stream_mut<'a>(
@@ -301,408 +136,6 @@ fn runtime_slot_for_target_scoped_stream_mut<'a>(
.map(|target| &mut target.runtime_slot)
}
-impl SessionPendingFetchOwner<'_> {
- fn register_pending_fetch_navigation_request(&mut self, pending: PendingFetchNavigation) {
- match self {
- Self::Active(owner) => owner.register_pending_fetch_navigation_request(pending),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .register_pending_fetch_navigation_request(pending),
- }
- }
-
- fn consume_pending_request_action(&mut self, request_id: &str) -> Result<(), &'static str> {
- match self {
- Self::Active(owner) => owner.consume_pending_request_action(request_id),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .consume_pending_request_action(request_id),
- }
- }
-
- fn take_pending_fetch_navigation_for_action_session(
- &mut self,
- request_id: &str,
- action_session_id: Option<&str>,
- ) -> Option<PendingFetchNavigation> {
- match self {
- Self::Active(owner) => owner
- .take_pending_fetch_navigation_for_action_session(request_id, action_session_id),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_fetch_navigation_for_action_session(request_id, action_session_id),
- }
- }
-
- fn take_pending_fetch_auth_navigation_for_action_session(
- &mut self,
- request_id: &str,
- action_session_id: Option<&str>,
- ) -> Option<PendingFetchAuthNavigation> {
- match self {
- Self::Active(owner) => owner.take_pending_fetch_auth_navigation_for_action_session(
- request_id,
- action_session_id,
- ),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_fetch_auth_navigation_for_action_session(
- request_id,
- action_session_id,
- ),
- }
- }
-
- fn register_pending_fetch_auth_navigation(
- &mut self,
- request_id: String,
- pending: PendingFetchAuthNavigation,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_pending_fetch_auth_navigation(request_id, pending);
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_pending_fetch_auth_navigation(request_id, pending);
- }
- }
- }
-
- fn register_pending_fetch_response_navigation(
- &mut self,
- request_id: String,
- document_navigation_token: Option<crate::conn::DocumentNavigationToken>,
- navigation: crate::conn::NavigationDispatchState,
- body: crate::conn::DocumentBodySource,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_pending_fetch_response_navigation(
- request_id,
- document_navigation_token,
- navigation,
- body,
- );
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_pending_fetch_response_navigation(
- request_id,
- document_navigation_token,
- navigation,
- body,
- );
- }
- }
- }
-
- fn take_pending_fetch_response_transfer_for_terminal_action(
- &mut self,
- request_id: &str,
- ) -> Option<PausedDocumentTransfer> {
- match self {
- Self::Active(owner) => {
- owner.take_pending_fetch_response_transfer_for_terminal_action(request_id)
- }
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_fetch_response_transfer_for_terminal_action(request_id),
- }
- }
-
- fn take_pending_fetch_response_transfer(
- &mut self,
- request_id: &str,
- ) -> Option<PausedDocumentTransfer> {
- match self {
- Self::Active(owner) => owner.take_pending_fetch_response_transfer(request_id),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_fetch_response_transfer(request_id),
- }
- }
-
- fn register_pending_fetch_response_transfer(
- &mut self,
- request_id: String,
- transfer: PausedDocumentTransfer,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_pending_fetch_response_transfer(request_id, transfer);
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_pending_fetch_response_transfer(request_id, transfer);
- }
- }
- }
-
- fn pending_subresource_fetch_response_request(
- &self,
- request_id: &str,
- session_id: Option<&str>,
- ) -> Option<PendingSubresourceFetchResponseRequest> {
- match self {
- Self::Active(owner) => owner
- .pending_subresource_fetch_response_request(request_id, session_id)
- .cloned(),
- Self::Parked(owner) => owner
- .fetch_state()
- .pending_subresource_fetch_response_request(request_id, session_id)
- .cloned(),
- }
- }
-
- fn mark_pending_subresource_fetch_response_body_taken_as_stream(
- &mut self,
- request_id: &str,
- session_id: Option<&str>,
- ) -> bool {
- match self {
- Self::Active(owner) => owner
- .mark_pending_subresource_fetch_response_body_taken_as_stream(
- request_id, session_id,
- ),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .mark_pending_subresource_fetch_response_body_taken_as_stream(
- request_id, session_id,
- ),
- }
- }
-
- fn take_pending_subresource_fetch_request(
- &mut self,
- request_id: &str,
- session_id: Option<&str>,
- ) -> Option<PendingSubresourceFetchRequest> {
- match self {
- Self::Active(owner) => {
- owner.take_pending_subresource_fetch_request(request_id, session_id)
- }
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_subresource_fetch_request(request_id, session_id),
- }
- }
-
- fn take_pending_subresource_fetch_auth_request(
- &mut self,
- request_id: &str,
- session_id: Option<&str>,
- ) -> Option<PendingSubresourceFetchAuthRequest> {
- match self {
- Self::Active(owner) => {
- owner.take_pending_subresource_fetch_auth_request(request_id, session_id)
- }
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_subresource_fetch_auth_request(request_id, session_id),
- }
- }
-
- fn take_pending_subresource_fetch_response_request(
- &mut self,
- request_id: &str,
- session_id: Option<&str>,
- ) -> Option<PendingSubresourceFetchResponseRequest> {
- match self {
- Self::Active(owner) => {
- owner.take_pending_subresource_fetch_response_request(request_id, session_id)
- }
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_pending_subresource_fetch_response_request(request_id, session_id),
- }
- }
-
- fn take_in_flight_subresource_fetch_request(
- &mut self,
- internal_id: u64,
- ) -> Option<InFlightSubresourceFetchRequest> {
- match self {
- Self::Active(owner) => owner.take_in_flight_subresource_fetch_request(internal_id),
- Self::Parked(owner) => owner
- .fetch_state_mut()
- .take_in_flight_subresource_fetch_request(internal_id),
- }
- }
-
- fn claim_subresource_continue_request(
- &mut self,
- expected_page_owner: &crate::conn::TargetPageResidenceIdentity,
- internal_id: u64,
- session_id: Option<&str>,
- allow_pending_completion: bool,
- ) -> Option<crate::conn::ClaimedSubresourceContinueRequest> {
- match self {
- Self::Active(owner) => owner.claim_subresource_continue_request(
- expected_page_owner,
- internal_id,
- session_id,
- allow_pending_completion,
- ),
- Self::Parked(owner) => owner.fetch_state_mut().claim_subresource_continue_request(
- expected_page_owner,
- internal_id,
- session_id,
- allow_pending_completion,
- ),
- }
- }
-
- fn in_flight_subresource_fetch_request_identity(
- &mut self,
- internal_id: u64,
- ) -> Option<(String, crate::conn::TargetPageResidenceIdentity)> {
- match self {
- Self::Active(owner) => Some((
- owner
- .in_flight_subresource_fetch_request_id(internal_id)?
- .to_owned(),
- owner
- .in_flight_subresource_fetch_request_page_owner(internal_id)?
- .clone(),
- )),
- Self::Parked(owner) => Some((
- owner
- .fetch_state()
- .in_flight_subresource_fetch_request_id(internal_id)?
- .to_owned(),
- owner
- .fetch_state()
- .in_flight_subresource_fetch_request_page_owner(internal_id)?
- .clone(),
- )),
- }
- }
-
- fn register_pending_subresource_fetch_request(
- &mut self,
- request_id: String,
- pending: PendingSubresourceFetchRequest,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_pending_subresource_fetch_request(request_id, pending);
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_pending_subresource_fetch_request(request_id, pending);
- }
- }
- }
-
- fn register_in_flight_subresource_fetch_request(
- &mut self,
- request_id: Option<String>,
- pending: PendingSubresourceFetchRequest,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_in_flight_subresource_fetch_request(request_id, pending);
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_in_flight_subresource_fetch_request(request_id, pending);
- }
- }
- }
-
- fn register_in_flight_response_stage_subresource_fetch_request(
- &mut self,
- request_id: Option<String>,
- pending: PendingSubresourceFetchRequest,
- response_stage_blocked_intercepts: Vec<DevToolsNetworkInterceptId>,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_in_flight_response_stage_subresource_fetch_request(
- request_id,
- pending,
- response_stage_blocked_intercepts,
- );
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_in_flight_response_stage_subresource_fetch_request(
- request_id,
- pending,
- response_stage_blocked_intercepts,
- );
- }
- }
- }
-
- fn register_in_flight_subresource_fetch_request_with_response_match_policy(
- &mut self,
- request_id: Option<String>,
- pending: PendingSubresourceFetchRequest,
- response_stage_url_match_policy: crate::conn::ResponseStageUrlMatchPolicy,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_in_flight_subresource_fetch_request_with_response_match_policy(
- request_id,
- pending,
- response_stage_url_match_policy,
- );
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_in_flight_subresource_fetch_request_with_response_match_policy(
- request_id,
- pending,
- response_stage_url_match_policy,
- );
- }
- }
- }
-
- fn register_pending_subresource_fetch_auth_request(
- &mut self,
- request_id: String,
- pending: PendingSubresourceFetchAuthRequest,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_pending_subresource_fetch_auth_request(request_id, pending);
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_pending_subresource_fetch_auth_request(request_id, pending);
- }
- }
- }
-
- fn register_pending_subresource_fetch_response_request(
- &mut self,
- request_id: String,
- pending: PendingSubresourceFetchResponseRequest,
- ) {
- match self {
- Self::Active(owner) => {
- owner.register_pending_subresource_fetch_response_request(request_id, pending);
- }
- Self::Parked(owner) => {
- owner
- .fetch_state_mut()
- .register_pending_subresource_fetch_response_request(request_id, pending);
- }
- }
- }
-}
-
impl TargetSessionOwnerMut<'_> {
fn open_scoped_io_stream_body_source(&mut self, body: CapturedBody) -> Result<String, String> {
match self {
@@ -721,7 +154,7 @@ impl TargetSessionOwnerMut<'_> {
runtime_slot.insert_io_stream_body_source(handle.clone(), body, 0);
Ok(handle)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -815,19 +248,12 @@ fn remove_network_intercept_from_browser_context(
}
let target_ids = browser_context
- .background_targets
- .iter()
+ .background_targets()
.map(|target| target.target_id().to_owned())
.collect::<Vec<_>>();
for target_id in target_ids {
- if browser_context
- .parked_page_session_state(&target_id)
- .is_none()
- {
- continue;
- }
let removed = browser_context.mutate_parked_page_session_state(&target_id, |state| {
- state.fetch_config.remove_network_intercept(intercept_id)
+ state.fetch_owner.remove_network_intercept(intercept_id)
});
if removed {
return Ok(Some(None));
@@ -918,24 +344,20 @@ impl CdpConnection {
} => self
.browser_context_by_id(&browser_context_id)
.map(|browser_context| browser_context.active_target.fetch_owner.config_snapshot()),
- CdpSessionRoute::BackgroundTarget {
+ CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
} => self
.browser_context_by_id(&browser_context_id)?
- .parked_page_session_state(&target_id)
- .map(|state| state.fetch_config.clone()),
+ .background_target(&target_id)
+ .map(|target| target.fetch_owner.config_snapshot()),
CdpSessionRoute::AuxiliaryTarget {
browser_context_id,
target_id,
} => self
.browser_context_by_id(&browser_context_id)?
.background_target(&target_id)
- .and_then(|_| {
- self.browser_context_by_id(&browser_context_id)?
- .parked_page_session_state(&target_id)
- .map(|state| state.fetch_config.clone())
- }),
+ .map(|target| target.fetch_owner.config_snapshot()),
CdpSessionRoute::Browser
| CdpSessionRoute::TabTarget { .. }
| CdpSessionRoute::SharedWorkerTarget { .. }
@@ -1771,25 +1193,21 @@ fn pending_fetch_request_route(
});
}
- browser_context
- .background_targets
- .iter()
- .find_map(|target| {
- browser_context
- .target_parking
- .fetch_state(target.target_id())
- .is_some_and(|state| state.contains_pending_request(request_id))
- .then(|| CdpSessionRoute::BackgroundTarget {
- browser_context_id: browser_context.id.clone(),
- target_id: target.target_id().to_owned(),
- })
- })
+ browser_context.background_targets().find_map(|target| {
+ target
+ .fetch_owner
+ .contains_pending_request(request_id)
+ .then(|| CdpSessionRoute::PageTargetHost {
+ browser_context_id: browser_context.id.clone(),
+ target_id: target.target_id().to_owned(),
+ })
+ })
}
impl TargetSessionOwnerMut<'_> {
fn session_id(&self) -> Option<&str> {
match self {
- Self::ActiveTarget { session_id, .. } | Self::BackgroundTarget { session_id, .. } => {
+ Self::ActiveTarget { session_id, .. } | Self::PageTargetHost { session_id, .. } => {
session_id.as_deref()
}
Self::NoLoadedBrowserContext => None,
@@ -1800,16 +1218,18 @@ impl TargetSessionOwnerMut<'_> {
match self {
Self::ActiveTarget {
browser_context, ..
- } => Some(SessionPendingFetchOwner::Active(
+ } => Some(SessionPendingFetchOwner(
&mut browser_context.active_target.fetch_owner,
)),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
- } => Some(SessionPendingFetchOwner::Parked(Box::new(
- ParkedPendingFetchOwner::take(browser_context, target_id),
- ))),
+ } => Some(SessionPendingFetchOwner(
+ &mut browser_context
+ .background_target_mut(target_id)?
+ .fetch_owner,
+ )),
Self::NoLoadedBrowserContext => None,
}
}
@@ -1824,7 +1244,7 @@ impl TargetSessionOwnerMut<'_> {
.unwrap_or_else(|| "active".to_owned());
fetch_body_stream_owner_for_target_mut(browser_context, &target_id)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1936,6 +1356,7 @@ impl TargetSessionOwnerMut<'_> {
) -> Option<PendingSubresourceFetchResponseRequest> {
self.pending_fetch_owner_mut()?
.pending_subresource_fetch_response_request(request_id, session_id)
+ .cloned()
}
fn mark_pending_subresource_fetch_response_body_taken_as_stream(
diff --git a/moli-protocol/src/conn/browser_context/lifecycle.rs b/moli-protocol/src/conn/browser_context/lifecycle.rs
index cbb4f760f..451270d61 100644
--- a/moli-protocol/src/conn/browser_context/lifecycle.rs
+++ b/moli-protocol/src/conn/browser_context/lifecycle.rs
@@ -27,8 +27,7 @@ impl CdpConnection {
self.activate_matching_browser_context(|bc| {
bc.is_active_target(target_id)
|| bc
- .background_targets
- .iter()
+ .background_targets()
.any(|target| target.is_target(target_id))
|| bc.has_shared_worker_target(target_id)
|| bc.has_dedicated_worker_target(target_id)
@@ -40,7 +39,7 @@ impl CdpConnection {
self.activate_browser_context_for_target(target_id)
}
- pub fn insert_browser_context(&mut self, browser_context: BrowserContext) {
+ pub fn insert_browser_context(&mut self, mut browser_context: BrowserContext) {
browser_context
.renderer_runtime()
.set_service_worker_pause_on_start_for_devtools(
@@ -51,15 +50,11 @@ impl CdpConnection {
.set_dedicated_worker_pause_on_start_for_devtools(
self.dedicated_worker_pause_on_start_for_devtools(),
);
+ browser_context.bind_page_navigation_engines(
+ self.standalone_navigation_engine.runtime_config(),
+ self.scheduler_hooks.renderer_publication_sender(),
+ );
if self.browser_context.is_none() {
- let renderer_runtime = browser_context.renderer_runtime_owner_access();
- let next_engine = moli_core::runtime::NavigationEngine::
- new_with_runtime_config_and_browser_context_access(
- self.engine.runtime_config(),
- renderer_runtime,
- )
- .expect("newly inserted BrowserContext owner must be live");
- self.replace_navigation_engine(next_engine);
self.browser_context = Some(browser_context);
self.apply_active_engine_fetch_overrides();
} else {
@@ -80,16 +75,7 @@ impl CdpConnection {
let removed = self.browser_context.take();
if self.browser_context.is_none() && !self.inactive_browser_contexts.is_empty() {
self.promote_inactive_browser_context_index_to_active(0);
- } else if self.browser_context.is_none() {
- // The active engine only carries weak access to the removed
- // context root. Move to a standalone root before returning
- // that BrowserContext to a caller that may drop it at once.
- let next_engine = moli_core::runtime::NavigationEngine::new_with_runtime_config(
- self.engine.runtime_config(),
- );
- self.replace_navigation_engine(next_engine);
}
- self.forget_retained_navigation_engines_for_browser_context(browser_context_id);
self.invalidate_resource_runtime_async().await;
self.restore_preferred_browser_context_async(
restore_browser_context_id,
@@ -106,7 +92,6 @@ impl CdpConnection {
.position(|bc| bc.id == browser_context_id)
{
let removed = self.inactive_browser_contexts.swap_remove(index);
- self.forget_retained_navigation_engines_for_browser_context(browser_context_id);
self.restore_preferred_browser_context_async(
restore_browser_context_id,
browser_context_id,
@@ -118,45 +103,12 @@ impl CdpConnection {
}
}
- fn forget_retained_navigation_engines_for_browser_context(&mut self, browser_context_id: &str) {
- self.retained_background_navigation_engines
- .retain(|(retained_context_id, _), _| retained_context_id != browser_context_id);
- }
-
pub(crate) async fn refresh_active_browser_context_loader_async(&mut self) {
self.apply_active_engine_fetch_overrides();
self.invalidate_resource_runtime_async().await;
}
- fn navigation_engine_for_inactive_browser_context_index(
- &mut self,
- index: usize,
- ) -> moli_core::runtime::NavigationEngine {
- let next_browser_context_id = self.inactive_browser_contexts[index].id.clone();
- let next_renderer_runtime =
- self.inactive_browser_contexts[index].renderer_runtime_owner_access();
- let navigation_runtime_config = self.engine.runtime_config();
- let next_active_target_id = self.inactive_browser_contexts[index]
- .active_target_id()
- .map(str::to_owned);
- next_active_target_id
- .as_ref()
- .and_then(|target_id| {
- self.retained_background_navigation_engines
- .remove(&(next_browser_context_id.clone(), target_id.clone()))
- })
- .unwrap_or_else(|| {
- moli_core::runtime::NavigationEngine::new_with_runtime_config_and_browser_context_access(
- navigation_runtime_config,
- next_renderer_runtime,
- )
- .expect("inactive BrowserContext owner must be live")
- })
- }
-
fn promote_inactive_browser_context_index_to_active(&mut self, index: usize) {
- let next_engine = self.navigation_engine_for_inactive_browser_context_index(index);
- self.replace_navigation_engine(next_engine);
self.browser_context = Some(self.inactive_browser_contexts.swap_remove(index));
}
@@ -176,24 +128,6 @@ impl CdpConnection {
let Some(index) = self.inactive_browser_contexts.iter().position(matches) else {
return false;
};
- let next_engine = self.navigation_engine_for_inactive_browser_context_index(index);
- let current_active_engine_key = self.browser_context.as_ref().and_then(|bc| {
- let active_target_id = bc.active_target_id()?;
- bc.has_loaded_page()
- .then(|| (bc.id.clone(), active_target_id.to_owned()))
- });
- if let Some((browser_context_id, target_id)) = current_active_engine_key {
- self.apply_scheduler_senders_to_navigation_engine(&next_engine);
- let active_engine = self
- .engine
- .replace(next_engine)
- .expect("active browser context must have a navigation engine");
- self.retain_background_navigation_engine(browser_context_id, target_id, active_engine)
- .expect("inactive BrowserContext must retain its exact active-target engine");
- } else {
- self.replace_navigation_engine(next_engine);
- }
-
let matched = self.inactive_browser_contexts.swap_remove(index);
if let Some(active) = self.browser_context.replace(matched) {
self.inactive_browser_contexts.push(active);
diff --git a/moli-protocol/src/conn/browser_context/lookup.rs b/moli-protocol/src/conn/browser_context/lookup.rs
index 95f924589..a114961ce 100644
--- a/moli-protocol/src/conn/browser_context/lookup.rs
+++ b/moli-protocol/src/conn/browser_context/lookup.rs
@@ -56,7 +56,7 @@ impl CdpConnection {
| CdpSessionRoute::AuxiliaryTarget {
browser_context_id, ..
}
- | CdpSessionRoute::BackgroundTarget {
+ | CdpSessionRoute::PageTargetHost {
browser_context_id, ..
}
| CdpSessionRoute::SharedWorkerTarget {
diff --git a/moli-protocol/src/conn/browser_context/network_owner.rs b/moli-protocol/src/conn/browser_context/network_owner.rs
index 480b4d9d7..f6718a7ea 100644
--- a/moli-protocol/src/conn/browser_context/network_owner.rs
+++ b/moli-protocol/src/conn/browser_context/network_owner.rs
@@ -35,8 +35,12 @@ impl TargetSessionStateMut<'_> {
mut self,
extra_headers: Vec<(String, String)>,
) -> Option<Vec<(String, String)>> {
+ let session_id = match &self {
+ Self::Active { session_id, .. } | Self::Parked { session_id, .. } => session_id.clone(),
+ Self::NoLoaded => None,
+ };
let network_policy = self.network_policy_mut()?;
- Some(network_policy.replace_extra_headers(extra_headers))
+ Some(network_policy.replace_extra_headers_for_session(session_id.as_deref(), extra_headers))
}
#[cfg(test)]
@@ -57,12 +61,13 @@ impl TargetSessionStateMut<'_> {
browser_identity: Option<moli_browser_profile::BrowserIdentityProfile>,
) -> bool {
let should_refresh_active_engine = matches!(self, Self::Active { .. });
+ let session_id = match &self {
+ Self::Active { session_id, .. } | Self::Parked { session_id, .. } => session_id.clone(),
+ Self::NoLoaded => None,
+ };
if let Some(network_policy) = self.network_policy_mut() {
- if let Some(browser_identity) = browser_identity {
- network_policy.set_browser_identity_override(browser_identity);
- } else {
- network_policy.clear_browser_identity_override();
- }
+ network_policy
+ .set_browser_identity_override_for_session(session_id.as_deref(), browser_identity);
}
should_refresh_active_engine
}
@@ -118,7 +123,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context,
is_auxiliary_target_session,
},
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
is_auxiliary_target_session,
@@ -166,8 +171,8 @@ impl TargetNetworkListenerOwnerMut<'_> {
});
}
browser_context
- .parked_page_session_state(target_id)
- .is_some_and(|state| state.network_enabled)
+ .background_target(target_id)
+ .is_some_and(|target| target.runtime_slot.primary_network_events_enabled())
}
Self::NoLoadedBrowserContext => false,
}
@@ -188,9 +193,6 @@ impl TargetNetworkListenerOwnerMut<'_> {
target_id,
..
} => {
- browser_context.mutate_parked_page_session_state(target_id, |state| {
- state.network_enabled = enabled;
- });
if let Some(target) = browser_context.background_target_mut(target_id) {
target
.runtime_slot
@@ -471,7 +473,7 @@ impl TargetSessionOwnerMut<'_> {
is_current_active_browser_context,
..
} => Some(is_current_active_browser_context),
- Self::BackgroundTarget { .. } => Some(false),
+ Self::PageTargetHost { .. } => Some(false),
Self::NoLoadedBrowserContext => None,
}
}
@@ -485,7 +487,7 @@ impl TargetSessionOwnerMut<'_> {
is_current_active_browser_context,
..
} => Some(is_current_active_browser_context),
- Self::BackgroundTarget { .. } => Some(false),
+ Self::PageTargetHost { .. } => Some(false),
Self::NoLoadedBrowserContext => None,
}
}
@@ -539,18 +541,15 @@ impl CdpConnection {
body.is_visible_to_session(session_id) || body.is_visible_to_session(None)
})
.or_else(|| {
- browser_context
- .background_targets
- .iter()
- .find_map(|target| {
- target
- .runtime_slot()
- .captured_response_body(request_id)
- .filter(|body| {
- body.is_visible_to_session(session_id)
- || body.is_visible_to_session(None)
- })
- })
+ browser_context.background_targets().find_map(|target| {
+ target
+ .runtime_slot()
+ .captured_response_body(request_id)
+ .filter(|body| {
+ body.is_visible_to_session(session_id)
+ || body.is_visible_to_session(None)
+ })
+ })
})
})
}
@@ -569,18 +568,15 @@ impl CdpConnection {
body.is_visible_to_session(session_id) || body.is_visible_to_session(None)
})
.or_else(|| {
- browser_context
- .background_targets
- .iter()
- .find_map(|target| {
- target
- .runtime_slot()
- .captured_request_body(request_id)
- .filter(|body| {
- body.is_visible_to_session(session_id)
- || body.is_visible_to_session(None)
- })
- })
+ browser_context.background_targets().find_map(|target| {
+ target
+ .runtime_slot()
+ .captured_request_body(request_id)
+ .filter(|body| {
+ body.is_visible_to_session(session_id)
+ || body.is_visible_to_session(None)
+ })
+ })
})
})
}
@@ -784,6 +780,12 @@ impl CdpConnection {
pub(crate) fn set_global_cache_disabled(&mut self, cache_disabled: bool) {
self.global_cache_disabled = cache_disabled;
+ if let Some(browser_context) = self.browser_context.as_mut() {
+ browser_context.global_cache_disabled = cache_disabled;
+ }
+ for browser_context in &mut self.inactive_browser_contexts {
+ browser_context.global_cache_disabled = cache_disabled;
+ }
}
pub(crate) fn set_global_extra_headers(&mut self, extra_headers: Vec<(String, String)>) {
@@ -946,7 +948,7 @@ impl CdpConnection {
)
{
if let Some(browser_context) = self.browser_context.as_mut() {
- browser_context.tls_verify_host_override = Some(enabled);
+ browser_context.default_tls_verify_host_override = Some(enabled);
} else {
self.base_tls_verify_host = enabled;
}
@@ -994,15 +996,11 @@ fn initialize_parked_network_observation_cursor(
target_id: &str,
session_id: Option<&str>,
) {
- if let Some(target) = browser_context.background_target_mut(target_id) {
- target
- .runtime_slot
- .initialize_network_session_observation_cursor_at_output_tail(session_id);
- return;
- }
- browser_context.mutate_parked_network_artifacts(target_id, |artifacts| {
- artifacts.set_session_observation_cursor_at_counts(session_id, 0, 0);
- });
+ browser_context
+ .background_target_mut(target_id)
+ .expect("background target route must retain its target")
+ .runtime_slot
+ .initialize_network_session_observation_cursor_at_output_tail(session_id);
}
fn remove_parked_network_observation_cursor(
@@ -1010,15 +1008,11 @@ fn remove_parked_network_observation_cursor(
target_id: &str,
session_id: Option<&str>,
) {
- if let Some(target) = browser_context.background_target_mut(target_id) {
- target
- .runtime_slot
- .remove_network_session_observation_cursor(session_id);
- return;
- }
- browser_context.mutate_parked_network_artifacts(target_id, |artifacts| {
- artifacts.remove_session_observation_cursor(session_id);
- });
+ browser_context
+ .background_target_mut(target_id)
+ .expect("background target route must retain its target")
+ .runtime_slot
+ .remove_network_session_observation_cursor(session_id);
}
fn remove_parked_captured_response_body_visibility(
@@ -1026,15 +1020,11 @@ fn remove_parked_captured_response_body_visibility(
target_id: &str,
session_id: Option<&str>,
) {
- if let Some(target) = browser_context.background_target_mut(target_id) {
- target
- .runtime_slot
- .remove_captured_response_body_visibility_for_session(session_id);
- return;
- }
- browser_context.mutate_parked_network_artifacts(target_id, |artifacts| {
- artifacts.remove_captured_response_body_visibility_for_session(session_id);
- });
+ browser_context
+ .background_target_mut(target_id)
+ .expect("background target route must retain its target")
+ .runtime_slot
+ .remove_captured_response_body_visibility_for_session(session_id);
}
fn clear_parked_network_observation_artifacts_if_unobserved(
@@ -1047,36 +1037,30 @@ fn clear_parked_network_observation_artifacts_if_unobserved(
}
target.runtime_slot.clear_captured_response_bodies();
target.runtime_slot.clear_websocket_request_ids();
- return;
- }
-
- let has_primary_listener = browser_context
- .parked_page_session_state(target_id)
- .is_some_and(|state| state.network_enabled);
- if has_primary_listener {
- return;
}
- browser_context.mutate_parked_network_artifacts(target_id, |artifacts| {
- artifacts.clear_captured_response_bodies_and_websocket_request_ids();
- });
}
#[cfg(test)]
mod tests {
use super::*;
- use crate::conn::{BackgroundTarget, ParkedPageSessionState};
+ use crate::conn::{PageTargetHost, TargetPageState};
fn active_session_state_mut(browser_context: &mut BrowserContext) -> TargetSessionStateMut<'_> {
+ let state = browser_context.active_page_state_mut();
TargetSessionStateMut::Active {
- devtools_session_state: &mut browser_context.devtools_session_state,
- network_policy: &mut browser_context.network_policy,
- tls_verify_host_override: &mut browser_context.tls_verify_host_override,
+ session_id: None,
+ devtools_session_state: &mut state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary],
+ network_policy: &mut state.network_policy,
+ tls_verify_host_override: &mut state.tls_verify_host_override,
}
}
- fn parked_session_state_mut(state: &mut ParkedPageSessionState) -> TargetSessionStateMut<'_> {
+ fn parked_session_state_mut(state: &mut TargetPageState) -> TargetSessionStateMut<'_> {
TargetSessionStateMut::Parked {
- devtools_session_state: &mut state.devtools_session_state,
+ session_id: None,
+ devtools_session_state: &mut state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary],
network_policy: &mut state.network_policy,
tls_verify_host_override: &mut state.tls_verify_host_override,
}
@@ -1085,13 +1069,11 @@ mod tests {
fn connection_with_background_auxiliary_session() -> CdpConnection {
let mut conn = CdpConnection::default();
let mut browser_context = BrowserContext::new("BID-background".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background".to_owned()),
- "https://background.example/".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background".to_owned()),
+ "https://background.example/".to_owned(),
+ ));
assert!(
browser_context
.assign_auxiliary_session_to_target("TID-background", "SID-aux".to_owned())
@@ -1106,13 +1088,11 @@ mod tests {
let mut browser_context = BrowserContext::new("BID-mixed".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background".to_owned()),
- "https://background.example/".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background".to_owned()),
+ "https://background.example/".to_owned(),
+ ));
conn.browser_context = Some(browser_context);
let (active_fetch_id, active_network_request_id) = conn
@@ -1190,7 +1170,7 @@ mod tests {
Some("cellular3g")
);
- let mut parked = ParkedPageSessionState::default();
+ let mut parked = TargetPageState::default();
parked_session_state_mut(&mut parked).set_cache_disabled(true);
parked_session_state_mut(&mut parked).set_bypass_service_worker(true);
let parked_blocked = parked_session_state_mut(&mut parked)
diff --git a/moli-protocol/src/conn/browser_context/page_owner.rs b/moli-protocol/src/conn/browser_context/page_owner.rs
index abb9fd1b6..66d938230 100644
--- a/moli-protocol/src/conn/browser_context/page_owner.rs
+++ b/moli-protocol/src/conn/browser_context/page_owner.rs
@@ -396,7 +396,7 @@ impl TargetSessionOwnerMut<'_> {
};
replay_session_id.map(|session_id| PageLifecycleReplayTarget { session_id })
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
session_id,
@@ -545,14 +545,13 @@ fn devtools_session_page_domain_enabled(state: &DevToolsSessionState) -> bool {
}
fn browser_context_has_page_domain_enabled_session(browser_context: &BrowserContext) -> bool {
- devtools_session_page_domain_enabled(&browser_context.devtools_session_state)
+ browser_context
+ .devtools_sessions
+ .states()
+ .any(devtools_session_page_domain_enabled)
|| browser_context
- .auxiliary_devtools_session_states
- .values()
- .any(devtools_session_page_domain_enabled)
- || browser_context
- .target_parking
- .has_page_domain_enabled_session()
+ .background_targets()
+ .any(|target| target.has_page_domain_enabled_session())
}
impl CdpConnection {
@@ -1006,19 +1005,24 @@ fn runtime_observable_console_payloads(
#[cfg(test)]
mod tests {
use super::*;
- use crate::conn::ParkedPageSessionState;
+ use crate::conn::TargetPageState;
fn active_session_state_mut(browser_context: &mut BrowserContext) -> TargetSessionStateMut<'_> {
+ let state = browser_context.active_page_state_mut();
TargetSessionStateMut::Active {
- devtools_session_state: &mut browser_context.devtools_session_state,
- network_policy: &mut browser_context.network_policy,
- tls_verify_host_override: &mut browser_context.tls_verify_host_override,
+ session_id: None,
+ devtools_session_state: &mut state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary],
+ network_policy: &mut state.network_policy,
+ tls_verify_host_override: &mut state.tls_verify_host_override,
}
}
- fn parked_session_state_mut(state: &mut ParkedPageSessionState) -> TargetSessionStateMut<'_> {
+ fn parked_session_state_mut(state: &mut TargetPageState) -> TargetSessionStateMut<'_> {
TargetSessionStateMut::Parked {
- devtools_session_state: &mut state.devtools_session_state,
+ session_id: None,
+ devtools_session_state: &mut state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary],
network_policy: &mut state.network_policy,
tls_verify_host_override: &mut state.tls_verify_host_override,
}
@@ -1042,46 +1046,44 @@ mod tests {
);
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled
);
- assert!(active.devtools_session_state.page_session_state.log_enabled);
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled
+ );
+ assert!(
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled
);
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_bypass_csp_enabled
);
assert_eq!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families,
font_families
);
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
);
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled()
);
- let mut parked = ParkedPageSessionState::default();
+ let mut parked = TargetPageState::default();
parked_session_state_mut(&mut parked).set_console_enabled(true);
parked_session_state_mut(&mut parked).set_log_enabled(true);
parked_session_state_mut(&mut parked).set_page_file_chooser_opened_event_enabled(true);
@@ -1094,40 +1096,38 @@ mod tests {
);
assert!(
- parked
- .devtools_session_state
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled
);
- assert!(parked.devtools_session_state.page_session_state.log_enabled);
assert!(
- parked
- .devtools_session_state
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled
+ );
+ assert!(
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled
);
assert!(
- parked
- .devtools_session_state
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_bypass_csp_enabled
);
assert_eq!(
- parked
- .devtools_session_state
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families,
font_families
);
assert!(
- parked
- .devtools_session_state
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
);
assert!(
- parked
- .devtools_session_state
+ parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled()
@@ -1199,7 +1199,7 @@ mod tests {
conn.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled
);
@@ -1210,7 +1210,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled
);
diff --git a/moli-protocol/src/conn/browser_context/session_owner.rs b/moli-protocol/src/conn/browser_context/session_owner.rs
index fc9c3d34d..2727809df 100644
--- a/moli-protocol/src/conn/browser_context/session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/session_owner.rs
@@ -1,11 +1,11 @@
-use crate::conn::{BrowserContext, CdpConnection, CdpSessionRoute, ParkedPageSessionState};
+use crate::conn::{BrowserContext, CdpConnection, CdpSessionRoute, TargetPageState};
pub(super) enum TargetSessionOwner {
ActiveTarget {
browser_context_id: String,
is_auxiliary_target_session: bool,
},
- BackgroundTarget {
+ PageTargetHost {
browser_context_id: String,
target_id: String,
is_auxiliary_target_session: bool,
@@ -27,7 +27,7 @@ impl CdpConnection {
pub(crate) fn mutate_background_target_page_session_state(
&mut self,
session_id: Option<&str>,
- f: impl FnOnce(&mut ParkedPageSessionState),
+ f: impl FnOnce(&mut TargetPageState),
) -> bool {
self.with_background_target_session(session_id, |browser_context, target_id| {
browser_context.mutate_parked_page_session_state(target_id, f);
@@ -44,15 +44,14 @@ impl CdpConnection {
None => match self.none_session_owner_route_override() {
Some(route) => route,
None => {
- let Some(browser_context_id) = self
- .browser_context
- .as_ref()
- .map(|browser_context| browser_context.id.clone())
- else {
+ let Some(browser_context) = self.browser_context.as_ref() else {
return Some(TargetSessionOwner::NoLoadedBrowserContext);
};
+ if !browser_context.has_active_target() {
+ return Some(TargetSessionOwner::NoLoadedBrowserContext);
+ }
return Some(TargetSessionOwner::ActiveTarget {
- browser_context_id,
+ browser_context_id: browser_context.id.clone(),
is_auxiliary_target_session: false,
});
}
@@ -60,20 +59,44 @@ impl CdpConnection {
};
match route {
- CdpSessionRoute::Browser => self
- .browser_context
- .as_ref()
- .map(|browser_context| TargetSessionOwner::ActiveTarget {
- browser_context_id: browser_context.id.clone(),
- is_auxiliary_target_session: false,
- })
- .or(Some(TargetSessionOwner::NoLoadedBrowserContext)),
+ CdpSessionRoute::Browser => Some(
+ self.browser_context
+ .as_ref()
+ .filter(|browser_context| browser_context.has_active_target())
+ .map(|browser_context| TargetSessionOwner::ActiveTarget {
+ browser_context_id: browser_context.id.clone(),
+ is_auxiliary_target_session: false,
+ })
+ .unwrap_or(TargetSessionOwner::NoLoadedBrowserContext),
+ ),
CdpSessionRoute::ActiveTarget {
- browser_context_id, ..
- } => Some(TargetSessionOwner::ActiveTarget {
browser_context_id,
- is_auxiliary_target_session: false,
- }),
+ target_id,
+ } => {
+ let browser_context = self.browser_context_by_id(&browser_context_id)?;
+ match target_id {
+ Some(target_id) if browser_context.is_active_target(&target_id) => {
+ Some(TargetSessionOwner::ActiveTarget {
+ browser_context_id,
+ is_auxiliary_target_session: false,
+ })
+ }
+ Some(target_id) if browser_context.page_target(&target_id).is_some() => {
+ Some(TargetSessionOwner::PageTargetHost {
+ browser_context_id,
+ target_id,
+ is_auxiliary_target_session: false,
+ })
+ }
+ None if browser_context.has_active_target() => {
+ Some(TargetSessionOwner::ActiveTarget {
+ browser_context_id,
+ is_auxiliary_target_session: false,
+ })
+ }
+ _ => Some(TargetSessionOwner::NoLoadedBrowserContext),
+ }
+ }
CdpSessionRoute::AuxiliaryTarget {
browser_context_id,
target_id,
@@ -83,26 +106,38 @@ impl CdpConnection {
.background_target(&target_id)
.is_some();
if is_background_target {
- Some(TargetSessionOwner::BackgroundTarget {
+ Some(TargetSessionOwner::PageTargetHost {
browser_context_id,
target_id,
is_auxiliary_target_session: true,
})
- } else {
+ } else if self
+ .browser_context_by_id(&browser_context_id)?
+ .is_active_target(&target_id)
+ {
Some(TargetSessionOwner::ActiveTarget {
browser_context_id,
is_auxiliary_target_session: true,
})
+ } else {
+ Some(TargetSessionOwner::NoLoadedBrowserContext)
}
}
- CdpSessionRoute::BackgroundTarget {
+ CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
- } => Some(TargetSessionOwner::BackgroundTarget {
- browser_context_id,
- target_id,
- is_auxiliary_target_session: false,
- }),
+ } => {
+ let browser_context = self.browser_context_by_id(&browser_context_id)?;
+ if browser_context.page_target(&target_id).is_some() {
+ Some(TargetSessionOwner::PageTargetHost {
+ browser_context_id,
+ target_id,
+ is_auxiliary_target_session: false,
+ })
+ } else {
+ Some(TargetSessionOwner::NoLoadedBrowserContext)
+ }
+ }
CdpSessionRoute::TabTarget { .. }
| CdpSessionRoute::SharedWorkerTarget { .. }
| CdpSessionRoute::DedicatedWorkerTarget { .. }
diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rs
index 7615257a8..e5acffe78 100644
--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs
@@ -5,8 +5,6 @@ use crate::conn::state::{
PageNavigationHistoryEntry, RendererMainDocumentCommitSeed, TargetFetchConfig,
TargetNetworkPolicyState, TargetOwnerState, TargetPageAbsenceReason,
TargetPageResidenceIdentity, TargetRuntimeSessionState, TargetRuntimeSlot,
- page_bypass_csp_enabled_for_devtools_sessions,
- prepare_renderer_call_replacements_for_devtools_sessions, runtime_bindings_for_renderer,
};
use crate::conn::{
BackgroundProtocolEvent, ConnectionNetworkRequestIdAllocator, DocumentStartScript,
@@ -22,9 +20,8 @@ use moli_cookie_jar::{StoredCookieQueryReport, StoredCookieSetReport};
#[cfg(test)]
use moli_core::page::RendererServiceWorkerVersionStatus;
use moli_core::page::{
- BidiPreloadChannelHandoff, Page, RendererInspectorProtocolConfiguration,
- RendererInspectorSessionRestoreSnapshot, RendererMainDocumentCommit,
- RendererPageCreationArtifacts, SubresourceResourceType, V8InspectorSessionAttach,
+ BidiPreloadChannelHandoff, Page, RendererInspectorSessionRestoreSnapshot,
+ RendererMainDocumentCommit, RendererPageCreationArtifacts, SubresourceResourceType,
};
use moli_core::runtime::RendererBrowserContextRuntimeOwnerAccess;
use moli_fetch::BrowserNavigationRequestKind;
@@ -37,7 +34,7 @@ pub(super) enum TargetSessionOwnerMut<'a> {
is_auxiliary_target_session: bool,
is_current_active_browser_context: bool,
},
- BackgroundTarget {
+ PageTargetHost {
browser_context: &'a mut BrowserContext,
target_id: String,
session_id: Option<String>,
@@ -52,7 +49,7 @@ pub(super) enum TargetSessionOwnerRef<'a> {
session_id: Option<String>,
is_auxiliary_target_session: bool,
},
- BackgroundTarget {
+ PageTargetHost {
browser_context: &'a BrowserContext,
target_id: String,
session_id: Option<String>,
@@ -107,11 +104,13 @@ impl ClosedPageTarget {
pub(super) enum TargetSessionStateMut<'a> {
Active {
+ session_id: Option<String>,
devtools_session_state: &'a mut DevToolsSessionState,
network_policy: &'a mut TargetNetworkPolicyState,
tls_verify_host_override: &'a mut Option<bool>,
},
Parked {
+ session_id: Option<String>,
devtools_session_state: &'a mut DevToolsSessionState,
network_policy: &'a mut TargetNetworkPolicyState,
tls_verify_host_override: &'a mut Option<bool>,
@@ -272,9 +271,9 @@ impl TargetNavigationLoadInputs {
renderer_runtime: browser_context.renderer_runtime_owner_access(),
browser_identity_override: browser_context
.effective_active_browser_identity_override_owned(),
- http_proxy_override: browser_context.http_proxy_override.clone(),
- http_no_proxy_override: browser_context.http_no_proxy_override.clone(),
- tls_verify_host_override: browser_context.tls_verify_host_override,
+ http_proxy_override: browser_context.effective_active_http_proxy_override_owned(),
+ http_no_proxy_override: browser_context.effective_active_http_no_proxy_override_owned(),
+ tls_verify_host_override: browser_context.effective_active_tls_verify_host_override(),
navigation_initiator_url: target_navigation_initiator_url(
browser_context.target_url(),
browser_context.loaded_page(),
@@ -282,23 +281,19 @@ impl TargetNavigationLoadInputs {
browser_navigation_kind: BrowserNavigationRequestKind::Navigate,
infer_navigation_referrer: true,
document_start_scripts: browser_context.document_start_script_descriptors(),
- runtime_bindings: runtime_bindings_for_renderer(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ),
- runtime_inspector_session_restore_snapshots:
- runtime_inspector_session_restore_snapshots_for_renderer(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ),
+ runtime_bindings: browser_context
+ .devtools_sessions
+ .runtime_bindings_for_renderer(),
+ runtime_inspector_session_restore_snapshots: browser_context
+ .devtools_sessions
+ .runtime_inspector_restore_snapshots(),
extra_http_headers: browser_context.effective_extra_headers(),
locale_override: browser_context.effective_active_locale_override_owned(),
timezone_override: browser_context.effective_active_timezone_override_owned(),
script_execution_disabled: browser_context.script_execution_disabled,
- bypass_content_security_policy: page_bypass_csp_enabled_for_devtools_sessions(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ),
+ bypass_content_security_policy: browser_context
+ .devtools_sessions
+ .page_bypass_csp_enabled(),
cpu_throttling_rate: browser_context.cpu_throttling_rate,
emulated_media: (&browser_context.emulated_media).into(),
viewport_surface: browser_context
@@ -322,10 +317,28 @@ impl TargetNavigationLoadInputs {
}
fn from_browser_context_fallback(browser_context: &BrowserContext) -> Self {
- TargetNavigationLoadInputs::no_loaded_browser_context(
+ let mut inputs = TargetNavigationLoadInputs::no_loaded_browser_context(
browser_context.page_storage_handles(),
browser_context.renderer_runtime_owner_access(),
- )
+ );
+ inputs.browser_context_id = Some(browser_context.id.clone());
+ inputs.browser_identity_override =
+ browser_context.effective_active_browser_identity_override_owned();
+ inputs.http_proxy_override = browser_context.effective_active_http_proxy_override_owned();
+ inputs.http_no_proxy_override =
+ browser_context.effective_active_http_no_proxy_override_owned();
+ inputs.tls_verify_host_override =
+ browser_context.effective_active_tls_verify_host_override();
+ inputs.document_start_scripts = browser_context.default_document_start_script_descriptors();
+ inputs.extra_http_headers = browser_context.effective_extra_headers();
+ inputs.locale_override = browser_context.effective_active_locale_override_owned();
+ inputs.timezone_override = browser_context.effective_active_timezone_override_owned();
+ inputs.viewport_surface = browser_context
+ .default_emulated_device_metrics
+ .as_ref()
+ .map(|metrics| metrics.viewport_surface().to_page_viewport_surface());
+ inputs.network_offline = browser_context.effective_active_network_offline();
+ inputs
}
fn no_loaded_browser_context(
@@ -395,16 +408,6 @@ fn apply_user_agent_header(headers: &mut Vec<(String, String)>, user_agent: &str
}
}
-fn apply_locale_header(headers: &mut Vec<(String, String)>, locale: Option<&str>) {
- if let Some(locale) = locale
- && !headers
- .iter()
- .any(|(name, _)| name.eq_ignore_ascii_case("accept-language"))
- {
- headers.push(("Accept-Language".to_owned(), locale.to_owned()));
- }
-}
-
fn target_navigation_initiator_url(target_url: &str, loaded_page: Option<&Page>) -> Option<Url> {
if let Some(loaded_page) = loaded_page {
let url = loaded_page.final_url().clone();
@@ -418,88 +421,24 @@ fn target_navigation_initiator_url(target_url: &str, loaded_page: Option<&Page>)
}
fn clear_parked_page_runtime_remote_object_tracking(
- state: &mut crate::conn::state::ParkedPageSessionState,
+ state: &mut crate::conn::state::TargetPageState,
) {
- state
- .devtools_session_state
- .clear_runtime_remote_object_tracking();
- for state in state.auxiliary_devtools_session_states.values_mut() {
- state.clear_runtime_remote_object_tracking();
+ for session in state.devtools_sessions.states_mut() {
+ session.clear_runtime_remote_object_tracking();
}
}
fn clear_parked_page_loaded_document_session_state(
- state: &mut crate::conn::state::ParkedPageSessionState,
+ state: &mut crate::conn::state::TargetPageState,
) {
clear_parked_page_runtime_remote_object_tracking(state);
- state
- .devtools_session_state
- .page_session_state
- .clear_loaded_document_context_state();
- for state in state.auxiliary_devtools_session_states.values_mut() {
- state
+ for session in state.devtools_sessions.states_mut() {
+ session
.page_session_state
.clear_loaded_document_context_state();
}
}
-fn runtime_inspector_session_restore_snapshots_for_renderer(
- primary: &DevToolsSessionState,
- auxiliary: &std::collections::HashMap<String, DevToolsSessionState>,
-) -> Vec<RendererInspectorSessionRestoreSnapshot> {
- let mut restores = Vec::new();
- if primary.runtime_session_state.runtime_frontend_enabled
- || primary.console_output_session_state.console_enabled
- || !primary.dom_debugger_event_listener_breakpoints.is_empty()
- || !primary.dom_debugger_xhr_breakpoints.is_empty()
- || primary.inspector_session_state.v8_state.is_some()
- {
- restores.push(RendererInspectorSessionRestoreSnapshot {
- inspector_session_id: None,
- v8_attach: V8InspectorSessionAttach::from_optional_state(
- primary.inspector_session_state.v8_state.clone(),
- ),
- protocol_configuration: RendererInspectorProtocolConfiguration {
- runtime_bindings: primary.runtime_bindings.clone(),
- runtime_frontend_enabled: primary.runtime_session_state.runtime_frontend_enabled,
- console_frontend_enabled: primary.console_output_session_state.console_enabled,
- dom_debugger_event_listener_breakpoints: primary
- .dom_debugger_event_listener_breakpoints
- .clone(),
- dom_debugger_xhr_breakpoints: primary.dom_debugger_xhr_breakpoints.clone(),
- },
- });
- }
- let mut auxiliary = auxiliary.iter().collect::<Vec<_>>();
- auxiliary.sort_by_key(|(session_id, _)| *session_id);
- for (session_id, state) in auxiliary {
- if !state.runtime_session_state.runtime_frontend_enabled
- && !state.console_output_session_state.console_enabled
- && state.dom_debugger_event_listener_breakpoints.is_empty()
- && state.dom_debugger_xhr_breakpoints.is_empty()
- && state.inspector_session_state.v8_state.is_none()
- {
- continue;
- }
- restores.push(RendererInspectorSessionRestoreSnapshot {
- inspector_session_id: Some(session_id.clone()),
- v8_attach: V8InspectorSessionAttach::from_optional_state(
- state.inspector_session_state.v8_state.clone(),
- ),
- protocol_configuration: RendererInspectorProtocolConfiguration {
- runtime_bindings: state.runtime_bindings.clone(),
- runtime_frontend_enabled: state.runtime_session_state.runtime_frontend_enabled,
- console_frontend_enabled: state.console_output_session_state.console_enabled,
- dom_debugger_event_listener_breakpoints: state
- .dom_debugger_event_listener_breakpoints
- .clone(),
- dom_debugger_xhr_breakpoints: state.dom_debugger_xhr_breakpoints.clone(),
- },
- });
- }
- restores
-}
-
fn renderer_runtime_inspector_session_id(
is_auxiliary_target_session: bool,
session_id: Option<&str>,
@@ -518,13 +457,10 @@ impl<'a> TargetSessionOwnerRef<'a> {
browser_context,
session_id,
is_auxiliary_target_session,
- } => target_devtools_session_state(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- *is_auxiliary_target_session,
- session_id.as_deref(),
- ),
- Self::BackgroundTarget {
+ } => browser_context
+ .devtools_sessions
+ .routed(*is_auxiliary_target_session, session_id.as_deref()),
+ Self::PageTargetHost {
browser_context,
target_id,
session_id,
@@ -532,12 +468,9 @@ impl<'a> TargetSessionOwnerRef<'a> {
} => browser_context
.parked_page_session_state(target_id)
.and_then(|state| {
- target_devtools_session_state(
- &state.devtools_session_state,
- &state.auxiliary_devtools_session_states,
- *is_auxiliary_target_session,
- session_id.as_deref(),
- )
+ state
+ .devtools_sessions
+ .routed(*is_auxiliary_target_session, session_id.as_deref())
}),
Self::NoLoadedBrowserContext => None,
}
@@ -552,22 +485,14 @@ impl<'a> TargetSessionOwnerRef<'a> {
match self {
Self::ActiveTarget {
browser_context, ..
- } => Some(page_bypass_csp_enabled_for_devtools_sessions(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- )),
- Self::BackgroundTarget {
+ } => Some(browser_context.devtools_sessions.page_bypass_csp_enabled()),
+ Self::PageTargetHost {
browser_context,
target_id,
..
} => browser_context
.parked_page_session_state(target_id)
- .map(|state| {
- page_bypass_csp_enabled_for_devtools_sessions(
- &state.devtools_session_state,
- &state.auxiliary_devtools_session_states,
- )
- }),
+ .map(|state| state.devtools_sessions.page_bypass_csp_enabled()),
Self::NoLoadedBrowserContext => None,
}
}
@@ -584,7 +509,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
is_auxiliary_target_session,
..
}
- | Self::BackgroundTarget {
+ | Self::PageTargetHost {
session_id,
is_auxiliary_target_session,
..
@@ -600,22 +525,16 @@ impl<'a> TargetSessionOwnerRef<'a> {
match self {
Self::ActiveTarget {
browser_context, ..
- } => runtime_bindings_for_renderer(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ),
- Self::BackgroundTarget {
+ } => browser_context
+ .devtools_sessions
+ .runtime_bindings_for_renderer(),
+ Self::PageTargetHost {
browser_context,
target_id,
..
} => browser_context
.parked_page_session_state(target_id)
- .map(|state| {
- runtime_bindings_for_renderer(
- &state.devtools_session_state,
- &state.auxiliary_devtools_session_states,
- )
- })
+ .map(|state| state.devtools_sessions.runtime_bindings_for_renderer())
.unwrap_or_default(),
Self::NoLoadedBrowserContext => Vec::new(),
}
@@ -626,7 +545,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(&browser_context.active_target.owner_state),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -663,13 +582,13 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(browser_context.active_target.fetch_owner.config_snapshot()),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
} => browser_context
- .parked_page_session_state(target_id)
- .map(|state| state.fetch_config.clone()),
+ .background_target(target_id)
+ .map(|target| target.fetch_owner.config_snapshot()),
Self::NoLoadedBrowserContext => None,
}
}
@@ -679,7 +598,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(&browser_context.active_target.runtime_slot),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -698,7 +617,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
browser_context.id.clone(),
browser_context.active_target_id_owned(),
)),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -712,7 +631,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => browser_context.active_session_id_owned(),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -728,7 +647,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(browser_context.target_url().to_owned()),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -761,7 +680,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
browser_context.target_secure_context_type().to_owned(),
))
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -798,7 +717,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => browser_context.effective_active_emulated_device_metrics(),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -812,7 +731,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
Self::ActiveTarget {
browser_context, ..
} => TargetNavigationLoadInputs::from_browser_context_active_target(browser_context),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -822,10 +741,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
browser_context,
);
};
- let page_state = browser_context
- .parked_page_session_state(target_id)
- .cloned()
- .unwrap_or_default();
+ let page_state = target.state();
let mut document_start_scripts = Vec::new();
if let Some(script) =
browser_context.generated_surface_override_script_for_parked_target(target_id)
@@ -837,34 +753,23 @@ impl<'a> TargetSessionOwnerRef<'a> {
if let Some(owner_state) = browser_context.parked_target_owner_state(target_id) {
document_start_scripts.extend(owner_state.document_start_scripts.iter().map(
|(identifier, script)| {
- script.with_registry_key(
- BrowserContext::target_document_start_script_registry_key(
- Some(target_id.as_str()),
- identifier,
- ),
+ BrowserContext::target_document_start_script_descriptor(
+ Some(target_id.as_str()),
+ identifier,
+ script,
)
},
));
}
- let runtime_bindings = runtime_bindings_for_renderer(
- &page_state.devtools_session_state,
- &page_state.auxiliary_devtools_session_states,
- );
- let runtime_inspector_session_restore_snapshots =
- runtime_inspector_session_restore_snapshots_for_renderer(
- &page_state.devtools_session_state,
- &page_state.auxiliary_devtools_session_states,
- );
- let mut extra_http_headers = page_state.network_policy.extra_headers().to_vec();
+ let runtime_bindings = page_state.devtools_sessions.runtime_bindings_for_renderer();
+ let runtime_inspector_session_restore_snapshots = page_state
+ .devtools_sessions
+ .runtime_inspector_restore_snapshots();
+ let extra_http_headers = page_state.network_policy.extra_headers().to_vec();
let locale_override = page_state
.locale_override
.clone()
.or_else(|| browser_context.default_locale_override.clone());
- let header_locale_override = browser_context
- .locale_override
- .as_deref()
- .or(locale_override.as_deref());
- apply_locale_header(&mut extra_http_headers, header_locale_override);
TargetNavigationLoadInputs {
browser_context_id: Some(browser_context.id.clone()),
@@ -879,9 +784,17 @@ impl<'a> TargetSessionOwnerRef<'a> {
.network_policy
.browser_identity_override_owned()
.or_else(|| browser_context.default_browser_identity_override.clone()),
- http_proxy_override: page_state.http_proxy_override,
- http_no_proxy_override: page_state.http_no_proxy_override,
- tls_verify_host_override: page_state.tls_verify_host_override,
+ http_proxy_override: page_state
+ .http_proxy_override
+ .clone()
+ .or_else(|| browser_context.default_http_proxy_override.clone()),
+ http_no_proxy_override: page_state
+ .http_no_proxy_override
+ .clone()
+ .or_else(|| browser_context.default_http_no_proxy_override.clone()),
+ tls_verify_host_override: page_state
+ .tls_verify_host_override
+ .or(browser_context.default_tls_verify_host_override),
navigation_initiator_url: target_navigation_initiator_url(
target.target_url(),
target.loaded_page(),
@@ -895,12 +808,12 @@ impl<'a> TargetSessionOwnerRef<'a> {
locale_override,
timezone_override: page_state
.timezone_override
+ .clone()
.or_else(|| browser_context.default_timezone_override.clone()),
script_execution_disabled: page_state.script_execution_disabled,
- bypass_content_security_policy: page_bypass_csp_enabled_for_devtools_sessions(
- &page_state.devtools_session_state,
- &page_state.auxiliary_devtools_session_states,
- ),
+ bypass_content_security_policy: page_state
+ .devtools_sessions
+ .page_bypass_csp_enabled(),
cpu_throttling_rate: page_state.cpu_throttling_rate,
emulated_media: (&page_state.emulated_media).into(),
viewport_surface: browser_context
@@ -912,7 +825,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
bypass_service_worker: page_state.network_policy.bypass_service_worker(),
blocked_url_patterns: page_state.network_policy.blocked_url_patterns().to_vec(),
fetch_subresource_interception: page_state
- .fetch_config
+ .fetch_owner
.subresource_interception_config(),
permission_overrides: Vec::new(),
main_document_commit_seed: None,
@@ -925,30 +838,6 @@ impl<'a> TargetSessionOwnerRef<'a> {
}
}
-fn target_devtools_session_state_mut<'a>(
- primary: &'a mut DevToolsSessionState,
- auxiliary: &'a mut std::collections::HashMap<String, DevToolsSessionState>,
- is_auxiliary_target_session: bool,
- session_id: Option<&str>,
-) -> &'a mut DevToolsSessionState {
- if is_auxiliary_target_session && let Some(session_id) = session_id {
- return auxiliary.entry(session_id.to_owned()).or_default();
- }
- primary
-}
-
-fn target_devtools_session_state<'a>(
- primary: &'a DevToolsSessionState,
- auxiliary: &'a std::collections::HashMap<String, DevToolsSessionState>,
- is_auxiliary_target_session: bool,
- session_id: Option<&str>,
-) -> Option<&'a DevToolsSessionState> {
- if is_auxiliary_target_session {
- return session_id.and_then(|session_id| auxiliary.get(session_id));
- }
- Some(primary)
-}
-
impl TargetSessionStateMut<'_> {
pub(super) fn devtools_session_state_mut(&mut self) -> Option<&mut DevToolsSessionState> {
match self {
@@ -1022,7 +911,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(browser_context.target_url().to_owned()),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1038,7 +927,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(&browser_context.active_target.runtime_slot),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1060,32 +949,29 @@ impl<'a> TargetSessionOwnerMut<'a> {
is_auxiliary_target_session,
..
} => {
- let devtools_session_state = target_devtools_session_state_mut(
- &mut browser_context.devtools_session_state,
- &mut browser_context.auxiliary_devtools_session_states,
- *is_auxiliary_target_session,
- session_id.as_deref(),
- );
+ let state = browser_context.active_page_state_mut();
+ let devtools_session_state = state
+ .devtools_sessions
+ .routed_mut_or_insert(*is_auxiliary_target_session, session_id.as_deref());
f(TargetSessionStateMut::Active {
+ session_id: session_id.clone(),
devtools_session_state,
- network_policy: &mut browser_context.network_policy,
- tls_verify_host_override: &mut browser_context.tls_verify_host_override,
+ network_policy: &mut state.network_policy,
+ tls_verify_host_override: &mut state.tls_verify_host_override,
})
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
session_id,
is_auxiliary_target_session,
..
} => browser_context.mutate_parked_page_session_state(target_id, |state| {
- let devtools_session_state = target_devtools_session_state_mut(
- &mut state.devtools_session_state,
- &mut state.auxiliary_devtools_session_states,
- *is_auxiliary_target_session,
- session_id.as_deref(),
- );
+ let devtools_session_state = state
+ .devtools_sessions
+ .routed_mut_or_insert(*is_auxiliary_target_session, session_id.as_deref());
f(TargetSessionStateMut::Parked {
+ session_id: session_id.clone(),
devtools_session_state,
network_policy: &mut state.network_policy,
tls_verify_host_override: &mut state.tls_verify_host_override,
@@ -1110,7 +996,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => f(Some(&mut browser_context.active_target.owner_state)),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1142,19 +1028,17 @@ impl<'a> TargetSessionOwnerMut<'a> {
.subresource_interception_config(),
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
} => {
let mut subresource_config = (false, None);
browser_context.mutate_parked_page_session_state(target_id, |state| {
- state.fetch_config.configure(
- command_session_id,
- handle_auth_requests,
- patterns,
- );
- subresource_config = state.fetch_config.subresource_interception_config();
+ state
+ .fetch_owner
+ .configure(command_session_id, handle_auth_requests, patterns);
+ subresource_config = state.fetch_owner.subresource_interception_config();
});
Some(subresource_config)
}
@@ -1191,21 +1075,21 @@ impl<'a> TargetSessionOwnerMut<'a> {
.subresource_interception_config(),
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
} => {
let mut subresource_config = (false, None);
browser_context.mutate_parked_page_session_state(target_id, |state| {
- state.fetch_config.add_network_intercept(
+ state.fetch_owner.add_network_intercept(
intercept_id,
command_session_id,
handle_auth_requests,
auth_url_patterns,
patterns,
);
- subresource_config = state.fetch_config.subresource_interception_config();
+ subresource_config = state.fetch_owner.subresource_interception_config();
});
Some(subresource_config)
}
@@ -1235,7 +1119,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
.subresource_interception_config(),
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1243,8 +1127,8 @@ impl<'a> TargetSessionOwnerMut<'a> {
let mut removed = false;
let mut subresource_config = (false, None);
browser_context.mutate_parked_page_session_state(target_id, |state| {
- removed = state.fetch_config.remove_network_intercept(intercept_id);
- subresource_config = state.fetch_config.subresource_interception_config();
+ removed = state.fetch_owner.remove_network_intercept(intercept_id);
+ subresource_config = state.fetch_owner.subresource_interception_config();
});
removed.then_some(subresource_config)
}
@@ -1284,27 +1168,26 @@ impl<'a> TargetSessionOwnerMut<'a> {
removed && previous_subresource_config != subresource_config;
Some((pending, subresource_config, page_update_required))
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
} => {
let previous_subresource_config = browser_context
- .parked_page_session_state(target_id)
- .map(|state| state.fetch_config.subresource_interception_config())
+ .background_target(target_id)
+ .map(|target| target.fetch_owner.subresource_interception_config())
.unwrap_or((false, None));
let mut subresource_config = (false, None);
let mut removed = false;
browser_context.mutate_parked_page_session_state(target_id, |state| {
- removed = state.fetch_config.remove_fetch_session(session_id);
- subresource_config = state.fetch_config.subresource_interception_config();
+ removed = state.fetch_owner.remove_fetch_session(session_id);
+ subresource_config = state.fetch_owner.subresource_interception_config();
});
let pending = if removed {
- let mut fetch_state = browser_context.take_parked_fetch_state(target_id);
- let pending =
- fetch_state.drain_pending_requests_for_disable_session(session_id);
- browser_context.replace_parked_fetch_state(target_id.clone(), fetch_state);
- pending
+ browser_context
+ .background_target_mut(target_id)?
+ .fetch_owner
+ .drain_pending_requests_for_disable_session(session_id)
} else {
empty_pending_fetch_state()
};
@@ -1330,16 +1213,16 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(browser_context.take_active_target_pending_fetch_state()),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
- } => {
- let mut fetch_state = browser_context.take_parked_fetch_state(target_id);
- let pending = fetch_state.drain_pending_requests();
- browser_context.replace_parked_fetch_state(target_id.clone(), fetch_state);
- Some(pending)
- }
+ } => Some(
+ browser_context
+ .background_target_mut(target_id)?
+ .fetch_owner
+ .drain_pending_requests(),
+ ),
Self::NoLoadedBrowserContext => None,
}
}
@@ -1352,7 +1235,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context.mark_active_target_crashed_async().await;
Some(())
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1378,9 +1261,6 @@ impl<'a> TargetSessionOwnerMut<'a> {
.reset_all_target_scoped_network_artifacts();
previous
};
- browser_context.replace_parked_fetch_state(target_id.clone(), Default::default());
- browser_context
- .replace_parked_network_artifacts(target_id.clone(), Default::default());
if let Some(page) = previous {
let _ = page.close_async().await;
}
@@ -1417,7 +1297,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
}
Some(())
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1460,16 +1340,14 @@ impl<'a> TargetSessionOwnerMut<'a> {
let primary_session_id = browser_context.active_session_id_owned();
let auxiliary_session_ids =
browser_context.remove_auxiliary_sessions_for_target(&target_id);
- browser_context
- .close_active_target_after_page_close_async()
- .await;
+ browser_context.remove_active_page_target_async().await;
Some(ClosedPageTarget {
target_id,
primary_session_id,
auxiliary_session_ids,
})
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1478,7 +1356,6 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context.forget_target_opener_references_for_target(target_id);
browser_context.forget_target_window_names_for_target(target_id);
browser_context.forget_target_popup_id_for_target(target_id);
- let _ = browser_context.take_parked_target_aux_state(target_id);
let primary_session_id = target.detach_session();
let auxiliary_session_ids =
browser_context.remove_auxiliary_sessions_for_target(target_id);
@@ -1498,7 +1375,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(&mut browser_context.active_target.runtime_slot),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1514,7 +1391,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => Some(&mut browser_context.active_target.runtime_slot),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1545,7 +1422,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
.navigation_history_snapshot(page_snapshot),
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1579,7 +1456,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
.owner_state
.commit_document_title(title),
),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1597,7 +1474,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
Self::ActiveTarget {
browser_context, ..
} => browser_context.navigation_history_entry_url(entry_id),
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1637,7 +1514,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
.reset_navigation_history(page_snapshot),
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1679,7 +1556,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
.can_reset_navigation_history(page_snapshot),
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1711,7 +1588,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context.mark_next_navigation_history_replace_current();
Some(())
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1736,7 +1613,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context.mark_next_navigation_history_traverse_to_entry(entry_id);
Some(())
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1768,7 +1645,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context.set_target_security_origin(security_origin);
Some(frame_id)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -1806,35 +1683,17 @@ impl<'a> TargetSessionOwnerMut<'a> {
pub(super) fn effective_extra_headers_for_target_policy(
&self,
- mut headers: Vec<(String, String)>,
+ headers: Vec<(String, String)>,
) -> Vec<(String, String)> {
- let locale_override = match self {
- Self::ActiveTarget {
- browser_context, ..
- } => browser_context.effective_active_locale_override(),
- Self::BackgroundTarget {
- browser_context,
- target_id,
- ..
- } => browser_context.locale_override.as_deref().or_else(|| {
- browser_context
- .parked_page_session_state(target_id)
- .and_then(|state| state.locale_override.as_deref())
- .or(browser_context.default_locale_override.as_deref())
- }),
- Self::NoLoadedBrowserContext => None,
- };
- headers = match self {
+ match self {
Self::ActiveTarget {
browser_context, ..
}
- | Self::BackgroundTarget {
+ | Self::PageTargetHost {
browser_context, ..
} => browser_context.merged_extra_headers_for_target_policy(&headers),
Self::NoLoadedBrowserContext => headers,
- };
- apply_locale_header(&mut headers, locale_override);
- headers
+ }
}
pub(super) fn prepare_navigation_request(
@@ -1948,7 +1807,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
fetch_navigation_request_id,
})
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
session_id: _,
@@ -1962,31 +1821,19 @@ impl<'a> TargetSessionOwnerMut<'a> {
target.target_identity().secure_context_type().to_owned();
let target_has_network_event_listeners =
target.runtime_slot().has_network_event_listeners();
- let page_state = browser_context
- .parked_page_session_state(target_id)
- .cloned()
- .unwrap_or_default();
- let mut request_headers = browser_context.merged_extra_headers_for_target_policy(
- page_state.network_policy.extra_headers(),
- );
- let user_agent = page_state
- .network_policy
+ let network_enabled = target.runtime_slot().primary_network_events_enabled();
+ let network_policy = target.network_policy.clone();
+ let fetch_config = target.fetch_owner.config_snapshot();
+ let mut request_headers = browser_context
+ .merged_extra_headers_for_target_policy(network_policy.extra_headers());
+ let user_agent = network_policy
.browser_identity_override()
.or(browser_context.default_browser_identity_override.as_ref())
.unwrap_or(fallback_browser_identity)
.user_agent();
apply_user_agent_header(&mut request_headers, user_agent);
- let locale_override = page_state
- .locale_override
- .as_deref()
- .or(browser_context.default_locale_override.as_deref());
- let header_locale_override = browser_context
- .locale_override
- .as_deref()
- .or(locale_override);
- apply_locale_header(&mut request_headers, header_locale_override);
apply_referrer_header(&mut request_headers, referrer);
- let fetch_snapshot = page_state.fetch_config.subresource_interception_snapshot();
+ let fetch_snapshot = fetch_config.subresource_interception_snapshot();
let document_request_pause = (!is_data_url)
.then(|| {
fetch_snapshot
@@ -2011,10 +1858,8 @@ impl<'a> TargetSessionOwnerMut<'a> {
.next()
})
.flatten();
- let document_fetch_response_stage_candidate = !is_data_url
- && page_state
- .fetch_config
- .has_document_response_stage_candidate();
+ let document_fetch_response_stage_candidate =
+ !is_data_url && fetch_config.has_document_response_stage_candidate();
let document_fetch_request_stage = document_request_pause
.as_ref()
.map(|_| FetchRequestStage::Request)
@@ -2036,20 +1881,17 @@ impl<'a> TargetSessionOwnerMut<'a> {
.and_then(|pause| pause.session_id.clone())
});
let document_auth_required =
- !is_data_url && page_state.fetch_config.matches_auth_required(requested_url);
+ !is_data_url && fetch_config.matches_auth_required(requested_url);
let document_auth_required_blocked_intercepts = if document_auth_required {
- page_state
- .fetch_config
- .matching_auth_required_network_intercepts(requested_url)
+ fetch_config.matching_auth_required_network_intercepts(requested_url)
} else {
Vec::new()
};
- let observes_document_request = page_state.network_enabled
+ let observes_document_request = network_enabled
|| target_has_network_event_listeners
- || (!is_data_url
- && (page_state.fetch_config.is_enabled() || document_auth_required));
+ || (!is_data_url && (fetch_config.is_enabled() || document_auth_required));
let clear_captured_response_bodies =
- page_state.network_enabled || target_has_network_event_listeners;
+ network_enabled || target_has_network_event_listeners;
let needs_fetch_navigation_request_id =
document_fetch_request_stage.is_some() || document_auth_required;
let (document_loader_id, document_request_id, fetch_navigation_request_id) =
@@ -2091,12 +1933,9 @@ impl<'a> TargetSessionOwnerMut<'a> {
is_auxiliary_target_session,
..
} => {
- let devtools_session_state = target_devtools_session_state(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- *is_auxiliary_target_session,
- session_id.as_deref(),
- );
+ let devtools_session_state = browser_context
+ .devtools_sessions
+ .routed(*is_auxiliary_target_session, session_id.as_deref());
Some(TargetLoadedNavigationCommitState {
browser_context_id: browser_context.id.clone(),
runtime_frontend_enabled: devtools_session_state
@@ -2106,15 +1945,12 @@ impl<'a> TargetSessionOwnerMut<'a> {
*is_auxiliary_target_session,
session_id.as_deref(),
),
- runtime_inspector_session_restore_snapshots:
- runtime_inspector_session_restore_snapshots_for_renderer(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ),
- stored_runtime_bindings: runtime_bindings_for_renderer(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ),
+ runtime_inspector_session_restore_snapshots: browser_context
+ .devtools_sessions
+ .runtime_inspector_restore_snapshots(),
+ stored_runtime_bindings: browser_context
+ .devtools_sessions
+ .runtime_bindings_for_renderer(),
session_runtime_bindings: devtools_session_state
.map(|state| state.runtime_bindings.clone())
.unwrap_or_default(),
@@ -2129,28 +1965,22 @@ impl<'a> TargetSessionOwnerMut<'a> {
.subresource_interception_config(),
})
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
session_id,
is_auxiliary_target_session,
} => {
- let page_state = browser_context
- .parked_page_session_state(target_id)
- .cloned()
- .unwrap_or_default();
- let devtools_session_state = target_devtools_session_state(
- &page_state.devtools_session_state,
- &page_state.auxiliary_devtools_session_states,
- *is_auxiliary_target_session,
- session_id.as_deref(),
- );
+ let target = browser_context.background_target(target_id)?;
+ let page_state = target.state();
+ let devtools_session_state = page_state
+ .devtools_sessions
+ .routed(*is_auxiliary_target_session, session_id.as_deref());
let isolated_worlds = browser_context
.parked_target_owner_state(target_id)
.map(|owner_state| owner_state.isolated_worlds.clone())
.unwrap_or_default();
let browser_context_id = browser_context.id.clone();
- browser_context.background_target(target_id)?;
Some(TargetLoadedNavigationCommitState {
browser_context_id,
runtime_frontend_enabled: devtools_session_state
@@ -2160,21 +1990,18 @@ impl<'a> TargetSessionOwnerMut<'a> {
*is_auxiliary_target_session,
session_id.as_deref(),
),
- runtime_inspector_session_restore_snapshots:
- runtime_inspector_session_restore_snapshots_for_renderer(
- &page_state.devtools_session_state,
- &page_state.auxiliary_devtools_session_states,
- ),
- stored_runtime_bindings: runtime_bindings_for_renderer(
- &page_state.devtools_session_state,
- &page_state.auxiliary_devtools_session_states,
- ),
+ runtime_inspector_session_restore_snapshots: page_state
+ .devtools_sessions
+ .runtime_inspector_restore_snapshots(),
+ stored_runtime_bindings: page_state
+ .devtools_sessions
+ .runtime_bindings_for_renderer(),
session_runtime_bindings: devtools_session_state
.map(|state| state.runtime_bindings.clone())
.unwrap_or_default(),
isolated_worlds,
fetch_subresource_config: page_state
- .fetch_config
+ .fetch_owner
.subresource_interception_config(),
})
}
@@ -2202,7 +2029,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
}
Some(())
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -2228,7 +2055,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
browser_context.clear_pending_navigation_history_update();
Some(())
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -2265,7 +2092,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
.await,
)
}
- Self::BackgroundTarget {
+ Self::PageTargetHost {
browser_context,
target_id,
..
@@ -2350,10 +2177,8 @@ impl<'a> TargetSessionOwnerMut<'a> {
{
let replacements =
match browser_context.mutate_parked_page_session_state(target_id, |state| {
- prepare_renderer_call_replacements_for_devtools_sessions(
+ state.devtools_sessions.prepare_renderer_call_replacements(
primary_session_id.as_deref(),
- &mut state.devtools_session_state,
- &mut state.auxiliary_devtools_session_states,
previous_attachment.id(),
new_attachment_id,
)
@@ -2401,12 +2226,18 @@ impl CdpConnection {
session_id: Option<&str>,
) -> TargetNavigationLoadInputs {
let mut inputs = match self.target_session_owner_ref(session_id) {
- Some(TargetSessionOwnerRef::NoLoadedBrowserContext) | None => {
- TargetNavigationLoadInputs::no_loaded_browser_context(
- self.initial_storage_partition.page_storage_handles(),
- self.engine.ensure().browser_context_owner_access(),
- )
- }
+ Some(TargetSessionOwnerRef::NoLoadedBrowserContext) | None => self
+ .browser_context
+ .as_ref()
+ .map(TargetNavigationLoadInputs::from_browser_context_fallback)
+ .unwrap_or_else(|| {
+ TargetNavigationLoadInputs::no_loaded_browser_context(
+ self.initial_storage_partition.page_storage_handles(),
+ self.standalone_navigation_engine
+ .ensure()
+ .browser_context_owner_access(),
+ )
+ }),
Some(owner) => owner.navigation_load_inputs(),
};
if let Some(browser_context_id) = inputs.browser_context_id.as_deref() {
@@ -2594,19 +2425,9 @@ impl CdpConnection {
&mut self,
session_id: Option<&str>,
) -> Option<()> {
- let target_id = self
- .target_owner_identity_for_session(session_id)
- .and_then(|(_, target_id)| target_id);
- let result = self
- .target_session_owner_mut(session_id)?
+ self.target_session_owner_mut(session_id)?
.mark_target_crashed_async()
- .await;
- if result.is_some()
- && let Some(target_id) = target_id.as_deref()
- {
- self.forget_retained_navigation_engine_for_target(target_id);
- }
- result
+ .await
}
pub(crate) async fn discard_loaded_page_after_failed_navigation_for_session_owner_async(
@@ -2614,47 +2435,24 @@ impl CdpConnection {
session_id: Option<&str>,
final_url: &Url,
) -> Option<()> {
- let target_id = self
- .target_owner_identity_for_session(session_id)
- .and_then(|(_, target_id)| target_id);
- let result = self
- .target_session_owner_mut(session_id)?
+ self.target_session_owner_mut(session_id)?
.discard_loaded_page_after_failed_navigation_async(final_url)
- .await;
- if result.is_some()
- && let Some(target_id) = target_id.as_deref()
- {
- self.forget_retained_navigation_engine_for_target(target_id);
- }
- result
+ .await
}
pub(crate) async fn close_page_target_for_session_owner_async(
&mut self,
session_id: Option<&str>,
) -> Option<ClosedPageTarget> {
- let target_id = self
- .target_owner_identity_for_session(session_id)
- .and_then(|(_, target_id)| target_id);
- let mut collected_network_data_artifacts = self
+ let collected_network_data_artifacts = self
.target_session_owner_ref(session_id)?
.runtime_slot()?
.collected_network_data_artifacts();
- if let Some(target_id) = target_id.as_deref()
- && let Some(browser_context) = self.browser_context.as_mut()
- {
- collected_network_data_artifacts.extend(
- browser_context
- .take_parked_network_artifacts(target_id)
- .collected_network_data_artifacts(),
- );
- }
let closed = self
.target_session_owner_mut(session_id)?
.close_page_target_async()
.await?;
self.record_collected_network_data_artifacts(collected_network_data_artifacts);
- self.forget_retained_navigation_engine_for_target(&closed.target_id);
Some(closed)
}
@@ -2666,30 +2464,22 @@ impl CdpConnection {
) -> Option<ClosedPageTarget> {
let (
mut target,
- mut parked_aux_state,
primary_session_id,
auxiliary_session_ids,
collected_network_data_artifacts,
) = {
let browser_context = self.browser_context.as_mut()?;
let mut target = browser_context.remove_background_target(target_id)?;
- let mut collected_network_data_artifacts =
- target.runtime_slot().collected_network_data_artifacts();
- collected_network_data_artifacts.extend(
- browser_context
- .take_parked_network_artifacts(target_id)
- .collected_network_data_artifacts(),
- );
+ let collected_network_data_artifacts =
+ target.runtime_slot.collected_network_data_artifacts();
browser_context.forget_target_opener_references_for_target(target_id);
browser_context.forget_target_window_names_for_target(target_id);
browser_context.forget_target_popup_id_for_target(target_id);
- let parked_aux_state = browser_context.take_parked_target_aux_state(target_id);
let primary_session_id = target.detach_session();
let auxiliary_session_ids =
browser_context.remove_auxiliary_sessions_for_target(target_id);
(
target,
- parked_aux_state,
primary_session_id,
auxiliary_session_ids,
collected_network_data_artifacts,
@@ -2697,7 +2487,6 @@ impl CdpConnection {
};
target.close_page_async().await;
self.record_collected_network_data_artifacts(collected_network_data_artifacts);
- self.forget_retained_navigation_engine_for_target(target_id);
let mut affected_sessions = Vec::new();
if let Some(session_id) = primary_session_id.as_deref() {
@@ -2708,7 +2497,7 @@ impl CdpConnection {
}
CdpConnection::fail_pending_inspector_awaits_from_page_session_state_for_sessions_background_events_into(
out,
- &mut parked_aux_state.page_session_state,
+ target.state_mut(),
primary_session_id.as_deref(),
&affected_sessions,
reason,
@@ -2729,7 +2518,6 @@ impl CdpConnection {
target_id,
primary_session_id,
auxiliary_session_ids,
- next_active_target_id,
collected_network_data_artifacts,
) = {
let browser_context = self.browser_context.as_mut()?;
@@ -2737,32 +2525,24 @@ impl CdpConnection {
let primary_session_id = browser_context.active_session_id_owned();
let auxiliary_session_ids =
browser_context.remove_auxiliary_sessions_for_target(&target_id);
- let next_active_target_id = browser_context.last_promotable_background_target_id();
let collected_network_data_artifacts = browser_context
.active_target
.runtime_slot
.collected_network_data_artifacts();
browser_context.clear_active_target_session_scoped_state_without_loaded_page();
- browser_context
- .reset_active_target_slot_to_empty_async()
- .await;
+ browser_context.remove_active_page_target_async().await;
(
target_id,
primary_session_id,
auxiliary_session_ids,
- next_active_target_id,
collected_network_data_artifacts,
)
};
self.record_collected_network_data_artifacts(collected_network_data_artifacts);
- if let Some(next_active_target_id) = next_active_target_id.as_deref() {
- self.handoff_navigation_engine_for_target_activation(next_active_target_id);
- }
let promoted_target_id = if let Some(browser_context) = self.browser_context.as_mut() {
browser_context
.promote_last_background_target_to_active_async()
.await
- .map(|target| target.target_id().to_owned())
} else {
None
};
@@ -2818,9 +2598,7 @@ impl CdpConnection {
}
page_session_ids
.extend(browser_context.remove_auxiliary_sessions_for_target(target_id));
- browser_context
- .reset_active_target_slot_to_empty_async()
- .await;
+ browser_context.remove_active_page_target_async().await;
}
} else {
let close_background_target = {
@@ -2850,7 +2628,6 @@ impl CdpConnection {
for session_id in page_session_ids {
self.rollback_attached_session_without_event(&session_id);
}
- self.forget_retained_navigation_engine_for_target(target_id);
}
pub(crate) fn target_session_owner_aggregate_fetch_config(
@@ -3299,7 +3076,7 @@ impl CdpConnection {
is_auxiliary_target_session,
..
}
- | TargetSessionOwner::BackgroundTarget {
+ | TargetSessionOwner::PageTargetHost {
is_auxiliary_target_session,
..
} => Some(
@@ -3610,13 +3387,13 @@ impl CdpConnection {
is_current_active_browser_context,
})
}
- TargetSessionOwner::BackgroundTarget {
+ TargetSessionOwner::PageTargetHost {
browser_context_id,
target_id,
is_auxiliary_target_session,
} => self
.browser_context_by_id_mut(&browser_context_id)
- .map(|browser_context| TargetSessionOwnerMut::BackgroundTarget {
+ .map(|browser_context| TargetSessionOwnerMut::PageTargetHost {
browser_context,
target_id,
session_id: session_id.map(str::to_owned),
@@ -3643,13 +3420,13 @@ impl CdpConnection {
session_id: session_id.map(str::to_owned),
is_auxiliary_target_session,
}),
- TargetSessionOwner::BackgroundTarget {
+ TargetSessionOwner::PageTargetHost {
browser_context_id,
target_id,
is_auxiliary_target_session,
} => self
.browser_context_by_id(&browser_context_id)
- .map(|browser_context| TargetSessionOwnerRef::BackgroundTarget {
+ .map(|browser_context| TargetSessionOwnerRef::PageTargetHost {
browser_context,
target_id,
session_id: session_id.map(str::to_owned),
@@ -3727,6 +3504,16 @@ mod tests {
}
}
+ fn parked_target_context() -> BrowserContext {
+ let mut context = BrowserContext::new("BID-parked".to_owned());
+ context.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ None,
+ "about:blank".to_owned(),
+ ));
+ context
+ }
+
#[test]
fn target_session_owner_mut_mutates_active_and_parked_owner_state() {
let mut active = BrowserContext::new("BID-active".to_owned());
@@ -3752,9 +3539,9 @@ mod tests {
.is_crashed()
);
- let mut parked = BrowserContext::new("BID-parked".to_owned());
+ let mut parked = parked_target_context();
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -3790,13 +3577,11 @@ mod tests {
.active_target
.runtime_slot
.set_page_attachment_id_for_test(1);
- browser_context
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background-primary".to_owned()),
- "about:blank#background".to_owned(),
- ));
+ browser_context.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background-primary".to_owned()),
+ "about:blank#background".to_owned(),
+ ));
browser_context
.background_target_mut("TID-background")
.expect("background target")
@@ -3894,9 +3679,9 @@ mod tests {
.has_pending_subresource_fetch_for_test("FETCH-active")
);
- let mut parked = BrowserContext::new("BID-parked".to_owned());
+ let mut parked = parked_target_context();
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -3966,9 +3751,9 @@ mod tests {
.has_pending_subresource_fetch_for_test("FETCH-active")
);
- let mut parked = BrowserContext::new("BID-parked".to_owned());
+ let mut parked = parked_target_context();
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -3992,7 +3777,7 @@ mod tests {
assert!(
parked
.parked_page_session_state("TID-parked")
- .is_none_or(|state| !state.fetch_config.is_enabled())
+ .is_none_or(|state| !state.fetch_owner.is_enabled())
);
assert!(parked.parked_fetch_state("TID-parked").is_none());
@@ -4033,7 +3818,7 @@ mod tests {
assert_eq!(entries[0].url, "https://active.example/");
}
- let mut parked = BrowserContext::new("BID-parked".to_owned());
+ let mut parked = parked_target_context();
parked.mutate_parked_target_owner_state("TID-parked", |owner_state| {
owner_state.record_loaded_page_navigation_history((
"https://parked.example/".to_owned(),
@@ -4041,7 +3826,7 @@ mod tests {
));
});
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -4168,19 +3953,17 @@ mod tests {
.set_browser_identity_override(test_browser_identity("Active-Only-UA"));
parked.default_browser_identity_override =
Some(test_browser_identity("Browser-Context-Default-UA"));
- parked
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-parked".to_owned(),
- Some("SID-parked".to_owned()),
- "about:blank".to_owned(),
- ));
+ parked.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ Some("SID-parked".to_owned()),
+ "about:blank".to_owned(),
+ ));
parked.mutate_parked_page_session_state("TID-parked", |state| {
- state.network_enabled = true;
+ state.runtime_slot.enable_primary_network_events();
state
.network_policy
.push_extra_header(("X-Owner".to_owned(), "parked".to_owned()));
- state.fetch_config.configure(
+ state.fetch_owner.configure(
Some("SID-parked".to_owned()),
false,
vec![FetchInterceptionPattern {
@@ -4207,7 +3990,7 @@ mod tests {
.has_captured_response_body("REQ-old")
);
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: Some("SID-parked".to_owned()),
@@ -4253,7 +4036,8 @@ mod tests {
assert!(
preflight
.request_headers
- .contains(&("Accept-Language".to_owned(), "zh-CN".to_owned()))
+ .iter()
+ .all(|(name, _)| !name.eq_ignore_ascii_case("accept-language"))
);
assert!(preflight.request_headers.contains(&(
"User-Agent".to_owned(),
@@ -4276,18 +4060,16 @@ mod tests {
#[test]
fn target_session_owner_mut_observes_background_data_url_navigation_with_network_listener() {
let mut parked = BrowserContext::new("BID-parked".to_owned());
- parked
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-parked".to_owned(),
- Some("SID-parked".to_owned()),
- "about:blank".to_owned(),
- ));
+ parked.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ Some("SID-parked".to_owned()),
+ "about:blank".to_owned(),
+ ));
parked.mutate_parked_page_session_state("TID-parked", |state| {
- state.network_enabled = true;
+ state.runtime_slot.enable_primary_network_events();
});
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -4324,13 +4106,11 @@ mod tests {
fn target_session_owner_ref_snapshots_background_navigation_load_inputs() {
let mut parked = BrowserContext::new("BID-parked".to_owned());
parked.locale_override = Some("zh-CN".to_owned());
- parked
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-parked".to_owned(),
- Some("SID-parked".to_owned()),
- "https://parked.example/start".to_owned(),
- ));
+ parked.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ Some("SID-parked".to_owned()),
+ "https://parked.example/start".to_owned(),
+ ));
parked.mutate_parked_page_session_state("TID-parked", |state| {
state.locale_override = Some("fr-FR".to_owned());
state.timezone_override = Some("Europe/Paris".to_owned());
@@ -4349,7 +4129,7 @@ mod tests {
.network_policy
.push_extra_header(("X-Owner".to_owned(), "parked".to_owned()));
state.emulated_media.media = Some("print".to_owned());
- state.fetch_config.configure(
+ state.fetch_owner.configure(
Some("SID-parked".to_owned()),
false,
vec![FetchInterceptionPattern {
@@ -4364,6 +4144,7 @@ mod tests {
"1".to_owned(),
DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.fromParkedPreload = true;".to_owned(),
world_name: Some("utility".to_owned()),
has_bidi_channel_argument: false,
@@ -4372,15 +4153,14 @@ mod tests {
));
});
parked.mutate_parked_page_session_state("TID-parked", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.upsert_runtime_binding_definition(
"fromParkedBinding".to_owned(),
Some("utility".to_owned()),
);
});
- let owner = TargetSessionOwnerRef::BackgroundTarget {
+ let owner = TargetSessionOwnerRef::PageTargetHost {
browser_context: &parked,
target_id: "TID-parked".to_owned(),
session_id: Some("SID-parked".to_owned()),
@@ -4409,6 +4189,7 @@ mod tests {
assert_eq!(
inputs.runtime_bindings,
vec![RuntimeBindingDefinition {
+ devtools_session: Some(moli_page_types::DevToolsSessionKey::Primary),
name: "fromParkedBinding".to_owned(),
execution_context_name: Some("utility".to_owned()),
}]
@@ -4421,7 +4202,8 @@ mod tests {
assert!(
inputs
.extra_http_headers
- .contains(&("Accept-Language".to_owned(), "zh-CN".to_owned()))
+ .iter()
+ .all(|(name, _)| !name.eq_ignore_ascii_case("accept-language"))
);
assert_eq!(inputs.locale_override.as_deref(), Some("fr-FR"));
assert_eq!(inputs.timezone_override.as_deref(), Some("Europe/Paris"));
@@ -4451,23 +4233,19 @@ mod tests {
#[test]
fn target_session_owner_mut_prepares_background_navigation_commit_state() {
let mut parked = BrowserContext::new("BID-parked".to_owned());
- parked
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-parked".to_owned(),
- Some("SID-parked".to_owned()),
- "about:blank".to_owned(),
- ));
+ parked.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ Some("SID-parked".to_owned()),
+ "about:blank".to_owned(),
+ ));
parked.mutate_parked_page_session_state("TID-parked", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- state.fetch_config.configure(
+ state.fetch_owner.configure(
Some("SID-parked".to_owned()),
false,
vec![FetchInterceptionPattern {
@@ -4479,7 +4257,7 @@ mod tests {
});
let commit_state = {
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -4515,7 +4293,7 @@ mod tests {
timestamp: 0.0,
};
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -4546,13 +4324,11 @@ mod tests {
#[test]
fn target_session_owner_mut_clears_background_navigation_history_update() {
let mut parked = BrowserContext::new("BID-parked".to_owned());
- parked
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-parked".to_owned(),
- Some("SID-parked".to_owned()),
- "about:blank".to_owned(),
- ));
+ parked.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ Some("SID-parked".to_owned()),
+ "about:blank".to_owned(),
+ ));
parked.mutate_parked_target_owner_state("TID-parked", |owner_state| {
owner_state.record_loaded_page_navigation_history((
"https://old.example/".to_owned(),
@@ -4561,7 +4337,7 @@ mod tests {
owner_state.mark_next_navigation_history_replace_current();
});
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -4599,20 +4375,18 @@ mod tests {
.expect("page should load");
let page_url = page.final_url().clone();
let mut parked = BrowserContext::new("BID-parked".to_owned());
- parked
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-parked".to_owned(),
- Some("SID-parked".to_owned()),
- "about:blank".to_owned(),
- ));
+ parked.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-parked".to_owned(),
+ Some("SID-parked".to_owned()),
+ "about:blank".to_owned(),
+ ));
let initial_attachment_id = parked
.background_target("TID-parked")
.expect("background target")
.page_attachment_id();
{
- let mut owner = TargetSessionOwnerMut::BackgroundTarget {
+ let mut owner = TargetSessionOwnerMut::PageTargetHost {
browser_context: &mut parked,
target_id: "TID-parked".to_owned(),
session_id: None,
@@ -4754,20 +4528,16 @@ mod tests {
let mut browser_context = BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background".to_owned()),
- "about:blank".to_owned(),
- ));
- browser_context
- .devtools_session_state
+ browser_context.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background".to_owned()),
+ "about:blank".to_owned(),
+ ));
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
browser_context.mutate_parked_page_session_state("TID-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
});
@@ -4967,15 +4737,15 @@ mod tests {
active.set_active_target_id("TID-active".to_owned());
active.set_target_url("https://active.example/".to_owned());
active.attach_active_session("SID-active".to_owned());
- active
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background".to_owned()),
- "https://background.example/".to_owned(),
- ));
+ active.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background".to_owned()),
+ "https://background.example/".to_owned(),
+ ));
active.mutate_parked_page_session_state("TID-background", |state| {
- state.devtools_session_state.page_session_state.log_enabled = true;
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
});
assert!(
active.assign_auxiliary_session_to_target(
@@ -4988,9 +4758,8 @@ mod tests {
inactive.set_active_target_id("TID-inactive".to_owned());
inactive.set_target_url("https://inactive.example/".to_owned());
inactive
- .auxiliary_devtools_session_states
- .entry("SID-aux-inactive".to_owned())
- .or_default()
+ .devtools_sessions
+ .ensure_attached("SID-aux-inactive")
.console_output_session_state
.console_enabled = true;
assert!(
@@ -5094,13 +4863,11 @@ mod tests {
let mut conn = CdpConnection::default();
let mut browser_context = BrowserContext::new("BID-dialog-scope".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
- browser_context
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
- "TID-background-dialog".to_owned(),
- Some("SID-background-dialog".to_owned()),
- "https://background.example/dialog".to_owned(),
- ));
+ browser_context.insert_page_target_host(crate::conn::PageTargetHost::with_url(
+ "TID-background-dialog".to_owned(),
+ Some("SID-background-dialog".to_owned()),
+ "https://background.example/dialog".to_owned(),
+ ));
assert!(
browser_context
.parked_page_session_state("TID-background-dialog")
diff --git a/moli-protocol/src/conn/cookie_manager_surface.rs b/moli-protocol/src/conn/cookie_manager_surface.rs
index ca308b69e..02196b814 100644
--- a/moli-protocol/src/conn/cookie_manager_surface.rs
+++ b/moli-protocol/src/conn/cookie_manager_surface.rs
@@ -915,19 +915,6 @@ pub(crate) struct BrowserContextCookieManagerSurface {
}
impl BrowserContextCookieManagerSurface {
- pub(crate) fn from_snapshot(snapshot: BrowserContextCookieManagerSurfaceSnapshot) -> Self {
- Self {
- policy_surface: BrowserContextDocumentCookiePolicySurface::from_snapshot(
- super::cookie_policy_surface::BrowserContextDocumentCookiePolicySurfaceSnapshot {
- overrides: snapshot.policy.overrides,
- cookies_enabled_override: snapshot.policy.cookies_enabled_override,
- browser_context_overrides: snapshot.policy.browser_context_overrides,
- generation: snapshot.policy.generation,
- },
- ),
- }
- }
-
pub(crate) fn snapshot(&self) -> BrowserContextCookieManagerSurfaceSnapshot {
let policy_surface = self.policy_surface.snapshot();
BrowserContextCookieManagerSurfaceSnapshot {
diff --git a/moli-protocol/src/conn/cookie_owner.rs b/moli-protocol/src/conn/cookie_owner.rs
index e3d7c1b87..3b2999825 100644
--- a/moli-protocol/src/conn/cookie_owner.rs
+++ b/moli-protocol/src/conn/cookie_owner.rs
@@ -196,28 +196,18 @@ fn browser_context_cookie_manager_surface_snapshot(
) -> BrowserContextCookieManagerSurfaceSnapshot {
let snapshot = browser_context.raw_cookie_manager_surface_snapshot();
let current_document_url = browser_context
- .active_target
- .runtime_slot
.loaded_page()
.map(|page| page.final_url().clone());
let navigation_initiator_url = browser_context
- .active_target
- .runtime_slot
.loaded_page()
.and_then(|page| page.navigation_initiator_url().cloned());
let requested_document_url = browser_context
- .active_target
- .runtime_slot
.loaded_page()
.map(|page| page.requested_url().clone());
let navigation_was_redirected = browser_context
- .active_target
- .runtime_slot
.loaded_page()
.is_some_and(|page| page.navigation_redirected());
let navigation_redirect_count = browser_context
- .active_target
- .runtime_slot
.loaded_page()
.map(|page| page.navigation_redirect_count())
.unwrap_or(0);
@@ -554,7 +544,11 @@ impl BrowserContext {
pub(crate) async fn document_cookie_owner_snapshot_async(
&mut self,
) -> Option<DocumentCookieOwnerSnapshot> {
- let page = self.active_target.runtime_slot.loaded_page_mut()?;
+ let page = self
+ .page_targets
+ .active_mut()?
+ .runtime_slot
+ .loaded_page_mut()?;
page.document_cookie_owner_snapshot_async().await.ok()
}
@@ -566,8 +560,6 @@ impl BrowserContext {
// document URL into every `set()` call. Prefer the live page URL when
// one exists; otherwise fall back to the BrowserContext's current URL.
if let Some(url) = self
- .active_target
- .runtime_slot
.loaded_page()
.map(|page| page.final_url().clone())
.filter(|url| matches!(url.scheme(), "http" | "https"))
@@ -578,8 +570,10 @@ impl BrowserContext {
);
}
- if let Some(url) = Url::parse(self.target_url())
- .ok()
+ if let Some(url) = self
+ .page_targets
+ .active()
+ .and_then(|host| Url::parse(host.target_url()).ok())
.filter(|url| matches!(url.scheme(), "http" | "https"))
{
return (
diff --git a/moli-protocol/src/conn/cookie_policy_surface.rs b/moli-protocol/src/conn/cookie_policy_surface.rs
index fdc3a2804..fb36cc3c3 100644
--- a/moli-protocol/src/conn/cookie_policy_surface.rs
+++ b/moli-protocol/src/conn/cookie_policy_surface.rs
@@ -17,20 +17,6 @@ pub(crate) struct BrowserContextDocumentCookiePolicySurface {
}
impl BrowserContextDocumentCookiePolicySurface {
- pub(crate) fn from_snapshot(
- snapshot: BrowserContextDocumentCookiePolicySurfaceSnapshot,
- ) -> Self {
- let mut overrides = snapshot.overrides;
- overrides.cookies_enabled = snapshot.cookies_enabled_override;
- overrides.site_for_cookies_url = snapshot.browser_context_overrides.site_for_cookies_url;
- overrides.top_frame_origin_url = snapshot.browser_context_overrides.top_frame_origin_url;
- overrides.storage_access_status = snapshot.browser_context_overrides.storage_access_status;
- Self {
- overrides,
- generation: snapshot.generation,
- }
- }
-
pub(crate) fn snapshot(&self) -> BrowserContextDocumentCookiePolicySurfaceSnapshot {
BrowserContextDocumentCookiePolicySurfaceSnapshot {
overrides: self.overrides.clone(),
diff --git a/moli-protocol/src/conn/dispatch_tests.rs b/moli-protocol/src/conn/dispatch_tests.rs
index ae65412c7..f7cfe3b1b 100644
--- a/moli-protocol/src/conn/dispatch_tests.rs
+++ b/moli-protocol/src/conn/dispatch_tests.rs
@@ -289,16 +289,17 @@ fn connection_with_background_pending_fetch_action(request_id: &str) -> CdpConne
let mut browser_context = BrowserContext::new("BID-fetch-background".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background".to_owned()),
+ "https://example.test/background".to_owned(),
+ ));
browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background".to_owned()),
- "https://example.test/background".to_owned(),
- ));
- let mut fetch_state = browser_context.take_parked_fetch_state("TID-background");
- fetch_state.insert_pending_fetch_request_id_for_test(request_id.to_owned());
- browser_context.replace_parked_fetch_state("TID-background".to_owned(), fetch_state);
+ .background_target_mut("TID-background")
+ .expect("background target")
+ .fetch_owner
+ .pending_state_mut()
+ .insert_pending_fetch_request_id_for_test(request_id.to_owned());
conn.browser_context = Some(browser_context);
conn
}
@@ -310,7 +311,7 @@ async fn assert_bidi_fetch_action_consumes_background_request(
let mut conn = connection_with_background_pending_fetch_action(request_id);
assert!(matches!(
conn.pending_fetch_request_session_route(request_id),
- Some(CdpSessionRoute::BackgroundTarget { target_id, .. }) if target_id == "TID-background"
+ Some(CdpSessionRoute::PageTargetHost { target_id, .. }) if target_id == "TID-background"
));
let (result, events, protocol_events, renderer_output_predecessor) = conn
@@ -686,13 +687,11 @@ async fn bidi_fetch_control_resolves_background_request_owner() {
let mut browser_context = BrowserContext::new("BID-fetch-background".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background".to_owned()),
- "https://example.test/background".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background".to_owned()),
+ "https://example.test/background".to_owned(),
+ ));
conn.browser_context = Some(browser_context);
conn.register_pending_fetch_navigation_request_for_session_owner(
@@ -729,7 +728,7 @@ async fn bidi_fetch_control_resolves_background_request_owner() {
assert!(matches!(
conn.pending_fetch_request_session_route("FETCH-background"),
- Some(CdpSessionRoute::BackgroundTarget { target_id, .. }) if target_id == "TID-background"
+ Some(CdpSessionRoute::PageTargetHost { target_id, .. }) if target_id == "TID-background"
));
let context = DevToolsCommandContext {
@@ -846,13 +845,16 @@ async fn devtools_browser_context_commands_create_list_and_remove_user_context()
let created_context = conn
.browser_context_by_id("user-context-1")
.expect("created browser context");
- assert_eq!(created_context.tls_verify_host_override, Some(false));
assert_eq!(
- created_context.http_proxy_override.as_deref(),
+ created_context.default_tls_verify_host_override,
+ Some(false)
+ );
+ assert_eq!(
+ created_context.default_http_proxy_override.as_deref(),
Some("127.0.0.1:80")
);
assert_eq!(
- created_context.http_no_proxy_override.as_deref(),
+ created_context.default_http_no_proxy_override.as_deref(),
Some("localhost,127.0.0.1")
);
assert_eq!(created_context.proxy_autoconfig_url, None);
@@ -971,7 +973,7 @@ async fn devtools_browser_context_create_preserves_proxy_autoconfig_and_socks_me
.browser_context_by_id(create_result.browser_context_id.as_str())
.expect("created browser context");
assert_eq!(
- created_context.http_proxy_override.as_deref(),
+ created_context.default_http_proxy_override.as_deref(),
Some("socks5://[::1]:1080")
);
assert_eq!(
@@ -3178,15 +3180,13 @@ async fn devtools_create_target_can_activate_created_target() {
);
assert!(
browser_context
- .background_targets
- .iter()
+ .background_targets()
.any(|target| target.target_id() == "TID-1"),
"the previous active target should be preserved as a background target"
);
assert!(
browser_context
- .background_targets
- .iter()
+ .background_targets()
.find(|target| target.target_id() == "TID-1")
.is_some_and(|target| target.has_loaded_page()),
"the previous active page should move into the demoted target slot"
@@ -4628,8 +4628,8 @@ async fn devtools_command_applies_known_user_context_viewport_default() {
.browser_context_by_id("custom-user-context")
.expect("custom user context should exist");
assert!(
- browser_context.emulated_device_metrics.is_none(),
- "userContext viewport should not install a target-scoped active override"
+ browser_context.active_target_id().is_none(),
+ "userContext viewport should not create a page target"
);
let default_metrics = browser_context
.default_emulated_device_metrics
@@ -8567,8 +8567,7 @@ async fn devtools_network_intercept_commands_route_to_fetch_owner() {
conn.browser_context
.as_mut()
.expect("browser context")
- .background_targets
- .push(BackgroundTarget::with_url(
+ .insert_page_target_host(PageTargetHost::with_url(
"TID-bidi-intercept-background".to_owned(),
None,
"https://example.test/background".to_owned(),
@@ -8593,7 +8592,7 @@ async fn devtools_network_intercept_commands_route_to_fetch_owner() {
.as_ref()
.expect("browser context")
.parked_page_session_state("TID-bidi-intercept-background")
- .is_some_and(|state| state.fetch_config.is_enabled()),
+ .is_some_and(|state| state.fetch_owner.is_enabled()),
"background target should own the intercept"
);
@@ -8615,7 +8614,7 @@ async fn devtools_network_intercept_commands_route_to_fetch_owner() {
.as_ref()
.expect("browser context")
.parked_page_session_state("TID-bidi-intercept-background")
- .is_none_or(|state| !state.fetch_config.is_enabled()),
+ .is_none_or(|state| !state.fetch_owner.is_enabled()),
"target-less remove should clear the background intercept"
);
diff --git a/moli-protocol/src/conn/inspector_route.rs b/moli-protocol/src/conn/inspector_route.rs
index 7d7369830..46305a449 100644
--- a/moli-protocol/src/conn/inspector_route.rs
+++ b/moli-protocol/src/conn/inspector_route.rs
@@ -248,7 +248,7 @@ mod tests {
use serde_json::json;
use super::*;
- use crate::conn::{BackgroundTarget, BrowserContext};
+ use crate::conn::{BrowserContext, PageTargetHost};
use crate::testing::TestContext;
fn batch(session: DevToolsSessionKey) -> RendererRuntimeInspectorMessageBatch {
@@ -267,13 +267,11 @@ mod tests {
let mut browser_context = BrowserContext::new("BID-route".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active-primary".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-background".to_owned(),
- Some("SID-background-primary".to_owned()),
- "about:blank#background".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-background".to_owned(),
+ Some("SID-background-primary".to_owned()),
+ "about:blank#background".to_owned(),
+ ));
assert!(
browser_context
.assign_auxiliary_session_to_target("TID-active", "SID-active-aux".to_owned(),)
@@ -348,7 +346,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state
.v8_state,
Some(accepted_state.clone())
@@ -373,7 +371,9 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .auxiliary_devtools_session_states["SID-state-aux"]
+ .devtools_sessions
+ .attached("SID-state-aux")
+ .expect("auxiliary session state")
.inspector_session_state
.v8_state,
Some(auxiliary_state),
@@ -422,7 +422,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state
.v8_state,
Some(route_completed_state)
@@ -452,7 +452,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state
.v8_state,
Some(response_state),
diff --git a/moli-protocol/src/conn/page_state/fetch_state.rs b/moli-protocol/src/conn/page_state/fetch_state.rs
index 227eb9b69..68249b3ab 100644
--- a/moli-protocol/src/conn/page_state/fetch_state.rs
+++ b/moli-protocol/src/conn/page_state/fetch_state.rs
@@ -1,5 +1,5 @@
use super::super::{
- BackgroundTarget, BrowserContext, ConnectionNetworkRequestIdAllocator, PausedDocumentTransfer,
+ BrowserContext, ConnectionNetworkRequestIdAllocator, PageTargetHost, PausedDocumentTransfer,
PendingFetchAuthNavigation, PendingFetchNavigation, PendingSubresourceFetchAuthRequest,
PendingSubresourceFetchRequest, PendingSubresourceFetchResponseRequest,
};
@@ -11,19 +11,62 @@ fn document_navigation_loader_id(sequence: u64) -> String {
}
impl BrowserContext {
- pub fn background_target(&self, target_id: &str) -> Option<&BackgroundTarget> {
- self.background_targets
- .iter()
- .find(|target| target.is_target(target_id))
+ pub(crate) fn page_target(&self, target_id: &str) -> Option<&PageTargetHost> {
+ self.page_targets.get(target_id)
}
- pub(crate) fn background_target_mut(
+ pub(crate) fn page_target_mut(&mut self, target_id: &str) -> Option<&mut PageTargetHost> {
+ self.page_targets.get_mut(target_id)
+ }
+
+ pub fn background_target(&self, target_id: &str) -> Option<&PageTargetHost> {
+ (!self.is_active_target(target_id))
+ .then(|| self.page_target(target_id))
+ .flatten()
+ }
+
+ pub(crate) fn background_target_mut(&mut self, target_id: &str) -> Option<&mut PageTargetHost> {
+ if self.is_active_target(target_id) {
+ return None;
+ }
+ self.page_target_mut(target_id)
+ }
+
+ pub(crate) fn background_targets(&self) -> impl DoubleEndedIterator<Item = &PageTargetHost> {
+ self.page_targets.background()
+ }
+
+ pub(crate) fn background_targets_mut(
&mut self,
- target_id: &str,
- ) -> Option<&mut BackgroundTarget> {
- self.background_targets
- .iter_mut()
- .find(|target| target.is_target(target_id))
+ ) -> impl DoubleEndedIterator<Item = &mut PageTargetHost> {
+ self.page_targets.background_mut()
+ }
+
+ pub(crate) fn background_target_at(&self, index: usize) -> Option<&PageTargetHost> {
+ self.page_targets.background_at(index)
+ }
+
+ pub(crate) fn background_target_at_mut(&mut self, index: usize) -> Option<&mut PageTargetHost> {
+ self.page_targets.background_at_mut(index)
+ }
+
+ pub(crate) fn background_target_count(&self) -> usize {
+ self.page_targets.background_len()
+ }
+
+ pub(crate) fn has_no_background_targets(&self) -> bool {
+ self.page_targets.background_is_empty()
+ }
+
+ pub(crate) fn insert_page_target_host(&mut self, mut host: PageTargetHost) -> bool {
+ host.network_policy
+ .set_cache_disabled(self.global_cache_disabled);
+ if let Some(config) = self.page_navigation_runtime_config.clone() {
+ let engine = self.new_page_navigation_engine(config);
+ let replaced = host.replace_navigation_engine(engine);
+ debug_assert!(replaced.is_none());
+ }
+ self.page_targets.insert(host)
}
pub(crate) fn take_active_target_pending_fetch_state(
@@ -49,10 +92,16 @@ impl BrowserContext {
request_id: &str,
) -> Result<Option<String>, String> {
let handle = self.active_target.runtime_slot.allocate_io_stream_handle();
- self.active_target
+ let active_target = &mut self
+ .page_targets
+ .active_mut()
+ .expect("cannot open a response stream without an active page target")
+ .state_mut()
+ .active_target;
+ active_target
.fetch_owner
.open_pending_fetch_response_body_stream(
- &mut self.active_target.runtime_slot,
+ &mut active_target.runtime_slot,
request_id,
handle,
)
@@ -168,9 +217,9 @@ impl BrowserContext {
}
pub(crate) fn clear_network_body_artifacts(&mut self) {
- self.active_target
- .runtime_slot
- .clear_network_body_artifacts();
+ for target in self.page_targets.iter_mut() {
+ target.runtime_slot.clear_network_body_artifacts();
+ }
}
pub(crate) fn remove_captured_response_body_visibility_for_session(
@@ -241,12 +290,6 @@ impl BrowserContext {
.clear_session_scoped_network_observation_artifacts();
}
- pub(crate) fn reset_target_scoped_network_artifacts(&mut self) {
- self.active_target
- .runtime_slot
- .reset_all_target_scoped_network_artifacts();
- }
-
#[cfg(test)]
pub(crate) fn has_captured_response_body_for_test(&self, request_id: &str) -> bool {
self.active_target
@@ -332,7 +375,7 @@ impl BrowserContext {
}
}
-impl BackgroundTarget {
+impl PageTargetHost {
pub(crate) fn prepare_document_navigation_request_ids(
&mut self,
network_request_id_allocator: &mut ConnectionNetworkRequestIdAllocator,
diff --git a/moli-protocol/src/conn/page_state/loaded.rs b/moli-protocol/src/conn/page_state/loaded.rs
index 4a6703e75..bf22da082 100644
--- a/moli-protocol/src/conn/page_state/loaded.rs
+++ b/moli-protocol/src/conn/page_state/loaded.rs
@@ -1,9 +1,8 @@
use super::super::state::{
CommittedRendererAgentAttachment, PreparedRendererAgentAttachment, TargetPageAbsenceReason,
- TargetPageAttachmentId, prepare_renderer_call_replacements_for_devtools_sessions,
- runtime_bindings_for_renderer,
+ TargetPageAttachmentId,
};
-use super::super::{BackgroundTarget, BrowserContext, TargetRuntimeSlot};
+use super::super::{BrowserContext, PageTargetHost, TargetRuntimeSlot};
use crate::conn::TargetPageResidenceIdentity;
use moli_core::page::{Page, RendererPageCommandPostResponseContinuation};
use url::Url;
@@ -25,96 +24,39 @@ impl BrowserContext {
}
pub(crate) fn loaded_page(&self) -> Option<&Page> {
- self.active_target.runtime_slot.loaded_page()
+ self.page_targets
+ .active()
+ .and_then(|host| host.runtime_slot.loaded_page())
}
pub(crate) fn has_loaded_page(&self) -> bool {
- self.active_target.runtime_slot.has_loaded_page()
+ self.page_targets
+ .active()
+ .is_some_and(|host| host.runtime_slot.has_loaded_page())
}
pub(crate) fn page_attachment_id(&self) -> Option<TargetPageAttachmentId> {
- self.active_target.runtime_slot.page_attachment_id()
+ self.page_targets
+ .active()
+ .and_then(|host| host.runtime_slot.page_attachment_id())
}
fn clear_active_target_session_scoped_state_fields(&mut self) {
- let retained_runtime_bindings = runtime_bindings_for_renderer(
- &self.devtools_session_state,
- &self.auxiliary_devtools_session_states,
- );
- self.devtools_session_state
- .page_session_state
- .page_lifecycle_events = false;
- self.devtools_session_state = Default::default();
- self.auxiliary_devtools_session_states.clear();
- self.devtools_session_state.runtime_bindings = retained_runtime_bindings;
- self.devtools_session_state.page_session_state.log_enabled = false;
- self.devtools_session_state
- .console_output_session_state
- .console_enabled = false;
- self.devtools_session_state
- .page_session_state
- .performance
- .disable();
- self.active_target
- .runtime_slot
- .disable_primary_network_events();
- self.network_policy.clear_session_scoped_overrides();
- self.tls_verify_host_override = None;
- self.http_proxy_override = None;
- self.http_no_proxy_override = None;
- self.locale_override = None;
- self.timezone_override = None;
- self.network_conditions = None;
- self.geolocation_override = None;
- self.emulated_media = Default::default();
- self.emulated_device_metrics = None;
- self.cpu_throttling_rate = 1.0;
- self.devtools_session_state
- .page_session_state
- .page_bypass_csp_enabled = false;
- self.devtools_session_state
- .page_session_state
- .page_font_families
- .clear();
- self.devtools_session_state
- .page_session_state
- .page_file_chooser_opened_event_enabled = false;
- self.devtools_session_state
- .page_session_state
- .page_intercept_file_chooser_dialog_enabled = false;
- self.touch_emulation_enabled = false;
- self.emit_touch_events_for_mouse = false;
- self.focus_emulation_enabled = false;
- self.script_execution_disabled = false;
- self.css_enabled = false;
- self.active_target.fetch_owner.reset_config();
- self.clear_pending_fetch_state();
- self.clear_session_scoped_network_observation_artifacts();
- self.active_target
- .runtime_slot
- .request_id_allocator()
- .reset_fetch_navigation_request_counter();
- self.active_target
- .owner_state
- .clear_observable_output_state();
+ self.active_page_state_mut()
+ .clear_session_scoped_state_fields(false);
}
fn clear_active_target_loaded_document_session_state(&mut self) {
- self.devtools_session_state
- .page_session_state
- .clear_loaded_document_context_state();
- for state in self.auxiliary_devtools_session_states.values_mut() {
- state
+ for session in self.devtools_sessions.states_mut() {
+ session
.page_session_state
.clear_loaded_document_context_state();
}
}
pub(crate) fn clear_active_target_runtime_remote_object_tracking(&mut self) {
- self.devtools_session_state
- .clear_runtime_remote_object_tracking();
- for state in self.auxiliary_devtools_session_states.values_mut() {
- state.clear_runtime_remote_object_tracking();
+ for session in self.devtools_sessions.states_mut() {
+ session.clear_runtime_remote_object_tracking();
}
}
@@ -233,15 +175,6 @@ impl BrowserContext {
.ingest_owner_page_observable_output_updates()
}
- async fn close_loaded_page_async(&mut self) -> bool {
- let page = self.clear_loaded_page_with_reason(TargetPageAbsenceReason::TargetClosed);
- let had_page = page.is_some();
- if let Some(page) = page {
- Self::close_page_best_effort(page).await;
- }
- had_page
- }
-
pub(crate) async fn commit_loaded_navigation_page_async(
&mut self,
mut page: Page,
@@ -283,14 +216,16 @@ impl BrowserContext {
if let Some(previous_attachment) = previous_attachment
&& previous_attachment.id() != new_attachment_id
{
- let replacements = prepare_renderer_call_replacements_for_devtools_sessions(
- primary_session_id.as_deref(),
- &mut self.devtools_session_state,
- &mut self.auxiliary_devtools_session_states,
- previous_attachment.id(),
- new_attachment_id,
- )?;
- self.active_target
+ let page_state = self.active_page_state_mut();
+ let replacements = page_state
+ .devtools_sessions
+ .prepare_renderer_call_replacements(
+ primary_session_id.as_deref(),
+ previous_attachment.id(),
+ new_attachment_id,
+ )?;
+ page_state
+ .active_target
.runtime_slot
.install_pending_renderer_call_replacements(replacements);
}
@@ -372,66 +307,28 @@ impl BrowserContext {
self.clear_session_scoped_network_observation_artifacts();
}
- pub(crate) async fn close_active_target_after_page_close_async(&mut self) {
- if let Some(target_id) = self.active_target_id_owned() {
- self.forget_target_opener_references_for_target(&target_id);
- self.forget_target_window_names_for_target(&target_id);
- self.forget_target_popup_id_for_target(&target_id);
- }
- self.clear_active_target_session_scoped_state_fields();
- self.active_target.owner_state.target_crash_state.clear();
- self.clear_active_target_id();
- self.clear_document_navigation_state_for_active_target();
- self.detach_active_session();
- self.close_loaded_page_async().await;
- self.active_target.owner_state.clear_page_local_state();
- self.reset_target_identity_to_about_blank();
- self.reset_target_scoped_network_artifacts();
- self.active_target
- .owner_state
- .clear_observable_output_state();
- self.active_target
- .runtime_slot
- .request_id_allocator()
- .reset_subresource_fetch_request_counter();
- }
-
- pub(crate) async fn reset_active_target_slot_to_empty_async(&mut self) {
- self.clear_active_target_session_scoped_state_fields();
- self.active_target.owner_state.target_crash_state.clear();
- if let Some(target_id) = self.active_target_id_owned() {
- self.forget_target_opener_references_for_target(&target_id);
- self.forget_target_window_names_for_target(&target_id);
- self.forget_target_popup_id_for_target(&target_id);
- }
- self.detach_active_session();
- self.clear_active_target_id();
- self.clear_document_navigation_state_for_active_target();
- self.close_loaded_page_async().await;
- self.clear_pending_fetch_state();
- self.active_target.owner_state.clear_page_local_state();
- self.restore_raw_cookie_manager_surface_async(Default::default())
- .await;
- self.reset_target_identity_to_new_tab();
- self.reset_target_scoped_network_artifacts();
- self.active_target
- .owner_state
- .clear_observable_output_state();
- self.active_target
- .runtime_slot
- .request_id_allocator()
- .reset_subresource_fetch_request_counter();
+ pub(crate) async fn remove_active_page_target_async(&mut self) -> bool {
+ let Some(target_id) = self.active_target_id_owned() else {
+ return false;
+ };
+ self.forget_target_opener_references_for_target(&target_id);
+ self.forget_target_window_names_for_target(&target_id);
+ self.forget_target_popup_id_for_target(&target_id);
+ let Some(mut host) = self.page_targets.remove(&target_id) else {
+ return false;
+ };
+ host.close_page_async().await;
+ true
}
pub(crate) async fn close_all_pages_async(&mut self) {
- self.close_loaded_page_async().await;
- for target in &mut self.background_targets {
+ for target in self.page_targets.iter_mut() {
target.close_page_async().await;
}
}
}
-impl BackgroundTarget {
+impl PageTargetHost {
pub(crate) fn target_url(&self) -> &str {
self.target_identity.url()
}
diff --git a/moli-protocol/src/conn/page_state/parked.rs b/moli-protocol/src/conn/page_state/parked.rs
index 03de3cbe5..ddfafa601 100644
--- a/moli-protocol/src/conn/page_state/parked.rs
+++ b/moli-protocol/src/conn/page_state/parked.rs
@@ -1,26 +1,21 @@
-use super::super::cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot;
-use super::super::state::{
- TargetPageAbsenceReason, TargetSessionStorageNamespace, runtime_bindings_for_renderer,
-};
+use super::super::state::{TargetPageAbsenceReason, TargetSessionStorageNamespace};
use super::super::{
- BackgroundTarget, BrowserContext, DedicatedWorkerTargetState, IsolatedWorldDefinition,
- ParkedFetchState, ParkedNetworkArtifacts, ParkedPageSessionState, ParkedTargetAuxState,
+ BrowserContext, DedicatedWorkerTargetState, IsolatedWorldDefinition, PageTargetHost,
ParkedTargetOwnerState, ServiceWorkerTargetState, SharedWorkerTargetState, TargetIdentityState,
- TargetInitialEmptyDocumentCreator, TargetSlotState,
+ TargetInitialEmptyDocumentCreator,
};
-use crate::conn::state::{DevToolsSessionState, TargetFetchConfig, TargetNetworkPolicyState};
+use crate::conn::state::{DevToolsSessionState, TargetNetworkPolicyState};
use crate::devtools_runtime::{
DevToolsBrowserContextId, DevToolsTargetId, DevToolsTargetInfo, DevToolsTargetKind,
};
use moli_core::network::SharedWebStorageStore;
impl BrowserContext {
- pub fn remove_background_target(&mut self, target_id: &str) -> Option<BackgroundTarget> {
- let index = self
- .background_targets
- .iter()
- .position(|target| target.is_target(target_id))?;
- Some(self.background_targets.swap_remove(index))
+ pub fn remove_background_target(&mut self, target_id: &str) -> Option<PageTargetHost> {
+ if self.is_active_target(target_id) {
+ return None;
+ }
+ self.page_targets.remove(target_id)
}
pub(crate) fn stage_background_target(
@@ -77,7 +72,7 @@ impl BrowserContext {
return Some(self.active_target.session_storage_namespace.deep_clone());
}
self.background_target(creator.target_id())
- .map(BackgroundTarget::deep_clone_session_storage_namespace)
+ .map(PageTargetHost::deep_clone_session_storage_namespace)
})
}
@@ -92,19 +87,19 @@ impl BrowserContext {
session_storage_namespace: Option<TargetSessionStorageNamespace>,
) {
let target_identity = background_target_identity_for_initial_url(&url, creator.as_ref());
- self.mutate_parked_target_owner_state(&target_id, |owner_state| {
- owner_state.begin_initial_empty_document(
- target_id.clone(),
- initial_empty_document_url.unwrap_or_else(|| url.clone()),
- creator,
- initial_empty_document_storage_key,
- );
- });
- let mut target = BackgroundTarget::with_identity(target_id, session_id, target_identity);
+ let mut target = PageTargetHost::with_identity(target_id, session_id, target_identity);
+ let target_id = target.target_id().to_owned();
+ target.state_mut().owner_state.begin_initial_empty_document(
+ target_id,
+ initial_empty_document_url.unwrap_or_else(|| url.clone()),
+ creator,
+ initial_empty_document_storage_key,
+ );
if let Some(namespace) = session_storage_namespace {
target.replace_session_storage_namespace(namespace);
}
- self.background_targets.push(target);
+ let inserted = self.insert_page_target_host(target);
+ debug_assert!(inserted, "staged page target id must be unique");
}
pub(crate) fn stage_active_target_demoting_current(
@@ -114,30 +109,21 @@ impl BrowserContext {
url: String,
initial_empty_document_url: Option<String>,
) {
- let previous_active_slot = self.take_active_target_slot_state();
- self.set_active_target_id(target_id.clone());
- self.replace_active_session(session_id);
- self.replace_target_identity(TargetIdentityState::with_url(url.clone()));
- self.clear_active_target_session_scoped_state_without_loaded_page();
- self.active_target.owner_state.clear_page_local_state();
- self.active_target.owner_state.begin_initial_empty_document(
- target_id,
+ let mut host = PageTargetHost::with_identity(
+ target_id.clone(),
+ session_id,
+ TargetIdentityState::with_url(url.clone()),
+ );
+ host.owner_state.begin_initial_empty_document(
+ target_id.clone(),
initial_empty_document_url.unwrap_or(url),
None,
None,
);
- self.reset_target_scoped_network_artifacts();
- self.active_target
- .owner_state
- .clear_observable_output_state();
- self.active_target.owner_state.target_crash_state.clear();
- self.active_target
- .runtime_slot
- .request_id_allocator()
- .reset_subresource_fetch_request_counter();
- if let Some(active_slot) = previous_active_slot {
- self.replace_background_target_slot(*active_slot);
- }
+ let inserted = self.insert_page_target_host(host);
+ debug_assert!(inserted, "new active page target id must be unique");
+ let selected = self.page_targets.select(&target_id);
+ debug_assert!(selected, "newly inserted page target must be selectable");
}
pub(crate) fn reusable_window_open_target_name(target_name: &str) -> Option<String> {
@@ -156,7 +142,7 @@ impl BrowserContext {
self.active_target
.owner_state
.has_attached_child_frame_id(frame_id)
- || self.background_targets.iter().any(|target| {
+ || self.background_targets().any(|target| {
self.parked_target_owner_state(target.target_id())
.is_some_and(|owner_state| owner_state.has_attached_child_frame_id(frame_id))
})
@@ -251,11 +237,7 @@ impl BrowserContext {
self.active_target.owner_state.target_crash_state.clear();
return true;
}
- if let Some(target) = self
- .background_targets
- .iter_mut()
- .find(|target| target.is_target(target_id))
- {
+ if let Some(target) = self.background_target_mut(target_id) {
target.set_target_url(url);
return true;
}
@@ -266,11 +248,7 @@ impl BrowserContext {
if self.is_active_target(target_id) {
self.attach_active_session(session_id);
true
- } else if let Some(target) = self
- .background_targets
- .iter_mut()
- .find(|target| target.is_target(target_id))
- {
+ } else if let Some(target) = self.background_target_mut(target_id) {
target.attach_session(session_id);
true
} else {
@@ -290,11 +268,7 @@ impl BrowserContext {
self.attach_active_session(session_id);
true
}
- } else if let Some(target) = self
- .background_targets
- .iter_mut()
- .find(|target| target.is_target(target_id))
- {
+ } else if let Some(target) = self.background_target_mut(target_id) {
if target.has_session() {
self.assign_auxiliary_session_to_target(target_id, session_id)
} else {
@@ -311,12 +285,7 @@ impl BrowserContext {
target_id: &str,
session_id: String,
) -> bool {
- if self.is_active_target(target_id)
- || self
- .background_targets
- .iter()
- .any(|target| target.is_target(target_id))
- {
+ if self.is_active_target(target_id) || self.background_target(target_id).is_some() {
self.auxiliary_target_sessions
.insert(session_id, target_id.to_owned());
true
@@ -361,35 +330,139 @@ impl BrowserContext {
}
pub(crate) fn remove_auxiliary_session(&mut self, session_id: &str) -> Option<String> {
- self.active_target
- .runtime_slot
- .remove_auxiliary_network_session(session_id);
- self.active_target
- .fetch_owner
- .remove_fetch_session(Some(session_id));
- self.auxiliary_devtools_session_states.remove(session_id);
let target_id = self.auxiliary_target_sessions.remove(session_id)?;
- if let Some(target) = self.background_target_mut(&target_id) {
+ if self.is_active_target(&target_id) {
+ self.active_target
+ .runtime_slot
+ .remove_auxiliary_network_session(session_id);
+ self.active_target
+ .fetch_owner
+ .remove_fetch_session(Some(session_id));
+ self.devtools_sessions.remove_attached(session_id);
+ } else if let Some(target) = self.background_target_mut(&target_id) {
target
.runtime_slot
.remove_auxiliary_network_session(session_id);
- }
- self.mutate_parked_page_session_state(&target_id, |state| {
- state.auxiliary_devtools_session_states.remove(session_id);
- state.fetch_config.remove_fetch_session(Some(session_id));
- });
- if self
- .background_targets
- .iter()
- .any(|target| target.is_target(&target_id))
- {
- self.mutate_parked_network_artifacts(&target_id, |artifacts| {
- artifacts.remove_session_observation_cursor(Some(session_id));
- });
+ target.devtools_sessions.remove_attached(session_id);
+ target.fetch_owner.remove_fetch_session(Some(session_id));
+ target
+ .runtime_slot
+ .remove_network_session_observation_cursor(Some(session_id));
}
Some(target_id)
}
+ pub(crate) async fn clear_target_session_overrides_async(
+ &mut self,
+ session_id: &str,
+ ) -> Result<bool, String> {
+ let Some(target_id) = (self.active_session_id() == Some(session_id))
+ .then(|| self.active_target_id_owned())
+ .flatten()
+ .or_else(|| {
+ self.background_targets()
+ .find(|target| target.is_session(session_id))
+ .map(|target| target.target_id().to_owned())
+ })
+ .or_else(|| {
+ self.auxiliary_target_id_for_session(session_id)
+ .map(str::to_owned)
+ })
+ else {
+ return Ok(false);
+ };
+
+ let (browser_identity_changed, extra_headers_changed, locale_changed, timezone_changed) =
+ if self.is_active_target(&target_id) {
+ let (browser_identity_changed, extra_headers_changed) =
+ self.network_policy.remove_session_overrides(session_id);
+ let locale_changed = self.locale_overrides.remove_session(session_id);
+ let timezone_changed = self.timezone_overrides.remove_session(session_id);
+ if locale_changed {
+ self.locale_override = self.locale_overrides.effective().cloned();
+ }
+ if timezone_changed {
+ self.timezone_override = self.timezone_overrides.effective().cloned();
+ }
+ (
+ browser_identity_changed,
+ extra_headers_changed,
+ locale_changed,
+ timezone_changed,
+ )
+ } else {
+ self.mutate_parked_page_session_state(&target_id, |state| {
+ let (browser_identity_changed, extra_headers_changed) =
+ state.network_policy.remove_session_overrides(session_id);
+ let locale_changed = state.locale_overrides.remove_session(session_id);
+ let timezone_changed = state.timezone_overrides.remove_session(session_id);
+ if locale_changed {
+ state.locale_override = state.locale_overrides.effective().cloned();
+ }
+ if timezone_changed {
+ state.timezone_override = state.timezone_overrides.effective().cloned();
+ }
+ (
+ browser_identity_changed,
+ extra_headers_changed,
+ locale_changed,
+ timezone_changed,
+ )
+ })
+ };
+
+ if !extra_headers_changed && !locale_changed && !timezone_changed {
+ return Ok(browser_identity_changed);
+ }
+
+ let (effective_headers, effective_locale, effective_timezone) =
+ if self.is_active_target(&target_id) {
+ (
+ self.effective_extra_headers(),
+ self.effective_active_locale_override_owned(),
+ self.effective_active_timezone_override_owned(),
+ )
+ } else {
+ let page_state = self.parked_page_session_state(&target_id);
+ (
+ self.effective_parked_extra_headers(&target_id),
+ page_state
+ .and_then(|state| state.locale_override.clone())
+ .or_else(|| self.default_locale_override.clone()),
+ page_state
+ .and_then(|state| state.timezone_override.clone())
+ .or_else(|| self.default_timezone_override.clone()),
+ )
+ };
+ let page = if self.is_active_target(&target_id) {
+ self.active_target.runtime_slot.loaded_page_mut()
+ } else {
+ self.background_target_mut(&target_id)
+ .and_then(|target| target.runtime_slot.loaded_page_mut())
+ };
+ let Some(page) = page else {
+ return Ok(browser_identity_changed);
+ };
+ if extra_headers_changed {
+ page.set_extra_http_headers_async(&effective_headers)
+ .await
+ .map_err(|error| {
+ format!("failed to restore detached session extra headers: {error}")
+ })?;
+ }
+ if locale_changed {
+ page.set_locale_override_async(effective_locale.as_deref())
+ .await
+ .map_err(|error| format!("failed to restore detached session locale: {error}"))?;
+ }
+ if timezone_changed {
+ page.set_timezone_override_async(effective_timezone.as_deref())
+ .await
+ .map_err(|error| format!("failed to restore detached session timezone: {error}"))?;
+ }
+ Ok(browser_identity_changed)
+ }
+
pub(crate) fn remove_auxiliary_sessions_for_target(&mut self, target_id: &str) -> Vec<String> {
let session_ids = self
.auxiliary_target_sessions
@@ -408,8 +481,7 @@ impl BrowserContext {
session_id: &str,
) -> Result<Option<String>, String> {
let Some(target_id) = self
- .background_targets
- .iter_mut()
+ .background_targets_mut()
.find(|target| target.is_session(session_id))
.map(|target| {
target.detach_session();
@@ -432,26 +504,15 @@ impl BrowserContext {
return Ok(None);
};
- let retained_runtime_bindings = self
- .parked_page_session_state(&target_id)
- .map(|state| {
- runtime_bindings_for_renderer(
- &state.devtools_session_state,
- &state.auxiliary_devtools_session_states,
- )
- })
- .unwrap_or_default();
- let mut cleared_page_session_state = ParkedPageSessionState::default();
- let cleared_emulated_media: moli_core::page::EmulatedMediaOverrides =
- (&cleared_page_session_state.emulated_media).into();
- cleared_page_session_state
- .devtools_session_state
- .runtime_bindings = retained_runtime_bindings;
- self.replace_parked_page_session_state(target_id.clone(), cleared_page_session_state);
- self.replace_parked_fetch_state(target_id.clone(), Default::default());
- self.mutate_parked_network_artifacts(&target_id, |artifacts| {
- artifacts.remove_session_observation_cursor(Some(session_id));
- });
+ let cleared_emulated_media = moli_core::page::EmulatedMediaOverrides::default();
+ self.background_target_mut(&target_id)
+ .expect("background target must exist")
+ .state_mut()
+ .clear_session_scoped_state_fields(true);
+ self.background_target_mut(&target_id)
+ .expect("background target must exist")
+ .runtime_slot
+ .remove_network_session_observation_cursor(Some(session_id));
if let Some(page) = self
.background_target_mut(&target_id)
@@ -487,8 +548,7 @@ impl BrowserContext {
session_id: &str,
) -> Option<String> {
let target_id = self
- .background_targets
- .iter_mut()
+ .background_targets_mut()
.find(|target| target.is_session(session_id))
.map(|target| {
target.detach_session();
@@ -508,14 +568,15 @@ impl BrowserContext {
target_id
})?;
self.mutate_parked_page_session_state(&target_id, |state| {
- state.devtools_session_state = DevToolsSessionState::default();
- state.network_enabled = false;
+ *state.devtools_sessions.primary_mut() = DevToolsSessionState::default();
+ state.runtime_slot.disable_primary_network_events();
state.network_policy = TargetNetworkPolicyState::default();
- state.fetch_config = TargetFetchConfig::default();
- });
- self.mutate_parked_network_artifacts(&target_id, |artifacts| {
- artifacts.remove_session_observation_cursor(Some(session_id));
+ state.fetch_owner.reset_config();
});
+ self.background_target_mut(&target_id)
+ .expect("background target must exist")
+ .runtime_slot
+ .remove_network_session_observation_cursor(Some(session_id));
Some(target_id)
}
@@ -699,8 +760,7 @@ impl BrowserContext {
return true;
}
let Some(target) = self
- .background_targets
- .iter_mut()
+ .background_targets_mut()
.find(|target| target.is_session(session_id))
else {
return false;
@@ -713,15 +773,14 @@ impl BrowserContext {
#[cfg(test)]
pub(crate) async fn promote_first_background_target_to_active_async(
&mut self,
- ) -> Option<BackgroundTarget> {
+ ) -> Option<String> {
let promoted = self
- .background_targets
- .iter()
- .position(|target| target.has_loaded_page())
- .map(|index| self.background_targets[index].target_id().to_owned())
+ .background_targets()
+ .find(|target| target.has_loaded_page())
+ .map(|target| target.target_id().to_owned())
.or_else(|| {
- self.background_targets
- .first()
+ self.background_targets()
+ .next()
.map(|target| target.target_id().to_owned())
})?;
self.promote_selected_background_target_to_active_async(promoted)
@@ -730,20 +789,20 @@ impl BrowserContext {
pub(crate) async fn promote_last_background_target_to_active_async(
&mut self,
- ) -> Option<BackgroundTarget> {
+ ) -> Option<String> {
let promoted = self.last_promotable_background_target_id()?;
self.promote_selected_background_target_to_active_async(promoted)
.await
}
pub(crate) fn last_promotable_background_target_id(&self) -> Option<String> {
- self.background_targets
- .iter()
- .rposition(|target| target.has_loaded_page())
- .map(|index| self.background_targets[index].target_id().to_owned())
+ self.background_targets()
+ .rev()
+ .find(|target| target.has_loaded_page())
+ .map(|target| target.target_id().to_owned())
.or_else(|| {
- self.background_targets
- .last()
+ self.background_targets()
+ .next_back()
.map(|target| target.target_id().to_owned())
})
}
@@ -751,24 +810,11 @@ impl BrowserContext {
async fn promote_selected_background_target_to_active_async(
&mut self,
promoted: String,
- ) -> Option<BackgroundTarget> {
- let synchronize_loaded_page = !self.has_pending_javascript_dialog();
- let (mut target, aux_state) = self
- .take_background_target_slot(&promoted)
- .expect("selected background target must remain removable")
- .into_parts();
- std::mem::swap(
- &mut self.active_target.runtime_slot,
- &mut target.runtime_slot,
- );
- Box::pin(self.apply_promoted_background_target_state_async(
- &mut target,
- aux_state,
- synchronize_loaded_page,
- ))
- .await
- .expect("restoring promoted target state should succeed");
- Some(target)
+ ) -> Option<String> {
+ self.promote_background_target_to_active_slot_async(&promoted)
+ .await
+ .expect("applying promoted target visibility should succeed")
+ .then_some(promoted)
}
pub(crate) async fn promote_background_target_to_active_slot_async(
@@ -778,159 +824,87 @@ impl BrowserContext {
if self.is_active_target(target_id) {
return Ok(true);
}
- let synchronize_loaded_page = !self.has_pending_javascript_dialog();
- let Some(promoted_slot) = self.take_background_target_slot(target_id) else {
+ if self.background_target(target_id).is_none() {
return Ok(false);
+ }
+ let synchronize_loaded_page = self
+ .page_targets
+ .active()
+ .is_none_or(|host| !host.has_pending_javascript_dialog())
+ && self
+ .page_target(target_id)
+ .is_none_or(|host| !host.has_pending_javascript_dialog());
+ let previous_active_target_id = self.active_target_id_owned();
+ let demoted_surface_script = if synchronize_loaded_page {
+ previous_active_target_id.as_deref().and_then(|target_id| {
+ let host = self.page_target(target_id)?;
+ self.generated_surface_override_script_for_parked_state(host.state())
+ })
+ } else {
+ None
};
- let previous_active = self.take_active_target_slot_state();
- let (mut target, aux_state) = promoted_slot.into_parts();
- std::mem::swap(
- &mut self.active_target.runtime_slot,
- &mut target.runtime_slot,
- );
+ let selected = self.page_targets.select(target_id);
+ debug_assert!(selected, "existing page target must be selectable");
if synchronize_loaded_page {
- self.clear_active_target_session_scoped_state_async()
- .await?;
- } else {
- self.clear_active_target_session_scoped_state_without_loaded_page();
- }
- self.active_target.owner_state.target_crash_state.clear();
- Box::pin(self.apply_promoted_background_target_state_async(
- &mut target,
- aux_state,
- synchronize_loaded_page,
- ))
- .await?;
- if let Some(previous_active_slot) = previous_active {
- Box::pin(
- self.park_demoted_active_target_async(
- *previous_active_slot,
- synchronize_loaded_page,
- ),
- )
- .await;
+ self.apply_surface_overrides_to_loaded_page_async().await?;
}
- Ok(true)
- }
-
- async fn park_demoted_active_target_async(
- &mut self,
- slot: TargetSlotState,
- synchronize_loaded_page: bool,
- ) {
- let (mut target, aux_state) = slot.into_parts();
- if synchronize_loaded_page {
- let target_id = target.target_id().to_owned();
- if let Err(error) = self
- .apply_parked_surface_overrides_to_loaded_page_async(
- &mut target.runtime_slot,
- &aux_state.page_session_state,
- )
+ if let (Some(previous_active_target_id), Some(script)) =
+ (previous_active_target_id, demoted_surface_script)
+ && let Some(page) = self
+ .page_target_mut(&previous_active_target_id)
+ .and_then(|host| host.runtime_slot.loaded_page_mut())
+ && let Err(error) = page
+ .run_page_surface_override_script_async(&script.source)
.await
- {
- tracing::warn!(
- target_id,
- %error,
- "failed to update demoted page visibility"
- );
- }
+ {
+ tracing::warn!(target_id = previous_active_target_id, %error, "failed to update demoted page visibility");
}
- self.replace_background_target_slot(TargetSlotState::new(target, aux_state));
+ Ok(true)
}
#[cfg(test)]
pub(crate) async fn demote_active_target_to_background_slot_async(
&mut self,
) -> Result<bool, String> {
- let Some(active_slot) = self.take_active_target_slot_state() else {
+ let Some(active_target_id) = self.active_target_id_owned() else {
return Ok(false);
};
- self.detach_active_session();
+ let surface_script = self
+ .page_target(&active_target_id)
+ .and_then(|host| self.generated_surface_override_script_for_parked_state(host.state()));
+ if let Some(script) = surface_script
+ && let Some(page) = self
+ .page_target_mut(&active_target_id)
+ .and_then(|host| host.runtime_slot.loaded_page_mut())
+ {
+ page.run_page_surface_override_script_async(&script.source)
+ .await
+ .map_err(|error| error.to_string())?;
+ }
self.clear_active_target_id();
- self.clear_active_target_session_scoped_state_without_loaded_page();
- self.active_target.owner_state.clear_page_local_state();
- self.restore_raw_cookie_manager_surface_async(Default::default())
- .await;
- self.reset_target_identity_to_new_tab();
- self.reset_target_scoped_network_artifacts();
- self.active_target
- .owner_state
- .clear_observable_output_state();
- self.active_target
- .runtime_slot
- .request_id_allocator()
- .reset_subresource_fetch_request_counter();
- self.replace_background_target_slot(*active_slot);
Ok(true)
}
- pub(crate) fn take_background_target_slot(
- &mut self,
- target_id: &str,
- ) -> Option<TargetSlotState> {
- let index = self
- .background_targets
- .iter()
- .position(|target| target.is_target(target_id))?;
- self.take_background_target_slot_by_index(index)
- }
-
- fn take_background_target_slot_by_index(&mut self, index: usize) -> Option<TargetSlotState> {
- if index >= self.background_targets.len() {
- return None;
- }
- let mut target = self.background_targets.swap_remove(index);
- let mut aux_state = self.take_parked_target_aux_state(target.target_id());
- aux_state
- .network_artifacts
- .drain_from_background_target(&mut target);
- Some(TargetSlotState::new(target, aux_state))
- }
-
- fn replace_background_target_slot(&mut self, slot: TargetSlotState) {
- let target_id = slot.target_id().to_owned();
- let (mut target, mut aux_state) = slot.into_parts();
- target
- .runtime_slot
- .set_primary_network_events_enabled(aux_state.page_session_state.network_enabled);
- aux_state
- .network_artifacts
- .drain_into_background_target(&mut target);
- self.replace_parked_target_aux_state(target_id, aux_state);
- self.background_targets.push(target);
- }
-
- fn take_active_target_slot_state(&mut self) -> Option<Box<TargetSlotState>> {
- let aux_state = self.snapshot_active_target_aux_state();
- let session_storage_namespace =
- std::mem::take(&mut self.active_target.session_storage_namespace);
- self.active_target_id_owned().map(|target_id| {
- let runtime_slot = std::mem::take(&mut self.active_target.runtime_slot);
- Box::new(TargetSlotState::from_active_snapshot(
- target_id,
- self.active_session_id_owned(),
- self.target_identity().clone(),
- runtime_slot,
- session_storage_namespace,
- aux_state,
- ))
- })
- }
-
pub fn take_parked_isolated_worlds(&mut self, target_id: &str) -> Vec<IsolatedWorldDefinition> {
- self.target_parking.take_isolated_worlds(target_id)
+ std::mem::take(
+ &mut self
+ .background_target_mut(target_id)
+ .expect("parked target must exist")
+ .state_mut()
+ .owner_state
+ .isolated_worlds,
+ )
}
pub fn take_parked_document_start_script_counter(&mut self, target_id: &str) -> u32 {
- self.target_parking
- .take_document_start_script_counter(target_id)
- }
-
- pub(crate) fn take_parked_cookie_manager_surface(
- &mut self,
- target_id: &str,
- ) -> BrowserContextCookieManagerSurfaceSnapshot {
- self.target_parking.take_cookie_manager_surface(target_id)
+ let owner_state = &mut self
+ .background_target_mut(target_id)
+ .expect("parked target must exist")
+ .state_mut()
+ .owner_state;
+ let counter = owner_state.next_document_start_script_id;
+ owner_state.next_document_start_script_id = 0;
+ counter
}
pub fn replace_parked_isolated_worlds(
@@ -938,8 +912,11 @@ impl BrowserContext {
target_id: String,
isolated_worlds: Vec<IsolatedWorldDefinition>,
) {
- self.target_parking
- .replace_isolated_worlds(target_id, isolated_worlds);
+ self.background_target_mut(&target_id)
+ .expect("parked target must exist")
+ .state_mut()
+ .owner_state
+ .isolated_worlds = isolated_worlds;
}
pub fn replace_parked_document_start_script_counter(
@@ -947,95 +924,31 @@ impl BrowserContext {
target_id: String,
counter: u32,
) {
- self.target_parking
- .replace_document_start_script_counter(target_id, counter);
- }
-
- pub(crate) fn replace_parked_cookie_manager_surface(
- &mut self,
- target_id: String,
- snapshot: BrowserContextCookieManagerSurfaceSnapshot,
- ) {
- self.target_parking
- .replace_cookie_manager_surface(target_id, snapshot);
+ self.background_target_mut(&target_id)
+ .expect("parked target must exist")
+ .state_mut()
+ .owner_state
+ .next_document_start_script_id = counter;
}
pub(crate) fn parked_page_session_state(
&self,
target_id: &str,
- ) -> Option<&ParkedPageSessionState> {
- self.target_parking.page_session_state(target_id)
- }
-
- pub fn take_parked_page_session_state(&mut self, target_id: &str) -> ParkedPageSessionState {
- self.target_parking.take_page_session_state(target_id)
- }
-
- pub fn replace_parked_page_session_state(
- &mut self,
- target_id: String,
- state: ParkedPageSessionState,
- ) {
- self.target_parking
- .replace_page_session_state(target_id, state);
+ ) -> Option<&crate::conn::state::TargetPageState> {
+ let state = self.background_target(target_id)?.state();
+ state.has_non_default_session_state().then_some(state)
}
pub fn mutate_parked_page_session_state<T>(
&mut self,
target_id: &str,
- mutate: impl FnOnce(&mut ParkedPageSessionState) -> T,
+ mutate: impl FnOnce(&mut crate::conn::state::TargetPageState) -> T,
) -> T {
- let mut state = self.take_parked_page_session_state(target_id);
- let result = mutate(&mut state);
- self.replace_parked_page_session_state(target_id.to_owned(), state);
- result
- }
-
- pub fn take_parked_network_artifacts(&mut self, target_id: &str) -> ParkedNetworkArtifacts {
- let mut artifacts = self.target_parking.take_network_artifacts(target_id);
- if let Some(target) = self.background_target_mut(target_id) {
- artifacts.drain_from_background_target(target);
- }
- artifacts
- }
-
- #[cfg(test)]
- pub(crate) fn parked_network_artifacts(
- &self,
- target_id: &str,
- ) -> Option<ParkedNetworkArtifacts> {
- let mut artifacts = self
- .target_parking
- .network_artifacts(target_id)
- .cloned()
- .unwrap_or_default();
- if let Some(target) = self.background_target(target_id) {
- artifacts = ParkedNetworkArtifacts::snapshot_from_runtime_slot(target.runtime_slot());
- }
- (artifacts != ParkedNetworkArtifacts::default()).then_some(artifacts)
- }
-
- pub fn replace_parked_network_artifacts(
- &mut self,
- target_id: String,
- mut artifacts: ParkedNetworkArtifacts,
- ) {
- if let Some(target) = self.background_target_mut(&target_id) {
- artifacts.drain_into_background_target(target);
- }
- self.target_parking
- .replace_network_artifacts(target_id, artifacts);
- }
-
- pub fn mutate_parked_network_artifacts<T>(
- &mut self,
- target_id: &str,
- mutate: impl FnOnce(&mut ParkedNetworkArtifacts) -> T,
- ) -> T {
- let mut artifacts = self.take_parked_network_artifacts(target_id);
- let result = mutate(&mut artifacts);
- self.replace_parked_network_artifacts(target_id.to_owned(), artifacts);
- result
+ mutate(
+ self.background_target_mut(target_id)
+ .expect("parked target must exist")
+ .state_mut(),
+ )
}
pub(crate) fn begin_active_target_initial_empty_document(&mut self, initial_url: String) {
@@ -1109,33 +1022,26 @@ impl BrowserContext {
Some(self.mutate_parked_target_owner_state(target_id, mutate))
}
- fn take_parked_target_owner_state(&mut self, target_id: &str) -> ParkedTargetOwnerState {
- self.target_parking.take_target_owner_state(target_id)
- }
-
- fn replace_parked_target_owner_state(
- &mut self,
- target_id: String,
- state: ParkedTargetOwnerState,
- ) {
- self.target_parking
- .replace_target_owner_state(target_id, state);
- }
-
pub(crate) fn mutate_parked_target_owner_state<T>(
&mut self,
target_id: &str,
mutate: impl FnOnce(&mut ParkedTargetOwnerState) -> T,
) -> T {
- self.target_parking
- .mutate_target_owner_state(target_id, mutate)
+ mutate(
+ &mut self
+ .background_target_mut(target_id)
+ .expect("parked target must exist")
+ .active_target
+ .owner_state,
+ )
}
pub(crate) fn parked_target_owner_state(
&self,
target_id: &str,
) -> Option<&ParkedTargetOwnerState> {
- self.target_parking.target_owner_state(target_id)
+ let state = &self.background_target(target_id)?.active_target.owner_state;
+ (!state.is_default()).then_some(state)
}
#[cfg(test)]
@@ -1143,232 +1049,22 @@ impl BrowserContext {
&self,
target_id: &str,
) -> ParkedTargetOwnerState {
- self.target_parking
- .target_owner_state(target_id)
- .cloned()
+ self.background_target(target_id)
+ .map(|target| target.active_target.owner_state.clone())
.unwrap_or_default()
}
- pub fn take_parked_fetch_state(&mut self, target_id: &str) -> ParkedFetchState {
- self.target_parking.take_fetch_state(target_id)
- }
-
#[cfg(test)]
- pub(crate) fn parked_fetch_state(&self, target_id: &str) -> Option<&ParkedFetchState> {
- self.target_parking.fetch_state(target_id)
- }
-
- pub fn replace_parked_fetch_state(&mut self, target_id: String, state: ParkedFetchState) {
- self.target_parking.replace_fetch_state(target_id, state);
- }
-
- pub(crate) fn snapshot_active_target_aux_state(&mut self) -> ParkedTargetAuxState {
- ParkedTargetAuxState {
- cookie_manager_surface: self.raw_cookie_manager_surface_snapshot(),
- page_session_state: self.snapshot_page_session_state(),
- fetch_state: self.snapshot_fetch_state(),
- network_artifacts: self.snapshot_network_artifacts(),
- target_owner_state: self.snapshot_target_owner_state(),
- }
- }
-
- pub(crate) async fn restore_active_target_aux_state_async(
- &mut self,
- state: ParkedTargetAuxState,
- ) -> Result<(), String> {
- self.restore_raw_cookie_manager_surface_async(state.cookie_manager_surface)
- .await;
- self.restore_page_session_state_async(state.page_session_state)
- .await?;
- self.restore_fetch_state(state.fetch_state);
- self.restore_network_artifacts(state.network_artifacts);
- self.restore_target_owner_state(state.target_owner_state);
- Ok(())
- }
-
- fn restore_active_target_aux_state_without_loaded_page_sync(
- &mut self,
- state: ParkedTargetAuxState,
- ) {
- self.restore_raw_cookie_manager_surface_without_loaded_page_sync(
- state.cookie_manager_surface,
- );
- self.restore_page_session_state_without_loaded_page_sync(state.page_session_state);
- self.restore_fetch_state(state.fetch_state);
- self.restore_network_artifacts(state.network_artifacts);
- self.restore_target_owner_state(state.target_owner_state);
- }
-
- pub(crate) async fn apply_promoted_background_target_state_async(
- &mut self,
- promoted: &mut BackgroundTarget,
- state: ParkedTargetAuxState,
- synchronize_loaded_page: bool,
- ) -> Result<(), String> {
- let has_pending_dialog = state.has_pending_javascript_dialog();
- self.set_active_target_id(promoted.target_id());
- self.replace_active_session(promoted.session_id().map(str::to_owned));
- self.replace_target_identity(promoted.target_identity().clone());
- self.active_target.session_storage_namespace = promoted.take_session_storage_namespace();
- if has_pending_dialog || !synchronize_loaded_page {
- self.restore_active_target_aux_state_without_loaded_page_sync(state);
- Ok(())
- } else {
- self.restore_active_target_aux_state_async(state).await
- }
- }
-
- fn snapshot_page_session_state(&self) -> ParkedPageSessionState {
- ParkedPageSessionState {
- devtools_session_state: self.devtools_session_state.clone(),
- auxiliary_devtools_session_states: self.auxiliary_devtools_session_states.clone(),
- network_enabled: self
- .active_target
- .runtime_slot
- .primary_network_events_enabled(),
- network_policy: self.network_policy.clone(),
- http_proxy_override: self.http_proxy_override.clone(),
- http_no_proxy_override: self.http_no_proxy_override.clone(),
- tls_verify_host_override: self.tls_verify_host_override,
- locale_override: self.locale_override.clone(),
- timezone_override: self.timezone_override.clone(),
- network_conditions: self.network_conditions,
- geolocation_override: self.geolocation_override.clone(),
- emulated_media: self.emulated_media.clone(),
- emulated_device_metrics: self.emulated_device_metrics.clone(),
- cpu_throttling_rate: self.cpu_throttling_rate,
- touch_emulation_enabled: self.touch_emulation_enabled,
- emit_touch_events_for_mouse: self.emit_touch_events_for_mouse,
- focus_emulation_enabled: self.focus_emulation_enabled,
- script_execution_disabled: self.script_execution_disabled,
- css_enabled: self.css_enabled,
- fetch_config: self.active_target.fetch_owner.config_snapshot(),
- }
- }
-
- async fn restore_page_session_state_async(
- &mut self,
- state: ParkedPageSessionState,
- ) -> Result<(), String> {
- self.restore_page_session_state_without_loaded_page_sync(state);
- let effective_headers = self.effective_extra_headers();
- let network_offline = self.network_policy.network_offline();
- let bypass_service_worker = self.network_policy.bypass_service_worker();
- let blocked_url_patterns = self.network_policy.blocked_url_patterns().to_vec();
- let script_execution_disabled = self.script_execution_disabled;
- let cpu_throttling_rate = self.cpu_throttling_rate;
- let (fetch_subresource_enabled, fetch_subresource_resource_type) = self
+ pub(crate) fn parked_fetch_state(
+ &self,
+ target_id: &str,
+ ) -> Option<&crate::conn::state::TargetFetchState> {
+ let state = self
+ .background_target(target_id)?
.active_target
.fetch_owner
- .subresource_interception_config();
- if let Some(page) = self.active_target.runtime_slot.loaded_page_mut() {
- page.set_extra_http_headers_async(&effective_headers)
- .await
- .map_err(|error| format!("failed to restore page extra headers: {error}"))?;
- page.set_network_offline_async(network_offline)
- .await
- .map_err(|error| format!("failed to restore page offline state: {error}"))?;
- page.set_bypass_service_worker_async(bypass_service_worker)
- .await
- .map_err(|error| {
- format!("failed to restore page service worker bypass: {error}")
- })?;
- page.set_blocked_url_patterns_async(&blocked_url_patterns)
- .await
- .map_err(|error| format!("failed to restore page blocked URLs: {error}"))?;
- page.set_script_execution_disabled_async(script_execution_disabled)
- .await
- .map_err(|error| {
- format!("failed to restore page script execution disabled state: {error}")
- })?;
- page.set_cpu_throttling_rate_async(cpu_throttling_rate)
- .await
- .map_err(|error| format!("failed to restore page CPU throttling rate: {error}"))?;
- page.set_fetch_subresource_interception_async(
- fetch_subresource_enabled,
- fetch_subresource_resource_type,
- )
- .await
- .map_err(|error| format!("failed to restore page fetch interception: {error}"))?;
- }
- self.apply_surface_overrides_to_loaded_page_async().await?;
- Ok(())
- }
-
- fn restore_page_session_state_without_loaded_page_sync(
- &mut self,
- state: ParkedPageSessionState,
- ) {
- self.devtools_session_state = state.devtools_session_state;
- self.auxiliary_devtools_session_states = state.auxiliary_devtools_session_states;
- self.active_target
- .runtime_slot
- .set_primary_network_events_enabled(state.network_enabled);
- self.network_policy = state.network_policy;
- self.http_proxy_override = state.http_proxy_override;
- self.http_no_proxy_override = state.http_no_proxy_override;
- self.tls_verify_host_override = state.tls_verify_host_override;
- self.locale_override = state.locale_override;
- self.timezone_override = state.timezone_override;
- self.network_conditions = state.network_conditions;
- self.geolocation_override = state.geolocation_override;
- self.emulated_media = state.emulated_media;
- self.emulated_device_metrics = state.emulated_device_metrics;
- self.cpu_throttling_rate = state.cpu_throttling_rate;
- self.touch_emulation_enabled = state.touch_emulation_enabled;
- self.emit_touch_events_for_mouse = state.emit_touch_events_for_mouse;
- self.focus_emulation_enabled = state.focus_emulation_enabled;
- self.script_execution_disabled = state.script_execution_disabled;
- self.css_enabled = state.css_enabled;
- self.active_target
- .fetch_owner
- .replace_config(state.fetch_config);
- }
-
- fn snapshot_network_artifacts(&self) -> ParkedNetworkArtifacts {
- ParkedNetworkArtifacts::snapshot_from_runtime_slot(&self.active_target.runtime_slot)
- }
-
- fn restore_network_artifacts(&mut self, artifacts: ParkedNetworkArtifacts) {
- artifacts.restore_into_runtime_slot(&mut self.active_target.runtime_slot);
- }
-
- fn snapshot_target_owner_state(&mut self) -> ParkedTargetOwnerState {
- std::mem::take(&mut self.active_target.owner_state)
- }
-
- fn restore_target_owner_state(&mut self, state: ParkedTargetOwnerState) {
- self.active_target.owner_state = state;
- }
-
- fn snapshot_fetch_state(&mut self) -> ParkedFetchState {
- self.active_target.fetch_owner.take_pending_state()
- }
-
- fn restore_fetch_state(&mut self, state: ParkedFetchState) {
- self.active_target.fetch_owner.replace_pending_state(state);
- }
-
- pub(crate) fn take_parked_target_aux_state(&mut self, target_id: &str) -> ParkedTargetAuxState {
- ParkedTargetAuxState {
- cookie_manager_surface: self.take_parked_cookie_manager_surface(target_id),
- page_session_state: self.take_parked_page_session_state(target_id),
- fetch_state: self.take_parked_fetch_state(target_id),
- network_artifacts: self.take_parked_network_artifacts(target_id),
- target_owner_state: self.take_parked_target_owner_state(target_id),
- }
- }
-
- pub(crate) fn replace_parked_target_aux_state(
- &mut self,
- target_id: String,
- state: ParkedTargetAuxState,
- ) {
- self.replace_parked_cookie_manager_surface(target_id.clone(), state.cookie_manager_surface);
- self.replace_parked_page_session_state(target_id.clone(), state.page_session_state);
- self.replace_parked_fetch_state(target_id.clone(), state.fetch_state);
- self.replace_parked_network_artifacts(target_id.clone(), state.network_artifacts);
- self.replace_parked_target_owner_state(target_id, state.target_owner_state);
+ .pending_state();
+ (!state.is_empty()).then_some(state)
}
#[cfg(test)]
@@ -1466,8 +1162,7 @@ impl BrowserContext {
);
}
infos.extend(
- self.background_targets
- .iter()
+ self.background_targets()
.filter_map(|target| self.devtools_target_info(target.target_id())),
);
infos.extend(
@@ -2120,7 +1815,7 @@ mod tests {
}
#[test]
- fn background_target_slot_take_and_replace_moves_aux_state_together() {
+ fn page_target_host_keeps_protocol_and_owner_state_together() {
let mut context = BrowserContext::new("BC-1".to_owned());
context.stage_background_target(
"TID-bg".to_owned(),
@@ -2137,59 +1832,40 @@ mod tests {
grant_universal_access: true,
}],
);
- context.replace_parked_page_session_state(
- "TID-bg".to_owned(),
- ParkedPageSessionState {
- devtools_session_state: DevToolsSessionState {
+ context.mutate_parked_page_session_state("TID-bg", |state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =
+ DevToolsSessionState {
runtime_session_state: TargetRuntimeSessionState {
runtime_frontend_enabled: true,
..Default::default()
},
..Default::default()
- },
- ..Default::default()
- },
- );
+ };
+ });
- let slot = context
- .take_background_target_slot("TID-bg")
- .expect("background target slot should be present");
+ let host = context
+ .background_target("TID-bg")
+ .expect("page target host should remain registered");
- assert!(context.background_targets.is_empty());
- assert!(context.parked_page_session_state("TID-bg").is_none());
- assert_eq!(
- context.take_parked_document_start_script_counter("TID-bg"),
- 0
- );
- assert_eq!(slot.target().target_id, "TID-bg");
- assert_eq!(
- slot.aux_state()
- .target_owner_state
- .next_document_start_script_id,
- 7
- );
- assert_eq!(slot.aux_state().target_owner_state.isolated_worlds.len(), 1);
- assert_eq!(
- slot.aux_state().target_owner_state.isolated_worlds[0].name,
- "utility"
- );
+ assert_eq!(host.target_id(), "TID-bg");
+ assert_eq!(host.state().owner_state.next_document_start_script_id, 7);
+ assert_eq!(host.state().owner_state.isolated_worlds.len(), 1);
+ assert_eq!(host.state().owner_state.isolated_worlds[0].name, "utility");
assert!(
- slot.aux_state()
- .page_session_state
- .devtools_session_state
+ host.state().devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
-
- context.replace_background_target_slot(slot);
-
- assert_eq!(context.background_targets.len(), 1);
- assert_eq!(context.background_targets[0].target_id(), "TID-bg");
+ assert_eq!(context.background_target_count(), 1);
+ assert_eq!(
+ context.background_target_at(0).unwrap().target_id(),
+ "TID-bg"
+ );
assert!(
context
.parked_page_session_state("TID-bg")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled)
);
@@ -2242,7 +1918,7 @@ mod tests {
}
#[test]
- fn active_target_slot_snapshot_carries_active_target_and_aux_state() {
+ fn clearing_selection_keeps_the_page_target_host_and_its_state() {
let mut context = BrowserContext::new("BC-1".to_owned());
context.set_active_target_id("TID-active".to_owned());
context.attach_active_session("SID-active".to_owned());
@@ -2253,12 +1929,10 @@ mod tests {
.active_target
.runtime_slot
.set_page_attachment_id_for_test(42);
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
context
@@ -2281,6 +1955,7 @@ mod tests {
"script-1".to_owned(),
DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.fromDocumentStart = true".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -2288,63 +1963,37 @@ mod tests {
},
));
- let slot = context
- .take_active_target_slot_state()
- .expect("active target slot should be present");
+ context.clear_active_target_id();
+ let host = context
+ .page_target("TID-active")
+ .expect("clearing foreground selection must not remove the host");
- assert_eq!(slot.target().target_id, "TID-active");
- assert_eq!(slot.target().session_id(), Some("SID-active"));
- assert_eq!(slot.target().target_url(), "https://active.test/");
+ assert_eq!(host.target_id(), "TID-active");
+ assert_eq!(host.session_id(), Some("SID-active"));
+ assert_eq!(host.target_url(), "https://active.test/");
assert_eq!(
- slot.target().target_identity().security_origin(),
+ host.target_identity().security_origin(),
"https://active.test"
);
+ assert_eq!(host.target_identity().secure_context_type(), "Secure");
assert_eq!(
- slot.target().target_identity().secure_context_type(),
- "Secure"
- );
- assert_eq!(
- slot.target()
- .page_attachment_id()
+ host.page_attachment_id()
.map(|attachment_id| attachment_id.get()),
Some(42)
);
- assert_eq!(
- slot.aux_state()
- .target_owner_state
- .document_start_scripts
- .len(),
- 1
- );
+ assert_eq!(host.state().owner_state.document_start_scripts.len(), 1);
assert!(
- slot.aux_state()
- .page_session_state
- .devtools_session_state
+ host.state().devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
assert!(
- slot.aux_state()
- .page_session_state
- .devtools_session_state
+ host.state().devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
- assert_eq!(
- slot.aux_state()
- .target_owner_state
- .next_document_start_script_id,
- 3
- );
- assert_eq!(slot.aux_state().target_owner_state.isolated_worlds.len(), 1);
- assert!(context.active_target.owner_state.isolated_worlds.is_empty());
- assert!(
- context
- .active_target
- .owner_state
- .document_start_scripts
- .is_empty()
- );
+ assert_eq!(host.state().owner_state.next_document_start_script_id, 3);
+ assert_eq!(host.state().owner_state.isolated_worlds.len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
@@ -2360,39 +2009,31 @@ mod tests {
context.set_active_target_id("TID-demote".to_owned());
context.attach_active_session("SID-demote".to_owned());
context.set_target_url(active_page.final_url().as_str().to_owned());
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled = true;
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enable(PerformanceTimeDomain::ThreadTicks)
);
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled = true;
context
@@ -2411,6 +2052,7 @@ mod tests {
"script-demote".to_owned(),
DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.demoted = true".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -2441,11 +2083,13 @@ mod tests {
assert_eq!(context.active_target_id(), None);
assert!(
- !context.has_loaded_page(),
- "demoting should leave the active slot empty"
+ context
+ .page_target("TID-demote")
+ .is_some_and(|host| host.has_loaded_page()),
+ "demoting should retain the loaded page in its stable host"
);
- assert_eq!(context.background_targets.len(), 1);
- let parked = &context.background_targets[0];
+ assert_eq!(context.background_target_count(), 1);
+ let parked = &context.background_target_at(0).unwrap();
assert_eq!(parked.target_id(), "TID-demote");
assert_eq!(parked.session_id(), Some("SID-demote"));
assert_eq!(
@@ -2478,8 +2122,8 @@ mod tests {
assert!(
context
.parked_page_session_state("TID-demote")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled),
"session-scoped Runtime.enable state should be parked with the target"
@@ -2488,44 +2132,44 @@ mod tests {
.parked_page_session_state("TID-demote")
.expect("demoted target should retain parked page session state");
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled,
"Runtime.enable state should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled,
"Inspector.enable state should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
"Console.enable state should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled,
"Log.enable state should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled(),
"Performance.enable state should move with the demoted target"
);
assert_eq!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.time_domain(),
@@ -2533,22 +2177,22 @@ mod tests {
"Performance time domain should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events,
"Page lifecycle listener state should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled,
"file chooser opened listener state should move with the demoted target"
);
assert!(
- parked_page_session_state
- .devtools_session_state
+ parked_page_session_state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled,
"file chooser interception state should move with the demoted target"
@@ -2560,33 +2204,27 @@ mod tests {
);
assert_eq!(
context
- .target_parking
- .take_target_owner_state("TID-demote")
+ .parked_target_owner_state("TID-demote")
+ .expect("demoted target should retain owner state")
.document_start_scripts
.len(),
1,
"document-start scripts should be parked with the target owner state"
);
- let parked_artifacts = context
- .parked_network_artifacts("TID-demote")
- .expect("demoted target should retain network artifacts");
- assert_eq!(parked_artifacts.next_fetch_request_id_for_test(), 77);
+ let parked_runtime = &context
+ .background_target("TID-demote")
+ .expect("demoted target should retain network state")
+ .runtime_slot;
+ assert_eq!(parked_runtime.next_fetch_request_id_for_test(), 77);
assert_eq!(
- parked_artifacts.next_subresource_fetch_request_id_for_test(),
+ parked_runtime.next_subresource_fetch_request_id_for_test(),
88
);
assert_eq!(
- parked_artifacts.emitted_subresource_record_count_for_session(None),
+ parked_runtime.emitted_subresource_record_count_for_session_for_test(None),
3,
"target network artifacts should move into the parked target runtime slot"
);
- assert!(
- context
- .target_parking
- .network_artifacts("TID-demote")
- .is_none(),
- "parking store should not own network artifacts or request counters while the background target exists"
- );
}
#[tokio::test]
@@ -2608,10 +2246,13 @@ mod tests {
);
assert_eq!(context.active_target_id(), None);
- assert_eq!(context.background_targets.len(), 1);
- assert_eq!(context.background_targets[0].target_id(), "TID-existing-bg");
+ assert_eq!(context.background_target_count(), 1);
assert_eq!(
- context.background_targets[0].session_id(),
+ context.background_target_at(0).unwrap().target_id(),
+ "TID-existing-bg"
+ );
+ assert_eq!(
+ context.background_target_at(0).unwrap().session_id(),
Some("SID-existing-bg")
);
}
@@ -2639,6 +2280,11 @@ mod tests {
json!("initial-document-page-build-pending"),
"production demotion must preserve a pending initial document absence reason"
);
+ assert_eq!(
+ context.active_target.runtime_slot.moli_memory_diagnostics()["loadedPageAbsenceReason"],
+ json!("initial-document-page-build-pending"),
+ "the replacement target must expose its own pending initial document build"
+ );
}
#[tokio::test]
@@ -2702,13 +2348,23 @@ mod tests {
None,
None,
);
- context.background_targets[1].replace_loaded_page(Some(first_loaded_page));
- context.background_targets[2].replace_loaded_page(Some(second_loaded_page));
- let first_attachment = context.background_targets[1]
+ context
+ .background_target_at_mut(1)
+ .unwrap()
+ .replace_loaded_page(Some(first_loaded_page));
+ context
+ .background_target_at_mut(2)
+ .unwrap()
+ .replace_loaded_page(Some(second_loaded_page));
+ let first_attachment = context
+ .background_target_at(1)
+ .unwrap()
.runtime_slot()
.current_renderer_attachment()
.expect("first loaded background target should have an attachment");
- let second_attachment = context.background_targets[2]
+ let second_attachment = context
+ .background_target_at(2)
+ .unwrap()
.runtime_slot()
.current_renderer_attachment()
.expect("second loaded background target should have an attachment");
@@ -2718,7 +2374,7 @@ mod tests {
.await
.expect("loaded background target should promote");
- assert_eq!(promoted.target_id(), "TID-first-loaded");
+ assert_eq!(promoted, "TID-first-loaded");
assert_eq!(context.active_target_id(), Some("TID-first-loaded"));
assert_eq!(context.active_session_id(), Some("SID-first-loaded"));
assert!(
@@ -2737,7 +2393,7 @@ mod tests {
assert!(
context
.background_target("TID-second-loaded")
- .is_some_and(BackgroundTarget::has_loaded_page),
+ .is_some_and(PageTargetHost::has_loaded_page),
"later loaded background target should remain parked"
);
assert_eq!(
@@ -2846,16 +2502,15 @@ mod tests {
devtools_session_state
.console_output_session_state
.console_enabled = true;
- context.replace_parked_page_session_state(
- "TID-bg".to_owned(),
- ParkedPageSessionState {
- devtools_session_state,
- ..Default::default()
- },
- );
- let mut network_artifacts = ParkedNetworkArtifacts::default();
- network_artifacts.set_session_observation_cursor_at_counts(None, 4, 5);
- context.replace_parked_network_artifacts("TID-bg".to_owned(), network_artifacts);
+ context.mutate_parked_page_session_state("TID-bg", |state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =
+ devtools_session_state;
+ });
+ context
+ .background_target_mut("TID-bg")
+ .expect("background target")
+ .runtime_slot
+ .set_session_observation_cursor_at_counts_for_test(None, 4, 5);
assert!(
context
@@ -2866,14 +2521,12 @@ mod tests {
assert_eq!(context.active_target_id(), Some("TID-bg"));
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -2894,47 +2547,40 @@ mod tests {
"websocket observation cursor should restore with target network artifacts"
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled()
);
assert_eq!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.time_domain(),
PerformanceTimeDomain::ThreadTicks
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled
);
assert!(
- context
- .devtools_session_state
+ context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
);
diff --git a/moli-protocol/src/conn/page_state/surfaces.rs b/moli-protocol/src/conn/page_state/surfaces.rs
index 8b89d2964..ebf99b311 100644
--- a/moli-protocol/src/conn/page_state/surfaces.rs
+++ b/moli-protocol/src/conn/page_state/surfaces.rs
@@ -1,8 +1,8 @@
use super::super::cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot;
use super::super::{
- BrowserContext, DocumentStartScript, EmulatedDeviceMetrics, EmulatedGeolocationOverrideState,
- EmulatedNetworkConditions, EmulatedViewportSurface, ParkedPageSessionState, TargetRuntimeSlot,
- viewport_surface_install_script,
+ BrowserContext, CdpConnection, DocumentStartScript, EmulatedDeviceMetrics,
+ EmulatedGeolocationOverrideState, EmulatedNetworkConditions, EmulatedViewportSurface,
+ TargetPageState, viewport_surface_install_script,
};
#[cfg(test)]
use moli_cookie_jar::{BrowserCookieFacadeContextOverrides, BrowserCookieFacadeOverrides};
@@ -40,7 +40,7 @@ impl SurfaceOverrideInputs {
}
fn from_parked(
- state: &ParkedPageSessionState,
+ state: &TargetPageState,
default_network_conditions: Option<EmulatedNetworkConditions>,
default_geolocation_override: Option<EmulatedGeolocationOverrideState>,
default_emulated_device_metrics: Option<EmulatedDeviceMetrics>,
@@ -114,13 +114,13 @@ impl BrowserContext {
&mut super::super::cookie_manager_surface::BrowserContextCookieManagerSurface,
) -> bool,
) -> bool {
- if !mutate(&mut self.document_cookie_manager_surface) {
+ let state = self.active_page_state_mut();
+ if !mutate(&mut state.document_cookie_manager_surface) {
return false;
}
- if let Some(page) = self.active_target.runtime_slot.loaded_page_mut() {
- self.document_cookie_manager_surface
- .apply_to_page_async(page)
- .await;
+ let surface = state.document_cookie_manager_surface.clone();
+ if let Some(page) = state.runtime_slot.loaded_page_mut() {
+ surface.apply_to_page_async(page).await;
}
true
}
@@ -128,30 +128,10 @@ impl BrowserContext {
pub(crate) fn raw_cookie_manager_surface_snapshot(
&self,
) -> BrowserContextCookieManagerSurfaceSnapshot {
- self.document_cookie_manager_surface.snapshot()
- }
-
- pub(crate) async fn restore_raw_cookie_manager_surface_async(
- &mut self,
- snapshot: BrowserContextCookieManagerSurfaceSnapshot,
- ) {
- self.restore_raw_cookie_manager_surface_without_loaded_page_sync(snapshot);
- #[cfg(test)]
- if let Some(page) = self.active_target.runtime_slot.loaded_page_mut() {
- self.document_cookie_manager_surface
- .apply_to_page_async(page)
- .await;
- }
- }
-
- pub(crate) fn restore_raw_cookie_manager_surface_without_loaded_page_sync(
- &mut self,
- snapshot: BrowserContextCookieManagerSurfaceSnapshot,
- ) {
- self.document_cookie_manager_surface =
- super::super::cookie_manager_surface::BrowserContextCookieManagerSurface::from_snapshot(
- snapshot,
- );
+ self.page_targets
+ .active()
+ .map(|host| host.document_cookie_manager_surface.snapshot())
+ .unwrap_or_default()
}
pub fn document_start_script_descriptors(&self) -> Vec<DocumentStartScript> {
@@ -167,9 +147,7 @@ impl BrowserContext {
.document_start_scripts
.iter()
.map(|(identifier, script)| {
- script.with_registry_key(Self::target_document_start_script_registry_key(
- target_id, identifier,
- ))
+ Self::target_document_start_script_descriptor(target_id, identifier, script)
}),
);
scripts
@@ -199,6 +177,32 @@ impl BrowserContext {
}
}
+ pub(crate) fn target_session_document_start_script_registry_key(
+ target_id: Option<&str>,
+ session_id: &str,
+ identifier: &str,
+ ) -> String {
+ match target_id {
+ Some(target_id) => {
+ format!("target:{target_id}:session:{session_id}:{identifier}")
+ }
+ None => format!("target:session:{session_id}:{identifier}"),
+ }
+ }
+
+ pub(crate) fn target_document_start_script_descriptor(
+ target_id: Option<&str>,
+ identifier: &str,
+ script: &DocumentStartScript,
+ ) -> DocumentStartScript {
+ if script.registry_key.is_some() {
+ return script.clone();
+ }
+ script.with_registry_key(Self::target_document_start_script_registry_key(
+ target_id, identifier,
+ ))
+ }
+
pub(crate) fn has_default_bidi_channel_preload_script(&self) -> bool {
self.default_document_start_scripts
.iter()
@@ -266,10 +270,12 @@ impl BrowserContext {
}
pub fn effective_extra_headers(&self) -> Vec<(String, String)> {
- let mut headers =
- self.merged_extra_headers_for_target_policy(self.network_policy.extra_headers());
- apply_locale_header_if_absent(&mut headers, self.effective_active_locale_override());
- headers
+ let target_headers = self
+ .page_targets
+ .active()
+ .map(|target| target.network_policy.extra_headers())
+ .unwrap_or(&[]);
+ self.merged_extra_headers_for_target_policy(target_headers)
}
pub(crate) fn effective_parked_extra_headers(&self, target_id: &str) -> Vec<(String, String)> {
@@ -277,18 +283,7 @@ impl BrowserContext {
.parked_page_session_state(target_id)
.map(|state| state.network_policy.extra_headers())
.unwrap_or(&[]);
- let mut headers = self.merged_extra_headers_for_target_policy(target_headers);
- let locale_override = self.locale_override.as_deref().or_else(|| {
- self.parked_page_session_state(target_id)
- .and_then(|state| state.locale_override.as_deref())
- .or(self.default_locale_override.as_deref())
- });
- apply_locale_header_if_absent(&mut headers, locale_override);
- headers
- }
-
- pub fn effective_language(&self) -> &str {
- self.effective_active_locale_override().unwrap_or("en-US")
+ self.merged_extra_headers_for_target_policy(target_headers)
}
pub fn viewport_width(&self) -> u32 {
@@ -350,20 +345,13 @@ impl BrowserContext {
&self,
target_id: &str,
) -> Option<DocumentStartScript> {
- self.background_target(target_id)?;
- let default_state;
- let state = if let Some(state) = self.parked_page_session_state(target_id) {
- state
- } else {
- default_state = ParkedPageSessionState::default();
- &default_state
- };
- self.generated_surface_override_script_for_parked_state(state)
+ let target = self.background_target(target_id)?;
+ self.generated_surface_override_script_for_parked_state(target.state())
}
- fn generated_surface_override_script_for_parked_state(
+ pub(crate) fn generated_surface_override_script_for_parked_state(
&self,
- state: &ParkedPageSessionState,
+ state: &TargetPageState,
) -> Option<DocumentStartScript> {
Self::generated_surface_override_script_from_inputs(&SurfaceOverrideInputs::from_parked(
state,
@@ -376,22 +364,6 @@ impl BrowserContext {
))
}
- pub(crate) async fn apply_parked_surface_overrides_to_loaded_page_async(
- &self,
- runtime_slot: &mut TargetRuntimeSlot,
- state: &ParkedPageSessionState,
- ) -> Result<(), String> {
- let Some(script) = self.generated_surface_override_script_for_parked_state(state) else {
- return Ok(());
- };
- let Some(page) = runtime_slot.loaded_page_mut() else {
- return Ok(());
- };
- page.run_page_surface_override_script_async(&script.source)
- .await
- .map_err(|error| format!("failed to hide demoted page surface: {error}"))
- }
-
pub(crate) async fn apply_parked_target_surface_overrides_async(
&mut self,
target_id: &str,
@@ -609,6 +581,7 @@ impl BrowserContext {
Some(DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source,
world_name: None,
has_bidi_channel_argument: false,
@@ -688,6 +661,76 @@ impl BrowserContext {
}
}
+impl CdpConnection {
+ pub(crate) async fn remove_document_start_scripts_for_detached_session_best_effort_async(
+ &mut self,
+ session_id: &str,
+ ) {
+ let renderer_inspector_session_id =
+ self.target_renderer_runtime_inspector_session_id_for_session(Some(session_id));
+ let devtools_session = moli_page_types::DevToolsSessionKey::from_wire_session_id(
+ renderer_inspector_session_id.as_deref(),
+ );
+ let registry_keys = self
+ .with_target_owner_state_for_session_mut(Some(session_id), |owner_state| {
+ owner_state.take_document_start_script_registry_keys_for_session(&devtools_session)
+ })
+ .unwrap_or_default();
+ for registry_key in registry_keys {
+ let pending = self
+ .runtime_session_owner_slot_mut(Some(session_id))
+ .ok()
+ .and_then(|slot| slot.loaded_page_mut())
+ .map(|page| page.start_remove_document_start_script_by_registry_key(&registry_key));
+ let Some(pending) = pending else {
+ continue;
+ };
+ let pending = match pending {
+ Ok(pending) => pending,
+ Err(error) => {
+ tracing::debug!(
+ %error,
+ session_id,
+ registry_key,
+ "failed to start detached-session document-start script cleanup"
+ );
+ continue;
+ }
+ };
+ let completion = match pending.wait().await {
+ Ok(completion) => completion,
+ Err(error) => {
+ tracing::debug!(
+ %error,
+ session_id,
+ registry_key,
+ "detached-session document-start script cleanup was canceled"
+ );
+ continue;
+ }
+ };
+ let Some(page) = self
+ .runtime_session_owner_slot_mut(Some(session_id))
+ .ok()
+ .and_then(|slot| slot.loaded_page_mut())
+ else {
+ continue;
+ };
+ if let Err(error) = page.finish_unit_runtime_page_command(
+ completion,
+ "remove detached-session document-start script",
+ ) {
+ tracing::debug!(
+ %error,
+ session_id,
+ registry_key,
+ "failed to finish detached-session document-start script cleanup"
+ );
+ }
+ }
+ }
+}
+
fn merge_extra_header_layers(layers: &[&[(String, String)]]) -> Vec<(String, String)> {
let mut headers = Vec::new();
for layer in layers {
@@ -698,13 +741,3 @@ fn merge_extra_header_layers(layers: &[&[(String, String)]]) -> Vec<(String, Str
}
headers
}
-
-fn apply_locale_header_if_absent(headers: &mut Vec<(String, String)>, locale: Option<&str>) {
- if let Some(locale) = locale
- && !headers
- .iter()
- .any(|(name, _)| name.eq_ignore_ascii_case("accept-language"))
- {
- headers.push(("Accept-Language".to_owned(), locale.to_owned()));
- }
-}
diff --git a/moli-protocol/src/conn/popup_navigation_work.rs b/moli-protocol/src/conn/popup_navigation_work.rs
index 0f6fe283a..0cb32241c 100644
--- a/moli-protocol/src/conn/popup_navigation_work.rs
+++ b/moli-protocol/src/conn/popup_navigation_work.rs
@@ -24,6 +24,7 @@ pub(crate) struct PopupTargetNavigationOwnerAction {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PopupTargetNavigationKind {
InitialDocument,
+ InitialDocumentAfterDebuggerResume,
NamedTargetReuse,
}
@@ -38,7 +39,7 @@ impl PopupTargetNavigationOwnerAction {
let route = conn.target_session_route_for_target_id(target_id)?;
(route.browser_context_id() == Some(browser_context_id)).then(|| Self {
// Activation has an independent owner action. Unlike a frozen
- // BackgroundTarget route, AuxiliaryTarget keeps this exact target
+ // PageTargetHost route, AuxiliaryTarget keeps this exact target
// addressable if that action changes its residence first.
owner_scope: CommandOwnerScope::from_session_and_owner_route(
None,
@@ -70,6 +71,10 @@ impl PopupTargetNavigationOwnerAction {
self.kind
}
+ pub(crate) fn is_command_followup(&self) -> bool {
+ self.kind != PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume
+ }
+
pub(crate) fn into_parts(
self,
) -> (
diff --git a/moli-protocol/src/conn/protocol_output.rs b/moli-protocol/src/conn/protocol_output.rs
index 83ad78797..5702014e8 100644
--- a/moli-protocol/src/conn/protocol_output.rs
+++ b/moli-protocol/src/conn/protocol_output.rs
@@ -55,11 +55,7 @@ impl CdpConnection {
.iter_mut()
.chain(self.inactive_browser_contexts.iter_mut())
{
- browser_context
- .active_target
- .runtime_slot
- .finish_renderer_page_output_retirement(renderer_page);
- for target in &mut browser_context.background_targets {
+ for target in browser_context.page_targets.iter_mut() {
target
.runtime_slot
.finish_renderer_page_output_retirement(renderer_page);
diff --git a/moli-protocol/src/conn/resource_runtime_support.rs b/moli-protocol/src/conn/resource_runtime_support.rs
index ae4dcc3ce..c7c60978a 100644
--- a/moli-protocol/src/conn/resource_runtime_support.rs
+++ b/moli-protocol/src/conn/resource_runtime_support.rs
@@ -10,14 +10,12 @@ use super::{
impl CdpConnection {
pub(crate) fn invalidate_resource_runtime(&mut self) {
- self.engine
- .ensure_mut()
+ self.active_navigation_engine_mut()
.reset_resource_runtime_without_loaded_page();
}
pub(crate) async fn invalidate_resource_runtime_async(&mut self) {
- self.engine
- .ensure_mut()
+ self.active_navigation_engine_mut()
.reset_resource_runtime_async(None)
.await;
}
@@ -34,12 +32,11 @@ impl CdpConnection {
) -> Result<ResourceRequestClient, String> {
self.apply_active_engine_fetch_overrides();
let storage = self.resource_storage_handles();
- self.engine
- .ensure_mut()
+ let engine = self.active_navigation_engine_mut();
+ engine
.ensure_resource_runtime_ready_for_navigation_storage(storage.into_navigation_storage())
.map_err(|error| format!("failed to initialize resource runtime: {error}"))?;
- self.engine
- .ensure()
+ engine
.resource_request_client()
.ok_or_else(|| "resource request client unavailable".to_owned())
}
@@ -48,63 +45,22 @@ impl CdpConnection {
&mut self,
load_inputs: &TargetNavigationLoadInputs,
) -> Result<ResourceRequestClient, String> {
- if !self.navigation_load_inputs_use_primary_engine(load_inputs) {
- let mut engine = self.background_navigation_engine_for_load_inputs(load_inputs);
- let storage = load_inputs.resource_storage_handles();
- engine
- .ensure_resource_runtime_ready_for_navigation_storage(
- storage.into_navigation_storage(),
- )
- .map_err(|error| format!("failed to initialize resource runtime: {error}"))?;
- let request_client = engine
- .resource_request_client()
- .ok_or_else(|| "resource request client unavailable".to_owned())?;
- if let (Some(browser_context_id), Some(target_id)) = (
- load_inputs.browser_context_id.clone(),
- load_inputs.root_frame_id.clone(),
- ) {
- self.retain_background_navigation_engine(browser_context_id, target_id, engine)?;
- }
- return Ok(request_client);
- }
- self.apply_navigation_load_input_engine_fetch_overrides(load_inputs);
let storage = load_inputs.resource_storage_handles();
- self.engine
- .ensure_mut()
+ let engine = self
+ .configured_navigation_engine_for_load_inputs_mut(load_inputs)
+ .ok_or_else(|| "navigation Page engine unavailable".to_owned())?;
+ engine
.ensure_resource_runtime_ready_for_navigation_storage(storage.into_navigation_storage())
.map_err(|error| format!("failed to initialize resource runtime: {error}"))?;
- self.engine
- .ensure()
+ engine
.resource_request_client()
.ok_or_else(|| "resource request client unavailable".to_owned())
}
- fn navigation_load_inputs_use_primary_engine(
- &self,
- load_inputs: &TargetNavigationLoadInputs,
- ) -> bool {
- let Some(browser_context_id) = load_inputs.browser_context_id.as_deref() else {
- return self
- .engine
- .ensure()
- .browser_context_runtime()
- .shares_state_with(&load_inputs.renderer_runtime.runtime());
- };
- self.browser_context.as_ref().is_some_and(|context| {
- context.id == browser_context_id
- && context.active_target_id() == load_inputs.root_frame_id.as_deref()
- && self
- .engine
- .ensure()
- .browser_context_runtime()
- .shares_state_with(&load_inputs.renderer_runtime.runtime())
- })
- }
-
- fn apply_navigation_load_input_engine_fetch_overrides(
+ fn configured_navigation_engine_for_load_inputs_mut(
&mut self,
load_inputs: &TargetNavigationLoadInputs,
- ) {
+ ) -> Option<&mut moli_core::runtime::NavigationEngine> {
let browser_identity = load_inputs
.browser_identity_override
.clone()
@@ -121,12 +77,39 @@ impl CdpConnection {
let tls_verify_host = load_inputs
.tls_verify_host_override
.unwrap_or(self.base_tls_verify_host);
- let engine = self.engine.ensure_mut();
+ let engine = self.navigation_engine_for_load_inputs_mut(load_inputs)?;
engine.set_browser_identity_override(browser_identity);
engine.set_http_proxy_override(http_proxy);
engine.set_http_no_proxy_override(http_no_proxy);
engine.set_tls_verify_host(tls_verify_host);
engine.set_bypass_service_worker(load_inputs.bypass_service_worker);
+ Some(engine)
+ }
+
+ pub(super) fn navigation_engine_for_load_inputs_mut(
+ &mut self,
+ load_inputs: &TargetNavigationLoadInputs,
+ ) -> Option<&mut moli_core::runtime::NavigationEngine> {
+ match (
+ load_inputs.browser_context_id.as_deref(),
+ load_inputs.root_frame_id.as_deref(),
+ ) {
+ (Some(browser_context_id), Some(target_id)) => {
+ self.ensure_page_navigation_engine_for_target(browser_context_id, target_id)
+ }
+ (Some(browser_context_id), None) => {
+ let active_target_id = self
+ .browser_context_by_id(browser_context_id)
+ .and_then(|context| context.page_targets.active_target_id())
+ .map(str::to_owned);
+ if let Some(target_id) = active_target_id {
+ self.ensure_page_navigation_engine_for_target(browser_context_id, &target_id)
+ } else {
+ Some(self.standalone_navigation_engine.ensure_mut())
+ }
+ }
+ (None, _) => Some(self.standalone_navigation_engine.ensure_mut()),
+ }
}
pub(crate) fn build_registered_browser_resource_runtime_for_navigation_load_inputs(
@@ -173,48 +156,69 @@ impl CdpConnection {
) -> Result<moli_cookie_jar::SharedBrowserCookieStore, String> {
self.apply_active_engine_fetch_overrides();
let storage = self.resource_storage_handles();
- self.engine
- .ensure_mut()
+ self.active_navigation_engine_mut()
.ensure_cookie_store_for_navigation_storage(storage.into_navigation_storage())
.map_err(|error| format!("failed to initialize loader: {error}"))
}
#[cfg(test)]
pub(crate) async fn reset_resource_runtime_async(&mut self) {
- let page = self
+ if let Some((engine, slot)) = self
.browser_context
.as_mut()
- .and_then(|bc| bc.active_target.runtime_slot.loaded_page_mut());
- self.engine
+ .and_then(|context| context.page_targets.active_mut())
+ .and_then(|host| host.navigation_engine_and_runtime_slot_mut())
+ {
+ engine
+ .reset_resource_runtime_async(slot.loaded_page_mut())
+ .await;
+ return;
+ }
+ self.standalone_navigation_engine
.ensure_mut()
- .reset_resource_runtime_async(page)
+ .reset_resource_runtime_async(None)
.await;
}
pub(crate) async fn rebuild_resource_runtime_for_loaded_page_async(&mut self) {
let storage = self.resource_storage_handles();
- let rebuild_result = {
- let page = self
- .browser_context
- .as_mut()
- .and_then(|bc| bc.active_target.runtime_slot.loaded_page_mut());
- self.engine
+ let rebuild_result = if let Some((engine, slot)) = self
+ .browser_context
+ .as_mut()
+ .and_then(|context| context.page_targets.active_mut())
+ .and_then(|host| host.navigation_engine_and_runtime_slot_mut())
+ {
+ engine
+ .rebuild_resource_runtime_for_page_with_storage_async(
+ storage.into_navigation_storage(),
+ slot.loaded_page_mut(),
+ )
+ .await
+ } else {
+ self.standalone_navigation_engine
.ensure_mut()
.rebuild_resource_runtime_for_page_with_storage_async(
storage.into_navigation_storage(),
- page,
+ None,
)
.await
};
if rebuild_result.is_err() {
- let page = self
+ if let Some((engine, slot)) = self
.browser_context
.as_mut()
- .and_then(|bc| bc.active_target.runtime_slot.loaded_page_mut());
- self.engine
- .ensure_mut()
- .reset_resource_runtime_async(page)
- .await;
+ .and_then(|context| context.page_targets.active_mut())
+ .and_then(|host| host.navigation_engine_and_runtime_slot_mut())
+ {
+ engine
+ .reset_resource_runtime_async(slot.loaded_page_mut())
+ .await;
+ } else {
+ self.standalone_navigation_engine
+ .ensure_mut()
+ .reset_resource_runtime_async(None)
+ .await;
+ }
}
}
@@ -224,31 +228,13 @@ impl CdpConnection {
) -> Result<Option<PendingPageCommand>, String> {
let load_inputs = self.navigation_load_inputs_for_session_owner(session_id);
let storage = load_inputs.resource_storage_handles();
- let request_client = if self.navigation_load_inputs_use_primary_engine(&load_inputs) {
- self.apply_navigation_load_input_engine_fetch_overrides(&load_inputs);
- self.engine
- .ensure_mut()
- .rebuild_resource_request_client_for_navigation_storage(
- storage.into_navigation_storage(),
- )
- .map_err(|error| format!("failed to rebuild resource runtime: {error}"))?
- } else {
- let mut engine = self.background_navigation_engine_for_load_inputs(&load_inputs);
- let request_client = engine
- .rebuild_resource_request_client_for_navigation_storage(
- storage.into_navigation_storage(),
- )
- .map_err(|error| format!("failed to rebuild resource runtime: {error}"))?;
- let browser_context_id = load_inputs.browser_context_id.clone().ok_or_else(|| {
- "background resource rebuild has no BrowserContext owner".to_owned()
- })?;
- let target_id = load_inputs
- .root_frame_id
- .clone()
- .ok_or_else(|| "background resource rebuild has no target owner".to_owned())?;
- self.retain_background_navigation_engine(browser_context_id, target_id, engine)?;
- request_client
- };
+ let request_client = self
+ .configured_navigation_engine_for_load_inputs_mut(&load_inputs)
+ .ok_or_else(|| "navigation Page engine unavailable".to_owned())?
+ .rebuild_resource_request_client_for_navigation_storage(
+ storage.into_navigation_storage(),
+ )
+ .map_err(|error| format!("failed to rebuild resource runtime: {error}"))?;
let Some(page) = self.resource_runtime_apply_page_for_session_owner(session_id) else {
return Ok(None);
};
diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rs
index a6a8b33e1..389ecd078 100644
--- a/moli-protocol/src/conn/runtime_eval.rs
+++ b/moli-protocol/src/conn/runtime_eval.rs
@@ -23,8 +23,7 @@ use moli_core::{
use crate::conn::state::{
DevToolsSessionState, PreparedRendererCallTermination, SessionRendererCallReplay,
- SessionRendererCallTermination, devtools_sessions_have_pending_inspector_awaits,
- drain_pending_inspector_awaits_for_devtools_sessions,
+ SessionRendererCallTermination,
};
use crate::domains::command_output::protocol_message_background_event;
use crate::domains::runtime_context_events::{
@@ -231,20 +230,21 @@ enum BidiChannelListenerRoute {
}
fn unregister_runtime_remote_object_group_from_parked_page_session_state(
- page_session_state: &mut ParkedPageSessionState,
+ page_session_state: &mut TargetPageState,
session_id: Option<&str>,
object_group: &str,
) {
if let Some(session_id) = session_id
&& let Some(state) = page_session_state
- .auxiliary_devtools_session_states
- .get_mut(session_id)
+ .devtools_sessions
+ .attached_mut(session_id)
{
state.unregister_runtime_remote_object_group(object_group);
return;
}
page_session_state
- .devtools_session_state
+ .devtools_sessions
+ .primary_mut()
.unregister_runtime_remote_object_group(object_group);
}
@@ -565,7 +565,8 @@ fn collect_moli_diagnostics_pending_snapshots(
});
}
- for target in &mut browser_context.background_targets {
+ let browser_context_id = browser_context.id.clone();
+ for target in browser_context.background_targets_mut() {
if !target.has_loaded_page() {
continue;
}
@@ -575,7 +576,7 @@ fn collect_moli_diagnostics_pending_snapshots(
.start_page_diagnostics_snapshot()
.map_err(|error| error.to_string())?;
pending.push(PendingMoliDiagnosticsPageSnapshot {
- browser_context_id: browser_context.id.clone(),
+ browser_context_id: browser_context_id.clone(),
target_id: Some(target.target_id().to_owned()),
pending: pending_snapshot,
});
@@ -1627,12 +1628,10 @@ impl CdpConnection {
return true;
}
self.browser_contexts().any(|browser_context| {
- devtools_sessions_have_pending_inspector_awaits(
- &browser_context.devtools_session_state,
- &browser_context.auxiliary_devtools_session_states,
- ) || browser_context
- .target_parking
- .has_pending_inspector_awaits()
+ browser_context
+ .page_targets
+ .iter()
+ .any(|target| target.has_pending_inspector_awaits())
|| browser_context
.shared_worker_targets
.values()
@@ -1672,16 +1671,15 @@ impl CdpConnection {
pub(crate) fn fail_pending_inspector_awaits_from_page_session_state_for_sessions_background_events_into(
out: &mut Vec<BackgroundProtocolEvent>,
- page_session_state: &mut ParkedPageSessionState,
+ page_session_state: &mut TargetPageState,
primary_session_id: Option<&str>,
session_ids: &[&str],
reason: &'static str,
) {
- for (cdp_id, entry) in drain_pending_inspector_awaits_for_devtools_sessions(
- &mut page_session_state.devtools_session_state,
- &mut page_session_state.auxiliary_devtools_session_states,
- session_ids,
- ) {
+ for (cdp_id, entry) in page_session_state
+ .devtools_sessions
+ .drain_pending_inspector_awaits_for_sessions(session_ids)
+ {
if let Some(listener) = entry.bidi_channel_listener() {
unregister_runtime_remote_object_group_from_parked_page_session_state(
page_session_state,
@@ -1701,7 +1699,8 @@ impl CdpConnection {
&& session_ids.contains(&primary_session_id)
{
let terminated = page_session_state
- .devtools_session_state
+ .devtools_sessions
+ .primary_mut()
.terminate_all_renderer_calls(reason);
push_terminated_renderer_call_error_background_events(
out,
@@ -1712,8 +1711,8 @@ impl CdpConnection {
}
for session_id in session_ids {
let Some(state) = page_session_state
- .auxiliary_devtools_session_states
- .get_mut(*session_id)
+ .devtools_sessions
+ .attached_mut(session_id)
else {
continue;
};
@@ -2443,24 +2442,26 @@ impl CdpConnection {
};
if current_devtools_session_id.is_some()
&& browser_context
- .devtools_session_state
+ .devtools_sessions
+ .primary()
.has_runtime_remote_object_id(object_id)
{
return true;
}
- for (session_id, state) in &browser_context.auxiliary_devtools_session_states {
- if Some(session_id.as_str()) != current_devtools_session_id
+ for (session_id, state) in browser_context.devtools_sessions.attached_entries() {
+ if Some(session_id) != current_devtools_session_id
&& state.has_runtime_remote_object_id(object_id)
{
return true;
}
}
} else if browser_context
- .devtools_session_state
+ .devtools_sessions
+ .primary()
.has_runtime_remote_object_id(object_id)
|| browser_context
- .auxiliary_devtools_session_states
- .values()
+ .devtools_sessions
+ .attached_states()
.any(|state| state.has_runtime_remote_object_id(object_id))
{
return true;
@@ -2473,21 +2474,24 @@ impl CdpConnection {
devtools_session_id,
} if browser_context_id == &browser_context.id => match target_id.as_deref() {
Some(target_id) if !browser_context.is_active_target(target_id) => {
- browser_context
- .target_parking
- .runtime_remote_object_id_known_for_different_page_owner(
- target_id,
- devtools_session_id.as_deref(),
- object_id,
- )
+ browser_context.background_targets().any(|target| {
+ if target.is_target(target_id) {
+ target.has_runtime_remote_object_id_for_different_session(
+ devtools_session_id.as_deref(),
+ object_id,
+ )
+ } else {
+ target.has_runtime_remote_object_id(object_id)
+ }
+ })
}
Some(_) | None => browser_context
- .target_parking
- .has_runtime_remote_object_id(object_id),
+ .background_targets()
+ .any(|target| target.has_runtime_remote_object_id(object_id)),
},
_ => browser_context
- .target_parking
- .has_runtime_remote_object_id(object_id),
+ .background_targets()
+ .any(|target| target.has_runtime_remote_object_id(object_id)),
};
if parked_has_different_owner {
return true;
@@ -4375,7 +4379,7 @@ impl CdpConnection {
.active_target_id_owned()
}),
CdpSessionRoute::AuxiliaryTarget { target_id, .. }
- | CdpSessionRoute::BackgroundTarget { target_id, .. } => Some(target_id),
+ | CdpSessionRoute::PageTargetHost { target_id, .. } => Some(target_id),
CdpSessionRoute::TabTarget { .. }
| CdpSessionRoute::SharedWorkerTarget { .. }
| CdpSessionRoute::DedicatedWorkerTarget { .. }
@@ -6481,14 +6485,15 @@ mod tests {
.browser_context
.as_mut()
.expect("test browser context should remain loaded");
- crate::conn::state::prepare_renderer_call_replacements_for_devtools_sessions(
- Some("SID-navigation-termination"),
- &mut browser_context.devtools_session_state,
- &mut browser_context.auxiliary_devtools_session_states,
- old_attachment,
- terminal_attachment,
- )
- .expect("navigation replacement should prepare")
+ let page_state = browser_context.active_page_state_mut();
+ page_state
+ .devtools_sessions
+ .prepare_renderer_call_replacements(
+ Some("SID-navigation-termination"),
+ old_attachment,
+ terminal_attachment,
+ )
+ .expect("navigation replacement should prepare")
};
let (replacement_attachment, terminations, replays) = replacements.into_parts();
assert_eq!(replacement_attachment, terminal_attachment);
@@ -6578,14 +6583,15 @@ mod tests {
.browser_context
.as_mut()
.expect("test browser context should remain loaded");
- crate::conn::state::prepare_renderer_call_replacements_for_devtools_sessions(
- Some("SID-navigation-primary"),
- &mut browser_context.devtools_session_state,
- &mut browser_context.auxiliary_devtools_session_states,
- old_attachment,
- terminal_attachment,
- )
- .expect("navigation replacement should prepare for every session")
+ let page_state = browser_context.active_page_state_mut();
+ page_state
+ .devtools_sessions
+ .prepare_renderer_call_replacements(
+ Some("SID-navigation-primary"),
+ old_attachment,
+ terminal_attachment,
+ )
+ .expect("navigation replacement should prepare for every session")
};
let (_, terminations, replays) = replacements.into_parts();
assert_eq!(terminations.len(), 2);
@@ -6677,14 +6683,11 @@ mod tests {
.browser_context
.as_mut()
.expect("test browser context should remain loaded");
- crate::conn::state::prepare_renderer_call_replacements_for_devtools_sessions(
- None,
- &mut browser_context.devtools_session_state,
- &mut browser_context.auxiliary_devtools_session_states,
- old_attachment,
- terminal_attachment,
- )
- .expect("sessionless navigation replacement should prepare")
+ let page_state = browser_context.active_page_state_mut();
+ page_state
+ .devtools_sessions
+ .prepare_renderer_call_replacements(None, old_attachment, terminal_attachment)
+ .expect("sessionless navigation replacement should prepare")
};
let (_, terminations, replays) = replacements.into_parts();
assert_eq!(terminations.len(), 1);
@@ -7435,13 +7438,11 @@ mod tests {
let mut browser_context = BrowserContext::new("BID-owner".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-bg".to_owned(),
- Some("SID-bg".to_owned()),
- "about:blank#bg".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-bg".to_owned(),
+ Some("SID-bg".to_owned()),
+ "about:blank#bg".to_owned(),
+ ));
conn.browser_context = Some(browser_context);
conn.register_pending_inspector_await(1, Some("SID-active"));
@@ -7450,17 +7451,15 @@ mod tests {
{
let browser_context = conn.browser_context.as_ref().expect("browser context");
assert!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.has_pending_inspector_awaits(),
"active DevTools session should physically store its pending await"
);
assert!(
browser_context
- .target_parking
- .page_session_state("TID-bg")
- .is_some_and(|state| state
- .devtools_session_state
+ .parked_page_session_state("TID-bg")
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.has_pending_inspector_awaits()),
"parked DevTools session should physically store its pending await"
);
@@ -7516,13 +7515,11 @@ mod tests {
let mut browser_context = BrowserContext::new("BID-same-id".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-bg".to_owned(),
- Some("SID-bg".to_owned()),
- "about:blank#bg".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-bg".to_owned(),
+ Some("SID-bg".to_owned()),
+ "about:blank#bg".to_owned(),
+ ));
conn.browser_context = Some(browser_context);
conn.register_pending_inspector_await(1, Some("SID-active"));
@@ -7796,13 +7793,11 @@ mod tests {
let mut browser_context = BrowserContext::new("BID-owner-output".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context
- .background_targets
- .push(BackgroundTarget::with_url(
- "TID-bg".to_owned(),
- Some("SID-bg".to_owned()),
- "about:blank#bg".to_owned(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::with_url(
+ "TID-bg".to_owned(),
+ Some("SID-bg".to_owned()),
+ "about:blank#bg".to_owned(),
+ ));
conn.browser_context = Some(browser_context);
conn.try_register_pending_inspector_await_with_object_group(
diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rs
index 44470f020..3cec5bcf9 100644
--- a/moli-protocol/src/conn/runtime_load.rs
+++ b/moli-protocol/src/conn/runtime_load.rs
@@ -2271,7 +2271,10 @@ impl CdpConnection {
body_progress_source: MainDocumentBodyProgressSource,
) -> Result<NavigationLoadOutcome, String> {
if load_inputs.browser_context_id.is_none() {
- let page_reservation = self.engine.ensure().reserve_page_for_creation();
+ let page_reservation = self
+ .standalone_navigation_engine
+ .ensure()
+ .reserve_page_for_creation();
if let Some(navigation) = self
.load_inline_html_navigation_async(
page_reservation,
@@ -2285,7 +2288,7 @@ impl CdpConnection {
return navigation;
}
if let Some(navigation) = load_data_url_navigation_with_engine_async(
- self.engine.ensure_mut(),
+ self.standalone_navigation_engine.ensure_mut(),
page_reservation,
&load_inputs,
method,
@@ -2510,35 +2513,22 @@ impl CdpConnection {
&self,
load_inputs: &TargetNavigationLoadInputs,
) -> NavigationEngine {
- // Same-browser-context CDP background targets retain only another
- // NavigationEngine wrapper; their page contexts still live under the
- // same renderer owner. Different browser contexts keep distinct
- // renderer owners.
- let mut engine = if self
- .engine
- .ensure()
- .browser_context_runtime()
- .shares_state_with(&load_inputs.renderer_runtime.runtime())
- {
- NavigationEngine::new_with_runtime_config_and_shared_renderer_owner(
- self.navigation_runtime_config_for_load_inputs(load_inputs),
- self.engine.ensure(),
- )
- .expect("active shared BrowserContext owner must be live")
- } else if let Some(engine) = self
- .retained_background_navigation_engine_for_load_inputs(load_inputs)
- .cloned()
- {
- engine
- } else {
- NavigationEngine::new_with_runtime_config_and_browser_context_access(
- self.navigation_runtime_config_for_load_inputs(load_inputs),
- load_inputs.renderer_runtime.clone(),
- )
- .expect("navigation load BrowserContext owner must be live")
- };
+ let mut engine =
+ if let Some(source) = self.page_navigation_engine_for_load_inputs(load_inputs) {
+ NavigationEngine::new_with_runtime_config_and_shared_renderer_owner(
+ self.navigation_runtime_config_for_load_inputs(load_inputs),
+ source,
+ )
+ .expect("target Page renderer owner must be live")
+ } else {
+ NavigationEngine::new_with_runtime_config_and_browser_context_access(
+ self.navigation_runtime_config_for_load_inputs(load_inputs),
+ load_inputs.renderer_runtime.clone(),
+ )
+ .expect("navigation load BrowserContext owner must be live")
+ };
self.apply_fetch_overrides_to_background_navigation_engine(&mut engine, load_inputs);
- if !self.active_resource_runtime_matches_navigation_load_inputs(load_inputs) {
+ if !self.page_resource_runtime_matches_navigation_load_inputs(load_inputs) {
// Sharing the renderer owner must not implicitly share a transport
// runtime that was rejected above for a different target policy.
// The next request rebuilds from this engine's effective fetch
@@ -2554,23 +2544,23 @@ impl CdpConnection {
engine
}
- fn navigation_runtime_config_for_load_inputs(
+ fn page_navigation_engine_for_load_inputs(
&self,
load_inputs: &TargetNavigationLoadInputs,
- ) -> moli_core::runtime::NavigationRuntimeConfig {
- let mut config = self.engine.runtime_config();
- *config.fetch_config_mut() = self.fetch_config_for_load_inputs(load_inputs);
- config
+ ) -> Option<&NavigationEngine> {
+ let browser_context_id = load_inputs.browser_context_id.as_deref()?;
+ let target_id = load_inputs.root_frame_id.as_deref()?;
+ self.browser_context_by_id(browser_context_id)?
+ .page_navigation_engine(target_id)
}
- fn retained_background_navigation_engine_for_load_inputs(
+ fn navigation_runtime_config_for_load_inputs(
&self,
load_inputs: &TargetNavigationLoadInputs,
- ) -> Option<&NavigationEngine> {
- let browser_context_id = load_inputs.browser_context_id.as_ref()?;
- let target_id = load_inputs.root_frame_id.as_ref()?;
- self.retained_background_navigation_engines
- .get(&(browser_context_id.clone(), target_id.clone()))
+ ) -> moli_core::runtime::NavigationRuntimeConfig {
+ let mut config = self.standalone_navigation_engine.runtime_config();
+ *config.fetch_config_mut() = self.fetch_config_for_load_inputs(load_inputs);
+ config
}
fn apply_fetch_overrides_to_background_navigation_engine(
@@ -2608,39 +2598,43 @@ impl CdpConnection {
&mut self,
load_inputs: &TargetNavigationLoadInputs,
) -> Option<moli_core::network::BrowserResourceRuntime> {
- if !self.active_resource_runtime_matches_navigation_load_inputs(load_inputs) {
+ if !self.page_resource_runtime_matches_navigation_load_inputs(load_inputs) {
return None;
}
let resource_storage = load_inputs.resource_storage_handles();
- self.engine
- .ensure_mut()
+ let browser_context_id = load_inputs.browser_context_id.as_deref()?;
+ let target_id = load_inputs.root_frame_id.as_deref()?;
+ let engine = self
+ .browser_context_by_id_mut(browser_context_id)?
+ .page_navigation_engine_mut(target_id)?;
+ engine
.ensure_resource_runtime_ready_for_navigation_storage(
resource_storage.into_navigation_storage(),
)
.ok()?;
- self.engine
- .ensure()
+ engine
.resource_request_client()
.map(|client| client.browser_resource_runtime())
}
- fn active_resource_runtime_matches_navigation_load_inputs(
+ fn page_resource_runtime_matches_navigation_load_inputs(
&self,
load_inputs: &TargetNavigationLoadInputs,
) -> bool {
- if !self
- .engine
- .ensure()
+ let Some(engine) = self.page_navigation_engine_for_load_inputs(load_inputs) else {
+ return false;
+ };
+ if !engine
.browser_context_runtime()
.shares_state_with(&load_inputs.renderer_runtime.runtime())
{
return false;
}
let fetch_config = self.fetch_config_for_load_inputs(load_inputs);
- fetch_config.browser_identity() == self.engine.fetch_config().browser_identity()
- && fetch_config.http_proxy() == self.http_proxy()
- && fetch_config.http_no_proxy() == self.http_no_proxy()
- && fetch_config.tls_verify_host() == self.tls_verify_host()
+ fetch_config.browser_identity() == engine.fetch_config().browser_identity()
+ && fetch_config.http_proxy() == engine.fetch_config().http_proxy()
+ && fetch_config.http_no_proxy() == engine.fetch_config().http_no_proxy()
+ && fetch_config.tls_verify_host() == engine.fetch_config().tls_verify_host()
}
fn fetch_config_for_load_inputs(
@@ -2678,7 +2672,15 @@ impl CdpConnection {
pub async fn load_page_via_runtime_async(&mut self, raw_url: &str) -> Result<Page, String> {
let navigation = self.load_navigation_via_runtime_async(raw_url).await?;
if let Some(engine) = navigation.navigation_engine {
- self.replace_navigation_engine(engine);
+ let page_owner = self.browser_context.as_ref().and_then(|context| {
+ Some((context.id.clone(), context.active_target_id()?.to_owned()))
+ });
+ if let Some((browser_context_id, target_id)) = page_owner {
+ self.install_page_navigation_engine(&browser_context_id, &target_id, engine)
+ .expect("loaded page must retain its exact PageTargetHost engine");
+ } else {
+ self.replace_standalone_navigation_engine(engine);
+ }
}
Ok(navigation.page)
}
@@ -2692,7 +2694,7 @@ impl CdpConnection {
request_headers: Vec<(String, String)>,
) -> Option<Result<NavigationLoadOutcome, String>> {
load_inline_html_navigation_with_engine_async(
- self.engine.ensure_mut(),
+ self.standalone_navigation_engine.ensure_mut(),
page_reservation,
load_inputs,
method,
@@ -2900,29 +2902,18 @@ impl CdpConnection {
from_cache: false,
negotiated_http_version: None,
};
- let page_reservation = self.engine.ensure().reserve_page_for_creation();
- self.bind_renderer_page_reservation_for_session_owner(
+ self.build_navigation_from_captured_raw_response_with_load_inputs_async(
session_id,
load_inputs,
- page_reservation,
- );
- prepare_navigation_from_captured_raw_response_with_engine_async(
- self.engine.ensure_mut(),
- page_reservation,
- load_inputs,
requested_url,
request_method,
request_headers,
head,
response_body,
- body_progress_source,
network_observation_journal,
- None,
- false,
- RendererReplyBoundary::Stage,
+ body_progress_source,
)
.await
- .map(NavigationLoadOutcome::response_commit_ready)
}
async fn build_loaded_navigation_from_buffered_response_with_request_cookie_report_async(
@@ -2946,8 +2937,8 @@ impl CdpConnection {
.main_document_commit_for_final_url(&requested_url, None)
.map(Arc::new);
let built = self
- .engine
- .ensure_mut()
+ .navigation_engine_for_load_inputs_mut(load_inputs)
+ .ok_or_else(|| "navigation Page engine unavailable".to_owned())?
.build_html_page_from_response_with_storage_and_inspector_session_restores_async(
page_storage.into_navigation_storage(),
requested_url.clone(),
@@ -3046,11 +3037,11 @@ impl CdpConnection {
return Err("Network emulation offline".to_owned());
}
let resource_storage = load_inputs.resource_storage_handles();
- self.engine
- .ensure_mut()
- .set_bypass_service_worker(load_inputs.bypass_service_worker);
- self.engine
- .ensure_mut()
+ let engine = self
+ .navigation_engine_for_load_inputs_mut(&load_inputs)
+ .ok_or_else(|| "navigation Page engine unavailable".to_owned())?;
+ engine.set_bypass_service_worker(load_inputs.bypass_service_worker);
+ engine
.fetch_navigation_response_with_storage_async(
resource_storage.into_navigation_storage(),
load_inputs.navigation_initiator_url.as_ref(),
@@ -3238,8 +3229,8 @@ impl CdpConnection {
.main_document_commit_for_final_url(&final_url, None)
.map(Arc::new);
let built = self
- .engine
- .ensure_mut()
+ .navigation_engine_for_load_inputs_mut(&load_inputs)
+ .ok_or_else(|| "navigation Page engine unavailable".to_owned())?
.build_html_page_from_response_with_storage_and_inspector_session_restores_async(
page_storage.into_navigation_storage(),
requested_url.clone(),
@@ -3472,14 +3463,35 @@ impl CdpConnection {
));
}
- let page_reservation = self.engine.ensure().reserve_page_for_creation();
- self.bind_renderer_page_reservation_for_session_owner(
- session_id,
- load_inputs,
- page_reservation,
- );
- prepare_navigation_from_captured_raw_response_with_engine_async(
- self.engine.ensure_mut(),
+ if load_inputs.browser_context_id.is_none() {
+ let page_reservation = self
+ .standalone_navigation_engine
+ .ensure()
+ .reserve_page_for_creation();
+ return prepare_navigation_from_captured_raw_response_with_engine_async(
+ self.standalone_navigation_engine.ensure_mut(),
+ page_reservation,
+ load_inputs,
+ requested_url,
+ request_method,
+ request_headers,
+ head,
+ body,
+ body_progress_source,
+ network_observation_journal,
+ None,
+ false,
+ RendererReplyBoundary::Stage,
+ )
+ .await
+ .map(NavigationLoadOutcome::response_commit_ready);
+ }
+
+ let mut engine = self.background_navigation_engine_for_load_inputs(load_inputs);
+ let page_reservation =
+ self.reserve_renderer_page_for_session_owner(session_id, load_inputs, &engine);
+ let navigation = prepare_navigation_from_captured_raw_response_with_engine_async(
+ &mut engine,
page_reservation,
load_inputs,
requested_url,
@@ -3493,8 +3505,10 @@ impl CdpConnection {
false,
RendererReplyBoundary::Stage,
)
- .await
- .map(NavigationLoadOutcome::response_commit_ready)
+ .await?;
+ Ok(NavigationLoadOutcome::response_commit_ready(
+ navigation.with_navigation_engine(engine),
+ ))
}
pub async fn build_navigation_from_streaming_raw_response_async(
@@ -3600,9 +3614,12 @@ impl CdpConnection {
let (response, network_observation_journal) =
response.into_parts_with_observation_journal();
if load_inputs.browser_context_id.is_none() {
- let page_reservation = self.engine.ensure().reserve_page_for_creation();
+ let page_reservation = self
+ .standalone_navigation_engine
+ .ensure()
+ .reserve_page_for_creation();
return build_navigation_from_streaming_raw_response_with_engine_async(
- self.engine.ensure_mut(),
+ self.standalone_navigation_engine.ensure_mut(),
page_reservation,
load_inputs,
requested_url,
diff --git a/moli-protocol/src/conn/settings/engine.rs b/moli-protocol/src/conn/settings/engine.rs
index 991988a80..72d592d1f 100644
--- a/moli-protocol/src/conn/settings/engine.rs
+++ b/moli-protocol/src/conn/settings/engine.rs
@@ -12,23 +12,24 @@ impl CdpConnection {
let http_proxy = self
.browser_context
.as_ref()
- .and_then(|bc| bc.http_proxy_override.clone())
+ .and_then(|bc| bc.effective_active_http_proxy_override_owned())
.or_else(|| self.base_http_proxy.clone());
let http_no_proxy = self
.browser_context
.as_ref()
- .and_then(|bc| bc.http_no_proxy_override.clone())
+ .and_then(|bc| bc.effective_active_http_no_proxy_override_owned())
.or_else(|| self.base_http_no_proxy.clone());
let tls_verify_host = self
.browser_context
.as_ref()
- .and_then(|bc| bc.tls_verify_host_override)
+ .and_then(|bc| bc.effective_active_tls_verify_host_override())
.unwrap_or(self.base_tls_verify_host);
let bypass_service_worker = self
.browser_context
.as_ref()
- .is_some_and(|bc| bc.network_policy.bypass_service_worker());
- let engine = self.engine.ensure_mut();
+ .and_then(|bc| bc.page_targets.active())
+ .is_some_and(|host| host.network_policy.bypass_service_worker());
+ let engine = self.active_navigation_engine_mut();
engine.set_browser_identity_override(browser_identity);
engine.set_http_proxy_override(http_proxy);
engine.set_http_no_proxy_override(http_no_proxy);
@@ -38,7 +39,7 @@ impl CdpConnection {
pub async fn set_tls_verify_host_async(&mut self, enabled: bool) {
if let Some(browser_context) = self.browser_context.as_mut() {
- browser_context.tls_verify_host_override = Some(enabled);
+ browser_context.default_tls_verify_host_override = Some(enabled);
} else {
self.base_tls_verify_host = enabled;
}
@@ -49,7 +50,7 @@ impl CdpConnection {
pub fn tls_verify_host(&self) -> bool {
self.browser_context
.as_ref()
- .and_then(|bc| bc.tls_verify_host_override)
+ .and_then(|bc| bc.effective_active_tls_verify_host_override())
.unwrap_or(self.base_tls_verify_host)
}
@@ -121,7 +122,7 @@ impl CdpConnection {
#[cfg(test)]
pub(crate) async fn set_http_proxy_override_async(&mut self, proxy: Option<String>) {
if let Some(browser_context) = self.browser_context.as_mut() {
- browser_context.http_proxy_override = proxy;
+ browser_context.default_http_proxy_override = proxy;
} else {
self.base_http_proxy = proxy;
}
@@ -132,7 +133,12 @@ impl CdpConnection {
pub fn http_proxy(&self) -> Option<&str> {
self.browser_context
.as_ref()
- .and_then(|bc| bc.http_proxy_override.as_deref())
+ .and_then(|bc| {
+ bc.page_targets
+ .active()
+ .and_then(|host| host.http_proxy_override.as_deref())
+ .or(bc.default_http_proxy_override.as_deref())
+ })
.or(self.base_http_proxy.as_deref())
}
@@ -148,12 +154,22 @@ impl CdpConnection {
pub fn http_no_proxy(&self) -> Option<&str> {
self.browser_context
.as_ref()
- .and_then(|bc| bc.http_no_proxy_override.as_deref())
+ .and_then(|bc| {
+ bc.page_targets
+ .active()
+ .and_then(|host| host.http_no_proxy_override.as_deref())
+ .or(bc.default_http_no_proxy_override.as_deref())
+ })
.or(self.base_http_no_proxy.as_deref())
}
pub(crate) fn fetch_config(&self) -> &moli_fetch::FetchConfig {
- self.engine.fetch_config()
+ self.browser_context
+ .as_ref()
+ .and_then(|context| context.page_targets.active())
+ .and_then(crate::conn::state::PageTargetHost::navigation_engine)
+ .map(moli_core::runtime::NavigationEngine::fetch_config)
+ .unwrap_or_else(|| self.standalone_navigation_engine.fetch_config())
}
pub(crate) fn base_browser_identity(&self) -> &moli_browser_profile::BrowserIdentityProfile {
diff --git a/moli-protocol/src/conn/state/browser_context.rs b/moli-protocol/src/conn/state/browser_context.rs
index 3d7a32d39..cb19bdac0 100644
--- a/moli-protocol/src/conn/state/browser_context.rs
+++ b/moli-protocol/src/conn/state/browser_context.rs
@@ -9,9 +9,10 @@ use moli_cookie_jar::{
};
use moli_core::network::{SharedWebStorageStore, new_shared_web_storage_store};
use moli_core::runtime::{
- NavigationPageStorageHandles, NavigationResourceStorageHandles, RendererBrowserContextRuntime,
- RendererBrowserContextRuntimeOwner, RendererBrowserContextRuntimeOwnerAccess,
- RendererSharedWorkerRuntimeDiagnostics, storage_partition::StoragePartitionState,
+ NavigationEngine, NavigationPageStorageHandles, NavigationResourceStorageHandles,
+ NavigationRuntimeConfig, RendererBrowserContextRuntime, RendererBrowserContextRuntimeOwner,
+ RendererBrowserContextRuntimeOwnerAccess, RendererSharedWorkerRuntimeDiagnostics,
+ storage_partition::StoragePartitionState,
};
use moli_core::storage::{
SharedIndexedDbManager, SharedStorageBucketStore, StorageBucketIdentity, WeakIndexedDbManager,
@@ -23,26 +24,25 @@ use serde_json::{Value, json};
use super::{
DevToolsSessionState,
dedicated_worker_target::DedicatedWorkerTargetState,
- devtools_sessions_have_pending_inspector_awaits,
- devtools_sessions_pending_inspector_await_count,
emulation::{
- EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedMediaOverrides,
- EmulatedNetworkConditions,
+ EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedNetworkConditions,
},
- identity::TargetIdentityState,
javascript_dialog::TargetPreparedJavaScriptDialog,
page_slot::{DocumentNavigationToken, DocumentStartScript},
- parking::{TargetOwnerState, TargetParkingStateStore},
+ page_target_host::{PageTargetHost, PageTargetRegistry},
+ parking::TargetOwnerState,
service_worker_target::ServiceWorkerTargetState,
- session::{ActiveTargetState, TargetNetworkPolicyState},
+ session::TargetPageState,
shared_worker_target::SharedWorkerTargetState,
};
+#[cfg(test)]
+const TEST_FIXTURE_PAGE_TARGET_ID: &str = "__moli_test_fixture_page__";
+
pub struct BrowserContext {
pub id: String,
storage_partition: BrowserContextStoragePartition,
- target_id: Option<String>,
- session_id: Option<String>,
+ pub(crate) page_targets: PageTargetRegistry,
pub auxiliary_target_sessions: HashMap<String, String>,
// Chromium exposes the live creator target, immutable creator frame, and
// window.opener access as three independent TargetInfo properties.
@@ -57,15 +57,10 @@ pub struct BrowserContext {
pub target_window_names: HashMap<String, String>,
pub target_popup_ids: HashMap<String, u64>,
pending_popup_javascript_dialogs: HashMap<u64, Vec<TargetPreparedJavaScriptDialog>>,
- pub background_targets: Vec<super::parking::BackgroundTarget>,
pub(crate) shared_worker_targets: BTreeMap<SharedWorkerInstanceId, SharedWorkerTargetState>,
pub(crate) dedicated_worker_targets: BTreeMap<u64, DedicatedWorkerTargetState>,
pub(crate) service_worker_targets: BTreeMap<u64, ServiceWorkerTargetState>,
pub(crate) service_worker_domain_sessions: BTreeSet<Option<String>>,
- target_identity: TargetIdentityState,
- pub(crate) devtools_session_state: DevToolsSessionState,
- pub(crate) auxiliary_devtools_session_states: HashMap<String, DevToolsSessionState>,
- pub(crate) network_policy: TargetNetworkPolicyState,
pub(crate) default_extra_headers: Vec<(String, String)>,
pub(crate) global_extra_headers: Vec<(String, String)>,
pub(crate) default_browser_identity_override:
@@ -76,36 +71,20 @@ pub struct BrowserContext {
pub(crate) default_geolocation_override: Option<EmulatedGeolocationOverrideState>,
pub(crate) global_network_conditions: Option<EmulatedNetworkConditions>,
pub(crate) global_geolocation_override: Option<EmulatedGeolocationOverrideState>,
- pub tls_verify_host_override: Option<bool>,
- pub http_proxy_override: Option<String>,
- pub http_no_proxy_override: Option<String>,
+ pub(crate) global_cache_disabled: bool,
+ pub(crate) default_http_proxy_override: Option<String>,
+ pub(crate) default_http_no_proxy_override: Option<String>,
+ pub(crate) default_tls_verify_host_override: Option<bool>,
pub proxy_autoconfig_url: Option<String>,
pub proxy_socks_version: Option<u8>,
pub(crate) default_emulated_device_metrics: Option<EmulatedDeviceMetrics>,
- pub locale_override: Option<String>,
- pub timezone_override: Option<String>,
- pub(crate) network_conditions: Option<EmulatedNetworkConditions>,
- pub geolocation_override: Option<EmulatedGeolocationOverrideState>,
- pub emulated_media: EmulatedMediaOverrides,
- pub emulated_device_metrics: Option<EmulatedDeviceMetrics>,
- pub cpu_throttling_rate: f64,
- pub input_intercept_drags_enabled: bool,
- pub input_drag_intercepted: bool,
- pub touch_emulation_enabled: bool,
- pub emit_touch_events_for_mouse: bool,
- pub focus_emulation_enabled: bool,
- pub script_execution_disabled: bool,
- pub css_enabled: bool,
pub(crate) next_default_document_start_script_id: u32,
pub(crate) default_document_start_scripts: Vec<(String, DocumentStartScript)>,
- pub(crate) document_cookie_manager_surface:
- super::super::cookie_manager_surface::BrowserContextCookieManagerSurface,
- pub(crate) target_parking: TargetParkingStateStore,
- pub dom_remote_object_node_cache: HashMap<String, Value>,
- pub(crate) active_target: ActiveTargetState,
pub(crate) storage_quota_overrides: HashMap<String, f64>,
pub(crate) http_cache_root: Option<PathBuf>,
pub(crate) http_cache_max_bytes: Option<u64>,
+ pub(crate) page_navigation_runtime_config: Option<NavigationRuntimeConfig>,
+ renderer_output_transport_sender: Option<moli_core::RendererOutputTransportSender>,
// Keep the sole strong per-context network owner last. Protocol teardown
// must drop pages and NavigationEngines before this field is released.
pub(crate) renderer_runtime_owner: Option<RendererBrowserContextRuntimeOwner>,
@@ -371,18 +350,46 @@ impl std::fmt::Debug for BrowserContext {
f.debug_struct("BrowserContext")
.field("id", &self.id)
.field("storage_partition", &self.storage_partition)
- .field("target_id", &self.target_id)
- .field("session_id", &self.session_id)
+ .field("active_target_id", &self.active_target_id())
+ .field("active_session_id", &self.active_session_id())
.field("has_loaded_page", &self.has_loaded_page())
.finish_non_exhaustive()
}
}
+impl std::ops::Deref for BrowserContext {
+ type Target = TargetPageState;
+
+ fn deref(&self) -> &Self::Target {
+ self.active_page_state()
+ }
+}
+
+impl std::ops::DerefMut for BrowserContext {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.active_page_state_mut()
+ }
+}
+
fn usize_to_u64_saturating(value: usize) -> u64 {
u64::try_from(value).unwrap_or(u64::MAX)
}
impl BrowserContext {
+ pub(crate) fn active_page_state(&self) -> &TargetPageState {
+ self.page_targets
+ .active()
+ .expect("BrowserContext has no active page target")
+ .state()
+ }
+
+ pub(crate) fn active_page_state_mut(&mut self) -> &mut TargetPageState {
+ self.page_targets
+ .active_mut()
+ .expect("BrowserContext has no active page target")
+ .state_mut()
+ }
+
/// Parks a dialog only until the matching lightweight-popup target obtains
/// a concrete protocol attachment.
///
@@ -416,7 +423,19 @@ impl BrowserContext {
}
pub fn new(id: String) -> Self {
- Self::new_with_initial_cookies(id, Vec::new())
+ let context = Self::new_with_initial_cookies(id, Vec::new());
+ #[cfg(test)]
+ let context = {
+ let mut context = context;
+ let inserted = context.page_targets.insert(PageTargetHost::empty(
+ TEST_FIXTURE_PAGE_TARGET_ID.to_owned(),
+ ));
+ debug_assert!(inserted);
+ let selected = context.page_targets.select(TEST_FIXTURE_PAGE_TARGET_ID);
+ debug_assert!(selected);
+ context
+ };
+ context
}
pub(crate) fn new_with_initial_cookies(
@@ -501,8 +520,7 @@ impl BrowserContext {
Self {
id,
storage_partition,
- target_id: None,
- session_id: None,
+ page_targets: PageTargetRegistry::default(),
auxiliary_target_sessions: HashMap::new(),
target_opener_ids: HashMap::new(),
target_opener_frame_ids: HashMap::new(),
@@ -510,15 +528,10 @@ impl BrowserContext {
target_window_names: HashMap::new(),
target_popup_ids: HashMap::new(),
pending_popup_javascript_dialogs: HashMap::new(),
- background_targets: Vec::new(),
shared_worker_targets: BTreeMap::new(),
dedicated_worker_targets: BTreeMap::new(),
service_worker_targets: BTreeMap::new(),
service_worker_domain_sessions: BTreeSet::new(),
- target_identity: TargetIdentityState::about_blank(),
- devtools_session_state: DevToolsSessionState::default(),
- auxiliary_devtools_session_states: HashMap::new(),
- network_policy: TargetNetworkPolicyState::default(),
default_extra_headers: Vec::new(),
global_extra_headers: Vec::new(),
default_browser_identity_override: None,
@@ -528,39 +541,112 @@ impl BrowserContext {
default_geolocation_override: None,
global_network_conditions: None,
global_geolocation_override: None,
- tls_verify_host_override: None,
- http_proxy_override: None,
- http_no_proxy_override: None,
+ global_cache_disabled: false,
+ default_http_proxy_override: None,
+ default_http_no_proxy_override: None,
+ default_tls_verify_host_override: None,
proxy_autoconfig_url: None,
proxy_socks_version: None,
default_emulated_device_metrics: None,
- locale_override: None,
- timezone_override: None,
- network_conditions: None,
- geolocation_override: None,
- emulated_media: EmulatedMediaOverrides::default(),
- emulated_device_metrics: None,
- cpu_throttling_rate: 1.0,
- input_intercept_drags_enabled: false,
- input_drag_intercepted: false,
- touch_emulation_enabled: false,
- emit_touch_events_for_mouse: false,
- focus_emulation_enabled: false,
- script_execution_disabled: false,
- css_enabled: false,
next_default_document_start_script_id: 0,
default_document_start_scripts: Vec::new(),
- document_cookie_manager_surface: Default::default(),
- target_parking: TargetParkingStateStore::default(),
- dom_remote_object_node_cache: HashMap::new(),
- active_target: ActiveTargetState::default(),
storage_quota_overrides: HashMap::new(),
http_cache_root,
http_cache_max_bytes,
+ page_navigation_runtime_config: None,
+ renderer_output_transport_sender: None,
renderer_runtime_owner: Some(RendererBrowserContextRuntime::new()),
}
}
+ pub(crate) fn new_page_navigation_engine(
+ &self,
+ config: NavigationRuntimeConfig,
+ ) -> NavigationEngine {
+ let engine = if let Some(source) = self
+ .page_targets
+ .iter()
+ .find_map(PageTargetHost::navigation_engine)
+ {
+ NavigationEngine::new_with_runtime_config_and_shared_renderer_owner(config, source)
+ .expect("live PageTargetHost renderer owner must accept another page engine")
+ } else {
+ NavigationEngine::new_with_runtime_config_and_browser_context_access(
+ config,
+ self.renderer_runtime_owner_access(),
+ )
+ .expect("live BrowserContext owner must accept a page engine")
+ };
+ if let Some(sender) = self.renderer_output_transport_sender.clone() {
+ engine.set_renderer_output_transport_sender(sender);
+ }
+ engine
+ }
+
+ pub(crate) fn bind_page_navigation_engines(
+ &mut self,
+ config: NavigationRuntimeConfig,
+ renderer_output_transport_sender: Option<moli_core::RendererOutputTransportSender>,
+ ) {
+ self.page_navigation_runtime_config = Some(config.clone());
+ self.renderer_output_transport_sender = renderer_output_transport_sender;
+
+ let mut shared_source = self
+ .page_targets
+ .iter()
+ .find_map(PageTargetHost::navigation_engine)
+ .cloned();
+ let renderer_runtime = self.renderer_runtime_owner_access();
+ let sender = self.renderer_output_transport_sender.clone();
+ for host in self.page_targets.iter_mut() {
+ if host.navigation_engine().is_some() {
+ continue;
+ }
+ let engine = if let Some(source) = shared_source.as_ref() {
+ NavigationEngine::new_with_runtime_config_and_shared_renderer_owner(
+ config.clone(),
+ source,
+ )
+ .expect("live PageTargetHost renderer owner must accept another page engine")
+ } else {
+ NavigationEngine::new_with_runtime_config_and_browser_context_access(
+ config.clone(),
+ renderer_runtime.clone(),
+ )
+ .expect("live BrowserContext owner must accept a page engine")
+ };
+ if let Some(sender) = sender.clone() {
+ engine.set_renderer_output_transport_sender(sender);
+ }
+ shared_source = Some(engine.clone());
+ let replaced = host.replace_navigation_engine(engine);
+ debug_assert!(replaced.is_none());
+ }
+ }
+
+ pub(crate) fn set_renderer_output_transport_sender(
+ &mut self,
+ sender: moli_core::RendererOutputTransportSender,
+ ) {
+ self.renderer_output_transport_sender = Some(sender.clone());
+ for host in self.page_targets.iter() {
+ if let Some(engine) = host.navigation_engine() {
+ engine.set_renderer_output_transport_sender(sender.clone());
+ }
+ }
+ }
+
+ pub(crate) fn page_navigation_engine(&self, target_id: &str) -> Option<&NavigationEngine> {
+ self.page_target(target_id)?.navigation_engine()
+ }
+
+ pub(crate) fn page_navigation_engine_mut(
+ &mut self,
+ target_id: &str,
+ ) -> Option<&mut NavigationEngine> {
+ self.page_target_mut(target_id)?.navigation_engine_mut()
+ }
+
pub(crate) fn is_profile_backed_storage_partition(&self) -> bool {
self.storage_partition.identity().kind()
== BrowserContextStoragePartitionKind::ProfileBacked
@@ -575,15 +661,25 @@ impl BrowserContext {
}
pub(crate) fn resource_storage_handles(&self) -> BrowserContextResourceStorageHandles {
+ let session_storage_store = self
+ .page_targets
+ .active()
+ .map(|target| target.session_storage_namespace.store().clone())
+ .unwrap_or_else(new_shared_web_storage_store);
self.storage_partition
.handles
- .resource_storage_handles(self.active_target.session_storage_namespace.store().clone())
+ .resource_storage_handles(session_storage_store)
}
pub(crate) fn page_storage_handles(&self) -> BrowserContextPageStorageHandles {
+ let session_storage_store = self
+ .page_targets
+ .active()
+ .map(|target| target.session_storage_namespace.store().clone())
+ .unwrap_or_else(new_shared_web_storage_store);
self.storage_partition
.handles
- .page_storage_handles(self.active_target.session_storage_namespace.store().clone())
+ .page_storage_handles(session_storage_store)
}
pub(crate) fn page_storage_handles_for_target(
@@ -746,9 +842,9 @@ impl BrowserContext {
.loaded_page()
.is_some_and(|page| page.renderer_owner_local_host_id() == owner_local_host_id)
{
- return self.target_id.clone();
+ return self.active_target_id_owned();
}
- self.background_targets.iter().find_map(|target| {
+ self.background_targets().find_map(|target| {
target
.loaded_page()
.is_some_and(|page| page.renderer_owner_local_host_id() == owner_local_host_id)
@@ -771,22 +867,66 @@ impl BrowserContext {
self.shared_worker_target_pending_inspector_await_count_for_diagnostics();
let service_worker_target_pending_inspector_await_count =
self.service_worker_target_pending_inspector_await_count_for_diagnostics();
- let auxiliary_devtools_pending_inspector_await_count: usize = self
- .auxiliary_devtools_session_states
- .values()
- .map(DevToolsSessionState::pending_inspector_await_count)
- .sum();
- let runtime_session_diagnostics = json!({
- "runtimeEnabled": self.devtools_session_state.runtime_session_state.runtime_frontend_enabled,
- "inspectorEnabled": self.devtools_session_state.runtime_session_state.inspector_enabled,
- "inspectorTargetCrashedDelivered": self.devtools_session_state.runtime_session_state.inspector_target_crashed_delivered(),
- "profilerCommandStateSource": "renderer-v8-inspector-agent",
- "v8InspectorStateBytes": self.devtools_session_state.inspector_session_state.v8_state.as_ref().map_or(0, |state| state.len()),
- "auxiliaryDevToolsSessionStateCount": self.auxiliary_devtools_session_states.len(),
- "pendingInspectorAwaitCount": self.devtools_session_state.pending_inspector_await_count()
- + auxiliary_devtools_pending_inspector_await_count,
- "primaryPendingInspectorAwaitCount": self.devtools_session_state.pending_inspector_await_count(),
- "auxiliaryPendingInspectorAwaitCount": auxiliary_devtools_pending_inspector_await_count,
+ let active_target = self.page_targets.active();
+ let runtime_session_diagnostics = active_target
+ .map(|target| {
+ let primary = target.devtools_sessions.primary();
+ let auxiliary_pending_inspector_await_count: usize = target
+ .devtools_sessions
+ .attached_states()
+ .map(DevToolsSessionState::pending_inspector_await_count)
+ .sum();
+ json!({
+ "runtimeEnabled": primary.runtime_session_state.runtime_frontend_enabled,
+ "inspectorEnabled": primary.runtime_session_state.inspector_enabled,
+ "inspectorTargetCrashedDelivered": primary.runtime_session_state.inspector_target_crashed_delivered(),
+ "profilerCommandStateSource": "renderer-v8-inspector-agent",
+ "v8InspectorStateBytes": primary.inspector_session_state.v8_state.as_ref().map_or(0, |state| state.len()),
+ "auxiliaryDevToolsSessionStateCount": target.devtools_sessions.attached_len(),
+ "pendingInspectorAwaitCount": target.devtools_sessions.pending_inspector_await_count(),
+ "primaryPendingInspectorAwaitCount": primary.pending_inspector_await_count(),
+ "auxiliaryPendingInspectorAwaitCount": auxiliary_pending_inspector_await_count,
+ })
+ })
+ .unwrap_or(Value::Null);
+ let page_session_diagnostics = active_target
+ .map(|target| {
+ let primary = target.devtools_sessions.primary();
+ json!({
+ "pageLifecycleEvents": primary.page_session_state.page_lifecycle_events,
+ "logEnabled": primary.page_session_state.log_enabled,
+ "consoleEnabled": primary.console_output_session_state.console_enabled,
+ "performanceEnabled": primary
+ .page_session_state
+ .performance
+ .enabled(),
+ "performanceTimeDomain": primary
+ .page_session_state
+ .performance
+ .time_domain()
+ .as_str(),
+ "pageFontFamilyCount": primary.page_session_state.page_font_families.len(),
+ })
+ })
+ .unwrap_or(Value::Null);
+ let target_host_state_diagnostics = json!({
+ "targetHostCount": self.background_target_count(),
+ "pageSessionStateCount": self.background_targets()
+ .filter(|target| target.state().has_non_default_session_state())
+ .count(),
+ "targetOwnerStateWithPendingInspectorAwaitCount": self.background_targets()
+ .filter(|target| target.has_pending_inspector_awaits())
+ .count(),
+ "pendingInspectorAwaitCount": self.background_targets()
+ .map(|target| target.pending_inspector_await_count())
+ .sum::<usize>(),
+ "nonEmptyFetchStateCount": self.background_targets()
+ .filter(|target| !target.fetch_owner.pending_state().is_empty())
+ .count(),
+ "ownerStates": self.background_targets().map(|target| json!({
+ "targetId": target.target_id(),
+ "ownerState": target.owner_state.moli_memory_diagnostics(),
+ })).collect::<Vec<_>>(),
});
json!({
"id": self.id,
@@ -802,10 +942,9 @@ impl BrowserContext {
"id": attachment_id.get(),
"targetId": self.active_target_id(),
})),
- "backgroundTargetCount": self.background_targets.len(),
+ "backgroundTargetCount": self.background_target_count(),
"backgroundLoadedPageCount": self
- .background_targets
- .iter()
+ .background_targets()
.filter(|target| target.has_loaded_page())
.count(),
"targetInfoCount": target_infos.len(),
@@ -819,7 +958,8 @@ impl BrowserContext {
"targetCanAccessOpenerCount": self.target_can_access_opener.len(),
"targetWindowNameCount": self.target_window_names.len(),
"defaultDocumentStartScriptCount": self.default_document_start_scripts.len(),
- "domRemoteObjectNodeCacheCount": self.dom_remote_object_node_cache.len(),
+ "domRemoteObjectNodeCacheCount": active_target
+ .map_or(0, |target| target.dom_remote_object_node_cache.len()),
"sharedWorkerTargetCount": self.shared_worker_targets.len(),
"serviceWorkerTargetCount": self.service_worker_targets.len(),
"pendingInspectorAwaitCount": page_target_pending_inspector_await_count
@@ -845,35 +985,21 @@ impl BrowserContext {
"browserContextRuntime": self.renderer_runtime().moli_memory_diagnostics(),
},
"runtimeSession": runtime_session_diagnostics,
- "pageSession": {
- "pageLifecycleEvents": self.devtools_session_state.page_session_state.page_lifecycle_events,
- "logEnabled": self.devtools_session_state.page_session_state.log_enabled,
- "consoleEnabled": self.devtools_session_state.console_output_session_state.console_enabled,
- "performanceEnabled": self
- .devtools_session_state
- .page_session_state
- .performance
- .enabled(),
- "performanceTimeDomain": self
- .devtools_session_state
- .page_session_state
- .performance
- .time_domain()
- .as_str(),
- "pageFontFamilyCount": self.devtools_session_state.page_session_state.page_font_families.len(),
- },
- "activeRuntimeSlot": self.active_target.runtime_slot.moli_memory_diagnostics(),
- "activeFetch": self.active_target.fetch_owner.moli_memory_diagnostics(),
- "activeOwnerState": self.active_target.owner_state.moli_memory_diagnostics(),
- "targetParking": self.target_parking.moli_memory_diagnostics(),
+ "pageSession": page_session_diagnostics,
+ "activeRuntimeSlot": active_target
+ .map(|target| target.runtime_slot.moli_memory_diagnostics()),
+ "activeFetch": active_target
+ .map(|target| target.fetch_owner.moli_memory_diagnostics()),
+ "activeOwnerState": active_target
+ .map(|target| target.owner_state.moli_memory_diagnostics()),
+ "targetHosts": target_host_state_diagnostics,
})
}
pub(crate) fn loaded_document_page_count(&self) -> usize {
usize::from(self.has_loaded_page())
+ self
- .background_targets
- .iter()
+ .background_targets()
.filter(|target| target.has_loaded_page())
.count()
}
@@ -886,8 +1012,7 @@ impl BrowserContext {
.runtime_slot
.has_pending_initial_document_page_build(),
) + self
- .background_targets
- .iter()
+ .background_targets()
.filter(|target| {
target
.runtime_slot()
@@ -978,7 +1103,7 @@ impl BrowserContext {
if let Some(page) = self.loaded_page() {
owner_ids.insert(page.renderer_owner_local_host_id().as_u64());
}
- for target in &self.background_targets {
+ for target in self.background_targets() {
if let Some(page) = target.loaded_page() {
owner_ids.insert(page.renderer_owner_local_host_id().as_u64());
}
@@ -1006,42 +1131,29 @@ impl BrowserContext {
fn loaded_pages_for_diagnostics(&self) -> impl Iterator<Item = &moli_core::page::Page> {
self.loaded_page().into_iter().chain(
- self.background_targets
- .iter()
+ self.background_targets()
.filter_map(|target| target.loaded_page()),
)
}
pub(crate) fn page_target_pending_inspector_await_count_for_diagnostics(&self) -> usize {
- devtools_sessions_pending_inspector_await_count(
- &self.devtools_session_state,
- &self.auxiliary_devtools_session_states,
- ) + self.target_parking.pending_inspector_await_count()
+ self.page_targets
+ .iter()
+ .map(|target| target.pending_inspector_await_count())
+ .sum()
}
pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
- !self
- .devtools_session_state
- .page_session_state
- .javascript_dialog_state
- .is_empty()
- || self
- .auxiliary_devtools_session_states
- .values()
- .any(|session| {
- !session
- .page_session_state
- .javascript_dialog_state
- .is_empty()
- })
- || self.target_parking.has_pending_javascript_dialog()
+ self.page_targets
+ .iter()
+ .any(PageTargetHost::has_pending_javascript_dialog)
}
pub(crate) fn page_target_with_pending_inspector_await_count_for_diagnostics(&self) -> usize {
- usize::from(devtools_sessions_have_pending_inspector_awaits(
- &self.devtools_session_state,
- &self.auxiliary_devtools_session_states,
- )) + self.target_parking.pending_inspector_await_target_count()
+ self.page_targets
+ .iter()
+ .filter(|target| target.has_pending_inspector_awaits())
+ .count()
}
pub(crate) fn shared_worker_target_pending_inspector_await_count_for_diagnostics(
@@ -1199,13 +1311,9 @@ impl BrowserContext {
}
pub(crate) fn has_inflight_background_navigation(&self) -> bool {
- self.active_target
- .runtime_slot
- .has_inflight_background_navigation()
- || self
- .background_targets
- .iter()
- .any(|target| target.runtime_slot().has_inflight_background_navigation())
+ self.page_targets
+ .iter()
+ .any(|target| target.runtime_slot().has_inflight_background_navigation())
}
pub(crate) fn has_inflight_background_navigation_for_target(&self, target_id: &str) -> bool {
@@ -1523,18 +1631,24 @@ impl BrowserContext {
}
pub(crate) fn active_target_id(&self) -> Option<&str> {
- self.target_id.as_deref()
+ let target_id = self.page_targets.active_target_id()?;
+ #[cfg(test)]
+ if target_id == TEST_FIXTURE_PAGE_TARGET_ID {
+ return None;
+ }
+ Some(target_id)
}
pub(crate) fn active_target_id_owned(&self) -> Option<String> {
- self.target_id.clone()
+ self.active_target_id().map(str::to_owned)
}
pub(crate) fn effective_active_browser_identity_override(
&self,
) -> Option<&moli_browser_profile::BrowserIdentityProfile> {
- self.network_policy
- .browser_identity_override()
+ self.page_targets
+ .active()
+ .and_then(|host| host.network_policy.browser_identity_override())
.or(self.default_browser_identity_override.as_ref())
}
@@ -1545,34 +1659,54 @@ impl BrowserContext {
}
pub(crate) fn effective_active_locale_override_owned(&self) -> Option<String> {
- self.locale_override
- .clone()
+ self.page_targets
+ .active()
+ .and_then(|host| host.locale_override.clone())
.or_else(|| self.default_locale_override.clone())
}
- pub(crate) fn effective_active_locale_override(&self) -> Option<&str> {
- self.locale_override
- .as_deref()
- .or(self.default_locale_override.as_deref())
- }
-
pub(crate) fn effective_active_timezone_override_owned(&self) -> Option<String> {
- self.timezone_override
- .clone()
+ self.page_targets
+ .active()
+ .and_then(|host| host.timezone_override.clone())
.or_else(|| self.default_timezone_override.clone())
}
pub(crate) fn effective_active_network_conditions(&self) -> Option<EmulatedNetworkConditions> {
- self.network_conditions
+ self.page_targets
+ .active()
+ .and_then(|host| host.network_conditions)
.or(self.default_network_conditions)
.or(self.global_network_conditions)
}
+ pub(crate) fn effective_active_http_proxy_override_owned(&self) -> Option<String> {
+ self.page_targets
+ .active()
+ .and_then(|host| host.http_proxy_override.clone())
+ .or_else(|| self.default_http_proxy_override.clone())
+ }
+
+ pub(crate) fn effective_active_http_no_proxy_override_owned(&self) -> Option<String> {
+ self.page_targets
+ .active()
+ .and_then(|host| host.http_no_proxy_override.clone())
+ .or_else(|| self.default_http_no_proxy_override.clone())
+ }
+
+ pub(crate) fn effective_active_tls_verify_host_override(&self) -> Option<bool> {
+ self.page_targets
+ .active()
+ .and_then(|host| host.tls_verify_host_override)
+ .or(self.default_tls_verify_host_override)
+ }
+
pub(crate) fn effective_active_geolocation_override(
&self,
) -> Option<EmulatedGeolocationOverrideState> {
- self.geolocation_override
- .clone()
+ self.page_targets
+ .active()
+ .and_then(|host| host.geolocation_override.clone())
.or_else(|| self.default_geolocation_override.clone())
.or_else(|| self.global_geolocation_override.clone())
}
@@ -1604,7 +1738,7 @@ impl BrowserContext {
}
pub(crate) fn has_active_target(&self) -> bool {
- self.target_id.is_some()
+ self.page_targets.active().is_some()
}
pub(crate) fn is_active_target(&self, target_id: &str) -> bool {
@@ -1613,37 +1747,39 @@ impl BrowserContext {
pub(crate) fn set_active_target_id(&mut self, target_id: impl Into<String>) {
let target_id = target_id.into();
- let target_changed = self.target_id.as_deref() != Some(target_id.as_str());
- if target_changed && !self.has_loaded_page() {
- self.active_target
- .runtime_slot
- .prepare_renderer_channel_for_new_target();
+ #[cfg(test)]
+ if self.page_targets.active_target_id() == Some(TEST_FIXTURE_PAGE_TARGET_ID) {
+ let rekeyed = self.page_targets.rekey_active(target_id.clone());
+ debug_assert!(rekeyed, "test fixture page target id must be replaceable");
+ return;
}
- if self
- .target_id
- .as_deref()
- .is_some_and(|current_target_id| current_target_id != target_id)
- {
- self.active_target.session_storage_namespace = Default::default();
+ if self.page_targets.get(&target_id).is_none() {
+ let inserted = self.insert_page_target_host(PageTargetHost::empty(target_id.clone()));
+ debug_assert!(inserted, "new page target id must be unique");
}
- self.target_id = Some(target_id);
+ let selected = self.page_targets.select(&target_id);
+ debug_assert!(selected, "registered page target must be selectable");
+ }
+
+ pub(crate) fn rekey_active_target(&mut self, target_id: impl Into<String>) -> bool {
+ self.page_targets.rekey_active(target_id.into())
}
+ #[cfg(test)]
pub(crate) fn clear_active_target_id(&mut self) {
- self.target_id = None;
- self.active_target.session_storage_namespace = Default::default();
+ self.page_targets.clear_selection();
}
pub(crate) fn active_session_id(&self) -> Option<&str> {
- self.session_id.as_deref()
+ self.page_targets.active()?.session_id()
}
pub(crate) fn active_session_id_owned(&self) -> Option<String> {
- self.session_id.clone()
+ self.active_session_id().map(str::to_owned)
}
pub(crate) fn has_active_session(&self) -> bool {
- self.session_id.is_some()
+ self.active_session_id().is_some()
}
pub(crate) fn active_target_is_unclaimed_default_placeholder(
@@ -1653,22 +1789,21 @@ impl BrowserContext {
self.active_target_id() == Some(default_target_id)
&& !self.has_active_session()
&& !self.has_loaded_page()
- && self.background_targets.is_empty()
+ && self.background_target_count() == 0
&& self.shared_worker_targets.is_empty()
&& self.dedicated_worker_targets.is_empty()
&& self.service_worker_targets.is_empty()
}
pub(crate) fn attach_active_session(&mut self, session_id: impl Into<String>) {
- self.session_id = Some(session_id.into());
- }
-
- pub(crate) fn replace_active_session(&mut self, session_id: Option<String>) {
- self.session_id = session_id;
+ self.page_targets
+ .active_mut()
+ .expect("cannot attach a session without an active page target")
+ .attach_session(session_id.into());
}
pub(crate) fn detach_active_session(&mut self) -> Option<String> {
- self.session_id.take()
+ self.page_targets.active_mut()?.detach_session()
}
pub(crate) fn target_url(&self) -> &str {
@@ -1683,10 +1818,6 @@ impl BrowserContext {
self.target_identity.secure_context_type()
}
- pub(crate) fn target_identity(&self) -> &TargetIdentityState {
- &self.target_identity
- }
-
pub(crate) fn set_target_url(&mut self, url: String) {
self.target_identity.set_url(url);
}
@@ -1699,18 +1830,6 @@ impl BrowserContext {
self.target_identity
.set_secure_context_type(secure_context_type);
}
-
- pub(crate) fn replace_target_identity(&mut self, identity: TargetIdentityState) {
- self.target_identity = identity;
- }
-
- pub(crate) fn reset_target_identity_to_new_tab(&mut self) {
- self.target_identity = TargetIdentityState::new_tab();
- }
-
- pub(crate) fn reset_target_identity_to_about_blank(&mut self) {
- self.target_identity = TargetIdentityState::about_blank();
- }
}
fn materialized_initial_empty_document_missing_page_error(
diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rs
index 2206c0e71..75cf08962 100644
--- a/moli-protocol/src/conn/state/devtools_session.rs
+++ b/moli-protocol/src/conn/state/devtools_session.rs
@@ -1,4 +1,7 @@
-use std::collections::{BTreeSet, HashMap, HashSet};
+use std::{
+ collections::{BTreeMap, BTreeSet, HashMap, HashSet},
+ ops::{Index, IndexMut},
+};
use super::{
page_slot::RuntimeBindingDefinition,
@@ -10,9 +13,16 @@ use super::{
},
session::{InspectorSessionState, TargetPageSessionState, TargetRuntimeSessionState},
};
-use moli_core::network::WebStorageMutationSubscription;
+use moli_core::{
+ network::WebStorageMutationSubscription,
+ page::{
+ RendererInspectorProtocolConfiguration, RendererInspectorSessionRestoreSnapshot,
+ V8InspectorSessionAttach,
+ },
+};
use moli_page_types::{
- RendererDomDebuggerEventListenerBreakpoint, RendererDomDebuggerXhrBreakpoint,
+ DevToolsSessionKey, RendererDomDebuggerEventListenerBreakpoint,
+ RendererDomDebuggerXhrBreakpoint,
};
/// CDP session-owned state for DevTools domains that are backed by a renderer
@@ -42,6 +52,295 @@ pub(crate) struct DevToolsSessionState {
pub(crate) pending_inspector_awaits: TargetPendingInspectorAwaitRegistry,
}
+/// Every DevTools session attached to one Page target.
+///
+/// The renderer's implicit root session is represented by `Primary`; flattened
+/// target sessions use `Attached(session_id)`. Keeping both in one ordered map
+/// gives attachment, disposal, replay, and effective-domain aggregation one
+/// source of truth.
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) struct DevToolsSessionRegistry {
+ states: BTreeMap<DevToolsSessionKey, DevToolsSessionState>,
+}
+
+impl Default for DevToolsSessionRegistry {
+ fn default() -> Self {
+ Self {
+ states: BTreeMap::from([(
+ DevToolsSessionKey::Primary,
+ DevToolsSessionState::default(),
+ )]),
+ }
+ }
+}
+
+impl DevToolsSessionRegistry {
+ pub(crate) fn primary(&self) -> &DevToolsSessionState {
+ self.states
+ .get(&DevToolsSessionKey::Primary)
+ .expect("DevTools session registry must retain its primary session")
+ }
+
+ pub(crate) fn primary_mut(&mut self) -> &mut DevToolsSessionState {
+ self.states
+ .get_mut(&DevToolsSessionKey::Primary)
+ .expect("DevTools session registry must retain its primary session")
+ }
+
+ pub(crate) fn routed(
+ &self,
+ is_attached_session: bool,
+ session_id: Option<&str>,
+ ) -> Option<&DevToolsSessionState> {
+ if is_attached_session {
+ return self.attached(session_id?);
+ }
+ Some(self.primary())
+ }
+
+ pub(crate) fn routed_mut_or_insert(
+ &mut self,
+ is_attached_session: bool,
+ session_id: Option<&str>,
+ ) -> &mut DevToolsSessionState {
+ if is_attached_session && let Some(session_id) = session_id {
+ return self.ensure_attached(session_id);
+ }
+ self.primary_mut()
+ }
+
+ pub(crate) fn attached(&self, session_id: &str) -> Option<&DevToolsSessionState> {
+ self.states
+ .get(&DevToolsSessionKey::Attached(session_id.to_owned()))
+ }
+
+ pub(crate) fn attached_mut(&mut self, session_id: &str) -> Option<&mut DevToolsSessionState> {
+ self.states
+ .get_mut(&DevToolsSessionKey::Attached(session_id.to_owned()))
+ }
+
+ pub(crate) fn ensure_attached(&mut self, session_id: &str) -> &mut DevToolsSessionState {
+ self.states
+ .entry(DevToolsSessionKey::Attached(session_id.to_owned()))
+ .or_default()
+ }
+
+ pub(crate) fn remove_attached(&mut self, session_id: &str) -> Option<DevToolsSessionState> {
+ self.states
+ .remove(&DevToolsSessionKey::Attached(session_id.to_owned()))
+ }
+
+ pub(crate) fn clear_attached(&mut self) {
+ self.states
+ .retain(|key, _state| matches!(key, DevToolsSessionKey::Primary));
+ }
+
+ pub(crate) fn attached_len(&self) -> usize {
+ self.states.len().saturating_sub(1)
+ }
+
+ pub(crate) fn attached_is_empty(&self) -> bool {
+ self.attached_len() == 0
+ }
+
+ pub(crate) fn attached_entries(&self) -> impl Iterator<Item = (&str, &DevToolsSessionState)> {
+ self.states.iter().filter_map(|(key, state)| match key {
+ DevToolsSessionKey::Primary => None,
+ DevToolsSessionKey::Attached(session_id) => Some((session_id.as_str(), state)),
+ })
+ }
+
+ pub(crate) fn attached_states(&self) -> impl Iterator<Item = &DevToolsSessionState> {
+ self.attached_entries().map(|(_session_id, state)| state)
+ }
+
+ pub(crate) fn states(&self) -> impl Iterator<Item = &DevToolsSessionState> {
+ self.states.values()
+ }
+
+ pub(crate) fn states_mut(&mut self) -> impl Iterator<Item = &mut DevToolsSessionState> {
+ self.states.values_mut()
+ }
+
+ pub(crate) fn reset(&mut self, preserve_attached_sessions: bool) {
+ *self.primary_mut() = DevToolsSessionState::default();
+ if !preserve_attached_sessions {
+ self.clear_attached();
+ }
+ }
+
+ pub(crate) fn has_non_default_state(&self) -> bool {
+ self.primary() != &DevToolsSessionState::default() || !self.attached_is_empty()
+ }
+
+ pub(crate) fn has_pending_inspector_awaits(&self) -> bool {
+ self.states()
+ .any(DevToolsSessionState::has_pending_inspector_awaits)
+ }
+
+ pub(crate) fn pending_inspector_await_count(&self) -> usize {
+ self.states()
+ .map(DevToolsSessionState::pending_inspector_await_count)
+ .sum()
+ }
+
+ pub(crate) fn drain_pending_inspector_awaits_for_sessions(
+ &mut self,
+ session_ids: &[&str],
+ ) -> Vec<(u64, PendingInspectorAwait)> {
+ self.states_mut()
+ .flat_map(|state| state.drain_pending_inspector_awaits_for_sessions(session_ids))
+ .collect()
+ }
+
+ pub(crate) fn prepare_renderer_call_replacements(
+ &mut self,
+ primary_session_id: Option<&str>,
+ old_attachment_id: moli_page_types::RendererAgentAttachmentId,
+ new_attachment_id: moli_page_types::RendererAgentAttachmentId,
+ ) -> Result<PreparedRendererCallReplacements, RendererCallIdExhausted> {
+ let terminations = self.prepare_renderer_call_terminations(
+ primary_session_id,
+ old_attachment_id,
+ new_attachment_id,
+ )?;
+ let replays = self.prepare_renderer_call_replays(
+ primary_session_id,
+ old_attachment_id,
+ new_attachment_id,
+ )?;
+ Ok(PreparedRendererCallReplacements::new(
+ new_attachment_id,
+ terminations,
+ replays,
+ ))
+ }
+
+ fn prepare_renderer_call_replays(
+ &mut self,
+ primary_session_id: Option<&str>,
+ old_attachment_id: moli_page_types::RendererAgentAttachmentId,
+ new_attachment_id: moli_page_types::RendererAgentAttachmentId,
+ ) -> Result<Vec<SessionRendererCallReplay>, RendererCallIdExhausted> {
+ let mut replays = Vec::new();
+ for (key, state) in &mut self.states {
+ let (frontend_session_id, renderer_inspector_session_id) = match key {
+ DevToolsSessionKey::Primary => (primary_session_id.map(str::to_owned), None),
+ DevToolsSessionKey::Attached(session_id) => {
+ (Some(session_id.clone()), Some(session_id.clone()))
+ }
+ };
+ replays.extend(
+ state
+ .prepare_renderer_call_replays(old_attachment_id, new_attachment_id)?
+ .into_iter()
+ .map(|replay| SessionRendererCallReplay {
+ frontend_session_id: frontend_session_id.clone(),
+ renderer_inspector_session_id: renderer_inspector_session_id.clone(),
+ replay,
+ }),
+ );
+ }
+ Ok(replays)
+ }
+
+ fn prepare_renderer_call_terminations(
+ &mut self,
+ primary_session_id: Option<&str>,
+ old_attachment_id: moli_page_types::RendererAgentAttachmentId,
+ terminal_attachment_id: moli_page_types::RendererAgentAttachmentId,
+ ) -> Result<Vec<SessionRendererCallTermination>, RendererCallIdExhausted> {
+ let mut terminations = Vec::new();
+ for (key, state) in &mut self.states {
+ let frontend_session_id = match key {
+ DevToolsSessionKey::Primary => primary_session_id.map(str::to_owned),
+ DevToolsSessionKey::Attached(session_id) => Some(session_id.clone()),
+ };
+ terminations.extend(
+ state
+ .prepare_renderer_call_terminations(old_attachment_id, terminal_attachment_id)?
+ .into_iter()
+ .map(|termination| SessionRendererCallTermination {
+ frontend_session_id: frontend_session_id.clone(),
+ termination,
+ }),
+ );
+ }
+ Ok(terminations)
+ }
+
+ pub(crate) fn runtime_bindings_for_renderer(&self) -> Vec<RuntimeBindingDefinition> {
+ let mut bindings = Vec::new();
+ for (key, state) in &self.states {
+ for binding in &state.runtime_bindings {
+ let binding = binding.with_devtools_session(key.clone());
+ if !bindings.iter().any(|existing| existing == &binding) {
+ bindings.push(binding);
+ }
+ }
+ }
+ bindings
+ }
+
+ pub(crate) fn runtime_inspector_restore_snapshots(
+ &self,
+ ) -> Vec<RendererInspectorSessionRestoreSnapshot> {
+ self.states
+ .iter()
+ .filter_map(|(key, state)| {
+ let requires_restore = state.runtime_session_state.runtime_frontend_enabled
+ || state.console_output_session_state.console_enabled
+ || !state.runtime_bindings.is_empty()
+ || !state.dom_debugger_event_listener_breakpoints.is_empty()
+ || !state.dom_debugger_xhr_breakpoints.is_empty()
+ || state.inspector_session_state.v8_state.is_some();
+ requires_restore.then(|| RendererInspectorSessionRestoreSnapshot {
+ inspector_session_id: key.wire_session_id().map(str::to_owned),
+ v8_attach: V8InspectorSessionAttach::from_optional_state(
+ state.inspector_session_state.v8_state.clone(),
+ ),
+ protocol_configuration: RendererInspectorProtocolConfiguration {
+ runtime_bindings: state.runtime_bindings.clone(),
+ runtime_frontend_enabled: state
+ .runtime_session_state
+ .runtime_frontend_enabled,
+ console_frontend_enabled: state
+ .console_output_session_state
+ .console_enabled,
+ dom_debugger_event_listener_breakpoints: state
+ .dom_debugger_event_listener_breakpoints
+ .clone(),
+ dom_debugger_xhr_breakpoints: state.dom_debugger_xhr_breakpoints.clone(),
+ },
+ })
+ })
+ .collect()
+ }
+
+ pub(crate) fn page_bypass_csp_enabled(&self) -> bool {
+ self.states()
+ .any(|state| state.page_session_state.page_bypass_csp_enabled)
+ }
+}
+
+impl Index<DevToolsSessionKey> for DevToolsSessionRegistry {
+ type Output = DevToolsSessionState;
+
+ fn index(&self, key: DevToolsSessionKey) -> &Self::Output {
+ self.states
+ .get(&key)
+ .expect("indexed DevTools session must be registered")
+ }
+}
+
+impl IndexMut<DevToolsSessionKey> for DevToolsSessionRegistry {
+ fn index_mut(&mut self, key: DevToolsSessionKey) -> &mut Self::Output {
+ self.states
+ .get_mut(&key)
+ .expect("indexed DevTools session must be registered")
+ }
+}
+
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct DevToolsDomSessionState {
pub(crate) enabled: bool,
@@ -162,6 +461,7 @@ impl DevToolsSessionState {
binding.name == name && binding.execution_context_name == execution_context_name
}) {
self.runtime_bindings.push(RuntimeBindingDefinition {
+ devtools_session: None,
name,
execution_context_name,
});
@@ -548,170 +848,107 @@ impl DevToolsDomStorageSessionState {
}
}
-pub(crate) fn devtools_sessions_have_pending_inspector_awaits(
- primary: &DevToolsSessionState,
- auxiliary: &HashMap<String, DevToolsSessionState>,
-) -> bool {
- primary.has_pending_inspector_awaits()
- || auxiliary
- .values()
- .any(DevToolsSessionState::has_pending_inspector_awaits)
-}
-
-pub(crate) fn devtools_sessions_pending_inspector_await_count(
- primary: &DevToolsSessionState,
- auxiliary: &HashMap<String, DevToolsSessionState>,
-) -> usize {
- primary.pending_inspector_await_count()
- + auxiliary
- .values()
- .map(DevToolsSessionState::pending_inspector_await_count)
- .sum::<usize>()
-}
+#[cfg(test)]
+mod tests {
+ use super::*;
-pub(crate) fn drain_pending_inspector_awaits_for_devtools_sessions(
- primary: &mut DevToolsSessionState,
- auxiliary: &mut HashMap<String, DevToolsSessionState>,
- session_ids: &[&str],
-) -> Vec<(u64, PendingInspectorAwait)> {
- let mut drained = primary.drain_pending_inspector_awaits_for_sessions(session_ids);
- for state in auxiliary.values_mut() {
- drained.extend(state.drain_pending_inspector_awaits_for_sessions(session_ids));
+ fn binding(name: &str) -> RuntimeBindingDefinition {
+ RuntimeBindingDefinition {
+ devtools_session: None,
+ name: name.to_owned(),
+ execution_context_name: None,
+ }
}
- drained
-}
-pub(crate) fn prepare_renderer_call_replays_for_devtools_sessions(
- primary_session_id: Option<&str>,
- primary: &mut DevToolsSessionState,
- auxiliary: &mut HashMap<String, DevToolsSessionState>,
- old_attachment_id: moli_page_types::RendererAgentAttachmentId,
- new_attachment_id: moli_page_types::RendererAgentAttachmentId,
-) -> Result<Vec<SessionRendererCallReplay>, RendererCallIdExhausted> {
- let mut replays = primary
- .prepare_renderer_call_replays(old_attachment_id, new_attachment_id)?
- .into_iter()
- .map(|replay| SessionRendererCallReplay {
- frontend_session_id: primary_session_id.map(str::to_owned),
- renderer_inspector_session_id: None,
- replay,
- })
- .collect::<Vec<_>>();
- let mut auxiliary_session_ids = auxiliary.keys().cloned().collect::<Vec<_>>();
- auxiliary_session_ids.sort();
- for session_id in auxiliary_session_ids {
- let state = auxiliary
- .get_mut(&session_id)
- .expect("selected auxiliary session must remain registered");
- replays.extend(
- state
- .prepare_renderer_call_replays(old_attachment_id, new_attachment_id)?
- .into_iter()
- .map(|replay| SessionRendererCallReplay {
- frontend_session_id: Some(session_id.clone()),
- renderer_inspector_session_id: Some(session_id.clone()),
- replay,
- }),
+ #[test]
+ fn registry_owns_primary_and_attached_sessions_in_stable_order() {
+ let mut sessions = DevToolsSessionRegistry::default();
+ sessions.ensure_attached("SID-b");
+ sessions.ensure_attached("SID-a");
+
+ assert_eq!(sessions.attached_len(), 2);
+ assert_eq!(
+ sessions
+ .attached_entries()
+ .map(|(session_id, _state)| session_id)
+ .collect::<Vec<_>>(),
+ ["SID-a", "SID-b"]
);
- }
- Ok(replays)
-}
-pub(crate) fn prepare_renderer_call_terminations_for_devtools_sessions(
- primary_session_id: Option<&str>,
- primary: &mut DevToolsSessionState,
- auxiliary: &mut HashMap<String, DevToolsSessionState>,
- old_attachment_id: moli_page_types::RendererAgentAttachmentId,
- terminal_attachment_id: moli_page_types::RendererAgentAttachmentId,
-) -> Result<Vec<SessionRendererCallTermination>, RendererCallIdExhausted> {
- let mut terminations = primary
- .prepare_renderer_call_terminations(old_attachment_id, terminal_attachment_id)?
- .into_iter()
- .map(|termination| SessionRendererCallTermination {
- frontend_session_id: primary_session_id.map(str::to_owned),
- termination,
- })
- .collect::<Vec<_>>();
- let mut auxiliary_session_ids = auxiliary.keys().cloned().collect::<Vec<_>>();
- auxiliary_session_ids.sort();
- for session_id in auxiliary_session_ids {
- let state = auxiliary
- .get_mut(&session_id)
- .expect("selected auxiliary session must remain registered");
- terminations.extend(
- state
- .prepare_renderer_call_terminations(old_attachment_id, terminal_attachment_id)?
- .into_iter()
- .map(|termination| SessionRendererCallTermination {
- frontend_session_id: Some(session_id.clone()),
- termination,
- }),
+ sessions.remove_attached("SID-a");
+ assert!(sessions.attached("SID-a").is_none());
+ assert!(sessions.attached("SID-b").is_some());
+ assert_eq!(sessions.primary(), &DevToolsSessionState::default());
+ }
+
+ #[test]
+ fn registry_aggregates_renderer_configuration_by_session_identity() {
+ let mut sessions = DevToolsSessionRegistry::default();
+ sessions
+ .primary_mut()
+ .runtime_bindings
+ .push(binding("primary"));
+ sessions
+ .ensure_attached("SID-b")
+ .runtime_bindings
+ .push(binding("attached-b"));
+ let attached_a = sessions.ensure_attached("SID-a");
+ attached_a.runtime_bindings.push(binding("attached-a"));
+ attached_a.runtime_session_state.runtime_frontend_enabled = true;
+ attached_a.page_session_state.page_bypass_csp_enabled = true;
+
+ let bindings = sessions.runtime_bindings_for_renderer();
+ assert_eq!(
+ bindings
+ .iter()
+ .map(|binding| (binding.name.as_str(), binding.devtools_session.clone()))
+ .collect::<Vec<_>>(),
+ [
+ ("primary", Some(DevToolsSessionKey::Primary)),
+ (
+ "attached-a",
+ Some(DevToolsSessionKey::Attached("SID-a".to_owned())),
+ ),
+ (
+ "attached-b",
+ Some(DevToolsSessionKey::Attached("SID-b".to_owned())),
+ ),
+ ]
+ );
+ assert!(sessions.page_bypass_csp_enabled());
+
+ let restores = sessions.runtime_inspector_restore_snapshots();
+ assert_eq!(
+ restores
+ .iter()
+ .map(|restore| restore.inspector_session_id.as_deref())
+ .collect::<Vec<_>>(),
+ [None, Some("SID-a"), Some("SID-b")]
);
+
+ sessions.remove_attached("SID-a");
+ assert!(!sessions.page_bypass_csp_enabled());
}
- Ok(terminations)
-}
-pub(crate) fn prepare_renderer_call_replacements_for_devtools_sessions(
- primary_session_id: Option<&str>,
- primary: &mut DevToolsSessionState,
- auxiliary: &mut HashMap<String, DevToolsSessionState>,
- old_attachment_id: moli_page_types::RendererAgentAttachmentId,
- new_attachment_id: moli_page_types::RendererAgentAttachmentId,
-) -> Result<PreparedRendererCallReplacements, RendererCallIdExhausted> {
- let terminations = prepare_renderer_call_terminations_for_devtools_sessions(
- primary_session_id,
- primary,
- auxiliary,
- old_attachment_id,
- new_attachment_id,
- )?;
- let replays = prepare_renderer_call_replays_for_devtools_sessions(
- primary_session_id,
- primary,
- auxiliary,
- old_attachment_id,
- new_attachment_id,
- )?;
- Ok(PreparedRendererCallReplacements::new(
- new_attachment_id,
- terminations,
- replays,
- ))
-}
+ #[test]
+ fn registry_pending_await_aggregation_tracks_attached_disposal() {
+ let mut sessions = DevToolsSessionRegistry::default();
+ sessions
+ .primary_mut()
+ .register_pending_inspector_await(1, Some("SID-primary"), None);
+ sessions
+ .ensure_attached("SID-attached")
+ .register_pending_inspector_await(2, Some("SID-attached"), Some("group"));
-pub(crate) fn runtime_bindings_for_renderer(
- primary: &DevToolsSessionState,
- auxiliary: &HashMap<String, DevToolsSessionState>,
-) -> Vec<RuntimeBindingDefinition> {
- fn push_unique(
- bindings: &mut Vec<RuntimeBindingDefinition>,
- binding: &RuntimeBindingDefinition,
- ) {
- if !bindings.iter().any(|existing| existing == binding) {
- bindings.push(binding.clone());
- }
- }
+ assert!(sessions.has_pending_inspector_awaits());
+ assert_eq!(sessions.pending_inspector_await_count(), 2);
+ let drained = sessions.drain_pending_inspector_awaits_for_sessions(&["SID-attached"]);
+ assert_eq!(drained.len(), 1);
+ assert_eq!(sessions.pending_inspector_await_count(), 1);
- let mut bindings = Vec::new();
- for binding in &primary.runtime_bindings {
- push_unique(&mut bindings, binding);
- }
- let mut auxiliary = auxiliary.iter().collect::<Vec<_>>();
- auxiliary.sort_by_key(|(session_id, _)| *session_id);
- for (_, state) in auxiliary {
- for binding in &state.runtime_bindings {
- push_unique(&mut bindings, binding);
- }
+ sessions.remove_attached("SID-attached");
+ assert_eq!(sessions.pending_inspector_await_count(), 1);
+ sessions.reset(false);
+ assert!(!sessions.has_pending_inspector_awaits());
}
- bindings
-}
-
-pub(crate) fn page_bypass_csp_enabled_for_devtools_sessions(
- primary: &DevToolsSessionState,
- auxiliary: &HashMap<String, DevToolsSessionState>,
-) -> bool {
- primary.page_session_state.page_bypass_csp_enabled
- || auxiliary
- .values()
- .any(|state| state.page_session_state.page_bypass_csp_enabled)
}
diff --git a/moli-protocol/src/conn/state/fetch.rs b/moli-protocol/src/conn/state/fetch.rs
index b8b37766c..039622f0b 100644
--- a/moli-protocol/src/conn/state/fetch.rs
+++ b/moli-protocol/src/conn/state/fetch.rs
@@ -987,8 +987,6 @@ impl TargetFetchState {
}
}
-pub type ParkedFetchState = TargetFetchState;
-
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetFetchConfig {
enabled: bool,
@@ -1725,6 +1723,15 @@ fn network_intercept_matches_auth_required(
}
impl TargetFetchOwner {
+ pub(crate) fn pending_state(&self) -> &TargetFetchState {
+ &self.pending
+ }
+
+ #[cfg(test)]
+ pub(crate) fn pending_state_mut(&mut self) -> &mut TargetFetchState {
+ &mut self.pending
+ }
+
pub(crate) fn configure(
&mut self,
session_id: Option<String>,
@@ -1764,10 +1771,6 @@ impl TargetFetchOwner {
self.config.remove_fetch_session(session_id)
}
- pub(crate) fn replace_config(&mut self, config: TargetFetchConfig) {
- self.config = config;
- }
-
pub(crate) fn config_snapshot(&self) -> TargetFetchConfig {
self.config.clone()
}
@@ -2212,14 +2215,6 @@ impl TargetFetchOwner {
pub(crate) fn clear_pending(&mut self) {
self.pending.clear();
}
-
- pub(crate) fn take_pending_state(&mut self) -> TargetFetchState {
- std::mem::take(&mut self.pending)
- }
-
- pub(crate) fn replace_pending_state(&mut self, state: TargetFetchState) {
- self.pending = state;
- }
}
#[cfg(test)]
diff --git a/moli-protocol/src/conn/state/mod.rs b/moli-protocol/src/conn/state/mod.rs
index 018774b0d..55ffdc7ee 100644
--- a/moli-protocol/src/conn/state/mod.rs
+++ b/moli-protocol/src/conn/state/mod.rs
@@ -15,6 +15,7 @@ mod navigation_outcome;
mod page_residence_token;
mod page_resource;
mod page_slot;
+mod page_target_host;
mod parking;
mod pending_renderer_command;
mod profiler;
@@ -49,11 +50,6 @@ pub(crate) use dedicated_worker_target::{
pub(crate) use devtools_session::{
DevToolsConsoleOutputSessionState, DevToolsLogViolationThreshold, DevToolsSessionState,
PreparedRendererCallReplacements, SessionRendererCallReplay, SessionRendererCallTermination,
- devtools_sessions_have_pending_inspector_awaits,
- devtools_sessions_pending_inspector_await_count,
- drain_pending_inspector_awaits_for_devtools_sessions,
- page_bypass_csp_enabled_for_devtools_sessions,
- prepare_renderer_call_replacements_for_devtools_sessions, runtime_bindings_for_renderer,
};
pub(crate) use document_lifecycle_observer::{
RendererDocumentLifecycleObservation, RendererDocumentLifecycleObserver,
@@ -73,10 +69,10 @@ pub use page_slot::{DocumentStartScript, IsolatedWorldDefinition, RuntimeBinding
pub(crate) use runtime_slot::{FinishedRendererDocumentNavigation, TargetRuntimeSlot};
-pub use fetch::{ParkedFetchState, TargetFetchConfig};
-pub(crate) use fetch::{
- TargetFetchOwner, TargetFetchState, TargetFetchSubresourceInterceptionSnapshot,
-};
+pub use fetch::TargetFetchConfig;
+#[cfg(test)]
+pub(crate) use fetch::TargetFetchState;
+pub(crate) use fetch::{TargetFetchOwner, TargetFetchSubresourceInterceptionSnapshot};
pub(crate) use inspector::InspectorCommandDispatch;
#[cfg(test)]
@@ -104,7 +100,7 @@ pub(crate) use service_worker_target::{
pub(crate) use session::TargetPerformanceSessionState;
pub(crate) use session::{
PageScreencastConfig, PageScreencastFormat, PerformanceTimeDomain, TargetNetworkPolicyState,
- TargetPageSessionState, TargetRuntimeSessionState,
+ TargetPageSessionState, TargetRuntimeSessionState, TargetSessionOverrideStack,
};
pub(crate) use session_storage::TargetSessionStorageNamespace;
pub(crate) use shared_worker_attachment::{
@@ -120,12 +116,12 @@ pub(crate) use browser_context::{
pub use navigation::{PageNavigationHistoryEntry, PendingNavigationHistoryUpdate};
-pub use parking::{BackgroundTarget, ParkedNetworkArtifacts, ParkedPageSessionState};
+pub use page_target_host::PageTargetHost;
pub(crate) use parking::{
- ParkedTargetAuxState, ParkedTargetOwnerState, PendingBidiChannelListener,
- PendingInspectorAwait, TargetInitialEmptyDocumentCreator, TargetOwnerState, TargetSlotState,
- TargetWindowSurfaceState,
+ ParkedTargetOwnerState, PendingBidiChannelListener, PendingInspectorAwait,
+ TargetInitialEmptyDocumentCreator, TargetOwnerState, TargetWindowSurfaceState,
};
+pub use session::TargetPageState;
pub use emulation::{
EmulatedDeviceMetrics, EmulatedGeolocationOverride, EmulatedGeolocationOverrideState,
diff --git a/moli-protocol/src/conn/state/page_resource.rs b/moli-protocol/src/conn/state/page_resource.rs
index 3dbb741f4..836f67122 100644
--- a/moli-protocol/src/conn/state/page_resource.rs
+++ b/moli-protocol/src/conn/state/page_resource.rs
@@ -115,11 +115,6 @@ impl TargetPageResourceStore {
}
}
- pub(crate) fn clear(&mut self) {
- self.committed_loader_id = None;
- self.main_documents.clear();
- }
-
pub(crate) fn is_empty(&self) -> bool {
self.committed_loader_id.is_none() && self.main_documents.is_empty()
}
diff --git a/moli-protocol/src/conn/state/page_target_host.rs b/moli-protocol/src/conn/state/page_target_host.rs
new file mode 100644
index 000000000..e3b93934b
--- /dev/null
+++ b/moli-protocol/src/conn/state/page_target_host.rs
@@ -0,0 +1,333 @@
+use moli_core::network::SharedWebStorageStore;
+use moli_core::runtime::NavigationEngine;
+
+use super::{
+ identity::TargetIdentityState,
+ page_slot::TargetPageSlot,
+ runtime_slot::TargetRuntimeSlot,
+ session::{ActiveTargetState, TargetPageState},
+ session_storage::TargetSessionStorageNamespace,
+};
+
+/// The stable owner of all state that belongs to one page target.
+///
+/// Selecting another page never replaces or reconstructs this object. The
+/// browser context registry keeps every page host alive and records foreground
+/// selection separately.
+#[derive(Debug)]
+pub struct PageTargetHost {
+ target_id: String,
+ primary_session_id: Option<String>,
+ state: Box<TargetPageState>,
+ navigation_engine: Option<NavigationEngine>,
+}
+
+impl PageTargetHost {
+ pub(crate) fn empty(target_id: String) -> Self {
+ Self {
+ target_id,
+ primary_session_id: None,
+ state: Box::default(),
+ navigation_engine: None,
+ }
+ }
+
+ pub(crate) fn new(
+ target_id: String,
+ primary_session_id: Option<String>,
+ target_identity: TargetIdentityState,
+ target_page_slot: TargetPageSlot,
+ ) -> Self {
+ Self {
+ target_id,
+ primary_session_id,
+ state: Box::new(TargetPageState {
+ target_identity,
+ active_target: ActiveTargetState {
+ runtime_slot: TargetRuntimeSlot::from_page_slot(target_page_slot),
+ ..Default::default()
+ },
+ ..Default::default()
+ }),
+ navigation_engine: None,
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_url(
+ target_id: String,
+ primary_session_id: Option<String>,
+ url: String,
+ ) -> Self {
+ Self::new(
+ target_id,
+ primary_session_id,
+ TargetIdentityState::with_url(url),
+ TargetPageSlot::empty_for_test_fixture(),
+ )
+ }
+
+ pub(crate) fn with_identity(
+ target_id: String,
+ primary_session_id: Option<String>,
+ target_identity: TargetIdentityState,
+ ) -> Self {
+ Self::new(
+ target_id,
+ primary_session_id,
+ target_identity,
+ TargetPageSlot::empty_for_initial_document_page_build(),
+ )
+ }
+
+ pub(crate) fn target_id(&self) -> &str {
+ &self.target_id
+ }
+
+ fn replace_target_id(&mut self, target_id: String) {
+ self.target_id = target_id;
+ }
+
+ pub(crate) fn is_target(&self, target_id: &str) -> bool {
+ self.target_id() == target_id
+ }
+
+ pub(crate) fn session_id(&self) -> Option<&str> {
+ self.primary_session_id.as_deref()
+ }
+
+ pub(crate) fn has_session(&self) -> bool {
+ self.primary_session_id.is_some()
+ }
+
+ pub(crate) fn is_session(&self, session_id: &str) -> bool {
+ self.session_id() == Some(session_id)
+ }
+
+ pub(crate) fn attach_session(&mut self, session_id: String) {
+ self.primary_session_id = Some(session_id);
+ }
+
+ pub(crate) fn detach_session(&mut self) -> Option<String> {
+ self.primary_session_id.take()
+ }
+
+ pub(crate) fn session_storage_store(&self) -> &SharedWebStorageStore {
+ self.session_storage_namespace.store()
+ }
+
+ pub(crate) fn deep_clone_session_storage_namespace(&self) -> TargetSessionStorageNamespace {
+ self.session_storage_namespace.deep_clone()
+ }
+
+ pub(crate) fn replace_session_storage_namespace(
+ &mut self,
+ namespace: TargetSessionStorageNamespace,
+ ) {
+ self.session_storage_namespace = namespace;
+ }
+
+ pub(crate) fn state(&self) -> &TargetPageState {
+ &self.state
+ }
+
+ pub(crate) fn state_mut(&mut self) -> &mut TargetPageState {
+ &mut self.state
+ }
+
+ pub(crate) fn navigation_engine(&self) -> Option<&NavigationEngine> {
+ self.navigation_engine.as_ref()
+ }
+
+ pub(crate) fn navigation_engine_mut(&mut self) -> Option<&mut NavigationEngine> {
+ self.navigation_engine.as_mut()
+ }
+
+ pub(crate) fn replace_navigation_engine(
+ &mut self,
+ engine: NavigationEngine,
+ ) -> Option<NavigationEngine> {
+ self.navigation_engine.replace(engine)
+ }
+
+ pub(crate) fn navigation_engine_and_runtime_slot_mut(
+ &mut self,
+ ) -> Option<(&mut NavigationEngine, &mut TargetRuntimeSlot)> {
+ let engine = self.navigation_engine.as_mut()?;
+ Some((engine, &mut self.state.active_target.runtime_slot))
+ }
+
+ pub(crate) fn has_page_domain_enabled_session(&self) -> bool {
+ self.devtools_sessions
+ .states()
+ .any(|session| session.page_session_state.page_domain_enabled)
+ }
+
+ pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
+ self.state.has_pending_javascript_dialog()
+ }
+
+ pub(crate) fn has_pending_inspector_awaits(&self) -> bool {
+ self.devtools_sessions.has_pending_inspector_awaits()
+ }
+
+ pub(crate) fn pending_inspector_await_count(&self) -> usize {
+ self.devtools_sessions.pending_inspector_await_count()
+ }
+
+ pub(crate) fn has_runtime_remote_object_id(&self, object_id: &str) -> bool {
+ self.devtools_sessions
+ .states()
+ .any(|session| session.has_runtime_remote_object_id(object_id))
+ }
+
+ pub(crate) fn has_runtime_remote_object_id_for_different_session(
+ &self,
+ devtools_session_id: Option<&str>,
+ object_id: &str,
+ ) -> bool {
+ if devtools_session_id.is_some()
+ && self
+ .devtools_sessions
+ .primary()
+ .has_runtime_remote_object_id(object_id)
+ {
+ return true;
+ }
+ self.devtools_sessions
+ .attached_entries()
+ .any(|(session_id, session_state)| {
+ Some(session_id) != devtools_session_id
+ && session_state.has_runtime_remote_object_id(object_id)
+ })
+ }
+}
+
+impl std::ops::Deref for PageTargetHost {
+ type Target = TargetPageState;
+
+ fn deref(&self) -> &Self::Target {
+ &self.state
+ }
+}
+
+impl std::ops::DerefMut for PageTargetHost {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.state
+ }
+}
+
+/// All page hosts in one browser context plus the foreground selector.
+///
+/// Insertion order is retained for Chromium-compatible fallback selection
+/// when the foreground page closes.
+#[derive(Debug, Default)]
+pub(crate) struct PageTargetRegistry {
+ active_target_id: Option<String>,
+ hosts: Vec<PageTargetHost>,
+}
+
+impl PageTargetRegistry {
+ pub(crate) fn active_target_id(&self) -> Option<&str> {
+ self.active_target_id.as_deref()
+ }
+
+ pub(crate) fn active(&self) -> Option<&PageTargetHost> {
+ self.get(self.active_target_id()?)
+ }
+
+ pub(crate) fn active_mut(&mut self) -> Option<&mut PageTargetHost> {
+ let target_id = self.active_target_id.clone()?;
+ self.get_mut(&target_id)
+ }
+
+ pub(crate) fn get(&self, target_id: &str) -> Option<&PageTargetHost> {
+ self.hosts.iter().find(|host| host.is_target(target_id))
+ }
+
+ pub(crate) fn get_mut(&mut self, target_id: &str) -> Option<&mut PageTargetHost> {
+ self.hosts.iter_mut().find(|host| host.is_target(target_id))
+ }
+
+ pub(crate) fn insert(&mut self, host: PageTargetHost) -> bool {
+ if self.get(host.target_id()).is_some() {
+ return false;
+ }
+ self.hosts.push(host);
+ true
+ }
+
+ pub(crate) fn remove(&mut self, target_id: &str) -> Option<PageTargetHost> {
+ let index = self
+ .hosts
+ .iter()
+ .position(|host| host.is_target(target_id))?;
+ if self.active_target_id() == Some(target_id) {
+ self.active_target_id = None;
+ }
+ Some(self.hosts.remove(index))
+ }
+
+ pub(crate) fn select(&mut self, target_id: &str) -> bool {
+ if self.get(target_id).is_none() {
+ return false;
+ }
+ self.active_target_id = Some(target_id.to_owned());
+ true
+ }
+
+ pub(crate) fn rekey_active(&mut self, target_id: String) -> bool {
+ if self.get(&target_id).is_some() {
+ return false;
+ }
+ let Some(active) = self.active_mut() else {
+ return false;
+ };
+ active.replace_target_id(target_id.clone());
+ self.active_target_id = Some(target_id);
+ true
+ }
+
+ #[cfg(test)]
+ pub(crate) fn clear_selection(&mut self) {
+ self.active_target_id = None;
+ }
+
+ pub(crate) fn iter(&self) -> impl DoubleEndedIterator<Item = &PageTargetHost> {
+ self.hosts.iter()
+ }
+
+ pub(crate) fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut PageTargetHost> {
+ self.hosts.iter_mut()
+ }
+
+ pub(crate) fn background(&self) -> impl DoubleEndedIterator<Item = &PageTargetHost> {
+ let active_target_id = self.active_target_id();
+ self.iter()
+ .filter(move |host| Some(host.target_id()) != active_target_id)
+ }
+
+ pub(crate) fn background_mut(
+ &mut self,
+ ) -> impl DoubleEndedIterator<Item = &mut PageTargetHost> {
+ let active_target_id = self.active_target_id.clone();
+ self.iter_mut()
+ .filter(move |host| Some(host.target_id()) != active_target_id.as_deref())
+ }
+
+ pub(crate) fn background_at(&self, index: usize) -> Option<&PageTargetHost> {
+ self.background().nth(index)
+ }
+
+ pub(crate) fn background_at_mut(&mut self, index: usize) -> Option<&mut PageTargetHost> {
+ self.background_mut().nth(index)
+ }
+
+ pub(crate) fn background_len(&self) -> usize {
+ self.background().count()
+ }
+
+ pub(crate) fn background_is_empty(&self) -> bool {
+ self.background().next().is_none()
+ }
+}
diff --git a/moli-protocol/src/conn/state/parking.rs b/moli-protocol/src/conn/state/parking.rs
index 9e18ac57f..8d86b759f 100644
--- a/moli-protocol/src/conn/state/parking.rs
+++ b/moli-protocol/src/conn/state/parking.rs
@@ -1,425 +1,31 @@
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
-use moli_core::network::SharedWebStorageStore;
-use moli_page_types::FrontendCommandId;
+use moli_page_types::{DevToolsSessionKey, FrontendCommandId};
use serde_json::{Value, json};
use crate::{
- conn::cookie_manager_surface,
devtools_runtime::{
DevToolsBidiChannelProperties, DevToolsRealmId, DevToolsRemoteHandleId, DevToolsTargetId,
},
domains::{
audits_output_state::TargetAuditsStorageState,
- console_output_state::TargetConsoleOutputState,
- log_output_state::TargetLogStorageState,
- network::{CollectedNetworkDataArtifact, TargetNetworkArtifacts},
+ console_output_state::TargetConsoleOutputState, log_output_state::TargetLogStorageState,
observable_output::TargetRuntimeObservableState,
},
};
use super::{
- DevToolsSessionState, devtools_sessions_have_pending_inspector_awaits,
- devtools_sessions_pending_inspector_await_count,
- emulation::{
- EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedMediaOverrides,
- EmulatedNetworkConditions,
- },
- fetch::{ParkedFetchState, TargetFetchConfig},
- identity::TargetIdentityState,
navigation::{PageNavigationHistoryEntry, TargetNavigationHistoryState},
page_resource::TargetPageResourceStore,
- page_slot::{DocumentStartScript, IsolatedWorldDefinition, TargetPageSlot},
+ page_slot::{DocumentStartScript, IsolatedWorldDefinition},
pending_renderer_command::{
DuplicatePendingRendererCommand, PendingRendererCommandRegistry,
PreparedRendererCallDispatch, PreparedRendererCallReplay, PreparedRendererCallTermination,
RegisterRendererCallError, RendererCallIdExhausted, RendererCommandCorrelation,
RendererCommandDescriptor,
},
- runtime_slot::{TargetNetworkRequestCounters, TargetRuntimeSlot},
- session::TargetNetworkPolicyState,
- session_storage::TargetSessionStorageNamespace,
};
-#[derive(Debug)]
-pub struct BackgroundTarget {
- pub(in crate::conn) target_id: String,
- pub(in crate::conn) session_id: Option<String>,
- pub(in crate::conn) target_identity: TargetIdentityState,
- pub(in crate::conn) runtime_slot: TargetRuntimeSlot,
- session_storage_namespace: TargetSessionStorageNamespace,
-}
-
-impl BackgroundTarget {
- pub(crate) fn new(
- target_id: String,
- session_id: Option<String>,
- target_identity: TargetIdentityState,
- target_page_slot: TargetPageSlot,
- ) -> Self {
- Self {
- target_id,
- session_id,
- target_identity,
- runtime_slot: TargetRuntimeSlot::from_page_slot(target_page_slot),
- session_storage_namespace: TargetSessionStorageNamespace::default(),
- }
- }
-
- #[cfg(test)]
- pub(crate) fn with_url(target_id: String, session_id: Option<String>, url: String) -> Self {
- Self::new(
- target_id,
- session_id,
- TargetIdentityState::with_url(url),
- TargetPageSlot::empty_for_test_fixture(),
- )
- }
-
- pub(crate) fn with_identity(
- target_id: String,
- session_id: Option<String>,
- target_identity: TargetIdentityState,
- ) -> Self {
- Self::new(
- target_id,
- session_id,
- target_identity,
- TargetPageSlot::empty_for_initial_document_page_build(),
- )
- }
-
- pub(crate) fn target_id(&self) -> &str {
- &self.target_id
- }
-
- pub(crate) fn is_target(&self, target_id: &str) -> bool {
- self.target_id() == target_id
- }
-
- pub(crate) fn session_id(&self) -> Option<&str> {
- self.session_id.as_deref()
- }
-
- pub(crate) fn has_session(&self) -> bool {
- self.session_id.is_some()
- }
-
- pub(crate) fn is_session(&self, session_id: &str) -> bool {
- self.session_id() == Some(session_id)
- }
-
- pub(crate) fn attach_session(&mut self, session_id: String) {
- self.session_id = Some(session_id);
- }
-
- pub(crate) fn detach_session(&mut self) -> Option<String> {
- self.session_id.take()
- }
-
- pub(crate) fn session_storage_store(&self) -> &SharedWebStorageStore {
- self.session_storage_namespace.store()
- }
-
- pub(crate) fn deep_clone_session_storage_namespace(&self) -> TargetSessionStorageNamespace {
- self.session_storage_namespace.deep_clone()
- }
-
- pub(crate) fn replace_session_storage_namespace(
- &mut self,
- namespace: TargetSessionStorageNamespace,
- ) {
- self.session_storage_namespace = namespace;
- }
-
- pub(crate) fn take_session_storage_namespace(&mut self) -> TargetSessionStorageNamespace {
- std::mem::take(&mut self.session_storage_namespace)
- }
-}
-
-#[derive(Debug)]
-pub(crate) struct TargetSlotState {
- target: BackgroundTarget,
- aux_state: ParkedTargetAuxState,
-}
-
-impl TargetSlotState {
- pub(crate) fn new(target: BackgroundTarget, aux_state: ParkedTargetAuxState) -> Self {
- Self { target, aux_state }
- }
-
- pub(crate) fn from_active_snapshot(
- target_id: String,
- session_id: Option<String>,
- target_identity: TargetIdentityState,
- runtime_slot: TargetRuntimeSlot,
- session_storage_namespace: TargetSessionStorageNamespace,
- aux_state: ParkedTargetAuxState,
- ) -> Self {
- Self {
- target: BackgroundTarget {
- target_id,
- session_id,
- target_identity,
- runtime_slot,
- session_storage_namespace,
- },
- aux_state,
- }
- }
-
- #[cfg(test)]
- pub(crate) fn target(&self) -> &BackgroundTarget {
- &self.target
- }
-
- pub(crate) fn target_id(&self) -> &str {
- self.target.target_id()
- }
-
- #[cfg(test)]
- pub(crate) fn aux_state(&self) -> &ParkedTargetAuxState {
- &self.aux_state
- }
-
- pub(crate) fn into_parts(self) -> (BackgroundTarget, ParkedTargetAuxState) {
- (self.target, self.aux_state)
- }
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct ParkedPageSessionState {
- pub(crate) devtools_session_state: DevToolsSessionState,
- pub(crate) auxiliary_devtools_session_states: HashMap<String, DevToolsSessionState>,
- pub network_enabled: bool,
- pub(crate) network_policy: TargetNetworkPolicyState,
- pub http_proxy_override: Option<String>,
- pub http_no_proxy_override: Option<String>,
- pub tls_verify_host_override: Option<bool>,
- pub locale_override: Option<String>,
- pub timezone_override: Option<String>,
- pub(crate) network_conditions: Option<EmulatedNetworkConditions>,
- pub geolocation_override: Option<EmulatedGeolocationOverrideState>,
- pub emulated_media: EmulatedMediaOverrides,
- pub emulated_device_metrics: Option<EmulatedDeviceMetrics>,
- pub cpu_throttling_rate: f64,
- pub touch_emulation_enabled: bool,
- pub emit_touch_events_for_mouse: bool,
- pub focus_emulation_enabled: bool,
- pub script_execution_disabled: bool,
- pub css_enabled: bool,
- pub fetch_config: TargetFetchConfig,
-}
-
-impl Default for ParkedPageSessionState {
- fn default() -> Self {
- Self {
- devtools_session_state: DevToolsSessionState::default(),
- auxiliary_devtools_session_states: HashMap::new(),
- network_enabled: false,
- network_policy: TargetNetworkPolicyState::default(),
- http_proxy_override: None,
- http_no_proxy_override: None,
- tls_verify_host_override: None,
- locale_override: None,
- timezone_override: None,
- network_conditions: None,
- geolocation_override: None,
- emulated_media: EmulatedMediaOverrides::default(),
- emulated_device_metrics: None,
- cpu_throttling_rate: 1.0,
- touch_emulation_enabled: false,
- emit_touch_events_for_mouse: false,
- focus_emulation_enabled: false,
- script_execution_disabled: false,
- css_enabled: false,
- fetch_config: TargetFetchConfig::default(),
- }
- }
-}
-
-impl ParkedPageSessionState {
- pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
- !self
- .devtools_session_state
- .page_session_state
- .javascript_dialog_state
- .is_empty()
- || self
- .auxiliary_devtools_session_states
- .values()
- .any(|session| {
- !session
- .page_session_state
- .javascript_dialog_state
- .is_empty()
- })
- }
-}
-
-fn parked_page_session_has_page_domain_enabled(state: &ParkedPageSessionState) -> bool {
- state
- .devtools_session_state
- .page_session_state
- .page_domain_enabled
- || state
- .auxiliary_devtools_session_states
- .values()
- .any(|session_state| session_state.page_session_state.page_domain_enabled)
-}
-
-fn parked_page_session_has_runtime_remote_object_id(
- state: &ParkedPageSessionState,
- object_id: &str,
-) -> bool {
- state
- .devtools_session_state
- .has_runtime_remote_object_id(object_id)
- || state
- .auxiliary_devtools_session_states
- .values()
- .any(|session_state| session_state.has_runtime_remote_object_id(object_id))
-}
-
-fn parked_page_session_has_runtime_remote_object_id_for_different_session(
- state: &ParkedPageSessionState,
- devtools_session_id: Option<&str>,
- object_id: &str,
-) -> bool {
- if devtools_session_id.is_some()
- && state
- .devtools_session_state
- .has_runtime_remote_object_id(object_id)
- {
- return true;
- }
- state
- .auxiliary_devtools_session_states
- .iter()
- .any(|(session_id, session_state)| {
- Some(session_id.as_str()) != devtools_session_id
- && session_state.has_runtime_remote_object_id(object_id)
- })
-}
-
-pub(crate) fn parked_page_session_has_pending_inspector_awaits(
- state: &ParkedPageSessionState,
-) -> bool {
- devtools_sessions_have_pending_inspector_awaits(
- &state.devtools_session_state,
- &state.auxiliary_devtools_session_states,
- )
-}
-
-pub(crate) fn parked_page_session_pending_inspector_await_count(
- state: &ParkedPageSessionState,
-) -> usize {
- devtools_sessions_pending_inspector_await_count(
- &state.devtools_session_state,
- &state.auxiliary_devtools_session_states,
- )
-}
-
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct ParkedNetworkArtifacts {
- target_network_artifacts: TargetNetworkArtifacts,
- request_counters: TargetNetworkRequestCounters,
-}
-
-impl ParkedNetworkArtifacts {
- pub(crate) fn snapshot_from_runtime_slot(runtime_slot: &TargetRuntimeSlot) -> Self {
- Self {
- target_network_artifacts: runtime_slot.snapshot_network_artifacts(),
- request_counters: runtime_slot.snapshot_network_request_counters(),
- }
- }
-
- pub(crate) fn restore_into_runtime_slot(self, runtime_slot: &mut TargetRuntimeSlot) {
- runtime_slot.restore_network_artifacts(self.target_network_artifacts);
- runtime_slot.restore_network_request_counters(self.request_counters);
- }
-
- pub(crate) fn collected_network_data_artifacts(&self) -> Vec<CollectedNetworkDataArtifact> {
- self.target_network_artifacts
- .collected_network_data_artifacts()
- }
-
- pub(crate) fn drain_from_background_target(&mut self, target: &mut BackgroundTarget) {
- self.target_network_artifacts = target.runtime_slot.take_network_artifacts();
- self.request_counters = target.runtime_slot.take_network_request_counters();
- }
-
- pub(crate) fn drain_into_background_target(&mut self, target: &mut BackgroundTarget) {
- target
- .runtime_slot
- .restore_network_artifacts(std::mem::take(&mut self.target_network_artifacts));
- target
- .runtime_slot
- .restore_network_request_counters(std::mem::take(&mut self.request_counters));
- }
-
- pub(crate) fn set_session_observation_cursor_at_counts(
- &mut self,
- session_id: Option<&str>,
- subresource_count: usize,
- websocket_count: usize,
- ) {
- self.target_network_artifacts
- .set_session_observation_cursor_at_counts(
- session_id,
- subresource_count,
- websocket_count,
- );
- }
-
- pub(crate) fn remove_session_observation_cursor(&mut self, session_id: Option<&str>) {
- self.target_network_artifacts
- .remove_session_observation_cursor(session_id);
- }
-
- pub(crate) fn remove_captured_response_body_visibility_for_session(
- &mut self,
- session_id: Option<&str>,
- ) {
- self.target_network_artifacts
- .remove_captured_response_body_visibility_for_session(session_id);
- }
-
- pub(crate) fn clear_captured_response_bodies_and_websocket_request_ids(&mut self) {
- self.target_network_artifacts
- .clear_captured_response_bodies();
- self.target_network_artifacts.clear_websocket_request_ids();
- }
-
- #[cfg(test)]
- pub(crate) fn next_fetch_request_id_for_test(&self) -> u32 {
- self.request_counters.next_fetch_request_id
- }
-
- #[cfg(test)]
- pub(crate) fn next_subresource_fetch_request_id_for_test(&self) -> u32 {
- self.request_counters.next_subresource_fetch_request_id
- }
-
- #[cfg(test)]
- pub(crate) fn emitted_subresource_record_count_for_session(
- &self,
- session_id: Option<&str>,
- ) -> usize {
- self.target_network_artifacts
- .emitted_subresource_record_count_for_session(session_id)
- }
-
- #[cfg(test)]
- pub(crate) fn emitted_websocket_event_count_for_session(
- &self,
- session_id: Option<&str>,
- ) -> usize {
- self.target_network_artifacts
- .emitted_websocket_event_count_for_session(session_id)
- }
-}
-
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct TargetCrashState {
crashed: bool,
@@ -928,6 +534,23 @@ impl TargetOwnerState {
.any(|(_, script)| script.has_bidi_channel_argument)
}
+ pub(crate) fn take_document_start_script_registry_keys_for_session(
+ &mut self,
+ devtools_session: &DevToolsSessionKey,
+ ) -> Vec<String> {
+ let mut registry_keys = Vec::new();
+ self.document_start_scripts.retain(|(_, script)| {
+ if script.devtools_session.as_ref() != Some(devtools_session) {
+ return true;
+ }
+ if let Some(registry_key) = script.registry_key.clone() {
+ registry_keys.push(registry_key);
+ }
+ false
+ });
+ registry_keys
+ }
+
pub(crate) fn begin_initial_empty_document(
&mut self,
target_id: String,
@@ -1048,6 +671,11 @@ impl TargetOwnerState {
json!({
"initialEmptyDocument": initial_empty_document,
"documentStartScriptCount": self.document_start_scripts.len(),
+ "sessionOwnedDocumentStartScriptCount": self
+ .document_start_scripts
+ .iter()
+ .filter(|(_, script)| script.devtools_session.is_some())
+ .count(),
"isolatedWorldCount": self.isolated_worlds.len(),
"retainedPageResourceBodyBytes": self.page_resource_store.retained_body_bytes(),
"windowSurfaceState": self.window_surface_state.label(),
@@ -1182,15 +810,6 @@ impl TargetOwnerState {
.record_same_document_update(url, title, history_update);
}
- pub(crate) fn clear_page_local_state(&mut self) {
- self.next_document_start_script_id = 0;
- self.isolated_worlds.clear();
- self.attached_child_frame_ids.clear();
- self.navigation_history_state.clear();
- self.page_resource_store.clear();
- self.target_crash_state.clear();
- }
-
pub(crate) fn clear_observable_output_state(&mut self) {
self.runtime_observable_state.clear();
self.console_output_state.clear();
@@ -1267,287 +886,6 @@ impl TargetOwnerState {
pub(crate) type ParkedTargetOwnerState = TargetOwnerState;
-#[derive(Debug)]
-pub(crate) struct ParkedTargetAuxState {
- pub(crate) cookie_manager_surface:
- cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot,
- pub(crate) page_session_state: ParkedPageSessionState,
- pub(crate) fetch_state: ParkedFetchState,
- pub(crate) network_artifacts: ParkedNetworkArtifacts,
- pub(crate) target_owner_state: ParkedTargetOwnerState,
-}
-
-impl ParkedTargetAuxState {
- pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
- self.page_session_state.has_pending_javascript_dialog()
- }
-}
-
-#[derive(Debug, Default)]
-pub(crate) struct TargetParkingStateStore {
- cookie_manager_surfaces:
- HashMap<String, cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot>,
- page_session_states: HashMap<String, ParkedPageSessionState>,
- fetch_states: HashMap<String, ParkedFetchState>,
- network_artifacts: HashMap<String, ParkedNetworkArtifacts>,
- target_owner_states: HashMap<String, ParkedTargetOwnerState>,
-}
-
-impl TargetParkingStateStore {
- pub(crate) fn moli_memory_diagnostics(&self) -> Value {
- let owner_state_summaries = self
- .target_owner_states
- .iter()
- .map(|(target_id, state)| {
- json!({
- "targetId": target_id,
- "ownerState": state.moli_memory_diagnostics(),
- })
- })
- .collect::<Vec<_>>();
- json!({
- "cookieManagerSurfaceCount": self.cookie_manager_surfaces.len(),
- "pageSessionStateCount": self.page_session_states.len(),
- "fetchStateCount": self.fetch_states.len(),
- "networkArtifactCount": self.network_artifacts.len(),
- "targetOwnerStateCount": self.target_owner_states.len(),
- "targetOwnerStateWithPendingInspectorAwaitCount": self
- .pending_inspector_await_target_count(),
- "pendingInspectorAwaitCount": self.pending_inspector_await_count(),
- "nonEmptyFetchStateCount": self
- .fetch_states
- .values()
- .filter(|state| !state.is_empty())
- .count(),
- "ownerStates": owner_state_summaries,
- })
- }
-
- pub(crate) fn mutate_target_owner_state<T>(
- &mut self,
- target_id: &str,
- mutate: impl FnOnce(&mut ParkedTargetOwnerState) -> T,
- ) -> T {
- let mut state = self.take_target_owner_state(target_id);
- let result = mutate(&mut state);
- self.replace_target_owner_state(target_id.to_owned(), state);
- result
- }
-
- pub(crate) fn take_isolated_worlds(&mut self, target_id: &str) -> Vec<IsolatedWorldDefinition> {
- self.mutate_target_owner_state(target_id, |state| {
- std::mem::take(&mut state.isolated_worlds)
- })
- }
-
- pub(crate) fn replace_isolated_worlds(
- &mut self,
- target_id: String,
- isolated_worlds: Vec<IsolatedWorldDefinition>,
- ) {
- self.mutate_target_owner_state(&target_id, |state| {
- state.isolated_worlds = isolated_worlds;
- });
- }
-
- pub(crate) fn take_document_start_script_counter(&mut self, target_id: &str) -> u32 {
- self.mutate_target_owner_state(target_id, |state| {
- let counter = state.next_document_start_script_id;
- state.next_document_start_script_id = 0;
- counter
- })
- }
-
- pub(crate) fn replace_document_start_script_counter(
- &mut self,
- target_id: String,
- counter: u32,
- ) {
- self.mutate_target_owner_state(&target_id, |state| {
- state.next_document_start_script_id = counter;
- });
- }
-
- pub(crate) fn take_cookie_manager_surface(
- &mut self,
- target_id: &str,
- ) -> cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot {
- self.cookie_manager_surfaces
- .remove(target_id)
- .unwrap_or_default()
- }
-
- pub(crate) fn replace_cookie_manager_surface(
- &mut self,
- target_id: String,
- snapshot: cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot,
- ) {
- if snapshot == cookie_manager_surface::BrowserContextCookieManagerSurfaceSnapshot::default()
- {
- self.cookie_manager_surfaces.remove(&target_id);
- return;
- }
- self.cookie_manager_surfaces.insert(target_id, snapshot);
- }
-
- pub(crate) fn page_session_state(&self, target_id: &str) -> Option<&ParkedPageSessionState> {
- self.page_session_states.get(target_id)
- }
-
- pub(crate) fn has_page_domain_enabled_session(&self) -> bool {
- self.page_session_states
- .values()
- .any(parked_page_session_has_page_domain_enabled)
- }
-
- pub(crate) fn take_page_session_state(&mut self, target_id: &str) -> ParkedPageSessionState {
- self.page_session_states
- .remove(target_id)
- .unwrap_or_default()
- }
-
- pub(crate) fn replace_page_session_state(
- &mut self,
- target_id: String,
- state: ParkedPageSessionState,
- ) {
- if state == ParkedPageSessionState::default() {
- self.page_session_states.remove(&target_id);
- return;
- }
- self.page_session_states.insert(target_id, state);
- }
-
- pub(crate) fn take_fetch_state(&mut self, target_id: &str) -> ParkedFetchState {
- self.fetch_states.remove(target_id).unwrap_or_default()
- }
-
- pub(crate) fn fetch_state(&self, target_id: &str) -> Option<&ParkedFetchState> {
- self.fetch_states.get(target_id)
- }
-
- pub(crate) fn replace_fetch_state(&mut self, target_id: String, state: ParkedFetchState) {
- if state.is_empty() {
- self.fetch_states.remove(&target_id);
- return;
- }
- self.fetch_states.insert(target_id, state);
- }
-
- #[cfg(test)]
- pub(crate) fn has_non_empty_fetch_state(&self, target_id: &str) -> bool {
- self.fetch_states
- .get(target_id)
- .is_some_and(|state| !state.is_empty())
- }
-
- pub(crate) fn take_network_artifacts(&mut self, target_id: &str) -> ParkedNetworkArtifacts {
- self.network_artifacts.remove(target_id).unwrap_or_default()
- }
-
- #[cfg(test)]
- pub(crate) fn network_artifacts(&self, target_id: &str) -> Option<&ParkedNetworkArtifacts> {
- self.network_artifacts.get(target_id)
- }
-
- pub(crate) fn replace_network_artifacts(
- &mut self,
- target_id: String,
- artifacts: ParkedNetworkArtifacts,
- ) {
- if artifacts == ParkedNetworkArtifacts::default() {
- self.network_artifacts.remove(&target_id);
- return;
- }
- self.network_artifacts.insert(target_id, artifacts);
- }
-
- pub(crate) fn take_target_owner_state(&mut self, target_id: &str) -> ParkedTargetOwnerState {
- self.target_owner_states
- .remove(target_id)
- .unwrap_or_default()
- }
-
- pub(crate) fn target_owner_state(&self, target_id: &str) -> Option<&ParkedTargetOwnerState> {
- self.target_owner_states.get(target_id)
- }
-
- pub(crate) fn replace_target_owner_state(
- &mut self,
- target_id: String,
- state: ParkedTargetOwnerState,
- ) {
- if state.is_default() {
- self.target_owner_states.remove(&target_id);
- return;
- }
- self.target_owner_states.insert(target_id, state);
- }
-
- pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
- self.page_session_states.values().any(|state| {
- !state
- .devtools_session_state
- .page_session_state
- .javascript_dialog_state
- .is_empty()
- || state
- .auxiliary_devtools_session_states
- .values()
- .any(|session| {
- !session
- .page_session_state
- .javascript_dialog_state
- .is_empty()
- })
- })
- }
-
- pub(crate) fn has_pending_inspector_awaits(&self) -> bool {
- self.page_session_states
- .values()
- .any(parked_page_session_has_pending_inspector_awaits)
- }
-
- pub(crate) fn pending_inspector_await_count(&self) -> usize {
- self.page_session_states
- .values()
- .map(parked_page_session_pending_inspector_await_count)
- .sum()
- }
-
- pub(crate) fn pending_inspector_await_target_count(&self) -> usize {
- self.page_session_states
- .values()
- .filter(|state| parked_page_session_has_pending_inspector_awaits(state))
- .count()
- }
-
- pub(crate) fn has_runtime_remote_object_id(&self, object_id: &str) -> bool {
- self.page_session_states
- .values()
- .any(|state| parked_page_session_has_runtime_remote_object_id(state, object_id))
- }
-
- pub(crate) fn runtime_remote_object_id_known_for_different_page_owner(
- &self,
- target_id: &str,
- devtools_session_id: Option<&str>,
- object_id: &str,
- ) -> bool {
- self.page_session_states.iter().any(|(id, state)| {
- if id == target_id {
- return parked_page_session_has_runtime_remote_object_id_for_different_session(
- state,
- devtools_session_id,
- object_id,
- );
- }
- parked_page_session_has_runtime_remote_object_id(state, object_id)
- })
- }
-}
-
fn is_initial_empty_document_url(raw_url: &str) -> bool {
url::Url::parse(raw_url)
.ok()
diff --git a/moli-protocol/src/conn/state/runtime_slot.rs b/moli-protocol/src/conn/state/runtime_slot.rs
index 8df55d07d..608ad7d0b 100644
--- a/moli-protocol/src/conn/state/runtime_slot.rs
+++ b/moli-protocol/src/conn/state/runtime_slot.rs
@@ -13,8 +13,7 @@ use crate::{
network::{
CapturedRequestBody, CapturedResponseBody, NetworkBacklogPreferredRequestId,
PendingNetworkBacklogDeliverySnapshot, RetiringTargetNetworkAgentState,
- TargetIoStreamRead, TargetNetworkAgentState, TargetNetworkArtifacts,
- TargetNetworkBacklogPreparedDelivery,
+ TargetIoStreamRead, TargetNetworkAgentState, TargetNetworkBacklogPreparedDelivery,
},
observable_output::{
TargetRuntimeObservableQueueState, TargetRuntimeObservableSourceOutput,
@@ -700,12 +699,6 @@ impl TargetRuntimeSlot {
page.bind_renderer_agent_attachment(current.id());
}
- pub(crate) fn prepare_renderer_channel_for_new_target(&mut self) {
- if self.devtools_renderer_channel.is_closed() {
- self.devtools_renderer_channel = DevToolsRendererChannel::default();
- }
- }
-
fn transition_renderer_channel_for_page_absence(&mut self, reason: TargetPageAbsenceReason) {
match reason {
TargetPageAbsenceReason::TargetClosed => {
@@ -1020,42 +1013,6 @@ impl TargetRuntimeSlot {
.remove_session_observation_cursor(session_id);
}
- pub(in crate::conn::state) fn snapshot_network_artifacts(&self) -> TargetNetworkArtifacts {
- self.network_agent.snapshot_artifacts()
- }
-
- pub(in crate::conn::state) fn take_network_artifacts(&mut self) -> TargetNetworkArtifacts {
- let artifacts = self.snapshot_network_artifacts();
- self.restore_network_artifacts(Default::default());
- artifacts
- }
-
- pub(in crate::conn::state) fn restore_network_artifacts(
- &mut self,
- artifacts: TargetNetworkArtifacts,
- ) {
- self.network_agent.restore_artifacts(artifacts);
- }
-
- pub(in crate::conn::state) fn snapshot_network_request_counters(
- &self,
- ) -> TargetNetworkRequestCounters {
- self.request_counters
- }
-
- pub(in crate::conn::state) fn take_network_request_counters(
- &mut self,
- ) -> TargetNetworkRequestCounters {
- std::mem::take(&mut self.request_counters)
- }
-
- pub(in crate::conn::state) fn restore_network_request_counters(
- &mut self,
- counters: TargetNetworkRequestCounters,
- ) {
- self.request_counters = counters;
- }
-
pub(crate) fn request_id_allocator(&mut self) -> TargetNetworkRequestIdAllocator<'_> {
TargetNetworkRequestIdAllocator { runtime_slot: self }
}
@@ -1345,13 +1302,12 @@ impl TargetRuntimeSlot {
subresource_count: usize,
websocket_count: usize,
) {
- let mut artifacts = self.snapshot_network_artifacts();
- artifacts.set_session_observation_cursor_at_counts(
- session_id,
- subresource_count,
- websocket_count,
- );
- self.restore_network_artifacts(artifacts);
+ self.network_agent
+ .set_session_observation_cursor_at_counts_for_test(
+ session_id,
+ subresource_count,
+ websocket_count,
+ );
}
#[cfg(test)]
@@ -1359,8 +1315,8 @@ impl TargetRuntimeSlot {
&self,
session_id: Option<&str>,
) -> usize {
- self.snapshot_network_artifacts()
- .emitted_subresource_record_count_for_session(session_id)
+ self.network_agent
+ .emitted_subresource_record_count_for_session_for_test(session_id)
}
#[cfg(test)]
@@ -1368,8 +1324,14 @@ impl TargetRuntimeSlot {
&self,
session_id: Option<&str>,
) -> usize {
- self.snapshot_network_artifacts()
- .emitted_websocket_event_count_for_session(session_id)
+ self.network_agent
+ .emitted_websocket_event_count_for_session_for_test(session_id)
+ }
+
+ #[cfg(test)]
+ pub(crate) fn network_artifacts_are_default_for_test(&self) -> bool {
+ self.network_agent.artifacts_are_default_for_test()
+ && self.request_counters == TargetNetworkRequestCounters::default()
}
#[cfg(test)]
@@ -1409,40 +1371,13 @@ impl TargetRuntimeSlot {
#[cfg(test)]
mod tests {
use moli_core::page::{
- RendererDevToolsAgentToken, RendererDocumentToken, RendererFrameToken,
- RendererLifecycleEpoch, ScriptNetworkOutputItem, SubresourceRequestInitiatorType,
- SubresourceRequestStarted, SubresourceResourceType,
+ RendererDocumentToken, RendererFrameToken, RendererLifecycleEpoch, ScriptNetworkOutputItem,
+ SubresourceRequestInitiatorType, SubresourceRequestStarted, SubresourceResourceType,
};
use url::Url;
use super::*;
- #[test]
- fn target_close_is_terminal_until_the_slot_is_assigned_to_a_new_target() {
- let mut slot = TargetRuntimeSlot::default();
- let old_agent = RendererDevToolsAgentToken::allocate();
- slot.devtools_renderer_channel
- .attach_current(old_agent)
- .expect("initial target attachment");
-
- slot.mark_loaded_page_absent(TargetPageAbsenceReason::TargetClosed);
-
- assert!(slot.devtools_renderer_channel.is_closed());
- assert_eq!(
- slot.devtools_renderer_channel.attach_current(old_agent),
- Err(DevToolsRendererChannelError::Closed),
- "the old target cannot reopen its terminal renderer channel"
- );
-
- slot.prepare_renderer_channel_for_new_target();
- assert!(
- slot.devtools_renderer_channel
- .attach_current(RendererDevToolsAgentToken::allocate())
- .is_ok(),
- "reusing the physical active slot for a new target must allocate a fresh channel"
- );
- }
-
#[test]
fn successor_network_idle_ignores_retained_predecessor_delivery_state() {
let page_id = moli_core::PageId::new_for_testing(41);
diff --git a/moli-protocol/src/conn/state/session.rs b/moli-protocol/src/conn/state/session.rs
index 88d52e5ba..bb97766c9 100644
--- a/moli-protocol/src/conn/state/session.rs
+++ b/moli-protocol/src/conn/state/session.rs
@@ -1,10 +1,20 @@
+use std::collections::HashMap;
+
+use super::devtools_session::DevToolsSessionRegistry;
+use super::emulation::{
+ EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedMediaOverrides,
+ EmulatedNetworkConditions,
+};
use super::fetch::TargetFetchOwner;
+use super::identity::TargetIdentityState;
use super::javascript_dialog::TargetJavaScriptDialogState;
use super::parking::TargetOwnerState;
use super::runtime_slot::TargetRuntimeSlot;
use super::session_storage::TargetSessionStorageNamespace;
+use crate::conn::cookie_manager_surface::BrowserContextCookieManagerSurface;
use crate::domains::audits_output_state::TargetAuditsSessionState;
use moli_core::page::V8InspectorSessionState;
+use serde_json::Value;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum PerformanceTimeDomain {
@@ -60,13 +70,174 @@ impl TargetPerformanceSessionState {
}
#[derive(Debug, Default)]
-pub(crate) struct ActiveTargetState {
+pub struct ActiveTargetState {
pub(crate) runtime_slot: TargetRuntimeSlot,
pub(crate) fetch_owner: TargetFetchOwner,
pub(crate) owner_state: TargetOwnerState,
pub(crate) session_storage_namespace: TargetSessionStorageNamespace,
}
+/// All mutable state owned by one page target.
+///
+/// Foreground selection is deliberately absent from this type. A page keeps
+/// the same state object while visible or hidden; selecting another page must
+/// not serialize this state into a second "parked" representation.
+#[derive(Debug)]
+pub struct TargetPageState {
+ pub(crate) target_identity: TargetIdentityState,
+ pub(crate) devtools_sessions: DevToolsSessionRegistry,
+ pub(crate) network_policy: TargetNetworkPolicyState,
+ pub(crate) http_proxy_override: Option<String>,
+ pub(crate) http_no_proxy_override: Option<String>,
+ pub(crate) tls_verify_host_override: Option<bool>,
+ pub(crate) locale_override: Option<String>,
+ pub(crate) timezone_override: Option<String>,
+ pub(crate) locale_overrides: TargetSessionOverrideStack<String>,
+ pub(crate) timezone_overrides: TargetSessionOverrideStack<String>,
+ pub(crate) network_conditions: Option<EmulatedNetworkConditions>,
+ pub(crate) geolocation_override: Option<EmulatedGeolocationOverrideState>,
+ pub(crate) emulated_media: EmulatedMediaOverrides,
+ pub(crate) emulated_device_metrics: Option<EmulatedDeviceMetrics>,
+ pub(crate) cpu_throttling_rate: f64,
+ pub(crate) input_intercept_drags_enabled: bool,
+ pub(crate) input_drag_intercepted: bool,
+ pub(crate) touch_emulation_enabled: bool,
+ pub(crate) emit_touch_events_for_mouse: bool,
+ pub(crate) focus_emulation_enabled: bool,
+ pub(crate) script_execution_disabled: bool,
+ pub(crate) css_enabled: bool,
+ pub(crate) document_cookie_manager_surface: BrowserContextCookieManagerSurface,
+ pub(crate) dom_remote_object_node_cache: HashMap<String, Value>,
+ pub(crate) active_target: ActiveTargetState,
+}
+
+impl Default for TargetPageState {
+ fn default() -> Self {
+ Self {
+ target_identity: TargetIdentityState::about_blank(),
+ devtools_sessions: DevToolsSessionRegistry::default(),
+ network_policy: TargetNetworkPolicyState::default(),
+ http_proxy_override: None,
+ http_no_proxy_override: None,
+ tls_verify_host_override: None,
+ locale_override: None,
+ timezone_override: None,
+ locale_overrides: TargetSessionOverrideStack::default(),
+ timezone_overrides: TargetSessionOverrideStack::default(),
+ network_conditions: None,
+ geolocation_override: None,
+ emulated_media: EmulatedMediaOverrides::default(),
+ emulated_device_metrics: None,
+ cpu_throttling_rate: 1.0,
+ input_intercept_drags_enabled: false,
+ input_drag_intercepted: false,
+ touch_emulation_enabled: false,
+ emit_touch_events_for_mouse: false,
+ focus_emulation_enabled: false,
+ script_execution_disabled: false,
+ css_enabled: false,
+ document_cookie_manager_surface: BrowserContextCookieManagerSurface::default(),
+ dom_remote_object_node_cache: HashMap::new(),
+ active_target: ActiveTargetState::default(),
+ }
+ }
+}
+
+impl TargetPageState {
+ pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
+ self.devtools_sessions.states().any(|session| {
+ !session
+ .page_session_state
+ .javascript_dialog_state
+ .is_empty()
+ })
+ }
+
+ pub(crate) fn has_non_default_session_state(&self) -> bool {
+ self.devtools_sessions.has_non_default_state()
+ || self
+ .active_target
+ .runtime_slot
+ .primary_network_events_enabled()
+ || self.network_policy != TargetNetworkPolicyState::default()
+ || self.http_proxy_override.is_some()
+ || self.http_no_proxy_override.is_some()
+ || self.tls_verify_host_override.is_some()
+ || self.locale_override.is_some()
+ || self.timezone_override.is_some()
+ || self.locale_overrides != TargetSessionOverrideStack::default()
+ || self.timezone_overrides != TargetSessionOverrideStack::default()
+ || self.network_conditions.is_some()
+ || self.geolocation_override.is_some()
+ || self.emulated_media != EmulatedMediaOverrides::default()
+ || self.emulated_device_metrics.is_some()
+ || self.cpu_throttling_rate != 1.0
+ || self.input_intercept_drags_enabled
+ || self.input_drag_intercepted
+ || self.touch_emulation_enabled
+ || self.emit_touch_events_for_mouse
+ || self.focus_emulation_enabled
+ || self.script_execution_disabled
+ || self.css_enabled
+ || self.active_target.fetch_owner.config_snapshot()
+ != super::fetch::TargetFetchConfig::default()
+ }
+
+ pub(crate) fn clear_session_scoped_state_fields(
+ &mut self,
+ preserve_auxiliary_devtools_sessions: bool,
+ ) {
+ self.devtools_sessions
+ .reset(preserve_auxiliary_devtools_sessions);
+ self.active_target
+ .runtime_slot
+ .disable_primary_network_events();
+ self.network_policy = TargetNetworkPolicyState::default();
+ self.http_proxy_override = None;
+ self.http_no_proxy_override = None;
+ self.tls_verify_host_override = None;
+ self.locale_override = None;
+ self.timezone_override = None;
+ self.locale_overrides.clear();
+ self.timezone_overrides.clear();
+ self.network_conditions = None;
+ self.geolocation_override = None;
+ self.emulated_media = EmulatedMediaOverrides::default();
+ self.emulated_device_metrics = None;
+ self.cpu_throttling_rate = 1.0;
+ self.touch_emulation_enabled = false;
+ self.emit_touch_events_for_mouse = false;
+ self.focus_emulation_enabled = false;
+ self.script_execution_disabled = false;
+ self.css_enabled = false;
+ self.active_target.fetch_owner = TargetFetchOwner::default();
+ self.active_target
+ .runtime_slot
+ .clear_session_scoped_network_observation_artifacts();
+ self.active_target
+ .runtime_slot
+ .request_id_allocator()
+ .reset_fetch_navigation_request_counter();
+ self.active_target
+ .owner_state
+ .clear_observable_output_state();
+ }
+}
+
+impl std::ops::Deref for TargetPageState {
+ type Target = ActiveTargetState;
+
+ fn deref(&self) -> &Self::Target {
+ &self.active_target
+ }
+}
+
+impl std::ops::DerefMut for TargetPageState {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.active_target
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PageScreencastFormat {
Png,
@@ -321,6 +492,47 @@ pub(crate) struct InspectorSessionState {
pub(crate) v8_state: Option<V8InspectorSessionState>,
}
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct TargetSessionOverrideStack<T> {
+ entries: Vec<(Option<String>, T)>,
+}
+
+impl<T> Default for TargetSessionOverrideStack<T> {
+ fn default() -> Self {
+ Self {
+ entries: Vec::new(),
+ }
+ }
+}
+
+impl<T> TargetSessionOverrideStack<T> {
+ pub(crate) fn effective(&self) -> Option<&T> {
+ self.entries.last().map(|(_session_id, value)| value)
+ }
+
+ pub(crate) fn replace(&mut self, session_id: Option<&str>, value: Option<T>) {
+ self.entries
+ .retain(|(owner, _value)| owner.as_deref() != session_id);
+ if let Some(value) = value {
+ self.entries.push((session_id.map(str::to_owned), value));
+ }
+ }
+
+ pub(crate) fn remove_session(&mut self, session_id: &str) -> bool {
+ let effective_changed = self
+ .entries
+ .last()
+ .is_some_and(|(owner, _value)| owner.as_deref() == Some(session_id));
+ self.entries
+ .retain(|(owner, _value)| owner.as_deref() != Some(session_id));
+ effective_changed
+ }
+
+ pub(crate) fn clear(&mut self) {
+ self.entries.clear();
+ }
+}
+
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct TargetNetworkPolicyState {
cache_disabled: bool,
@@ -331,8 +543,9 @@ pub(crate) struct TargetNetworkPolicyState {
emulated_download_throughput: f64,
emulated_upload_throughput: f64,
emulated_connection_type: Option<String>,
- browser_identity_override: Option<moli_browser_profile::BrowserIdentityProfile>,
- extra_headers: Vec<(String, String)>,
+ browser_identity_overrides:
+ TargetSessionOverrideStack<moli_browser_profile::BrowserIdentityProfile>,
+ extra_header_overrides: TargetSessionOverrideStack<Vec<(String, String)>>,
}
impl Default for TargetNetworkPolicyState {
@@ -346,8 +559,8 @@ impl Default for TargetNetworkPolicyState {
emulated_download_throughput: -1.0,
emulated_upload_throughput: -1.0,
emulated_connection_type: None,
- browser_identity_override: None,
- extra_headers: Vec::new(),
+ browser_identity_overrides: TargetSessionOverrideStack::default(),
+ extra_header_overrides: TargetSessionOverrideStack::default(),
}
}
}
@@ -397,26 +610,34 @@ impl TargetNetworkPolicyState {
}
pub(crate) fn extra_headers(&self) -> &[(String, String)] {
- &self.extra_headers
+ self.extra_header_overrides
+ .effective()
+ .map(Vec::as_slice)
+ .unwrap_or(&[])
}
- pub(crate) fn replace_extra_headers(
+ pub(crate) fn replace_extra_headers_for_session(
&mut self,
+ session_id: Option<&str>,
extra_headers: Vec<(String, String)>,
) -> Vec<(String, String)> {
- self.extra_headers = extra_headers;
- self.extra_headers.clone()
+ let override_value = (!extra_headers.is_empty()).then_some(extra_headers);
+ self.extra_header_overrides
+ .replace(session_id, override_value);
+ self.extra_headers().to_vec()
}
#[cfg(test)]
pub(crate) fn push_extra_header(&mut self, header: (String, String)) {
- self.extra_headers.push(header);
+ let mut headers = self.extra_headers().to_vec();
+ headers.push(header);
+ self.replace_extra_headers_for_session(None, headers);
}
pub(crate) fn browser_identity_override(
&self,
) -> Option<&moli_browser_profile::BrowserIdentityProfile> {
- self.browser_identity_override.as_ref()
+ self.browser_identity_overrides.effective()
}
#[cfg(test)]
@@ -428,7 +649,7 @@ impl TargetNetworkPolicyState {
pub(crate) fn browser_identity_override_owned(
&self,
) -> Option<moli_browser_profile::BrowserIdentityProfile> {
- self.browser_identity_override.clone()
+ self.browser_identity_override().cloned()
}
#[cfg(test)]
@@ -443,11 +664,26 @@ impl TargetNetworkPolicyState {
&mut self,
browser_identity: moli_browser_profile::BrowserIdentityProfile,
) {
- self.browser_identity_override = Some(browser_identity);
+ self.set_browser_identity_override_for_session(None, Some(browser_identity));
}
pub(crate) fn clear_browser_identity_override(&mut self) {
- self.browser_identity_override = None;
+ self.set_browser_identity_override_for_session(None, None);
+ }
+
+ pub(crate) fn set_browser_identity_override_for_session(
+ &mut self,
+ session_id: Option<&str>,
+ browser_identity: Option<moli_browser_profile::BrowserIdentityProfile>,
+ ) {
+ self.browser_identity_overrides
+ .replace(session_id, browser_identity);
+ }
+
+ pub(crate) fn remove_session_overrides(&mut self, session_id: &str) -> (bool, bool) {
+ let browser_identity_changed = self.browser_identity_overrides.remove_session(session_id);
+ let extra_headers_changed = self.extra_header_overrides.remove_session(session_id);
+ (browser_identity_changed, extra_headers_changed)
}
#[cfg(test)]
@@ -485,24 +721,61 @@ impl TargetNetworkPolicyState {
self.emulated_connection_type = connection_type;
self.network_offline
}
-
- pub(crate) fn clear_session_scoped_overrides(&mut self) {
- self.cache_disabled = false;
- self.bypass_service_worker = false;
- self.network_offline = false;
- self.blocked_url_patterns.clear();
- self.emulated_network_latency = 0.0;
- self.emulated_download_throughput = -1.0;
- self.emulated_upload_throughput = -1.0;
- self.emulated_connection_type = None;
- self.browser_identity_override = None;
- self.extra_headers.clear();
- }
}
#[cfg(test)]
mod tests {
- use super::{PageScreencastConfig, PageScreencastFormat, PageScreencastSessionState};
+ use super::{
+ PageScreencastConfig, PageScreencastFormat, PageScreencastSessionState,
+ TargetNetworkPolicyState, TargetSessionOverrideStack,
+ };
+
+ #[test]
+ fn detached_session_network_overrides_restore_the_previous_session() {
+ let mut policy = TargetNetworkPolicyState::default();
+ policy.replace_extra_headers_for_session(
+ Some("session-a"),
+ vec![("X-Test".to_owned(), "A".to_owned())],
+ );
+ policy.set_browser_identity_override_for_session(
+ Some("session-a"),
+ Some(moli_browser_profile::BrowserIdentityProfile::new(
+ "Moli/A", "fr-FR",
+ )),
+ );
+ policy.replace_extra_headers_for_session(
+ Some("session-b"),
+ vec![("X-Test".to_owned(), "B".to_owned())],
+ );
+ policy.set_browser_identity_override_for_session(
+ Some("session-b"),
+ Some(moli_browser_profile::BrowserIdentityProfile::new(
+ "Moli/B", "ja-JP",
+ )),
+ );
+
+ assert_eq!(policy.extra_headers()[0].1, "B");
+ assert_eq!(policy.user_agent_override(), Some("Moli/B"));
+ assert_eq!(policy.remove_session_overrides("session-b"), (true, true));
+ assert_eq!(policy.extra_headers()[0].1, "A");
+ assert_eq!(policy.user_agent_override(), Some("Moli/A"));
+ assert_eq!(policy.remove_session_overrides("session-a"), (true, true));
+ assert!(policy.extra_headers().is_empty());
+ assert_eq!(policy.user_agent_override(), None);
+ }
+
+ #[test]
+ fn detached_session_emulation_override_restores_the_previous_session() {
+ let mut overrides = TargetSessionOverrideStack::default();
+ overrides.replace(Some("session-a"), Some("fr-FR".to_owned()));
+ overrides.replace(Some("session-b"), Some("ja-JP".to_owned()));
+ assert_eq!(overrides.effective().map(String::as_str), Some("ja-JP"));
+
+ assert!(overrides.remove_session("session-b"));
+ assert_eq!(overrides.effective().map(String::as_str), Some("fr-FR"));
+ overrides.replace(Some("session-a"), None);
+ assert!(overrides.effective().is_none());
+ }
fn jpeg_config() -> PageScreencastConfig {
PageScreencastConfig::new(PageScreencastFormat::Jpeg, 80, Some(1200), Some(900), 1)
diff --git a/moli-protocol/src/conn/state/tests.rs b/moli-protocol/src/conn/state/tests.rs
index 0ae9ab7ba..920d59024 100644
--- a/moli-protocol/src/conn/state/tests.rs
+++ b/moli-protocol/src/conn/state/tests.rs
@@ -9,17 +9,18 @@ use super::super::fetch_support::{
use super::browser_context::BrowserContext;
use super::devtools_session::DevToolsSessionState;
use super::fetch::{
- FetchInterceptionPattern, FetchRequestStage, FetchResourceTypeFilter, ParkedFetchState,
- TargetFetchOwner, TargetFetchState,
+ FetchInterceptionPattern, FetchRequestStage, FetchResourceTypeFilter, TargetFetchOwner,
+ TargetFetchState,
};
use super::navigation::{PageNavigationHistoryEntry, TargetNavigationHistoryState};
use super::navigation_outcome::{NavigationDispatchState, NavigationResultProjection};
use super::page_slot::{DocumentStartScript, IsolatedWorldDefinition};
-use super::parking::{
- ParkedPageSessionState, ParkedTargetOwnerState, TargetOwnerState, TargetParkingStateStore,
-};
use super::runtime_slot::TargetRuntimeSlot;
-use super::session::TargetPageSessionState;
+use super::session::{TargetPageSessionState, TargetPageState};
+use super::{
+ PageTargetHost,
+ parking::{ParkedTargetOwnerState, TargetOwnerState},
+};
use serde_json::json;
use std::collections::HashMap;
@@ -49,32 +50,32 @@ fn test_navigation_dispatch_state(fetch_request_id: &str) -> NavigationDispatchS
}
#[test]
-fn target_parking_store_collapses_default_target_state() {
- let mut store = TargetParkingStateStore::default();
-
- let mut page_state = ParkedPageSessionState {
- devtools_session_state: DevToolsSessionState {
- page_session_state: TargetPageSessionState {
- log_enabled: true,
- ..Default::default()
- },
+fn background_target_owns_page_session_state_atomically() {
+ let mut target = PageTargetHost::with_url("TID-A".to_owned(), None, "about:blank".to_owned());
+
+ let mut state = TargetPageState::default();
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] = DevToolsSessionState {
+ page_session_state: TargetPageSessionState {
+ log_enabled: true,
..Default::default()
},
..Default::default()
};
- store.replace_page_session_state("TID-A".to_owned(), page_state.clone());
+ *target.state_mut() = state;
assert!(
- store
- .page_session_state("TID-A")
- .is_some_and(|state| state.devtools_session_state.page_session_state.log_enabled)
+ target.state().devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled
);
- page_state
- .devtools_session_state
+ target.state_mut().devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled = false;
- store.replace_page_session_state("TID-A".to_owned(), page_state);
- assert!(store.page_session_state("TID-A").is_none());
+ assert!(
+ !target.state().devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled
+ );
}
#[test]
@@ -1026,20 +1027,21 @@ fn replace_loaded_page_rejects_implicit_no_page_transition() {
}
#[test]
-fn target_parking_store_tracks_non_empty_fetch_state() {
- let mut store = TargetParkingStateStore::default();
-
- store.replace_fetch_state("TID-A".to_owned(), ParkedFetchState::default());
- assert!(!store.has_non_empty_fetch_state("TID-A"));
-
- let mut fetch_state = ParkedFetchState::default();
- fetch_state.insert_pending_fetch_request_id_for_test("FETCH-1".to_owned());
- store.replace_fetch_state("TID-A".to_owned(), fetch_state);
- assert!(store.has_non_empty_fetch_state("TID-A"));
-
- let restored = store.take_fetch_state("TID-A");
- assert!(restored.has_pending_fetch_request_id_for_test("FETCH-1"));
- assert!(!store.has_non_empty_fetch_state("TID-A"));
+fn background_target_owns_fetch_state() {
+ let mut target = PageTargetHost::with_url("TID-A".to_owned(), None, "about:blank".to_owned());
+ assert!(target.fetch_owner.pending_state().is_empty());
+
+ target
+ .fetch_owner
+ .pending_state_mut()
+ .insert_pending_fetch_request_id_for_test("FETCH-1".to_owned());
+ assert!(!target.fetch_owner.pending_state().is_empty());
+ assert!(
+ target
+ .fetch_owner
+ .pending_state()
+ .has_pending_fetch_request_id_for_test("FETCH-1")
+ );
}
#[test]
@@ -1207,11 +1209,8 @@ fn navigation_history_traversal_reuses_same_document_entries() {
}
#[test]
-fn target_parking_store_tracks_target_owner_state_independently() {
- let mut store = TargetParkingStateStore::default();
-
- store.replace_target_owner_state("TID-A".to_owned(), ParkedTargetOwnerState::default());
- assert!(store.target_owner_state("TID-A").is_none());
+fn background_target_keeps_owner_state_independent_from_network_artifacts() {
+ let mut target = PageTargetHost::with_url("TID-A".to_owned(), None, "about:blank".to_owned());
let mut owner_state = ParkedTargetOwnerState {
next_document_start_script_id: 9,
@@ -1231,10 +1230,15 @@ fn target_parking_store_tracks_target_owner_state_independently() {
owner_state
.console_output_state
.advance_console_domain_to_current(3, 1);
- store.replace_target_owner_state("TID-A".to_owned(), owner_state);
+ target.owner_state = owner_state;
- assert_eq!(store.network_artifacts("TID-A"), None);
- let restored = store.take_target_owner_state("TID-A");
+ assert!(
+ target
+ .runtime_slot
+ .collected_network_data_artifacts()
+ .is_empty()
+ );
+ let restored = std::mem::take(&mut target.owner_state);
assert_eq!(
restored
.runtime_observable_state
@@ -1261,7 +1265,7 @@ fn target_parking_store_tracks_target_owner_state_independently() {
);
assert_eq!(restored.next_document_start_script_id, 9);
assert_eq!(restored.isolated_worlds.len(), 1);
- assert!(store.take_target_owner_state("TID-A").is_default());
+ assert!(target.owner_state.is_default());
}
#[test]
@@ -1271,6 +1275,7 @@ fn committed_document_navigation_state_clears_document_local_runtime_state() {
"1".to_owned(),
DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.fromPreload = true;".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -1319,10 +1324,11 @@ fn devtools_session_runtime_context_clear_resets_child_default_emission_cursor()
}
#[test]
-fn target_parking_store_mutates_target_owner_state_with_default_elision() {
- let mut store = TargetParkingStateStore::default();
+fn background_target_mutates_owner_state_in_place() {
+ let mut target = PageTargetHost::with_url("TID-A".to_owned(), None, "about:blank".to_owned());
- let identifier = store.mutate_target_owner_state("TID-A", |owner_state| {
+ let identifier = {
+ let owner_state = &mut target.owner_state;
owner_state.next_document_start_script_id =
owner_state.next_document_start_script_id.wrapping_add(1);
let identifier = owner_state.next_document_start_script_id.to_string();
@@ -1330,6 +1336,7 @@ fn target_parking_store_mutates_target_owner_state_with_default_elision() {
identifier.clone(),
DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.fromPreload = true;".to_owned(),
world_name: Some("utility".to_owned()),
has_bidi_channel_argument: false,
@@ -1340,12 +1347,10 @@ fn target_parking_store_mutates_target_owner_state_with_default_elision() {
.console_output_state
.advance_console_domain_to_current(7, 3);
identifier
- });
+ };
assert_eq!(identifier, "1");
- let parked_state = store
- .target_owner_state("TID-A")
- .expect("non-default owner state should be parked");
+ let parked_state = &target.owner_state;
assert_eq!(parked_state.next_document_start_script_id, 1);
assert_eq!(parked_state.document_start_scripts.len(), 1);
assert!(
@@ -1354,15 +1359,16 @@ fn target_parking_store_mutates_target_owner_state_with_default_elision() {
.has_unemitted_console_domain(7, 3)
);
- store.mutate_target_owner_state("TID-A", |owner_state| {
+ {
+ let owner_state = &mut target.owner_state;
owner_state.next_document_start_script_id = 0;
owner_state.document_start_scripts.clear();
owner_state.clear_observable_output_state();
- });
+ }
assert!(
- store.target_owner_state("TID-A").is_none(),
- "mutating back to default must remove the parked owner-state entry"
+ target.owner_state.is_default(),
+ "resetting owner state must leave the host's embedded state at its default"
);
}
@@ -1620,7 +1626,9 @@ fn background_target_initial_empty_document_record_tracks_navigation_lifecycle()
);
assert_eq!(
- context.background_targets[0]
+ context
+ .background_target_at(0)
+ .unwrap()
.runtime_slot()
.moli_memory_diagnostics()["loadedPageAbsenceReason"],
json!("initial-document-page-build-pending"),
diff --git a/moli-protocol/src/conn/target/activation.rs b/moli-protocol/src/conn/target/activation.rs
index 5dae8c22b..5dd93d1b4 100644
--- a/moli-protocol/src/conn/target/activation.rs
+++ b/moli-protocol/src/conn/target/activation.rs
@@ -1,5 +1,3 @@
-use moli_core::runtime::NavigationEngine;
-
use crate::conn::{BackgroundProtocolEvent, BrowserContext, CdpConnection};
/// The stable Target identities on both sides of one foreground selection.
@@ -91,77 +89,6 @@ impl CdpConnection {
CompletedTargetActivation::new(protocol_events)
}
- pub(crate) fn handoff_navigation_engine_for_target_activation(&mut self, target_id: &str) {
- let Some(browser_context) = self.browser_context.as_ref() else {
- return;
- };
- let browser_context_id = browser_context.id.clone();
- let renderer_runtime = browser_context.renderer_runtime_owner_access();
- let navigation_runtime_config = self.engine.runtime_config();
- let promoted_key = (browser_context_id.clone(), target_id.to_owned());
- let promoted_engine = self
- .retained_background_navigation_engines
- .remove(&promoted_key);
-
- let active_target_id = browser_context.active_target_id().map(str::to_owned);
- let active_has_loaded_page = browser_context.has_loaded_page();
- if let Some(active_target_id) = active_target_id
- && active_has_loaded_page
- {
- let next_engine = promoted_engine.unwrap_or_else(|| {
- NavigationEngine::new_with_runtime_config_and_browser_context_access(
- navigation_runtime_config,
- renderer_runtime.clone(),
- )
- .expect("active BrowserContext owner must be live")
- });
- self.apply_scheduler_senders_to_navigation_engine(&next_engine);
- let active_engine = self
- .engine
- .replace(next_engine)
- .expect("active target must have a navigation engine");
- self.retain_background_navigation_engine(
- browser_context_id,
- active_target_id,
- active_engine,
- )
- .expect("demoted active engine must retain its exact BrowserContext owner");
- } else if let Some(promoted_engine) = promoted_engine {
- self.replace_navigation_engine(promoted_engine);
- }
- }
-
- pub(crate) fn handoff_navigation_engine_for_active_target_demotion(&mut self) {
- let Some(browser_context) = self.browser_context.as_ref() else {
- return;
- };
- let Some(active_target_id) = browser_context.active_target_id().map(str::to_owned) else {
- return;
- };
- if !browser_context.has_loaded_page() {
- return;
- }
-
- let browser_context_id = browser_context.id.clone();
- let renderer_runtime = browser_context.renderer_runtime_owner_access();
- let next_engine = NavigationEngine::new_with_runtime_config_and_browser_context_access(
- self.engine.runtime_config(),
- renderer_runtime,
- )
- .expect("active BrowserContext owner must be live");
- self.apply_scheduler_senders_to_navigation_engine(&next_engine);
- let active_engine = self
- .engine
- .replace(next_engine)
- .expect("active target must have a navigation engine");
- self.retain_background_navigation_engine(
- browser_context_id,
- active_target_id,
- active_engine,
- )
- .expect("demoted active engine must retain its exact BrowserContext owner");
- }
-
pub(crate) async fn promote_background_target_to_active_for_connection_async(
&mut self,
target_id: &str,
@@ -175,7 +102,6 @@ impl CdpConnection {
.demoted_target_id()
.map(|active_target_id| self.page_screencast_session_ids_for_target(active_target_id))
.unwrap_or_default();
- self.handoff_navigation_engine_for_target_activation(target_id);
let Some(browser_context) = self.browser_context.as_mut() else {
return Err("BrowserContextNotLoaded".to_owned());
};
diff --git a/moli-protocol/src/conn/target/route.rs b/moli-protocol/src/conn/target/route.rs
index 6b076d464..ddc5be74f 100644
--- a/moli-protocol/src/conn/target/route.rs
+++ b/moli-protocol/src/conn/target/route.rs
@@ -22,7 +22,7 @@ pub(crate) enum CdpSessionRoute {
browser_context_id: String,
target_id: String,
},
- BackgroundTarget {
+ PageTargetHost {
browser_context_id: String,
target_id: String,
},
@@ -53,7 +53,7 @@ impl CdpSessionRoute {
| Self::AuxiliaryTarget {
browser_context_id, ..
}
- | Self::BackgroundTarget {
+ | Self::PageTargetHost {
browser_context_id, ..
}
| Self::SharedWorkerTarget {
@@ -90,7 +90,7 @@ impl CdpSessionRoute {
Self::TabTarget { .. } => matches!(domain, "IO" | "Target" | "Tracing"),
Self::ActiveTarget { .. }
| Self::AuxiliaryTarget { .. }
- | Self::BackgroundTarget { .. }
+ | Self::PageTargetHost { .. }
| Self::SharedWorkerTarget { .. }
| Self::DedicatedWorkerTarget { .. }
| Self::ServiceWorkerTarget { .. } => true,
@@ -103,7 +103,7 @@ impl CdpSessionRoute {
Self::TabTarget { .. }
| Self::ActiveTarget { .. }
| Self::AuxiliaryTarget { .. }
- | Self::BackgroundTarget { .. } => TargetHandlerAccessMode::Regular,
+ | Self::PageTargetHost { .. } => TargetHandlerAccessMode::Regular,
Self::SharedWorkerTarget { .. }
| Self::DedicatedWorkerTarget { .. }
| Self::ServiceWorkerTarget { .. } => TargetHandlerAccessMode::AutoAttachOnly,
@@ -202,7 +202,7 @@ impl CdpConnection {
});
}
if browser_context.background_target(target_id).is_some() {
- return Some(CdpSessionRoute::BackgroundTarget {
+ return Some(CdpSessionRoute::PageTargetHost {
browser_context_id: browser_context.id.clone(),
target_id: target_id.to_owned(),
});
@@ -244,7 +244,7 @@ impl CdpConnection {
..
}
| CdpSessionRoute::AuxiliaryTarget { target_id, .. }
- | CdpSessionRoute::BackgroundTarget { target_id, .. }
+ | CdpSessionRoute::PageTargetHost { target_id, .. }
| CdpSessionRoute::SharedWorkerTarget { target_id, .. }
| CdpSessionRoute::DedicatedWorkerTarget { target_id, .. }
| CdpSessionRoute::ServiceWorkerTarget { target_id, .. }
@@ -277,30 +277,24 @@ impl CdpConnection {
frame_id: &str,
) -> Option<CdpSessionRoute> {
self.browser_contexts().find_map(|browser_context| {
- if browser_context
- .active_target
- .owner_state
- .has_attached_child_frame_id(frame_id)
- {
- return Some(CdpSessionRoute::ActiveTarget {
- browser_context_id: browser_context.id.clone(),
- target_id: None,
- });
- }
- browser_context
- .background_targets
- .iter()
- .find_map(|target| {
- browser_context
- .parked_target_owner_state(target.target_id())
- .is_some_and(|owner_state| {
- owner_state.has_attached_child_frame_id(frame_id)
- })
- .then(|| CdpSessionRoute::BackgroundTarget {
- browser_context_id: browser_context.id.clone(),
- target_id: target.target_id().to_owned(),
- })
- })
+ browser_context.page_targets.iter().find_map(|target| {
+ target
+ .owner_state
+ .has_attached_child_frame_id(frame_id)
+ .then(|| {
+ if browser_context.is_active_target(target.target_id()) {
+ CdpSessionRoute::ActiveTarget {
+ browser_context_id: browser_context.id.clone(),
+ target_id: None,
+ }
+ } else {
+ CdpSessionRoute::PageTargetHost {
+ browser_context_id: browser_context.id.clone(),
+ target_id: target.target_id().to_owned(),
+ }
+ }
+ })
+ })
})
}
@@ -328,7 +322,7 @@ impl CdpConnection {
session_id: Option<&str>,
) -> Option<(String, String)> {
match self.session_route(session_id)? {
- CdpSessionRoute::BackgroundTarget {
+ CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
} => Some((browser_context_id, target_id)),
@@ -368,10 +362,9 @@ fn browser_context_session_route(
}
browser_context
- .background_targets
- .iter()
+ .background_targets()
.find(|target| target.is_session(session_id))
- .map(|target| CdpSessionRoute::BackgroundTarget {
+ .map(|target| CdpSessionRoute::PageTargetHost {
browser_context_id: browser_context.id.clone(),
target_id: target.target_id().to_owned(),
})
diff --git a/moli-protocol/src/conn/target/session_binding.rs b/moli-protocol/src/conn/target/session_binding.rs
index 4863962c5..0fe5fc6c8 100644
--- a/moli-protocol/src/conn/target/session_binding.rs
+++ b/moli-protocol/src/conn/target/session_binding.rs
@@ -8,6 +8,34 @@ use super::{
};
impl CdpConnection {
+ pub(crate) async fn clear_target_session_overrides_async(
+ &mut self,
+ session_id: &str,
+ ) -> Result<(), String> {
+ let browser_identity_changed = match self.browser_context.as_mut() {
+ Some(browser_context) => {
+ browser_context
+ .clear_target_session_overrides_async(session_id)
+ .await?
+ }
+ None => false,
+ };
+ if !browser_identity_changed {
+ return Ok(());
+ }
+
+ let Some(pending) =
+ self.start_rebuild_resource_runtime_for_session_owner(Some(session_id))?
+ else {
+ return Ok(());
+ };
+ let completion = pending
+ .wait()
+ .await
+ .map_err(|error| format!("failed to restore detached session user agent: {error}"))?;
+ self.finish_rebuild_resource_runtime_for_session_owner(Some(session_id), completion)
+ }
+
pub(crate) fn is_browser_session_id(&self, session_id: Option<&str>) -> bool {
let Some(session_id) = session_id else {
return false;
@@ -659,6 +687,10 @@ impl CdpConnection {
&mut self,
cleanup_plan: &TargetBindingCleanupPlan,
) {
+ self.remove_document_start_scripts_for_detached_session_best_effort_async(
+ cleanup_plan.session_id(),
+ )
+ .await;
match cleanup_plan.action() {
TargetBindingCleanupAction::ActiveTargetPrimaryAutoAttached => {
if let Some(bc) = self.browser_context.as_mut() {
@@ -823,6 +855,8 @@ impl CdpConnection {
let target_id = cleanup_plan.target_id().to_owned();
let reason = cleanup_plan.reason().map(str::to_owned);
let parent_session_id = cleanup_plan.parent_session_id().map(str::to_owned);
+ self.remove_document_start_scripts_for_detached_session_best_effort_async(&session_id)
+ .await;
self.clear_active_target_session_binding_for_detach_async()
.await?;
Ok(self.detach_known_session_event_plan(
@@ -841,6 +875,8 @@ impl CdpConnection {
let target_id = cleanup_plan.target_id().to_owned();
let reason = cleanup_plan.reason().map(str::to_owned);
let parent_session_id = cleanup_plan.parent_session_id().map(str::to_owned);
+ self.remove_document_start_scripts_for_detached_session_best_effort_async(&session_id)
+ .await;
let Some(detached_target_id) = self
.clear_background_target_session_binding_for_detach_async(&session_id)
.await?
@@ -864,8 +900,7 @@ impl CdpConnection {
self.browser_context
.as_ref()
.map(|bc| {
- bc.background_targets
- .iter()
+ bc.background_targets()
.filter_map(|target| {
Some(TargetSessionDetachCleanupPlan::new(
target.target_id().to_owned(),
diff --git a/moli-protocol/src/conn/target/transaction.rs b/moli-protocol/src/conn/target/transaction.rs
index b3a02d31b..35ff79846 100644
--- a/moli-protocol/src/conn/target/transaction.rs
+++ b/moli-protocol/src/conn/target/transaction.rs
@@ -331,7 +331,7 @@ impl TargetBindingCleanupAction {
fn from_route(route: &CdpSessionRoute) -> Self {
match route {
CdpSessionRoute::ActiveTarget { .. } => Self::ActiveTargetPrimaryAutoAttached,
- CdpSessionRoute::BackgroundTarget { target_id, .. } => {
+ CdpSessionRoute::PageTargetHost { target_id, .. } => {
Self::BackgroundTargetPrimaryAutoAttached {
target_id: target_id.clone(),
}
@@ -572,7 +572,7 @@ mod tests {
assert_eq!(
TargetBindingCleanupPlan::from_route(
"SID-bg",
- &CdpSessionRoute::BackgroundTarget {
+ &CdpSessionRoute::PageTargetHost {
browser_context_id: "BID-1".to_owned(),
target_id: "TID-bg".to_owned(),
},
diff --git a/moli-protocol/src/conn/tests/mod.rs b/moli-protocol/src/conn/tests/mod.rs
index f1ab53bf1..b6037b037 100644
--- a/moli-protocol/src/conn/tests/mod.rs
+++ b/moli-protocol/src/conn/tests/mod.rs
@@ -55,13 +55,13 @@ fn published_default_target_defers_navigation_runtime_until_materialization() {
NavigationRuntimeConfig::default(),
);
- assert!(!conn.engine.is_materialized());
+ assert!(!conn.standalone_navigation_engine.is_materialized());
let (renderer_publication_sender, _renderer_publication_receiver) =
moli_core::renderer_output_transport_channel();
conn.set_renderer_publication_sender(renderer_publication_sender);
conn.publish_default_browser_target();
- assert!(!conn.engine.is_materialized());
+ assert!(!conn.standalone_navigation_engine.is_materialized());
let page = conn
.devtools_target_info(conn.default_target_id())
.expect("published default page target");
@@ -73,7 +73,17 @@ fn published_default_target_defers_navigation_runtime_until_materialization() {
conn.install_default_browser_target();
- assert!(conn.engine.is_materialized());
+ assert!(
+ !conn.standalone_navigation_engine.is_materialized(),
+ "materializing the default Page must not allocate the fallback engine"
+ );
+ assert!(
+ conn.browser_context
+ .as_ref()
+ .and_then(|context| context.page_navigation_engine(conn.default_target_id()))
+ .is_some(),
+ "materializing the default target must install its Page-owned engine"
+ );
assert!(
conn.devtools_target_info(conn.default_target_id())
.is_some()
@@ -109,7 +119,7 @@ async fn activating_the_only_default_placeholder_does_not_start_the_runtime() {
let messages = conn.process_message_messages_only_for_test(&raw).await;
assert_eq!(messages, vec![json!({ "id": 1, "result": {} })]);
- assert!(!conn.engine.is_materialized());
+ assert!(!conn.standalone_navigation_engine.is_materialized());
assert!(conn.devtools_target_info(target_id).is_some());
}
@@ -129,7 +139,7 @@ async fn closing_the_default_placeholder_does_not_start_the_runtime() {
messages.first(),
Some(&json!({ "id": 2, "result": { "success": true } }))
);
- assert!(!conn.engine.is_materialized());
+ assert!(!conn.standalone_navigation_engine.is_materialized());
assert!(
conn.devtools_target_info(conn.default_target_id())
.is_none()
@@ -158,7 +168,17 @@ async fn creating_a_target_preserves_the_published_default_as_a_placeholder() {
.expect("createTarget response");
assert_ne!(created_target_id, conn.default_target_id());
- assert!(conn.engine.is_materialized());
+ assert!(
+ conn.standalone_navigation_engine.is_materialized(),
+ "creating a real Page target is the first operation that needs the renderer runtime"
+ );
+ assert!(
+ conn.browser_context
+ .as_ref()
+ .and_then(|context| context.page_navigation_engine(created_target_id))
+ .is_some(),
+ "the created Page must own the materialized navigation engine"
+ );
assert!(conn.default_target_lifecycle.is_placeholder());
assert!(
conn.devtools_target_info(conn.default_target_id())
@@ -211,11 +231,17 @@ fn idle_navigation_engine_reset_preserves_mock_layout_policy() {
),
);
- assert_eq!(conn.engine.layout_policy(), LayoutPolicy::Mock);
+ assert_eq!(
+ conn.standalone_navigation_engine.layout_policy(),
+ LayoutPolicy::Mock
+ );
let reset = conn.release_idle_navigation_engine_memory_if_idle();
assert!(reset.reset);
- assert_eq!(conn.engine.layout_policy(), LayoutPolicy::Mock);
+ assert_eq!(
+ conn.standalone_navigation_engine.layout_policy(),
+ LayoutPolicy::Mock
+ );
}
#[tokio::test]
@@ -231,13 +257,19 @@ async fn browser_context_install_and_removal_preserve_mock_layout_policy() {
);
conn.insert_browser_context(BrowserContext::new("CTX-layout".to_owned()));
- assert_eq!(conn.engine.layout_policy(), LayoutPolicy::Mock);
+ assert_eq!(
+ conn.standalone_navigation_engine.layout_policy(),
+ LayoutPolicy::Mock
+ );
let removed = conn
.remove_browser_context_by_id_restoring_active_async("CTX-layout", None)
.await;
assert!(removed.is_some());
- assert_eq!(conn.engine.layout_policy(), LayoutPolicy::Mock);
+ assert_eq!(
+ conn.standalone_navigation_engine.layout_policy(),
+ LayoutPolicy::Mock
+ );
}
#[test]
@@ -461,7 +493,7 @@ fn none_session_owner_route_override_scope_restores_previous_route_on_drop() {
browser_context_id: "BID-active".to_owned(),
target_id: Some("TID-active".to_owned()),
};
- let scoped_route = CdpSessionRoute::BackgroundTarget {
+ let scoped_route = CdpSessionRoute::PageTargetHost {
browser_context_id: "BID-background".to_owned(),
target_id: "TID-background".to_owned(),
};
@@ -508,14 +540,14 @@ fn navigation_background_event_queue_drains_current_token() {
#[test]
fn active_browser_context_installs_its_renderer_runtime_on_engine() {
let mut conn = CdpConnection::new();
- let browser_context = conn.new_browser_context("CTX-runtime".to_owned());
+ let mut browser_context = conn.new_browser_context("CTX-runtime".to_owned());
+ browser_context.set_active_target_id("TID-runtime");
let renderer_runtime = browser_context.renderer_runtime();
conn.insert_browser_context(browser_context);
assert!(
- conn.engine
- .ensure()
+ conn.active_navigation_engine()
.browser_context_runtime()
.shares_state_with(&renderer_runtime)
);
@@ -524,30 +556,97 @@ fn active_browser_context_installs_its_renderer_runtime_on_engine() {
#[test]
fn activating_inactive_browser_context_switches_engine_renderer_runtime() {
let mut conn = CdpConnection::new();
- let first = conn.new_browser_context("CTX-first".to_owned());
+ let mut first = conn.new_browser_context("CTX-first".to_owned());
+ first.set_active_target_id("TID-first");
conn.insert_browser_context(first);
- let second = conn.new_browser_context("CTX-second".to_owned());
+ let mut second = conn.new_browser_context("CTX-second".to_owned());
+ second.set_active_target_id("TID-second");
let second_renderer_runtime = second.renderer_runtime();
- conn.inactive_browser_contexts.push(second);
+ conn.insert_browser_context(second);
assert!(conn.activate_browser_context_by_id("CTX-second"));
assert!(
- conn.engine
- .ensure()
+ conn.active_navigation_engine()
.browser_context_runtime()
.shares_state_with(&second_renderer_runtime)
);
}
+#[test]
+fn activating_another_browser_context_retains_pending_initial_document_engine() {
+ let mut conn = CdpConnection::new();
+ let mut first = conn.new_browser_context("CTX-pending-first".to_owned());
+ first.set_active_target_id("TID-pending-first");
+ first.begin_active_target_initial_empty_document("about:blank".to_owned());
+ conn.insert_browser_context(first);
+ let pending_renderer_owner = conn
+ .active_navigation_engine()
+ .renderer_owner_id_for_diagnostics();
+
+ let mut second = conn.new_browser_context("CTX-pending-second".to_owned());
+ second.set_active_target_id("TID-pending-second");
+ conn.insert_browser_context(second);
+
+ assert!(conn.activate_browser_context_by_id("CTX-pending-second"));
+
+ let retained = conn
+ .browser_context_by_id("CTX-pending-first")
+ .and_then(|context| context.page_navigation_engine("TID-pending-first"))
+ .expect("a pending initial document must keep its renderer engine alive");
+ assert_eq!(
+ retained.renderer_owner_id_for_diagnostics(),
+ pending_renderer_owner,
+ "context switching must retain the exact engine that owns the pending renderer page"
+ );
+}
+
+#[test]
+fn activating_another_target_retains_pending_initial_document_engine() {
+ let mut conn = CdpConnection::new();
+ let mut browser_context = conn.new_browser_context("CTX-pending-target".to_owned());
+ browser_context.set_active_target_id("TID-pending-active");
+ browser_context.begin_active_target_initial_empty_document("about:blank".to_owned());
+ conn.insert_browser_context(browser_context);
+ let pending_renderer_owner = conn
+ .active_navigation_engine()
+ .renderer_owner_id_for_diagnostics();
+ conn.browser_context
+ .as_mut()
+ .expect("browser context")
+ .stage_background_target(
+ "TID-promoted".to_owned(),
+ None,
+ "about:blank".to_owned(),
+ Some("about:blank".to_owned()),
+ None,
+ );
+ conn.browser_context
+ .as_mut()
+ .expect("browser context")
+ .set_active_target_id("TID-promoted");
+
+ let retained = conn
+ .browser_context_by_id("CTX-pending-target")
+ .and_then(|context| context.page_navigation_engine("TID-pending-active"))
+ .expect("a pending initial document must survive target activation");
+ assert_eq!(
+ retained.renderer_owner_id_for_diagnostics(),
+ pending_renderer_owner,
+ "target switching must retain the exact engine that owns the pending renderer page"
+ );
+}
+
#[tokio::test]
async fn removing_active_browser_context_switches_engine_to_promoted_context() {
let mut conn = CdpConnection::new();
- let first = conn.new_browser_context("CTX-first".to_owned());
+ let mut first = conn.new_browser_context("CTX-first".to_owned());
+ first.set_active_target_id("TID-first");
conn.insert_browser_context(first);
- let second = conn.new_browser_context("CTX-second".to_owned());
+ let mut second = conn.new_browser_context("CTX-second".to_owned());
+ second.set_active_target_id("TID-second");
let second_renderer_runtime = second.renderer_runtime();
- conn.inactive_browser_contexts.push(second);
+ conn.insert_browser_context(second);
let removed = conn
.remove_browser_context_by_id_restoring_active_async("CTX-first", Some("CTX-first"))
@@ -560,8 +659,7 @@ async fn removing_active_browser_context_switches_engine_to_promoted_context() {
Some("CTX-second")
);
assert!(
- conn.engine
- .ensure()
+ conn.active_navigation_engine()
.browser_context_runtime()
.shares_state_with(&second_renderer_runtime)
);
@@ -570,28 +668,41 @@ async fn removing_active_browser_context_switches_engine_to_promoted_context() {
#[tokio::test]
async fn memory_diagnostics_reports_page_vm_document_isolate_model() {
let mut conn = CdpConnection::new();
- conn.replace_navigation_engine(
+ conn.replace_standalone_navigation_engine(
NavigationEngine::new_with_page_vm_document_isolate_for_diagnostics(),
);
- conn.browser_context = Some(BrowserContext::new("BID-shared-diagnostics".to_owned()));
+ let mut browser_context = conn.new_browser_context("BID-shared-diagnostics".to_owned());
+ browser_context.set_active_target_id("TID-shared-diagnostics-active");
+ browser_context.stage_background_target(
+ "TID-shared-diagnostics-bg".to_owned(),
+ Some("SID-shared-diagnostics-bg".to_owned()),
+ "data:text/html,<!doctype html><body>second</body>".to_owned(),
+ Some("about:blank".to_owned()),
+ None,
+ );
+ conn.insert_browser_context(browser_context);
let first_page = conn
.load_page_via_runtime_async("data:text/html,<!doctype html><body>first</body>")
.await
.expect("first shared diagnostics page should load");
+ conn.browser_context
+ .as_mut()
+ .expect("browser context")
+ .set_active_target_id("TID-shared-diagnostics-bg");
let second_page = conn
.load_page_via_runtime_async("data:text/html,<!doctype html><body>second</body>")
.await
.expect("second shared diagnostics page should load");
let browser_context = conn.browser_context.as_mut().expect("browser context");
- browser_context.replace_loaded_page(Some(first_page));
- let mut background = super::BackgroundTarget::with_url(
- "TID-shared-diagnostics-bg".to_owned(),
- Some("SID-shared-diagnostics-bg".to_owned()),
- "data:text/html,<!doctype html><body>second</body>".to_owned(),
- );
- background.replace_loaded_page(Some(second_page));
- browser_context.background_targets.push(background);
+ browser_context
+ .page_target_mut("TID-shared-diagnostics-active")
+ .expect("active diagnostics target")
+ .replace_loaded_page(Some(first_page));
+ browser_context
+ .page_target_mut("TID-shared-diagnostics-bg")
+ .expect("background diagnostics target")
+ .replace_loaded_page(Some(second_page));
let pending_diagnostics = conn
.start_moli_diagnostics()
@@ -787,50 +898,51 @@ async fn moli_diagnostics_preserves_runtime_observable_diagnostics() {
}
#[tokio::test]
-async fn memory_diagnostics_ignores_empty_retained_renderer_owner_for_document_isolates() {
+async fn memory_diagnostics_excludes_empty_page_hosts_from_document_isolates() {
let mut conn = CdpConnection::new();
- conn.replace_navigation_engine(
- NavigationEngine::new_with_page_vm_document_isolate_for_diagnostics(),
+ let mut browser_context = conn.new_browser_context("BID-doc-owner-diagnostics".to_owned());
+ browser_context.set_active_target_id("TID-doc-owner-diagnostics-active");
+ browser_context.stage_background_target(
+ "TID-doc-owner-diagnostics-bg".to_owned(),
+ Some("SID-doc-owner-diagnostics-bg".to_owned()),
+ "data:text/html,<!doctype html><body>second</body>".to_owned(),
+ Some("about:blank".to_owned()),
+ None,
);
-
- conn.browser_context = Some(BrowserContext::new("BID-doc-owner-diagnostics".to_owned()));
+ conn.insert_browser_context(browser_context);
let first_page = conn
.load_page_via_runtime_async("data:text/html,<!doctype html><body>first</body>")
.await
.expect("first shared diagnostics page should load");
+ conn.browser_context
+ .as_mut()
+ .expect("browser context")
+ .set_active_target_id("TID-doc-owner-diagnostics-bg");
let second_page = conn
.load_page_via_runtime_async("data:text/html,<!doctype html><body>second</body>")
.await
.expect("second shared diagnostics page should load");
let browser_context = conn.browser_context.as_mut().expect("browser context");
- browser_context.replace_loaded_page(Some(first_page));
- let mut background = super::BackgroundTarget::with_url(
- "TID-doc-owner-diagnostics-bg".to_owned(),
- Some("SID-doc-owner-diagnostics-bg".to_owned()),
- "data:text/html,<!doctype html><body>second</body>".to_owned(),
- );
- background.replace_loaded_page(Some(second_page));
- browser_context.background_targets.push(background);
+ browser_context
+ .page_target_mut("TID-doc-owner-diagnostics-active")
+ .expect("active diagnostics target")
+ .replace_loaded_page(Some(first_page));
+ browser_context
+ .page_target_mut("TID-doc-owner-diagnostics-bg")
+ .expect("background diagnostics target")
+ .replace_loaded_page(Some(second_page));
- let retained_context = BrowserContext::new("BID-empty-retained".to_owned());
- let retained = NavigationEngine::new_with_fetch_config_and_browser_context_access(
- FetchConfig::default(),
- retained_context.renderer_runtime_owner_access(),
- conn.engine.ensure().optional_resource_fetch_mask(),
- conn.engine.ensure().subframe_loading_enabled(),
- )
- .expect("retained diagnostics context owner should be live");
+ let mut empty_context = BrowserContext::new("BID-empty-page".to_owned());
+ empty_context.set_active_target_id("TID-empty-page");
+ conn.insert_browser_context(empty_context);
+ let empty_page_engine = conn
+ .browser_context_by_id("BID-empty-page")
+ .and_then(|context| context.page_navigation_engine("TID-empty-page"))
+ .expect("empty PageTargetHost must own its navigation engine");
assert!(
- !retained.shares_renderer_owner_with(conn.engine.ensure()),
- "test setup must retain a distinct renderer owner without a loaded document"
- );
- conn.inactive_browser_contexts.push(retained_context);
- conn.retain_background_navigation_engine(
- "BID-empty-retained".to_owned(),
- "TID-empty-retained".to_owned(),
- retained,
- )
- .expect("diagnostics engine must match its retained BrowserContext");
+ !empty_page_engine.shares_renderer_owner_with(conn.standalone_navigation_engine.ensure()),
+ "test setup must keep a distinct renderer owner without a loaded document"
+ );
let diagnostics = conn.moli_memory_diagnostics();
@@ -839,13 +951,13 @@ async fn memory_diagnostics_ignores_empty_retained_renderer_owner_for_document_i
json!(2)
);
assert_eq!(
- diagnostics["isolateScope"]["retainedBackgroundNavigationEngineRendererOwnerCount"],
+ diagnostics["isolateScope"]["pageNavigationEngineRendererOwnerCount"],
json!(1)
);
assert_eq!(
diagnostics["isolateScope"]["estimatedRendererOwnerCount"],
json!(2),
- "the empty retained engine still contributes renderer owner fixed cost"
+ "the empty Page host still contributes renderer owner fixed cost"
);
assert_eq!(
diagnostics["isolateScope"]["loadedDocumentRendererOwnerCount"],
@@ -860,7 +972,7 @@ async fn memory_diagnostics_ignores_empty_retained_renderer_owner_for_document_i
assert_eq!(
diagnostics["isolateScope"]["estimatedLiveV8IsolateCount"],
json!(2),
- "empty retained renderer owners contribute fixed owner cost but no extra live V8 isolate"
+ "empty Page hosts contribute fixed owner cost but no extra live V8 isolate"
);
}
@@ -950,7 +1062,7 @@ async fn memory_diagnostics_counts_different_browser_context_document_isolates_s
let mut second_context = conn.new_browser_context("BID-doc-owner-second".to_owned());
second_context.set_active_target_id("TID-doc-owner-second");
- conn.inactive_browser_contexts.push(second_context);
+ conn.insert_browser_context(second_context);
assert!(conn.activate_browser_context_by_id("BID-doc-owner-second"));
let second_page = conn
@@ -977,7 +1089,7 @@ async fn memory_diagnostics_counts_different_browser_context_document_isolates_s
json!(2)
);
assert_eq!(
- diagnostics["isolateScope"]["retainedBackgroundNavigationEngineRendererOwnerCount"],
+ diagnostics["isolateScope"]["pageNavigationEngineRendererOwnerCount"],
json!(1),
"switching browser contexts should retain the first loaded target's renderer owner fixed cost"
);
@@ -1004,48 +1116,41 @@ async fn memory_diagnostics_counts_different_browser_context_document_isolates_s
}
#[test]
-fn memory_diagnostics_counts_shared_retained_background_engine_by_renderer_owner() {
+fn memory_diagnostics_counts_page_engines_by_renderer_owner() {
let mut conn = CdpConnection::new();
- let browser_context = BrowserContext::new("BID-shared-diagnostics".to_owned());
- let active = NavigationEngine::new_with_fetch_config_and_browser_context_access(
- FetchConfig::default(),
- browser_context.renderer_runtime_owner_access(),
- conn.engine.ensure().optional_resource_fetch_mask(),
- conn.engine.ensure().subframe_loading_enabled(),
- )
- .expect("active diagnostics context owner should be live");
- conn.replace_navigation_engine(active);
- conn.browser_context = Some(browser_context);
+ let mut browser_context = BrowserContext::new("BID-shared-diagnostics".to_owned());
+ browser_context.set_active_target_id("TID-shared-diagnostics-active");
+ browser_context.stage_background_target(
+ "TID-shared-diagnostics-bg".to_owned(),
+ None,
+ "about:blank".to_owned(),
+ Some("about:blank".to_owned()),
+ None,
+ );
+ conn.insert_browser_context(browser_context);
- let retained = NavigationEngine::new_with_fetch_config_and_shared_renderer_owner(
- FetchConfig::default(),
- conn.engine.ensure(),
- conn.engine.ensure().optional_resource_fetch_mask(),
- conn.engine.ensure().subframe_loading_enabled(),
- )
- .expect("retained diagnostics wrapper should share a live context owner");
+ let active = conn.active_navigation_engine();
+ let background = conn
+ .browser_context
+ .as_ref()
+ .and_then(|context| context.page_navigation_engine("TID-shared-diagnostics-bg"))
+ .expect("background PageTargetHost must own an engine");
assert!(
- retained.shares_renderer_owner_with(conn.engine.ensure()),
- "test setup must retain a NavigationEngine wrapper that shares the active renderer owner"
+ background.shares_renderer_owner_with(active),
+ "same-context PageTargetHost engines must share one renderer owner"
);
- conn.retain_background_navigation_engine(
- "BID-shared-diagnostics".to_owned(),
- "TID-shared-diagnostics-bg".to_owned(),
- retained,
- )
- .expect("diagnostics wrapper must match its retained BrowserContext");
let diagnostics = conn.moli_memory_diagnostics();
assert_eq!(
- diagnostics["connection"]["retainedBackgroundNavigationEngineCount"],
- json!(1),
- "the CDP connection still retains a background NavigationEngine wrapper"
+ diagnostics["connection"]["pageNavigationEngineCount"],
+ json!(2),
+ "each PageTargetHost must expose one resident NavigationEngine"
);
assert_eq!(
- diagnostics["isolateScope"]["retainedBackgroundNavigationEngineRendererOwnerCount"],
+ diagnostics["isolateScope"]["pageNavigationEngineRendererOwnerCount"],
json!(0),
- "a retained background NavigationEngine that shares the active renderer owner must not count as another renderer owner"
+ "same-context Page engines must not count as another renderer owner"
);
assert_eq!(
diagnostics["isolateScope"]["estimatedRendererOwnerCount"],
@@ -1054,28 +1159,95 @@ fn memory_diagnostics_counts_shared_retained_background_engine_by_renderer_owner
}
#[test]
-fn retained_background_engine_rejects_a_foreign_browser_context_route() {
+fn page_navigation_engines_remain_target_local_across_selection() {
+ let mut conn = CdpConnection::new();
+ let mut browser_context = conn.new_browser_context("BID-engine-residence".to_owned());
+ browser_context.set_active_target_id("TID-engine-first");
+ browser_context.stage_background_target(
+ "TID-engine-second".to_owned(),
+ None,
+ "about:blank".to_owned(),
+ Some("about:blank".to_owned()),
+ None,
+ );
+ conn.insert_browser_context(browser_context);
+
+ conn.active_navigation_engine_mut()
+ .set_user_agent_override("Moli/Page-First");
+
+ conn.browser_context
+ .as_mut()
+ .expect("browser context")
+ .set_active_target_id("TID-engine-second");
+ assert_ne!(
+ conn.active_navigation_engine()
+ .fetch_config()
+ .browser_identity()
+ .user_agent(),
+ "Moli/Page-First",
+ "selecting another Page must expose that host's own engine"
+ );
+ conn.active_navigation_engine_mut()
+ .set_user_agent_override("Moli/Page-Second");
+
+ conn.browser_context
+ .as_mut()
+ .expect("browser context")
+ .set_active_target_id("TID-engine-first");
+ assert_eq!(
+ conn.active_navigation_engine()
+ .fetch_config()
+ .browser_identity()
+ .user_agent(),
+ "Moli/Page-First",
+ "selection must not replace or move a PageTargetHost engine"
+ );
+ assert_eq!(
+ conn.browser_context
+ .as_ref()
+ .and_then(|context| context.page_navigation_engine("TID-engine-second"))
+ .expect("second Page engine")
+ .fetch_config()
+ .browser_identity()
+ .user_agent(),
+ "Moli/Page-Second",
+ "the unselected Page must retain its engine state in place"
+ );
+}
+
+#[test]
+fn page_target_host_rejects_a_foreign_browser_context_engine() {
let mut conn = CdpConnection::new();
- conn.browser_context = Some(BrowserContext::new("BID-retain-route".to_owned()));
+ let mut context = BrowserContext::new("BID-retain-route".to_owned());
+ context.set_active_target_id("TID-retain-route");
+ conn.insert_browser_context(context);
+ let original_owner = conn
+ .active_navigation_engine()
+ .renderer_owner_id_for_diagnostics();
let foreign_context = BrowserContext::new("BID-retain-route-foreign".to_owned());
let foreign_engine = NavigationEngine::new_with_fetch_config_and_browser_context_access(
FetchConfig::default(),
foreign_context.renderer_runtime_owner_access(),
- conn.engine.ensure().optional_resource_fetch_mask(),
- conn.engine.ensure().subframe_loading_enabled(),
+ conn.standalone_navigation_engine
+ .ensure()
+ .optional_resource_fetch_mask(),
+ conn.standalone_navigation_engine
+ .ensure()
+ .subframe_loading_enabled(),
)
.expect("foreign context owner should be live during the regression");
let error = conn
- .retain_background_navigation_engine(
- "BID-retain-route".to_owned(),
- "TID-retain-route".to_owned(),
- foreign_engine,
- )
- .expect_err("a retained route must reject an engine from another BrowserContext");
+ .install_page_navigation_engine("BID-retain-route", "TID-retain-route", foreign_engine)
+ .expect_err("a PageTargetHost must reject an engine from another BrowserContext");
assert!(error.contains("does not match BrowserContext `BID-retain-route`"));
- assert!(conn.retained_background_navigation_engines.is_empty());
+ assert_eq!(
+ conn.active_navigation_engine()
+ .renderer_owner_id_for_diagnostics(),
+ original_owner,
+ "rejecting a foreign engine must preserve the host's resident engine"
+ );
}
#[tokio::test]
@@ -1098,32 +1270,24 @@ async fn memory_diagnostics_splits_pending_inspector_await_counts_by_target_owne
browser_context.set_active_target_id("TID-pending-await-active");
browser_context.attach_active_session("SID-pending-await-active");
browser_context.replace_loaded_page(Some(active_page));
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.register_pending_inspector_await(10_001, Some("SID-pending-await-active"), None);
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.register_pending_inspector_await(
10_002,
Some("SID-pending-await-active"),
Some("active-group"),
);
- let mut background = super::BackgroundTarget::with_url(
+ let mut background = super::PageTargetHost::with_url(
"TID-pending-await-bg".to_owned(),
Some("SID-pending-await-bg".to_owned()),
"data:text/html,<!doctype html><body>background</body>".to_owned(),
);
background.replace_loaded_page(Some(background_page));
- let mut background_page_session_state = super::ParkedPageSessionState::default();
- background_page_session_state
- .devtools_session_state
+ background.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.register_pending_inspector_await(20_001, Some("SID-pending-await-bg"), None);
- browser_context.target_parking.replace_page_session_state(
- "TID-pending-await-bg".to_owned(),
- background_page_session_state,
- );
- browser_context.background_targets.push(background);
+ browser_context.insert_page_target_host(background);
let shared_worker_instance_id = SharedWorkerInstanceId::from_u64(30_001);
let mut shared_worker_target = SharedWorkerTargetState::new(
@@ -1225,7 +1389,7 @@ async fn memory_diagnostics_splits_pending_inspector_await_counts_by_target_owne
json!(2)
);
assert_eq!(
- diagnostics["activeBrowserContext"]["targetParking"]["pendingInspectorAwaitCount"],
+ diagnostics["activeBrowserContext"]["targetHosts"]["pendingInspectorAwaitCount"],
json!(1)
);
}
diff --git a/moli-protocol/src/conn/tests/resource_runtime.rs b/moli-protocol/src/conn/tests/resource_runtime.rs
index 3ddf620df..8f968cf22 100644
--- a/moli-protocol/src/conn/tests/resource_runtime.rs
+++ b/moli-protocol/src/conn/tests/resource_runtime.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::DevToolsDocumentLifecycleWaitState;
use crate::conn::{
- BackgroundTarget, CdpInitialStoragePartition, LoadedNavigation, NavigationLoadOutcome,
+ CdpInitialStoragePartition, LoadedNavigation, NavigationLoadOutcome, PageTargetHost,
TargetIdentityState, TargetPageSlot,
};
use moli_core::runtime::storage_partition::StoragePartitionState;
@@ -36,12 +36,20 @@ fn stored_cookie(name: &str, value: &str) -> moli_cookie_jar::StoredCookie {
async fn commit_navigation_outcome_for_test(
conn: &mut CdpConnection,
outcome: NavigationLoadOutcome,
+) -> LoadedNavigation {
+ commit_navigation_outcome_for_session_test(conn, outcome, None).await
+}
+
+async fn commit_navigation_outcome_for_session_test(
+ conn: &mut CdpConnection,
+ outcome: NavigationLoadOutcome,
+ session_id: Option<&str>,
) -> LoadedNavigation {
match outcome {
NavigationLoadOutcome::ResponseCommitReady(navigation) => {
let navigation = *navigation;
let configuration = conn.prepared_document_commit_configuration_for_session_owner(
- None,
+ session_id,
navigation.final_url(),
);
navigation
@@ -64,6 +72,80 @@ async fn commit_navigation_outcome_for_test(
}
}
+#[tokio::test]
+async fn buffered_navigation_for_inactive_session_carries_its_target_engine() {
+ let mut conn = CdpConnection::new();
+ let ambient_context = conn.new_browser_context("BID-ambient".to_owned());
+ conn.insert_browser_context(ambient_context);
+ let ambient_renderer_owner = conn
+ .standalone_navigation_engine
+ .ensure()
+ .renderer_owner_id_for_diagnostics();
+
+ let mut target_context = conn.new_browser_context("BID-target".to_owned());
+ target_context.set_active_target_id("TID-target");
+ target_context.attach_active_session("SID-target");
+ target_context.begin_active_target_initial_empty_document("about:blank".to_owned());
+ target_context
+ .start_document_navigation_for_active_target("LOADER-target".to_owned())
+ .expect("target should accept its synthetic navigation");
+ conn.inactive_browser_contexts.push(target_context);
+
+ let requested_url = Url::parse("https://target.example/fulfilled").unwrap();
+ let navigation = NavigationDispatchState {
+ navigate_id: Some(1),
+ navigate_session_id: Some("SID-target".to_owned()),
+ result_projection: NavigationResultProjection::Cdp(json!({
+ "frameId": "TID-target",
+ "loaderId": "LOADER-target",
+ })),
+ frame_id: "TID-target".to_owned(),
+ session_id: Some("SID-target".to_owned()),
+ request_id: Some("LOADER-target".to_owned()),
+ loader_id: "LOADER-target".to_owned(),
+ request_announced: true,
+ requested_url: requested_url.clone(),
+ request_method: "GET".to_owned(),
+ request_body: None,
+ request_body_bytes: None,
+ request_headers: Vec::new(),
+ request_load_policy: crate::conn::NavigationRequestLoadPolicy::DocumentInitiated,
+ timestamp: 0.0,
+ source_document_security: Default::default(),
+ };
+
+ let outcome = conn
+ .build_navigation_from_buffered_body_source_for_navigation_async(
+ &navigation,
+ requested_url,
+ 200,
+ vec![("content-type".to_owned(), "text/html".to_owned())],
+ crate::conn::CapturedBody::from_string("<main>target</main>".to_owned()),
+ None,
+ moli_fetch::NetworkObservationJournal::default(),
+ crate::domains::network::MainDocumentBodyProgressSource::default(),
+ )
+ .await
+ .expect("buffered target navigation should prepare");
+ let loaded =
+ commit_navigation_outcome_for_session_test(&mut conn, outcome, Some("SID-target")).await;
+ let target_engine = loaded
+ .navigation_engine
+ .as_ref()
+ .expect("target-scoped buffered navigation must carry its engine to commit");
+ let target_renderer_owner = target_engine.renderer_owner_id_for_diagnostics();
+
+ assert_eq!(
+ loaded.page.renderer_owner_local_host_id().as_u64(),
+ target_renderer_owner,
+ "the loaded Page and the engine handed to its target must share one renderer owner"
+ );
+ assert_ne!(
+ target_renderer_owner, ambient_renderer_owner,
+ "a browser-level Fetch action must not build an inactive target on the ambient context engine"
+ );
+}
+
#[test]
fn current_navigation_initiator_url_uses_loaded_browser_context_url_when_available() {
let mut conn = CdpConnection::new();
@@ -140,8 +222,10 @@ fn default_browser_contexts_reuse_partition_with_distinct_target_session_storage
CdpInitialStoragePartition::from_storage_partition(Vec::new(), &storage_partition);
let conn = CdpConnection::new_with_initial_storage_partition(initial_storage_partition);
- let first = conn.new_browser_context("BID-first".to_owned());
- let second = conn.new_browser_context("BID-second".to_owned());
+ let mut first = conn.new_browser_context("BID-first".to_owned());
+ first.set_active_target_id("TID-first");
+ let mut second = conn.new_browser_context("BID-second".to_owned());
+ second.set_active_target_id("TID-second");
let expected_web_storage_store = storage_partition
.shared_storage_handles()
.web_storage_store();
@@ -1335,8 +1419,7 @@ async fn direct_runtime_evaluate_routes_to_inactive_active_owner_without_promoti
let mut inactive = BrowserContext::new("BID-B".into());
inactive.set_active_target_id("TID-B".to_owned());
inactive.attach_active_session("SID-B");
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.inactive_browser_contexts.push(inactive);
@@ -1378,13 +1461,13 @@ async fn direct_runtime_evaluate_document_replacement_lifecycle_uses_inactive_ow
let mut inactive = BrowserContext::new("BID-document-replacement".into());
inactive.set_active_target_id("TID-document-replacement".to_owned());
inactive.attach_active_session("SID-document-replacement");
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- inactive.devtools_session_state.dom_session_state.enabled = true;
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .dom_session_state
+ .enabled = true;
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
ctx.conn.inactive_browser_contexts.push(inactive);
@@ -1629,8 +1712,7 @@ async fn direct_runtime_evaluate_same_document_navigation_updates_inactive_owner
let mut inactive = BrowserContext::new("BID-same-document".into());
inactive.set_active_target_id("TID-same-document".to_owned());
inactive.attach_active_session("SID-same-document");
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
inactive.set_target_url(initial_url.clone());
@@ -1698,17 +1780,16 @@ async fn direct_runtime_evaluate_same_document_navigation_updates_inactive_owner
async fn direct_runtime_evaluate_javascript_dialog_uses_inactive_background_owner() {
let mut ctx = crate::testing::TestContext::new();
let page_url = "data:text/html,<!doctype html><title>dialog-owner</title>".to_owned();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-dialog-background".to_owned(),
Some("SID-dialog-background".to_owned()),
page_url.clone(),
);
let mut inactive = BrowserContext::new("BID-dialog-background".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
inactive.mutate_parked_page_session_state("TID-dialog-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
});
@@ -1791,7 +1872,7 @@ async fn direct_runtime_evaluate_javascript_dialog_uses_inactive_background_owne
inactive
.parked_page_session_state("TID-dialog-background")
.expect("background page session state should remain parked")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.javascript_dialog_state
.is_empty(),
@@ -1803,17 +1884,16 @@ async fn direct_runtime_evaluate_javascript_dialog_uses_inactive_background_owne
async fn direct_runtime_evaluate_popup_creates_target_in_inactive_background_owner() {
let mut ctx = crate::testing::TestContext::new();
let page_url = "data:text/html,<!doctype html><title>popup-owner</title>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-popup-background".to_owned(),
Some("SID-popup-background".to_owned()),
page_url.to_owned(),
);
let mut inactive = BrowserContext::new("BID-popup-background".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
inactive.mutate_parked_page_session_state("TID-popup-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
});
@@ -1893,17 +1973,16 @@ async fn direct_runtime_evaluate_self_popup_does_not_navigate_active_target_for_
ctx.conn.browser_context = Some(active);
let page_url = "data:text/html,<!doctype html><title>self-popup</title>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-self-popup-background".to_owned(),
Some("SID-self-popup-background".to_owned()),
page_url.to_owned(),
);
let mut inactive = BrowserContext::new("BID-self-popup-background".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
inactive.mutate_parked_page_session_state("TID-self-popup-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
});
@@ -1948,21 +2027,19 @@ async fn direct_runtime_evaluate_self_popup_does_not_navigate_active_target_for_
async fn direct_runtime_evaluate_file_chooser_uses_inactive_background_owner() {
let mut ctx = crate::testing::TestContext::new();
let page_url = "data:text/html,<!doctype html><input id='picker' type='file' multiple>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-file-background".to_owned(),
Some("SID-file-background".to_owned()),
page_url.to_owned(),
);
let mut inactive = BrowserContext::new("BID-file-background".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
inactive.mutate_parked_page_session_state("TID-file-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
});
@@ -2027,8 +2104,7 @@ async fn direct_runtime_evaluate_routes_to_inactive_auxiliary_owner_without_prom
inactive.set_active_target_id("TID-B".to_owned());
inactive.attach_active_session("SID-primary");
assert!(inactive.assign_auxiliary_session_to_target("TID-B", "SID-aux".to_owned()));
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.inactive_browser_contexts.push(inactive);
@@ -2191,7 +2267,7 @@ async fn direct_page_preload_routes_to_inactive_background_owner_without_promoti
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2237,9 +2313,7 @@ async fn direct_page_preload_routes_to_inactive_background_owner_without_promoti
);
assert!(
conn.target_owner_state_for_session(Some("SID-background"))
- .expect("background owner state should be readable")
- .document_start_scripts
- .is_empty(),
+ .is_none_or(|state| state.document_start_scripts.is_empty()),
"removeScriptToEvaluateOnNewDocument should mutate the inactive background owner"
);
}
@@ -2249,7 +2323,7 @@ async fn direct_network_enable_routes_to_inactive_background_owner_without_promo
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2279,7 +2353,8 @@ async fn direct_network_enable_routes_to_inactive_background_owner_without_promo
inactive
.parked_page_session_state("TID-background")
.expect("background session state should be staged")
- .network_enabled
+ .runtime_slot
+ .primary_network_events_enabled()
);
}
@@ -2288,7 +2363,7 @@ async fn direct_auxiliary_network_enable_for_background_target_does_not_enable_p
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2317,7 +2392,7 @@ async fn direct_auxiliary_network_enable_for_background_target_does_not_enable_p
assert!(
inactive
.parked_page_session_state("TID-background")
- .is_none_or(|state| !state.network_enabled),
+ .is_none_or(|state| !state.runtime_slot.primary_network_events_enabled()),
"auxiliary background Network.enable must not enable the target's primary listener"
);
}
@@ -2329,7 +2404,7 @@ async fn direct_network_enable_routes_to_active_background_owner_without_promoti
let mut active = BrowserContext::new("BID-A".into());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active");
- active.background_targets.push(BackgroundTarget::new(
+ active.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2363,7 +2438,8 @@ async fn direct_network_enable_routes_to_active_background_owner_without_promoti
active
.parked_page_session_state("TID-background")
.expect("background session state should be staged")
- .network_enabled
+ .runtime_slot
+ .primary_network_events_enabled()
);
}
@@ -2425,14 +2501,14 @@ async fn direct_network_enable_for_loaded_background_owner_starts_at_network_tai
let mut ctx = crate::testing::TestContext::new();
let page_url = format!("http://{addr}/page");
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
page_url.clone(),
);
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
ctx.conn.inactive_browser_contexts.push(inactive);
ctx.install_navigation_fixture_for_session_owner(&page_url, Some("SID-background"))
.await;
@@ -2462,16 +2538,17 @@ async fn direct_network_enable_for_loaded_background_owner_starts_at_network_tai
.iter()
.find(|bc| bc.id == "BID-B")
.expect("inactive owner must remain parked");
- let artifacts = inactive
- .parked_network_artifacts("TID-background")
- .expect("background network artifacts should be staged");
+ let runtime_slot = &inactive
+ .background_target("TID-background")
+ .expect("background network target should remain live")
+ .runtime_slot;
assert_eq!(
- artifacts.emitted_subresource_record_count_for_session(None),
+ runtime_slot.emitted_subresource_record_count_for_session_for_test(None),
1,
"background Network.enable should not replay pre-enable subresource records"
);
assert_eq!(
- artifacts.emitted_websocket_event_count_for_session(None),
+ runtime_slot.emitted_websocket_event_count_for_session_for_test(None),
0,
"background Network.enable should initialize websocket cursor at the loaded target tail"
);
@@ -2493,12 +2570,11 @@ async fn direct_background_command_does_not_emit_active_observable_output_under_
let mut active = BrowserContext::new("BID-A".into());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active");
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
active.replace_loaded_page(Some(active_page));
- active.background_targets.push(BackgroundTarget::new(
+ active.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2567,8 +2643,7 @@ async fn direct_console_routes_to_inactive_active_owner_without_promoting_slot()
.find(|bc| bc.id == "BID-B")
.expect("inactive owner must remain parked");
assert!(
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled
);
@@ -2620,8 +2695,7 @@ async fn direct_console_routes_to_inactive_active_owner_without_promoting_slot()
.find(|bc| bc.id == "BID-B")
.expect("inactive owner must remain parked");
assert!(
- !inactive
- .devtools_session_state
+ !inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled
);
@@ -2641,7 +2715,7 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2670,8 +2744,8 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl
assert!(
inactive
.parked_page_session_state("TID-background")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled),
"background target should stage Console.enable"
@@ -2698,8 +2772,8 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl
assert!(
inactive
.parked_page_session_state("TID-background")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled),
"clearMessages should not disable the staged background Console state"
@@ -2726,8 +2800,8 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl
assert!(
inactive
.parked_page_session_state("TID-background")
- .is_none_or(|state| !state
- .devtools_session_state
+ .is_none_or(|state| !state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled),
"background target should stage or collapse Console.disable"
@@ -2739,14 +2813,14 @@ async fn direct_console_routes_to_loaded_background_owner_and_advances_parked_cu
let mut ctx = crate::testing::TestContext::new();
let page_url =
"data:text/html,<!doctype html><script>console.warn('background warning')</script>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
page_url.to_owned(),
);
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
ctx.conn.inactive_browser_contexts.push(inactive);
ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-background"))
.await;
@@ -2864,14 +2938,12 @@ async fn direct_log_enable_routes_to_inactive_active_owner_without_promoting_slo
.find(|bc| bc.id == "BID-B")
.expect("inactive owner must remain parked");
assert!(
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled
);
assert_eq!(
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.log_lifecycle_entries,
0,
@@ -2884,7 +2956,7 @@ async fn direct_log_enable_routes_to_inactive_background_owner_without_promoting
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2913,7 +2985,10 @@ async fn direct_log_enable_routes_to_inactive_background_owner_without_promoting
assert!(
inactive
.parked_page_session_state("TID-background")
- .is_some_and(|state| state.devtools_session_state.page_session_state.log_enabled),
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled),
"background target should stage Log.enable"
);
}
@@ -2928,7 +3003,7 @@ async fn direct_log_enable_routes_to_loaded_background_owner_without_replaying_c
.await
.expect("background page should load");
- let mut background = BackgroundTarget::new(
+ let mut background = PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2938,7 +3013,7 @@ async fn direct_log_enable_routes_to_loaded_background_owner_without_replaying_c
background.replace_loaded_page(Some(page));
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
conn.inactive_browser_contexts.push(inactive);
let response = conn
@@ -2966,7 +3041,7 @@ async fn direct_log_enable_routes_to_loaded_background_owner_without_replaying_c
inactive
.parked_page_session_state("TID-background")
.expect("parked session state")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.log_lifecycle_entries,
0,
@@ -2992,8 +3067,7 @@ async fn direct_log_disable_routes_to_inactive_active_owner_without_promoting_sl
let mut inactive = BrowserContext::new("BID-B".into());
inactive.set_active_target_id("TID-B".to_owned());
inactive.attach_active_session("SID-B");
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled = true;
ctx.conn.inactive_browser_contexts.push(inactive);
@@ -3023,14 +3097,12 @@ async fn direct_log_disable_routes_to_inactive_active_owner_without_promoting_sl
.find(|bc| bc.id == "BID-B")
.expect("inactive owner must remain parked");
assert!(
- !inactive
- .devtools_session_state
+ !inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.log_enabled
);
assert_eq!(
- inactive
- .devtools_session_state
+ inactive.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.log_lifecycle_entries,
0,
@@ -3043,14 +3115,16 @@ async fn direct_log_disable_routes_to_inactive_background_owner_without_promotin
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
TargetPageSlot::empty_for_test_fixture(),
));
inactive.mutate_parked_page_session_state("TID-background", |state| {
- state.devtools_session_state.page_session_state.log_enabled = true;
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
});
conn.inactive_browser_contexts.push(inactive);
@@ -3075,7 +3149,10 @@ async fn direct_log_disable_routes_to_inactive_background_owner_without_promotin
assert!(
inactive
.parked_page_session_state("TID-background")
- .is_none_or(|state| !state.devtools_session_state.page_session_state.log_enabled),
+ .is_none_or(|state| !state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled),
"background target should stage or collapse Log.disable"
);
}
@@ -3195,7 +3272,7 @@ async fn direct_network_policy_routes_to_inactive_background_owner_without_promo
let mut conn = CdpConnection::new();
let mut inactive = BrowserContext::new("BID-B".into());
- inactive.background_targets.push(BackgroundTarget::new(
+ inactive.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
diff --git a/moli-protocol/src/domains/accessibility/tests.rs b/moli-protocol/src/domains/accessibility/tests.rs
index 0471b221a..74a203ef4 100644
--- a/moli-protocol/src/domains/accessibility/tests.rs
+++ b/moli-protocol/src/domains/accessibility/tests.rs
@@ -1,4 +1,4 @@
-use crate::conn::{BackgroundTarget, BrowserContext, CdpCommandTaskStep, CdpSchedulerEvent};
+use crate::conn::{BrowserContext, CdpCommandTaskStep, CdpSchedulerEvent, PageTargetHost};
use crate::domains::page::LOADER_ID;
use crate::testing::{
TestContext, wait_until_renderer_document_load, wait_until_scheduler_message,
@@ -411,7 +411,7 @@ fn renderer_backed_ax_node_id(node: &Value) -> String {
#[tokio::test(flavor = "multi_thread")]
async fn accessibility_loaded_page_methods_target_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -420,7 +420,7 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<html><body><p>Intro</p><button>Owner</button></body></html>",
diff --git a/moli-protocol/src/domains/activity/main_document.rs b/moli-protocol/src/domains/activity/main_document.rs
index acc978d72..b22d8b079 100644
--- a/moli-protocol/src/domains/activity/main_document.rs
+++ b/moli-protocol/src/domains/activity/main_document.rs
@@ -1326,8 +1326,7 @@ mod tests {
browser_context.set_active_target_id("FRAME-1");
browser_context.attach_active_session("SID-nav");
browser_context.set_target_url("https://example.test/parent".to_owned());
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
let mut conn = CdpConnection::new();
diff --git a/moli-protocol/src/domains/activity/publication_route.rs b/moli-protocol/src/domains/activity/publication_route.rs
index d018dfbeb..daa394d57 100644
--- a/moli-protocol/src/domains/activity/publication_route.rs
+++ b/moli-protocol/src/domains/activity/publication_route.rs
@@ -64,7 +64,7 @@ impl RendererPublicationRoute {
};
}
let owner_route = match target_id {
- Some(target_id) => CdpSessionRoute::BackgroundTarget {
+ Some(target_id) => CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
},
@@ -180,24 +180,25 @@ impl RendererPublicationOwner {
// Prefer the target route captured when the renderer stream
// was bound. This disambiguates the brief handoff window in
// which active and parked state can both refer to one Page.
- let frozen_route = if target_id.is_none()
- || browser_context.active_target_id() == target_id.as_deref()
- {
+ let frozen_target = target_id
+ .as_deref()
+ .and_then(|target_id| browser_context.page_target(target_id))
+ .or_else(|| {
+ target_id
+ .is_none()
+ .then(|| browser_context.page_targets.active())
+ .flatten()
+ });
+ let frozen_route = frozen_target.and_then(|target| {
+ let route_target_id = (!browser_context
+ .is_active_target(target.target_id()))
+ .then(|| target.target_id().to_owned());
route_for(
- &browser_context.active_target.runtime_slot,
- None,
- browser_context.active_session_id_owned(),
+ target.runtime_slot(),
+ route_target_id,
+ target.session_id().map(str::to_owned),
)
- } else {
- target_id.as_deref().and_then(|target_id| {
- let target = browser_context.background_target(target_id)?;
- route_for(
- target.runtime_slot(),
- Some(target_id.to_owned()),
- target.session_id().map(str::to_owned),
- )
- })
- };
+ });
if frozen_route.is_some() {
return frozen_route;
}
@@ -206,23 +207,16 @@ impl RendererPublicationOwner {
// initial Page was installed. The Page residence and Page
// attachment id remain stable across that rename, so use
// those identities to recover the current concrete route.
- if let Some(route) = route_for(
- &browser_context.active_target.runtime_slot,
- None,
- browser_context.active_session_id_owned(),
- ) {
- return Some(route);
- }
- browser_context
- .background_targets
- .iter()
- .find_map(|target| {
- route_for(
- target.runtime_slot(),
- Some(target.target_id().to_owned()),
- target.session_id().map(str::to_owned),
- )
- })
+ browser_context.page_targets.iter().find_map(|target| {
+ let route_target_id = (!browser_context
+ .is_active_target(target.target_id()))
+ .then(|| target.target_id().to_owned());
+ route_for(
+ target.runtime_slot(),
+ route_target_id,
+ target.session_id().map(str::to_owned),
+ )
+ })
}),
}
}
diff --git a/moli-protocol/src/domains/activity/scheduler_work.rs b/moli-protocol/src/domains/activity/scheduler_work.rs
index 60184f204..f37fb688c 100644
--- a/moli-protocol/src/domains/activity/scheduler_work.rs
+++ b/moli-protocol/src/domains/activity/scheduler_work.rs
@@ -260,20 +260,23 @@ impl ProtocolSchedulerWork {
/// Reports owner work that must complete inside the producing command's
/// turn.
///
- /// Popup navigation is safe to start while completing the producing
- /// command: it retains its exact target route and cannot replace the
- /// command's active renderer. Popup activation is deliberately excluded.
- /// It can replace that renderer and must therefore cross the ordinary
- /// client-turn predecessor so the opener's command result is collected
- /// from its original owner first.
+ /// Popup navigation produced by the opener is safe to start while
+ /// completing that command because it targets a different renderer. The
+ /// initial navigation released by `Runtime.runIfWaitingForDebugger` is an
+ /// exception: it replaces the command's own initial empty Document, so it
+ /// crosses the ordinary client-turn predecessor just like activation.
pub fn is_command_followup(&self) -> bool {
- matches!(
- &self.payload,
+ match &self.payload {
ProtocolSchedulerWorkPayload::BidiChannelOwnerAction(_)
- | ProtocolSchedulerWorkPayload::TopLevelLocationNavigationOwnerAction(_)
- | ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(_)
- | ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(_)
- )
+ | ProtocolSchedulerWorkPayload::TopLevelLocationNavigationOwnerAction(_)
+ | ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(_) => true,
+ ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(action) => {
+ action.is_command_followup()
+ }
+ ProtocolSchedulerWorkPayload::ProtocolObservation(_)
+ | ProtocolSchedulerWorkPayload::MainDocumentLoadOwnerAction(_)
+ | ProtocolSchedulerWorkPayload::PopupTargetActivationAction(_) => false,
+ }
}
pub fn navigation_gate_target_id(&self) -> Option<&str> {
diff --git a/moli-protocol/src/domains/browser.rs b/moli-protocol/src/domains/browser.rs
index ceec80423..72ddf54e6 100644
--- a/moli-protocol/src/domains/browser.rs
+++ b/moli-protocol/src/domains/browser.rs
@@ -702,7 +702,7 @@ fn start_loaded_page_permission_override_commands(
})?,
});
}
- for target in &mut browser_context.background_targets {
+ for target in browser_context.background_targets_mut() {
let target_id = target.target_id().to_owned();
let Some(page) = target.loaded_page_mut() else {
continue;
diff --git a/moli-protocol/src/domains/console.rs b/moli-protocol/src/domains/console.rs
index d2b175a5b..c2155aa04 100644
--- a/moli-protocol/src/domains/console.rs
+++ b/moli-protocol/src/domains/console.rs
@@ -199,8 +199,7 @@ mod tests {
}
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- !browser_context
- .devtools_session_state
+ !browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
"transitional observable-output enabled bit should track Console.disable"
@@ -222,7 +221,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
"transitional Console projection must not flip before V8 Console.enable succeeds"
@@ -246,7 +245,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
"transitional Console projection should flip after V8 Console.enable succeeds"
@@ -323,7 +322,7 @@ mod tests {
.browser_context
.as_mut()
.expect("browser context should be loaded");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
assert_eq!(
@@ -546,16 +545,15 @@ mod tests {
ctx.expect_result(13, json!({}), Some("SID-background"));
let active = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled
);
assert!(
active
.parked_page_session_state("TID-background")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled),
"background target should stage Console.enable"
diff --git a/moli-protocol/src/domains/css.rs b/moli-protocol/src/domains/css.rs
index de9f02ed2..6ecc2b964 100644
--- a/moli-protocol/src/domains/css.rs
+++ b/moli-protocol/src/domains/css.rs
@@ -733,7 +733,7 @@ fn parse_inline_style_declarations(style_text: &str) -> Vec<CssDeclaration> {
#[cfg(test)]
mod tests {
use super::parse_inline_style_declarations;
- use crate::conn::{BackgroundTarget, BrowserContext, CdpCommandTaskStep, CdpSchedulerEvent};
+ use crate::conn::{BrowserContext, CdpCommandTaskStep, CdpSchedulerEvent, PageTargetHost};
use crate::domains::page::LOADER_ID;
use crate::testing::{TestContext, wait_until_renderer_document_load};
use moli_core::page::{
@@ -972,7 +972,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn css_loaded_page_methods_target_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -981,7 +981,7 @@ mod tests {
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<html><head><style title='owner'>body { color: red; }</style></head><body><div id='target' style='display:flex;width:123px;color:blue'></div></body></html>",
diff --git a/moli-protocol/src/domains/dom/tests/frames.rs b/moli-protocol/src/domains/dom/tests/frames.rs
index b979b0dcf..7436f1598 100644
--- a/moli-protocol/src/domains/dom/tests/frames.rs
+++ b/moli-protocol/src/domains/dom/tests/frames.rs
@@ -5011,7 +5011,7 @@ async fn get_frame_owner_invalid_params_error() {
}
#[tokio::test(flavor = "multi_thread")]
-async fn get_frame_owner_without_target_id_errors() {
+async fn get_frame_owner_without_selected_target_errors() {
let mut ctx = TestContext::new();
load_bc(&mut ctx, "BID-A");
@@ -5037,11 +5037,7 @@ async fn get_frame_owner_without_target_id_errors() {
"params": { "frameId": "TID-1" }
}))
.await;
- ctx.expect_error(
- 2,
- -32000,
- "Frame with the given id does not belong to the target.",
- );
+ ctx.expect_error(2, -31998, "BrowserContextNotLoaded");
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-protocol/src/domains/dom/tests/geometry.rs b/moli-protocol/src/domains/dom/tests/geometry.rs
index f966c0bac..c935ce563 100644
--- a/moli-protocol/src/domains/dom/tests/geometry.rs
+++ b/moli-protocol/src/domains/dom/tests/geometry.rs
@@ -40,7 +40,7 @@ async fn renderer_backend_node_id_for_live_expression(
async fn dom_resolve_geometry_and_mutation_target_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let background_url = url::Url::parse("https://background.test/owned").unwrap();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
background_url.as_str().to_owned(),
@@ -49,7 +49,7 @@ async fn dom_resolve_geometry_and_mutation_target_loaded_background_owner_withou
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_buffered_navigation_fixture_for_session_owner(
background_url,
diff --git a/moli-protocol/src/domains/dom/tests/misc.rs b/moli-protocol/src/domains/dom/tests/misc.rs
index f3436c15c..38fc4dc1a 100644
--- a/moli-protocol/src/domains/dom/tests/misc.rs
+++ b/moli-protocol/src/domains/dom/tests/misc.rs
@@ -213,7 +213,7 @@ async fn dom_enable_include_whitespace_controls_inspector_tree_projection() {
#[tokio::test(flavor = "multi_thread")]
async fn dom_document_reads_target_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -222,7 +222,7 @@ async fn dom_document_reads_target_loaded_background_owner_without_promotion() {
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<!doctype html><html><body><section id='owned'>background</section></body></html>",
diff --git a/moli-protocol/src/domains/dom/tests/mod.rs b/moli-protocol/src/domains/dom/tests/mod.rs
index b6e595378..9f63b5ec3 100644
--- a/moli-protocol/src/domains/dom/tests/mod.rs
+++ b/moli-protocol/src/domains/dom/tests/mod.rs
@@ -2,9 +2,7 @@ use super::{
backend_node_id_for_snapshot, frontend_node_id_for_snapshot, node_snapshot_base_payload,
node_snapshot_to_cdp, node_snapshot_to_cdp_with_limit,
};
-use crate::conn::{
- BackgroundTarget, BrowserContext, CdpCommandTaskStep, PendingCdpCommandDispatch,
-};
+use crate::conn::{BrowserContext, CdpCommandTaskStep, PageTargetHost, PendingCdpCommandDispatch};
use crate::testing::TestContext;
use moli_core::page::{RENDERER_BACKEND_NODE_ID_START, is_renderer_backend_node_id};
use moli_page_types::{DocumentNodeSnapshot, DocumentSnapshotNodeId};
diff --git a/moli-protocol/src/domains/dom/tests/search.rs b/moli-protocol/src/domains/dom/tests/search.rs
index a1479cce5..4ea2f3808 100644
--- a/moli-protocol/src/domains/dom/tests/search.rs
+++ b/moli-protocol/src/domains/dom/tests/search.rs
@@ -473,7 +473,7 @@ async fn perform_search_selectors_cover_all_frame_documents_and_author_shadow_ro
#[tokio::test(flavor = "multi_thread")]
async fn dom_search_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -482,7 +482,7 @@ async fn dom_search_targets_loaded_background_owner_without_promotion() {
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<!doctype html><html><body><span>one</span><span>two</span></body></html>",
diff --git a/moli-protocol/src/domains/dom_snapshot.rs b/moli-protocol/src/domains/dom_snapshot.rs
index 85a4f0d8d..a1fef064e 100644
--- a/moli-protocol/src/domains/dom_snapshot.rs
+++ b/moli-protocol/src/domains/dom_snapshot.rs
@@ -204,7 +204,7 @@ mod tests {
use serde_json::json;
use crate::{
- conn::{BackgroundTarget, BrowserContext, CdpCommandTaskStep},
+ conn::{BrowserContext, CdpCommandTaskStep, PageTargetHost},
domains::page::LOADER_ID,
testing::{TestContext, wait_until_renderer_document_load, wait_until_scheduler_message},
};
@@ -1028,7 +1028,7 @@ mod tests {
.await
.expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let mut background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
page.final_url().as_str().to_owned(),
@@ -1038,7 +1038,7 @@ mod tests {
let mut bc = BrowserContext::new("BID-DS-BG".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/dom_storage/activity.rs b/moli-protocol/src/domains/dom_storage/activity.rs
index 7e5e70a3e..c7e8422f1 100644
--- a/moli-protocol/src/domains/dom_storage/activity.rs
+++ b/moli-protocol/src/domains/dom_storage/activity.rs
@@ -85,46 +85,50 @@ fn dom_storage_subscriptions_for_browser_context_owner(
};
let mut subscriptions = Vec::new();
- if let Some(subscription) = browser_context
- .devtools_session_state
- .dom_storage_session_state
- .mutation_subscription()
- {
- subscriptions.push((
- browser_context.active_session_id_owned(),
- subscription.clone(),
- ));
+ if browser_context.page_targets.active().is_some() {
+ if let Some(subscription) = browser_context
+ .devtools_sessions
+ .primary()
+ .dom_storage_session_state
+ .mutation_subscription()
+ {
+ subscriptions.push((
+ browser_context.active_session_id_owned(),
+ subscription.clone(),
+ ));
+ }
+ subscriptions.extend(
+ browser_context
+ .devtools_sessions
+ .attached_entries()
+ .filter_map(|(session_id, state)| {
+ state
+ .dom_storage_session_state
+ .mutation_subscription()
+ .map(|subscription| (Some(session_id.to_owned()), subscription.clone()))
+ }),
+ );
}
- subscriptions.extend(
- browser_context
- .auxiliary_devtools_session_states
- .iter()
- .filter_map(|(session_id, state)| {
- state
- .dom_storage_session_state
- .mutation_subscription()
- .map(|subscription| (Some(session_id.clone()), subscription.clone()))
- }),
- );
- for target in &browser_context.background_targets {
+ for target in browser_context.background_targets() {
let Some(state) = browser_context.parked_page_session_state(target.target_id()) else {
continue;
};
if let (Some(session_id), Some(subscription)) = (
target.session_id(),
state
- .devtools_session_state
+ .devtools_sessions
+ .primary()
.dom_storage_session_state
.mutation_subscription(),
) {
subscriptions.push((Some(session_id.to_owned()), subscription.clone()));
}
- subscriptions.extend(state.auxiliary_devtools_session_states.iter().filter_map(
+ subscriptions.extend(state.devtools_sessions.attached_entries().filter_map(
|(session_id, state)| {
state
.dom_storage_session_state
.mutation_subscription()
- .map(|subscription| (Some(session_id.clone()), subscription.clone()))
+ .map(|subscription| (Some(session_id.to_owned()), subscription.clone()))
},
));
}
diff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rs
index 6e26c4805..5f30f3017 100644
--- a/moli-protocol/src/domains/emulation.rs
+++ b/moli-protocol/src/domains/emulation.rs
@@ -1,7 +1,8 @@
use crate::conn::{
BrowserContext, CdpConnection, CdpSessionRoute, Cmd, CommandOwnerScope, EmulatedDeviceMetrics,
- EmulatedGeolocationOverrideState, EmulatedViewportSurface, RendererCommandCorrelation,
- RendererCommandDescriptor, RuntimeInspectorAsyncCompletionReceiver, TargetWindowSurfaceState,
+ EmulatedGeolocationOverrideState, EmulatedViewportSurface, PageTargetHost,
+ RendererCommandCorrelation, RendererCommandDescriptor, RuntimeInspectorAsyncCompletionReceiver,
+ TargetWindowSurfaceState,
};
use crate::devtools_runtime::{
DevToolsCommand, DevToolsCommandResult, DevToolsDevicePixelRatioSetting, DevToolsError,
@@ -457,8 +458,8 @@ fn start_locale_override_command(
}
let locale_override = params.locale.clone().filter(|value| !value.is_empty());
if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.locale_override = locale_override.clone();
+ if let Some(mut state) = state {
+ state.set_locale_override(locale_override.clone());
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -571,8 +572,8 @@ fn start_timezone_override_command(
(!trimmed.is_empty()).then(|| trimmed.to_owned())
};
if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.timezone_override = timezone_override.clone();
+ if let Some(mut state) = state {
+ state.set_timezone_override(timezone_override.clone());
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -1771,8 +1772,8 @@ fn start_locale_override_for_current_route(
locale: Option<String>,
) -> Result<Vec<PendingEmulationPageCommand>, DevToolsError> {
if !conn.mutate_emulation_session_state_for_session_owner(None, |state| {
- if let Some(state) = state {
- *state.locale_override = locale.clone();
+ if let Some(mut state) = state {
+ state.set_locale_override(locale.clone());
}
}) {
return Err(devtools_emulation_owner_error(
@@ -1787,13 +1788,13 @@ fn start_locale_update_for_current_route(
route: &CdpSessionRoute,
) -> Result<Vec<PendingEmulationPageCommand>, DevToolsError> {
let target = pending_emulation_target_for_route(route)?;
- let Some((headers, locale_override)) = locale_apply_inputs_for_session(conn, None) else {
+ let Some(locale_override) = locale_override_for_session(conn, None) else {
return Ok(Vec::new());
};
let Some(page) = loaded_page_mut_for_session(conn, None) else {
return Ok(Vec::new());
};
- start_locale_override_page_commands(target, page, &headers, locale_override.as_deref())
+ start_locale_override_page_command(target, page, locale_override.as_deref())
.map_err(|error| DevToolsError::new(DevToolsErrorKind::Internal, error))
}
@@ -1880,8 +1881,8 @@ fn start_timezone_override_for_current_route(
timezone: Option<String>,
) -> Result<Option<PendingEmulationPageCommand>, DevToolsError> {
if !conn.mutate_emulation_session_state_for_session_owner(None, |state| {
- if let Some(state) = state {
- *state.timezone_override = timezone.clone();
+ if let Some(mut state) = state {
+ state.set_timezone_override(timezone.clone());
}
}) {
return Err(devtools_emulation_owner_error(
@@ -1920,7 +1921,7 @@ fn pending_emulation_target_for_route(
} => Ok(PendingEmulationPageTarget::BrowserContextActive {
browser_context_id: browser_context_id.clone(),
}),
- CdpSessionRoute::BackgroundTarget {
+ CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
} => Ok(PendingEmulationPageTarget::BrowserContextBackground {
@@ -2016,8 +2017,8 @@ fn top_level_target_routes_for_browser_contexts(
target_id: None,
});
}
- routes.extend(browser_context.background_targets.iter().map(|target| {
- CdpSessionRoute::BackgroundTarget {
+ routes.extend(browser_context.background_targets().map(|target| {
+ CdpSessionRoute::PageTargetHost {
browser_context_id: browser_context.id.clone(),
target_id: target.target_id().to_owned(),
}
@@ -2276,17 +2277,11 @@ fn is_moli_internal_default_user_context(browser_context_id: &str) -> bool {
fn browser_context_default_device_metrics_runtime_command_count(
browser_context: &BrowserContext,
) -> usize {
- let active_count = usize::from(
- browser_context.emulated_device_metrics.is_none()
- && browser_context
- .active_target
- .runtime_slot
- .loaded_page()
- .is_some(),
- );
+ let active_count = usize::from(browser_context.page_targets.active().is_some_and(|target| {
+ target.emulated_device_metrics.is_none() && target.runtime_slot.loaded_page().is_some()
+ }));
let background_count = browser_context
- .background_targets
- .iter()
+ .background_targets()
.filter(|target| {
let target_id = target.target_id();
browser_context
@@ -2307,8 +2302,9 @@ fn start_browser_context_default_device_metrics_page_commands(
let browser_context_id = browser_context.id.clone();
let mut pending = Vec::new();
let viewport_surface = Some(metrics.viewport_surface().to_page_viewport_surface());
- if browser_context.emulated_device_metrics.is_none()
- && let Some(page) = browser_context.active_target.runtime_slot.loaded_page_mut()
+ if let Some(active_target) = browser_context.page_targets.active_mut()
+ && active_target.emulated_device_metrics.is_none()
+ && let Some(page) = active_target.runtime_slot.loaded_page_mut()
{
pending.push(PendingEmulationPageCommand {
target: PendingEmulationPageTarget::BrowserContextActive {
@@ -2339,8 +2335,10 @@ fn start_browser_context_default_device_metrics_page_commands(
runtime_response_rx,
});
}
- for index in 0..browser_context.background_targets.len() {
- let target_id = browser_context.background_targets[index]
+ for index in 0..browser_context.background_target_count() {
+ let target_id = browser_context
+ .background_target_at(index)
+ .expect("background target index must remain valid")
.target_id()
.to_owned();
let has_target_override = browser_context
@@ -2349,7 +2347,10 @@ fn start_browser_context_default_device_metrics_page_commands(
if has_target_override {
continue;
}
- let Some(page) = browser_context.background_targets[index].loaded_page_mut() else {
+ let Some(page) = browser_context
+ .background_target_at_mut(index)
+ .and_then(PageTargetHost::loaded_page_mut)
+ else {
continue;
};
pending.push(PendingEmulationPageCommand {
@@ -2602,7 +2603,7 @@ fn start_context_emulated_media_page_commands(
runtime_response_rx: None,
});
}
- for target in &mut browser_context.background_targets {
+ for target in browser_context.background_targets_mut() {
let target_id = target.target_id().to_owned();
let Some(page) = target.loaded_page_mut() else {
continue;
@@ -2626,17 +2627,16 @@ fn start_session_locale_override_page_commands(
conn: &mut CdpConnection,
session_id: Option<&str>,
) -> Result<Vec<PendingEmulationPageCommand>, String> {
- let Some((headers, locale_override)) = locale_apply_inputs_for_session(conn, session_id) else {
+ let Some(locale_override) = locale_override_for_session(conn, session_id) else {
return Ok(Vec::new());
};
let owner_scope = CommandOwnerScope::capture(conn, session_id);
let Some(page) = loaded_page_mut_for_session(conn, session_id) else {
return Ok(Vec::new());
};
- start_locale_override_page_commands(
+ start_locale_override_page_command(
PendingEmulationPageTarget::SessionOwner { owner_scope },
page,
- &headers,
locale_override.as_deref(),
)
}
@@ -2651,32 +2651,34 @@ fn start_context_locale_override_page_commands(
.chain(conn.inactive_browser_contexts.iter_mut())
{
let browser_context_id = browser_context.id.clone();
- let active_headers = browser_context.effective_extra_headers();
let active_locale = browser_context.effective_active_locale_override_owned();
if let Some(page) = browser_context.active_target.runtime_slot.loaded_page_mut() {
- pending.extend(start_locale_override_page_commands(
+ pending.extend(start_locale_override_page_command(
PendingEmulationPageTarget::BrowserContextActive {
browser_context_id: browser_context_id.clone(),
},
page,
- &active_headers,
active_locale.as_deref(),
)?);
}
- for index in 0..browser_context.background_targets.len() {
- let target_id = browser_context.background_targets[index]
+ for index in 0..browser_context.background_target_count() {
+ let target_id = browser_context
+ .background_target_at(index)
+ .expect("background target index must remain valid")
.target_id()
.to_owned();
- let Some(page) = browser_context.background_targets[index].loaded_page_mut() else {
+ let Some(page) = browser_context
+ .background_target_at_mut(index)
+ .and_then(PageTargetHost::loaded_page_mut)
+ else {
continue;
};
- pending.extend(start_locale_override_page_commands(
+ pending.extend(start_locale_override_page_command(
PendingEmulationPageTarget::BrowserContextBackground {
browser_context_id: browser_context_id.clone(),
target_id,
},
page,
- &active_headers,
active_locale.as_deref(),
)?);
}
@@ -2800,69 +2802,34 @@ fn start_surface_override_page_command(
})
}
-fn start_locale_override_page_commands(
+fn start_locale_override_page_command(
target: PendingEmulationPageTarget,
page: &moli_core::page::Page,
- headers: &[(String, String)],
locale_override: Option<&str>,
) -> Result<Vec<PendingEmulationPageCommand>, String> {
- let header_update = page
- .start_set_extra_http_headers(headers)
- .map_err(|error| format!("failed to update page extra HTTP headers: {error}"))?;
let locale_update = page
.start_set_locale_override(locale_override)
.map_err(|error| format!("failed to update page locale override: {error}"))?;
- Ok(vec![
- PendingEmulationPageCommand {
- target: target.clone(),
- operation: PendingEmulationPageOperation::SetExtraHttpHeaders,
- pending: header_update,
- runtime_response_rx: None,
- },
- PendingEmulationPageCommand {
- target,
- operation: PendingEmulationPageOperation::SetLocaleOverride,
- pending: locale_update,
- runtime_response_rx: None,
- },
- ])
+ Ok(vec![PendingEmulationPageCommand {
+ target,
+ operation: PendingEmulationPageOperation::SetLocaleOverride,
+ pending: locale_update,
+ runtime_response_rx: None,
+ }])
}
-fn locale_apply_inputs_for_session(
+fn locale_override_for_session(
conn: &CdpConnection,
session_id: Option<&str>,
-) -> Option<(Vec<(String, String)>, Option<String>)> {
+) -> Option<Option<String>> {
let (browser_context_id, target_id) = conn.target_owner_identity_for_session(session_id)?;
let browser_context = conn.browser_context_by_id(&browser_context_id)?;
if let Some(target_id) = target_id
&& browser_context.background_target(&target_id).is_some()
{
- return parked_locale_apply_inputs(browser_context, &target_id);
+ return Some(browser_context.effective_parked_locale_override_owned(&target_id));
}
- Some((
- browser_context.effective_extra_headers(),
- browser_context.effective_active_locale_override_owned(),
- ))
-}
-
-fn parked_locale_apply_inputs(
- browser_context: &crate::conn::BrowserContext,
- target_id: &str,
-) -> Option<(Vec<(String, String)>, Option<String>)> {
- browser_context.background_target(target_id)?;
- let mut headers = browser_context
- .parked_page_session_state(target_id)
- .map(|state| state.network_policy.extra_headers().to_vec())
- .unwrap_or_default();
- let locale_override = browser_context.effective_parked_locale_override_owned(target_id);
- if let Some(locale) = locale_override.as_deref()
- && !headers
- .iter()
- .any(|(name, _)| name.eq_ignore_ascii_case("accept-language"))
- {
- headers.push(("Accept-Language".to_owned(), locale.to_owned()));
- }
- Some((headers, locale_override))
+ Some(browser_context.effective_active_locale_override_owned())
}
fn finish_pending_emulation_page_command(
@@ -2882,19 +2849,19 @@ fn finish_pending_emulation_page_command(
completion,
);
}
- let page =
- loaded_page_mut_for_session(route_scope.conn_mut(), owner_scope.session_id())
- .ok_or_else(|| "NoDocumentLoaded".to_owned())?;
- finish_emulation_page_operation(page, operation, completion)
+ let page = route_scope
+ .conn_mut()
+ .loaded_page_mut_for_interruptible_protocol_access(owner_scope.session_id())
+ .ok();
+ finish_emulation_page_operation_on_current_attachment(page, operation, completion)
}
PendingEmulationPageTarget::BrowserContextActive { browser_context_id } => {
let page = conn
.browser_context_by_id_mut(&browser_context_id)
.and_then(|browser_context| {
browser_context.active_target.runtime_slot.loaded_page_mut()
- })
- .ok_or_else(|| "NoDocumentLoaded".to_owned())?;
- finish_emulation_page_operation(page, operation, completion)
+ });
+ finish_emulation_page_operation_on_current_attachment(page, operation, completion)
}
PendingEmulationPageTarget::BrowserContextBackground {
browser_context_id,
@@ -2903,13 +2870,41 @@ fn finish_pending_emulation_page_command(
let page = conn
.browser_context_by_id_mut(&browser_context_id)
.and_then(|browser_context| browser_context.background_target_mut(&target_id))
- .and_then(|target| target.loaded_page_mut())
- .ok_or_else(|| "NoDocumentLoaded".to_owned())?;
- finish_emulation_page_operation(page, operation, completion)
+ .and_then(|target| target.loaded_page_mut());
+ finish_emulation_page_operation_on_current_attachment(page, operation, completion)
}
}
}
+fn finish_emulation_page_operation_on_current_attachment(
+ page: Option<&mut moli_core::page::Page>,
+ operation: PendingEmulationPageOperation,
+ completion: CompletedPageCommand,
+) -> Result<(), String> {
+ let completion_attachment = completion.renderer_agent_attachment_id();
+ if let Some(page) = page
+ && page.renderer_agent_attachment_id() == completion_attachment
+ {
+ return finish_emulation_page_operation(page, operation, completion);
+ }
+
+ // The renderer command has already settled successfully. A cross-Document
+ // navigation may replace its Page before the protocol actor decodes that
+ // frozen completion; do not turn that success into NoDocumentLoaded or
+ // apply the old PageState snapshot to the replacement attachment. The
+ // authoritative emulation state was stored before dispatch and is replayed
+ // while the replacement Page is installed.
+ let output = match operation {
+ PendingEmulationPageOperation::RuntimeProtocolMessage => {
+ completion.into_runtime_protocol_message_command_turn()
+ }
+ _ => completion.into_unit_page_command_turn(),
+ };
+ output
+ .map(drop)
+ .map_err(|error| format!("stale Emulation command returned an unexpected reply: {error}"))
+}
+
fn finish_emulation_page_operation(
page: &mut moli_core::page::Page,
operation: PendingEmulationPageOperation,
diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rs
index f9e9b3540..35bd55335 100644
--- a/moli-protocol/src/domains/emulation/tests.rs
+++ b/moli-protocol/src/domains/emulation/tests.rs
@@ -1,7 +1,7 @@
use crate::conn::{
- BackgroundTarget, BrowserContext, CdpCommandTaskStep, EmulatedGeolocationOverride,
- EmulatedGeolocationOverrideState, PendingCdpCommandDispatch, TargetIdentityState,
- TargetPageSlot,
+ BrowserContext, CdpCommandTaskStep, EmulatedGeolocationOverride,
+ EmulatedGeolocationOverrideState, PageTargetHost, PendingCdpCommandDispatch,
+ TargetIdentityState, TargetPageSlot,
};
use crate::devtools_runtime::{
DevToolsBrowserContextId, DevToolsCommand, DevToolsCommandContext, DevToolsCommandResult,
@@ -653,6 +653,71 @@ async fn live_geolocation_override_uses_pending_command_dispatch() {
}));
}
+#[tokio::test(flavor = "multi_thread")]
+async fn device_metrics_completion_survives_initial_page_replacement() {
+ let mut ctx = TestContext::new();
+ load_session_page_for_pending_emulation_test_at_url(
+ &mut ctx,
+ "data:text/html,<body>initial</body>",
+ )
+ .await;
+
+ let raw = json!({
+ "id": 9128,
+ "sessionId": "SID-1",
+ "method": "Emulation.setDeviceMetricsOverride",
+ "params": {
+ "width": 640,
+ "height": 360,
+ "deviceScaleFactor": 2,
+ "mobile": false
+ }
+ })
+ .to_string();
+ let CdpCommandTaskStep::Pending(pending) = ctx.conn.start_command_dispatch(&raw) else {
+ panic!("loaded Emulation.setDeviceMetricsOverride should update the renderer Page");
+ };
+ let completed = pending.wait().await;
+
+ ctx.process_async(json!({
+ "id": 9129,
+ "sessionId": "SID-1",
+ "method": "Page.navigate",
+ "params": { "url": "data:text/html,<body>replacement</body>" }
+ }))
+ .await;
+ let navigate = ctx.take_response_by_id(9129);
+ assert_eq!(navigate["result"]["frameId"], json!("TID-1"));
+ assert!(navigate["result"]["loaderId"].is_string());
+
+ let CdpCommandTaskStep::Complete(outcome) =
+ ctx.conn.complete_pending_command_dispatch(completed).await
+ else {
+ panic!("device metrics completion should settle after Page replacement");
+ };
+ let messages = outcome.into_parts().0;
+ assert!(messages.iter().any(|message| {
+ message["id"] == json!(9128)
+ && message["sessionId"] == json!("SID-1")
+ && message["result"] == json!({})
+ }));
+
+ ctx.process_async(json!({
+ "id": 9130,
+ "sessionId": "SID-1",
+ "method": "Runtime.evaluate",
+ "params": {
+ "expression": "JSON.stringify([innerWidth, innerHeight, devicePixelRatio])",
+ "returnByValue": true
+ }
+ }))
+ .await;
+ assert_eq!(
+ ctx.take_response_by_id(9130)["result"]["result"]["value"],
+ json!("[640,360,2]")
+ );
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn live_cpu_throttling_rate_uses_pending_command_dispatch() {
let mut ctx = TestContext::new();
@@ -1418,7 +1483,7 @@ async fn emulation_async_dispatch_updates_live_page_user_agent_and_xhr_header()
}
#[tokio::test(flavor = "multi_thread")]
-async fn emulation_async_dispatch_updates_live_page_surface_and_accept_language() {
+async fn emulation_async_dispatch_updates_live_page_surface_without_mutating_accept_language() {
async fn page_handler() -> impl IntoResponse {
"<!doctype html><html><body>ok</body></html>"
}
@@ -1519,7 +1584,7 @@ async fn emulation_async_dispatch_updates_live_page_surface_and_accept_language(
assert_eq!(payload["localized"], json!("02/01/2020 11:04:05"));
assert_eq!(payload["dark"], json!(true));
assert_eq!(payload["light"], json!(false));
- assert_eq!(seen.lock().as_deref(), Some("fr-FR"));
+ assert_eq!(seen.lock().as_deref(), Some("en-US,en;q=0.9"));
server.abort();
}
@@ -1882,14 +1947,14 @@ async fn device_metrics_override_updates_layout_metrics() {
}
#[tokio::test(flavor = "multi_thread")]
-async fn locale_override_updates_headers_and_navigator_language() {
+async fn locale_override_updates_intl_without_mutating_language_surfaces() {
async fn handler(headers: HeaderMap) -> impl IntoResponse {
let accept_language = headers
.get(axum::http::header::ACCEPT_LANGUAGE)
.and_then(|value| value.to_str().ok())
.unwrap_or("");
format!(
- "<!doctype html><html><body data-accept-language=\"{accept_language}\"><script>document.body.textContent = [navigator.language, navigator.languages[0], document.body.dataset.acceptLanguage].join('|');</script></body></html>"
+ "<!doctype html><html><body data-accept-language=\"{accept_language}\"><script>document.body.textContent = [Intl.DateTimeFormat().resolvedOptions().locale, navigator.language, navigator.languages.join(','), document.body.dataset.acceptLanguage].join('|');</script></body></html>"
)
}
@@ -1925,13 +1990,16 @@ async fn locale_override_updates_headers_and_navigator_language() {
let _ = ctx.take_all();
let html = loaded_page_html_for_test(&mut ctx).await;
- assert!(html.contains(">fr-FR|fr-FR|fr-FR<"), "got {html}");
+ assert!(
+ html.contains(">fr-FR|en-US|en-US,en|en-US,en;q=0.9<"),
+ "got {html}"
+ );
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
-async fn live_locale_override_updates_navigator_without_page_define_property() {
+async fn live_locale_override_updates_intl_without_mutating_navigator() {
let mut ctx = TestContext::new();
load_session_page_for_pending_emulation_test(&mut ctx).await;
@@ -1969,7 +2037,7 @@ async fn live_locale_override_updates_navigator_without_page_define_property() {
"method": "Runtime.evaluate",
"sessionId": "SID-1",
"params": {
- "expression": "JSON.stringify({ language: navigator.language, languages: Array.from(navigator.languages || []), reflectedLocaleSlot: Object.prototype.hasOwnProperty.call(globalThis, '__moliLocaleOverride') })"
+ "expression": "JSON.stringify({ intlLocale: Intl.DateTimeFormat().resolvedOptions().locale, language: navigator.language, languages: Array.from(navigator.languages || []), reflectedLocaleSlot: Object.prototype.hasOwnProperty.call(globalThis, '__moliLocaleOverride') })"
}
}))
.await;
@@ -1979,8 +2047,9 @@ async fn live_locale_override_updates_navigator_without_page_define_property() {
.expect("runtime evaluate should return a JSON string");
let payload: serde_json::Value =
serde_json::from_str(payload).expect("runtime evaluate payload should be json");
- assert_eq!(payload["language"], json!("fr-FR"));
- assert_eq!(payload["languages"], json!(["fr-FR"]));
+ assert_eq!(payload["intlLocale"], json!("fr-FR"));
+ assert_eq!(payload["language"], json!("en-US"));
+ assert_eq!(payload["languages"], json!(["en-US", "en"]));
assert_eq!(payload["reflectedLocaleSlot"], json!(false));
}
@@ -2066,7 +2135,7 @@ async fn locale_and_timezone_overrides_apply_to_locale_date_formatting() {
#[tokio::test(flavor = "multi_thread")]
async fn context_emulated_media_applies_to_loaded_background_page_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::new(
+ let background = PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2076,7 +2145,7 @@ async fn context_emulated_media_applies_to_loaded_background_page_without_promot
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active");
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<body>background</body>",
@@ -2142,7 +2211,7 @@ async fn context_emulated_media_applies_to_loaded_background_page_without_promot
#[tokio::test(flavor = "multi_thread")]
async fn context_locale_override_applies_to_loaded_background_page_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::new(
+ let background = PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2152,7 +2221,7 @@ async fn context_locale_override_applies_to_loaded_background_page_without_promo
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active");
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<body>background</body>",
@@ -2219,7 +2288,7 @@ async fn context_locale_override_applies_to_loaded_background_page_without_promo
#[tokio::test(flavor = "multi_thread")]
async fn session_emulation_routes_to_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::new(
+ let background = PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -2229,7 +2298,7 @@ async fn session_emulation_routes_to_loaded_background_owner_without_promotion()
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active");
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<body>background</body>",
diff --git a/moli-protocol/src/domains/fetch/subresource.rs b/moli-protocol/src/domains/fetch/subresource.rs
index 4d5360223..c2a651149 100644
--- a/moli-protocol/src/domains/fetch/subresource.rs
+++ b/moli-protocol/src/domains/fetch/subresource.rs
@@ -587,7 +587,7 @@ mod tests {
use url::Url;
use crate::conn::{
- BackgroundProtocolEvent, BackgroundTarget, BrowserContext, CdpConnection,
+ BackgroundProtocolEvent, BrowserContext, CdpConnection, PageTargetHost,
PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest,
};
use crate::devtools_runtime::{AutomationEvent, DevToolsNetworkResourceType};
@@ -863,12 +863,12 @@ mod tests {
fn prepared_subresource_fetch_pause_can_emit_for_background_owner() {
let mut conn = CdpConnection::default();
let mut bc = BrowserContext::new("BID-1".to_owned());
- let target = BackgroundTarget::with_url(
+ let target = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"https://example.test/background".to_owned(),
);
- bc.background_targets.push(target);
+ bc.insert_page_target_host(target);
conn.browser_context = Some(bc);
conn.runtime_session_owner_slot_mut(Some("SID-background"))
.expect("background test target runtime slot")
diff --git a/moli-protocol/src/domains/fetch/tests/basics.rs b/moli-protocol/src/domains/fetch/tests/basics.rs
index 0921d0109..dd077ec2c 100644
--- a/moli-protocol/src/domains/fetch/tests/basics.rs
+++ b/moli-protocol/src/domains/fetch/tests/basics.rs
@@ -398,7 +398,7 @@ async fn disable_drains_fetch_owned_pending_when_same_session_network_intercept_
#[tokio::test(flavor = "multi_thread")]
async fn enable_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -407,7 +407,7 @@ async fn enable_targets_loaded_background_owner_without_promotion() {
let mut bc = BrowserContext::new("BID-fetch-bg".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<title>fetch background</title>",
@@ -435,11 +435,14 @@ async fn enable_targets_loaded_background_owner_without_promotion() {
let staged = bc
.parked_page_session_state("TID-background")
.expect("background owner fetch config should be staged");
- assert!(staged.fetch_config.is_enabled());
- assert_eq!(staged.fetch_config.session_id(), Some("SID-background"));
- assert_eq!(staged.fetch_config.patterns().len(), 1);
+ assert!(staged.fetch_owner.config_snapshot().is_enabled());
assert_eq!(
- staged.fetch_config.patterns()[0].resource_type_filter,
+ staged.fetch_owner.config_snapshot().session_id(),
+ Some("SID-background")
+ );
+ assert_eq!(staged.fetch_owner.config_snapshot().patterns().len(), 1);
+ assert_eq!(
+ staged.fetch_owner.config_snapshot().patterns()[0].resource_type_filter,
Some(FetchResourceTypeFilter::Xhr)
);
}
@@ -447,7 +450,7 @@ async fn enable_targets_loaded_background_owner_without_promotion() {
#[tokio::test(flavor = "multi_thread")]
async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-fetch-background".to_owned(),
None,
"about:blank".to_owned(),
@@ -455,7 +458,7 @@ async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {
let mut bc = BrowserContext::new("BID-fetch-owner-route".to_owned());
bc.set_active_target_id("TID-fetch-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
@@ -529,10 +532,10 @@ async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {
let staged = bc
.parked_page_session_state("TID-fetch-background")
.expect("background fetch config should stay parked");
- assert!(staged.fetch_config.is_enabled());
- assert_eq!(staged.fetch_config.patterns().len(), 1);
+ assert!(staged.fetch_owner.config_snapshot().is_enabled());
+ assert_eq!(staged.fetch_owner.config_snapshot().patterns().len(), 1);
assert_eq!(
- staged.fetch_config.patterns()[0].resource_type_filter,
+ staged.fetch_owner.config_snapshot().patterns()[0].resource_type_filter,
Some(FetchResourceTypeFilter::Xhr)
);
}
@@ -598,7 +601,7 @@ async fn enable_targets_inactive_owner_without_activation() {
#[tokio::test(flavor = "multi_thread")]
async fn disable_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -607,9 +610,9 @@ async fn disable_targets_loaded_background_owner_without_promotion() {
let mut bc = BrowserContext::new("BID-fetch-disable-bg".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
bc.mutate_parked_page_session_state("TID-background", |state| {
- state.fetch_config.configure(
+ state.fetch_owner.configure(
Some("SID-background".to_owned()),
false,
vec![crate::conn::FetchInterceptionPattern {
diff --git a/moli-protocol/src/domains/fetch/tests/mod.rs b/moli-protocol/src/domains/fetch/tests/mod.rs
index fcf89d696..3c48c4d1f 100644
--- a/moli-protocol/src/domains/fetch/tests/mod.rs
+++ b/moli-protocol/src/domains/fetch/tests/mod.rs
@@ -8,7 +8,7 @@ use super::{
PendingFetchNavigation, emit_auth_required, encode_basic_auth, extract_auth_challenge,
request_auth_for_challenge, response_headers_from_params, url_pattern_matches,
};
-use crate::conn::{BackgroundTarget, BrowserContext, NETWORK_ERROR_PAGE_URL};
+use crate::conn::{BrowserContext, NETWORK_ERROR_PAGE_URL, PageTargetHost};
use crate::domains::page::LOADER_ID;
use crate::testing::{
TestContext, wait_until_frame_stopped_loading, wait_until_message, wait_until_messages,
@@ -62,7 +62,7 @@ async fn with_loaded_http_background_document(
background_session_id: &str,
background_target_id: &str,
) {
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
background_target_id.to_owned(),
Some(background_session_id.to_owned()),
url.to_owned(),
@@ -71,7 +71,7 @@ async fn with_loaded_http_background_document(
let mut bc = BrowserContext::new("BID-1".into());
bc.attach_active_session(active_session_id.to_owned());
bc.set_active_target_id(active_target_id.to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(url, Some(background_session_id))
.await;
diff --git a/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs b/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs
index a8ee88f12..007e5ce69 100644
--- a/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs
+++ b/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs
@@ -472,11 +472,8 @@ async fn runtime_child_frame_fetch_subresource_interception_uses_child_frame_att
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &top_url, "SID-1", "TID-1").await;
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -5185,11 +5182,8 @@ async fn close_aborts_paused_response_stage_runtime_xhr_subresource() {
let xhr_url = format!("http://{addr}/xhr");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -5521,11 +5515,8 @@ async fn close_aborts_paused_runtime_xhr_auth_subresource() {
let protected_url = format!("http://{addr}/protected");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
diff --git a/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs b/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs
index cc4fdcc48..596b3ecf2 100644
--- a/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs
+++ b/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs
@@ -1776,11 +1776,8 @@ async fn continue_request_returns_before_delayed_subresource_response() {
let api_url = format!("http://{addr}/api");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -5464,11 +5461,8 @@ async fn runtime_fetch_subresource_pauses_until_continue_request_then_resolves_p
let api_url = format!("http://{addr}/api");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -5617,11 +5611,8 @@ async fn runtime_fetch_subresource_continue_request_fails_when_network_offline()
"TID-1",
)
.await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -5747,11 +5738,8 @@ async fn runtime_fetch_subresource_request_animation_frame_pauses_until_continue
let api_url = format!("http://{addr}/api");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -5927,11 +5915,8 @@ async fn runtime_fetch_subresource_queue_microtask_pauses_until_continue_request
let api_url = format!("http://{addr}/api");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -7756,11 +7741,8 @@ async fn close_aborts_paused_runtime_fetch_subresource() {
let api_url = format!("http://{addr}/api");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
diff --git a/moli-protocol/src/domains/fetch/tests/runtime_xhr.rs b/moli-protocol/src/domains/fetch/tests/runtime_xhr.rs
index 6e50ffa2b..8eeb196cc 100644
--- a/moli-protocol/src/domains/fetch/tests/runtime_xhr.rs
+++ b/moli-protocol/src/domains/fetch/tests/runtime_xhr.rs
@@ -160,11 +160,8 @@ async fn runtime_xhr_subresource_pauses_until_continue_request_then_loads_respon
let xhr_url = format!("http://{addr}/xhr");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -464,11 +461,8 @@ async fn runtime_xhr_subresource_request_animation_frame_pauses_until_continue_r
let xhr_url = format!("http://{addr}/xhr");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
@@ -625,11 +619,8 @@ async fn runtime_xhr_subresource_queue_microtask_pauses_until_continue_request_t
let xhr_url = format!("http://{addr}/xhr");
let mut ctx = TestContext::new();
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.sent.clear();
diff --git a/moli-protocol/src/domains/input.rs b/moli-protocol/src/domains/input.rs
index 3c04d7c13..ea990291a 100644
--- a/moli-protocol/src/domains/input.rs
+++ b/moli-protocol/src/domains/input.rs
@@ -2198,7 +2198,7 @@ mod producer_tests {
let mut conn = CdpConnection::default();
let mut bc = BrowserContext::new("BID-typed".into());
bc.attach_active_session("SID-typed");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
conn.browser_context = Some(bc);
@@ -2281,7 +2281,7 @@ mod producer_tests {
let mut bc = BrowserContext::new("BID-document-collision".into());
bc.set_active_target_id("TID-document-collision");
bc.attach_active_session("SID-document-collision");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
conn.browser_context = Some(bc);
@@ -2351,7 +2351,7 @@ mod producer_tests {
let mut bc = BrowserContext::new("BID-page-replacement".into());
bc.set_active_target_id("TID-page-replacement");
bc.attach_active_session("SID-page-replacement");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
conn.browser_context = Some(bc);
@@ -2465,7 +2465,7 @@ mod producer_tests {
let mut conn = CdpConnection::default();
let mut bc = BrowserContext::new("BID-1".into());
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
conn.browser_context = Some(bc);
@@ -2512,7 +2512,7 @@ mod producer_tests {
let mut conn = CdpConnection::default();
let mut bc = BrowserContext::new("BID-context".into());
bc.attach_active_session("SID-context");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
conn.browser_context = Some(bc);
diff --git a/moli-protocol/src/domains/inspector.rs b/moli-protocol/src/domains/inspector.rs
index 32654d893..ebb5cbf6a 100644
--- a/moli-protocol/src/domains/inspector.rs
+++ b/moli-protocol/src/domains/inspector.rs
@@ -68,7 +68,7 @@ mod tests {
use moli_core::page::RendererServiceWorkerVersionStatus;
use crate::{
- conn::{BackgroundTarget, BrowserContext, ServiceWorkerTargetState},
+ conn::{BrowserContext, PageTargetHost, ServiceWorkerTargetState},
testing::TestContext,
};
use serde_json::json;
@@ -86,7 +86,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -99,7 +99,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -173,7 +173,7 @@ mod tests {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active");
bc.attach_active_session("SID-active");
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".into(),
Some("SID-background".into()),
"about:blank#background".into(),
@@ -197,8 +197,8 @@ mod tests {
assert_eq!(bc.active_target_id(), Some("TID-active"));
assert!(
bc.parked_page_session_state("TID-background")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_target_crashed_delivered())
);
@@ -259,17 +259,16 @@ mod tests {
let mut bc = BrowserContext::new("BID-1".into());
bc.attach_active_session("SID-active");
bc.set_active_target_id("TID-A");
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-B".into(),
- Some("SID-B".into()),
- crate::conn::TargetIdentityState::new(
- "about:blank#background".into(),
- "null".into(),
- "InsecureScheme".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-B".into(),
+ Some("SID-B".into()),
+ crate::conn::TargetIdentityState::new(
+ "about:blank#background".into(),
+ "null".into(),
+ "InsecureScheme".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
bc.active_target
.owner_state
.target_crash_state
@@ -288,13 +287,12 @@ mod tests {
{
let bc = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
assert!(bc.parked_page_session_state("TID-B").is_some_and(|state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
}));
@@ -305,7 +303,7 @@ mod tests {
ctx.expect_result(5, json!({}), Some("SID-B"));
let bc = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
diff --git a/moli-protocol/src/domains/io.rs b/moli-protocol/src/domains/io.rs
index 7d8e4e859..3f6bfddc5 100644
--- a/moli-protocol/src/domains/io.rs
+++ b/moli-protocol/src/domains/io.rs
@@ -376,7 +376,7 @@ mod tests {
use super::{DEFAULT_IO_READ_SIZE, read_io_stream_state};
use crate::{
- conn::{BackgroundTarget, BrowserContext, CdpCommandTaskStep, IoStreamState},
+ conn::{BrowserContext, CdpCommandTaskStep, IoStreamState, PageTargetHost},
testing::TestContext,
};
@@ -542,7 +542,7 @@ mod tests {
let mut bc = BrowserContext::new("BID-io-owner".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank#background".to_owned(),
diff --git a/moli-protocol/src/domains/log.rs b/moli-protocol/src/domains/log.rs
index 3c26b581c..41d725867 100644
--- a/moli-protocol/src/domains/log.rs
+++ b/moli-protocol/src/domains/log.rs
@@ -664,11 +664,18 @@ mod tests {
ctx.expect_result(1, json!({}), Some("SID-background"));
let active = ctx.conn.browser_context.as_ref().expect("browser context");
- assert!(!active.devtools_session_state.page_session_state.log_enabled);
+ assert!(
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled
+ );
assert!(
active
.parked_page_session_state("TID-background")
- .is_some_and(|state| state.devtools_session_state.page_session_state.log_enabled),
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled),
"background target should stage Log.enable"
);
}
@@ -851,7 +858,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.log_violation_thresholds;
assert_eq!(thresholds.len(), 1);
@@ -868,7 +875,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.log_violation_thresholds
.is_empty()
diff --git a/moli-protocol/src/domains/network.rs b/moli-protocol/src/domains/network.rs
index 221e7667e..9fca28945 100644
--- a/moli-protocol/src/domains/network.rs
+++ b/moli-protocol/src/domains/network.rs
@@ -63,7 +63,6 @@ pub(crate) use agent::TargetIoStreamRead;
pub(crate) use agent::{
CapturedRequestBody, CapturedResponseBody, CollectedNetworkDataArtifact,
NetworkBacklogPreferredRequestId, RetiringTargetNetworkAgentState, TargetNetworkAgentState,
- TargetNetworkArtifacts,
};
pub(crate) use backlog::{
NetworkBacklogProjectionContext, emit_pending_network_backlog_activity_background_events,
@@ -419,8 +418,7 @@ fn top_level_target_ids(conn: &CdpConnection) -> Vec<String> {
.into_iter()
.chain(
browser_context
- .background_targets
- .iter()
+ .background_targets()
.map(|target| target.target_id().to_owned()),
)
})
diff --git a/moli-protocol/src/domains/network/activity.rs b/moli-protocol/src/domains/network/activity.rs
index 1c4f36332..474aa5d61 100644
--- a/moli-protocol/src/domains/network/activity.rs
+++ b/moli-protocol/src/domains/network/activity.rs
@@ -504,7 +504,7 @@ mod tests {
use super::NetworkPreparedOutputs;
use crate::{
- conn::{BackgroundTarget, BrowserContext, CdpConnection, PendingSubresourceFetchRequest},
+ conn::{BrowserContext, CdpConnection, PageTargetHost, PendingSubresourceFetchRequest},
domains::activity::{ProtocolOutputPayloads, ProtocolOutputProjectionContext},
testing::{TestContext, wait_until_message, wait_until_messages},
};
@@ -920,7 +920,7 @@ mod tests {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active");
bc.attach_active_session("SID-active");
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
page_url.clone(),
diff --git a/moli-protocol/src/domains/network/agent.rs b/moli-protocol/src/domains/network/agent.rs
index 1fabaf974..ecf948f35 100644
--- a/moli-protocol/src/domains/network/agent.rs
+++ b/moli-protocol/src/domains/network/agent.rs
@@ -481,10 +481,6 @@ impl TargetNetworkAgentState {
.remove_session_cursors(session_id);
}
- pub(crate) fn snapshot_artifacts(&self) -> TargetNetworkArtifacts {
- self.artifacts.clone()
- }
-
pub(crate) fn collected_network_data_artifacts(&self) -> Vec<CollectedNetworkDataArtifact> {
self.artifacts.collected_network_data_artifacts()
}
@@ -542,15 +538,48 @@ impl TargetNetworkAgentState {
.claim_completed_request_id(request_id)
}
- pub(crate) fn restore_artifacts(&mut self, artifacts: TargetNetworkArtifacts) {
- self.artifacts = artifacts;
- }
-
#[cfg(test)]
pub(crate) fn allocate_network_request_id(&mut self) -> String {
self.artifacts.allocate_network_request_id()
}
+ #[cfg(test)]
+ pub(crate) fn set_session_observation_cursor_at_counts_for_test(
+ &mut self,
+ session_id: Option<&str>,
+ subresource_count: usize,
+ websocket_count: usize,
+ ) {
+ self.artifacts.set_session_observation_cursor_at_counts(
+ session_id,
+ subresource_count,
+ websocket_count,
+ );
+ }
+
+ #[cfg(test)]
+ pub(crate) fn emitted_subresource_record_count_for_session_for_test(
+ &self,
+ session_id: Option<&str>,
+ ) -> usize {
+ self.artifacts
+ .emitted_subresource_record_count_for_session(session_id)
+ }
+
+ #[cfg(test)]
+ pub(crate) fn emitted_websocket_event_count_for_session_for_test(
+ &self,
+ session_id: Option<&str>,
+ ) -> usize {
+ self.artifacts
+ .emitted_websocket_event_count_for_session(session_id)
+ }
+
+ #[cfg(test)]
+ pub(crate) fn artifacts_are_default_for_test(&self) -> bool {
+ self.artifacts == TargetNetworkArtifacts::default()
+ }
+
#[cfg(test)]
pub(crate) fn record_captured_response_body(
&mut self,
@@ -1438,7 +1467,7 @@ impl CapturedResponseBodyStore {
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct TargetNetworkArtifacts {
+struct TargetNetworkArtifacts {
request_id_allocator: TargetNetworkRequestIdAllocator,
body_artifacts: TargetNetworkBodyArtifacts,
subresource_network_artifacts: SubresourceNetworkArtifacts,
@@ -1451,7 +1480,8 @@ impl TargetNetworkArtifacts {
self.request_id_allocator.allocate_request_id()
}
- pub(crate) fn set_session_observation_cursor_at_counts(
+ #[cfg(test)]
+ fn set_session_observation_cursor_at_counts(
&mut self,
session_id: Option<&str>,
subresource_record_count: usize,
@@ -1466,32 +1496,10 @@ impl TargetNetworkArtifacts {
);
}
- pub(crate) fn remove_session_observation_cursor(&mut self, session_id: Option<&str>) {
- self.subresource_network_artifacts
- .remove_session_cursor(session_id);
- self.websocket_network_artifacts
- .remove_session_cursors(session_id);
- }
-
- pub(crate) fn remove_captured_response_body_visibility_for_session(
- &mut self,
- session_id: Option<&str>,
- ) {
- self.body_artifacts.remove_session_visibility(session_id);
- }
-
- pub(crate) fn clear_captured_response_bodies(&mut self) {
- self.body_artifacts.clear_captured_response_bodies();
- }
-
- pub(crate) fn collected_network_data_artifacts(&self) -> Vec<CollectedNetworkDataArtifact> {
+ fn collected_network_data_artifacts(&self) -> Vec<CollectedNetworkDataArtifact> {
self.body_artifacts.collected_network_data_artifacts()
}
- pub(crate) fn clear_websocket_request_ids(&mut self) {
- self.websocket_network_artifacts.clear_request_ids();
- }
-
#[cfg(test)]
pub(crate) fn emitted_subresource_record_count_for_session(
&self,
diff --git a/moli-protocol/src/domains/network/settings.rs b/moli-protocol/src/domains/network/settings.rs
index 0475fd671..eba5711b8 100644
--- a/moli-protocol/src/domains/network/settings.rs
+++ b/moli-protocol/src/domains/network/settings.rs
@@ -61,9 +61,9 @@ pub(super) fn clear_browser_cache_command_output_plan(
Err((code, message)) => return CommandOutputPlan::error(code, message),
};
bc.clear_network_body_artifacts();
- bc.active_target
- .fetch_owner
- .drop_active_fetch_response_body_streams();
+ for target in bc.page_targets.iter_mut() {
+ target.fetch_owner.drop_active_fetch_response_body_streams();
+ }
if let Err(message) = bc.clear_http_cache() {
return CommandOutputPlan::error(-32000, message);
}
diff --git a/moli-protocol/src/domains/network/tests/blocked_urls.rs b/moli-protocol/src/domains/network/tests/blocked_urls.rs
index b8806af5b..7ee9c3cd6 100644
--- a/moli-protocol/src/domains/network/tests/blocked_urls.rs
+++ b/moli-protocol/src/domains/network/tests/blocked_urls.rs
@@ -250,14 +250,14 @@ async fn background_set_blocked_urls_updates_loaded_owner_page_without_promotion
ctx.conn.browser_context = None;
ctx.sent.clear();
- let background = BackgroundTarget::new(
+ let background = PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
TargetPageSlot::empty_for_test_fixture(),
);
let mut inactive = BrowserContext::new("BID-background".to_owned());
- inactive.background_targets.push(background);
+ inactive.insert_page_target_host(background);
ctx.conn.inactive_browser_contexts.push(inactive);
ctx.install_navigation_fixture_for_session_owner(&page_url, Some("SID-background"))
.await;
diff --git a/moli-protocol/src/domains/network/tests/cache.rs b/moli-protocol/src/domains/network/tests/cache.rs
index 849f170fa..b9db94bc0 100644
--- a/moli-protocol/src/domains/network/tests/cache.rs
+++ b/moli-protocol/src/domains/network/tests/cache.rs
@@ -616,7 +616,7 @@ async fn devtools_set_cache_behavior_global_updates_existing_targets_and_default
let mut ctx = TestContext::new();
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
- bc.background_targets.push(BackgroundTarget::new(
+ bc.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
None,
TargetIdentityState::about_blank(),
@@ -660,8 +660,7 @@ async fn devtools_set_cache_behavior_global_updates_existing_targets_and_default
assert!(
ctx.conn
.new_browser_context("BID-future".to_owned())
- .network_policy
- .cache_disabled()
+ .global_cache_disabled
);
}
@@ -670,7 +669,7 @@ async fn devtools_set_cache_behavior_contexts_only_updates_requested_targets() {
let mut ctx = TestContext::new();
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
- bc.background_targets.push(BackgroundTarget::new(
+ bc.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
None,
TargetIdentityState::about_blank(),
@@ -711,8 +710,7 @@ async fn devtools_set_cache_behavior_contexts_only_updates_requested_targets() {
assert!(
!ctx.conn
.new_browser_context("BID-future".to_owned())
- .network_policy
- .cache_disabled()
+ .global_cache_disabled
);
}
@@ -778,8 +776,7 @@ async fn devtools_set_cache_behavior_without_contexts_sets_future_default() {
assert!(
ctx.conn
.new_browser_context("BID-future".to_owned())
- .network_policy
- .cache_disabled()
+ .global_cache_disabled
);
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-protocol/src/domains/network/tests/cookies.rs b/moli-protocol/src/domains/network/tests/cookies.rs
index 624c70973..ea8a9e99d 100644
--- a/moli-protocol/src/domains/network/tests/cookies.rs
+++ b/moli-protocol/src/domains/network/tests/cookies.rs
@@ -181,7 +181,7 @@ async fn background_target_user_agent_override_reaches_replacement_document() {
true,
)
.expect("new BrowserContext owner should be live");
- ctx.conn.replace_navigation_engine(engine);
+ ctx.conn.replace_standalone_navigation_engine(engine);
ctx.conn.browser_context = Some(browser_context);
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/network/tests/mod.rs b/moli-protocol/src/domains/network/tests/mod.rs
index 2a763fbbe..f71cb6158 100644
--- a/moli-protocol/src/domains/network/tests/mod.rs
+++ b/moli-protocol/src/domains/network/tests/mod.rs
@@ -21,8 +21,8 @@ use crate::testing::{
};
use crate::{
conn::{
- BackgroundTarget, BrowserContext, CapturedBody, CdpConnection, DocumentBodySource,
- NETWORK_ERROR_PAGE_URL, NavigationDispatchState, TargetIdentityState, TargetPageSlot,
+ BrowserContext, CapturedBody, CdpConnection, DocumentBodySource, NETWORK_ERROR_PAGE_URL,
+ NavigationDispatchState, PageTargetHost, TargetIdentityState, TargetPageSlot,
},
domains::page::LOADER_ID,
};
diff --git a/moli-protocol/src/domains/network/tests/response_body.rs b/moli-protocol/src/domains/network/tests/response_body.rs
index 98d622a97..d28aaf6b1 100644
--- a/moli-protocol/src/domains/network/tests/response_body.rs
+++ b/moli-protocol/src/domains/network/tests/response_body.rs
@@ -1682,7 +1682,7 @@ async fn network_data_collector_membership_uses_recorded_target_scope() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("bidi-session-1".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-other".to_owned(),
None,
"about:blank".to_owned(),
@@ -1805,7 +1805,7 @@ async fn network_data_collector_gated_body_without_match_is_not_readable() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("bidi-session-1".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-other".to_owned(),
None,
"about:blank".to_owned(),
diff --git a/moli-protocol/src/domains/network/tests/session.rs b/moli-protocol/src/domains/network/tests/session.rs
index a0c48a3ed..65412ab08 100644
--- a/moli-protocol/src/domains/network/tests/session.rs
+++ b/moli-protocol/src/domains/network/tests/session.rs
@@ -607,7 +607,7 @@ async fn background_fetch_runtime_activity_broadcasts_to_auxiliary_network_sessi
let page_url = format!("http://{addr}/page");
let mut ctx = TestContext::new();
- let target = BackgroundTarget::new(
+ let target = PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
@@ -615,7 +615,7 @@ async fn background_fetch_runtime_activity_broadcasts_to_auxiliary_network_sessi
);
let mut bc = BrowserContext::new("BID-background".into());
- bc.background_targets.push(target);
+ bc.insert_page_target_host(target);
assert!(
bc.assign_auxiliary_session_to_target("TID-background", "SID-aux-background".to_owned())
);
@@ -785,7 +785,7 @@ async fn get_response_body_reads_background_auxiliary_target_slot() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"https://background.example/".to_owned(),
diff --git a/moli-protocol/src/domains/observable_output/emission.rs b/moli-protocol/src/domains/observable_output/emission.rs
index 4f82aafc2..92cd2a1b1 100644
--- a/moli-protocol/src/domains/observable_output/emission.rs
+++ b/moli-protocol/src/domains/observable_output/emission.rs
@@ -346,7 +346,7 @@ mod tests {
use serde_json::json;
use crate::conn::{
- BackgroundProtocolEvent, BackgroundTarget, BrowserContext, TargetIdentityState,
+ BackgroundProtocolEvent, BrowserContext, PageTargetHost, TargetIdentityState,
TargetPageSlot,
};
use crate::domains::observable_output::{
@@ -407,10 +407,12 @@ mod tests {
.active_target
.runtime_slot
.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.devtools_session_state.page_session_state.log_enabled = true;
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
ctx.conn.browser_context = Some(bc);
let queue = TargetObservableOutputQueue::for_test(vec![
@@ -426,13 +428,16 @@ mod tests {
bc.target_url(),
bc.page_attachment_id()
.expect("loaded Page must have an attachment id"),
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
- bc.devtools_session_state.page_session_state.log_enabled,
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled,
true,
&bc.active_target.owner_state,
- &bc.devtools_session_state.console_output_session_state,
+ &bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .console_output_session_state,
Some("SID-1"),
);
let mut duplicate_slot =
@@ -491,7 +496,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context should be loaded")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.log_lifecycle_entries
== 1,
@@ -540,7 +545,7 @@ mod tests {
.active_target
.runtime_slot
.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -602,7 +607,7 @@ mod tests {
.active_target
.runtime_slot
.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -663,7 +668,7 @@ mod tests {
.await
.expect("first test page should load");
let _ = bc.replace_loaded_page(Some(first_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -685,7 +690,7 @@ mod tests {
.expect("browser context should remain loaded");
let _ = bc.replace_loaded_page(Some(second_page));
bc.set_target_url(page_url.to_owned());
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
}
@@ -732,18 +737,17 @@ mod tests {
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
let _ = bc.replace_loaded_page(Some(active_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.background_targets.push(BackgroundTarget::new(
+ bc.insert_page_target_host(PageTargetHost::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::with_url("data:text/html,background-owner".to_owned()),
TargetPageSlot::with_loaded_page_for_test(background_page),
));
bc.mutate_parked_page_session_state("TID-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
});
@@ -821,18 +825,17 @@ mod tests {
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
let _ = bc.replace_loaded_page(Some(active_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.background_targets.push(BackgroundTarget::new(
+ bc.insert_page_target_host(PageTargetHost::new(
"TID-promoted".to_owned(),
Some("SID-promoted".to_owned()),
TargetIdentityState::with_url("data:text/html,promoted-owner".to_owned()),
TargetPageSlot::with_loaded_page_for_test(promoted_page),
));
bc.mutate_parked_page_session_state("TID-promoted", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
});
@@ -942,7 +945,7 @@ mod tests {
.await
.expect("test page should load");
let _ = bc.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -1000,7 +1003,7 @@ mod tests {
.await
.expect("test page should load");
let _ = bc.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -1055,7 +1058,7 @@ mod tests {
.await
.expect("test page should load");
let _ = bc.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -1109,10 +1112,10 @@ mod tests {
.await
.expect("test page should load");
let _ = bc.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.renderer_runtime_agent_owns_page_console_api_events = true;
ctx.conn.browser_context = Some(bc);
@@ -1185,7 +1188,7 @@ mod tests {
.await
.expect("test page should load");
let _ = bc.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -1221,7 +1224,7 @@ mod tests {
.await
.expect("first test page should load");
let _ = bc.replace_loaded_page(Some(first_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -1249,7 +1252,7 @@ mod tests {
.expect("browser context should remain loaded");
let _ = bc.replace_loaded_page(Some(second_page));
bc.set_target_url(page_url.to_owned());
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
}
@@ -1281,7 +1284,7 @@ mod tests {
.await
.expect("first test page should load");
let _ = bc.replace_loaded_page(Some(first_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -1309,7 +1312,7 @@ mod tests {
.expect("browser context should remain loaded");
let _ = bc.replace_loaded_page(Some(second_page));
bc.set_target_url(page_url.to_owned());
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
}
diff --git a/moli-protocol/src/domains/observable_output/output_queue.rs b/moli-protocol/src/domains/observable_output/output_queue.rs
index 5df548eb7..a3361e616 100644
--- a/moli-protocol/src/domains/observable_output/output_queue.rs
+++ b/moli-protocol/src/domains/observable_output/output_queue.rs
@@ -1606,10 +1606,12 @@ mod tests {
fn observable_backlog_queue_reports_console_and_log_ranges_from_owner_cursors() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_target_url("http://example.test/observable".to_owned());
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.devtools_session_state.page_session_state.log_enabled = true;
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
let queue = TargetObservableOutputQueue {
observable_output_items: vec![
ScriptObservableOutputItem::ConsoleMessage("warn: observable".to_owned()),
@@ -1622,13 +1624,16 @@ mod tests {
let mut prepared = queue.console_log_backlog_ranges(
bc.target_url(),
page_attachment_id(1),
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
- bc.devtools_session_state.page_session_state.log_enabled,
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled,
true,
&bc.active_target.owner_state,
- &bc.devtools_session_state.console_output_session_state,
+ &bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .console_output_session_state,
None,
);
let console = prepared
@@ -1672,7 +1677,7 @@ mod tests {
fn observable_backlog_queue_filters_single_raw_queue_by_kind_cursor() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_target_url("http://example.test/observable".to_owned());
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
bc.active_target
@@ -1692,13 +1697,16 @@ mod tests {
let mut prepared = queue.console_log_backlog_ranges(
bc.target_url(),
page_attachment_id(1),
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled,
- bc.devtools_session_state.page_session_state.log_enabled,
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled,
true,
&bc.active_target.owner_state,
- &bc.devtools_session_state.console_output_session_state,
+ &bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .console_output_session_state,
None,
);
let console = prepared
diff --git a/moli-protocol/src/domains/observable_output/presence.rs b/moli-protocol/src/domains/observable_output/presence.rs
index a0e950224..bc98ecf18 100644
--- a/moli-protocol/src/domains/observable_output/presence.rs
+++ b/moli-protocol/src/domains/observable_output/presence.rs
@@ -607,7 +607,7 @@ mod tests {
bc.active_target
.runtime_slot
.set_page_attachment_id_for_test(1);
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
conn.browser_context = Some(bc);
@@ -655,11 +655,13 @@ mod tests {
bc.active_target
.runtime_slot
.set_page_attachment_id_for_test(1);
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.devtools_session_state.page_session_state.log_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = false;
conn.browser_context = Some(bc);
@@ -704,7 +706,7 @@ mod tests {
bc.active_target
.runtime_slot
.set_page_attachment_id_for_test(1);
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
conn.browser_context = Some(bc);
@@ -743,10 +745,12 @@ mod tests {
.active_target
.runtime_slot
.replace_loaded_page(Some(page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.devtools_session_state.page_session_state.log_enabled = true;
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
ctx.conn.browser_context = Some(bc);
let outputs = observable_backlog_activity_outputs(&ctx.conn, None);
diff --git a/moli-protocol/src/domains/observable_output/runtime_emission.rs b/moli-protocol/src/domains/observable_output/runtime_emission.rs
index a11d85952..eddb81c8d 100644
--- a/moli-protocol/src/domains/observable_output/runtime_emission.rs
+++ b/moli-protocol/src/domains/observable_output/runtime_emission.rs
@@ -229,7 +229,7 @@ mod tests {
.browser_context
.as_mut()
.expect("browser context should exist");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
}
@@ -320,9 +320,8 @@ mod tests {
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
inactive
- .auxiliary_devtools_session_states
- .entry("SID-aux".to_owned())
- .or_default()
+ .devtools_sessions
+ .ensure_attached("SID-aux")
.runtime_session_state
.runtime_frontend_enabled = true;
assert!(inactive.assign_auxiliary_session_to_target("TID-inactive", "SID-aux".to_owned()));
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index a514a756a..6e262bb29 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -1399,7 +1399,7 @@ async fn bring_session_route_to_front_async(
browser_context_id,
target_id,
}
- | CdpSessionRoute::BackgroundTarget {
+ | CdpSessionRoute::PageTargetHost {
browser_context_id,
target_id,
} => (browser_context_id, target_id),
@@ -3455,7 +3455,7 @@ mod producer_tests {
bc.set_active_target_id("TID-activity-order");
bc.set_target_url("https://example.test/page".to_owned());
bc.attach_active_session("SID-activity-order");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled = true;
conn.browser_context = Some(bc);
@@ -3611,10 +3611,10 @@ mod producer_tests {
bc.set_active_target_id("TID-later-activity-order");
bc.set_target_url("https://example.test/page".to_owned());
bc.attach_active_session("SID-later-activity-order");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(bc);
@@ -3777,13 +3777,13 @@ mod producer_tests {
bc.set_target_url("https://example.test/page".to_owned());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
conn.browser_context = Some(bc);
@@ -3858,10 +3858,10 @@ mod producer_tests {
bc.set_target_url("https://example.test/page".to_owned());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(bc);
@@ -3994,7 +3994,7 @@ mod producer_tests {
bc.set_target_url("https://top.example/page".to_owned());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(bc);
@@ -4201,10 +4201,10 @@ mod producer_tests {
bc.set_target_url("https://example.test/page".to_owned());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(bc);
@@ -4379,7 +4379,7 @@ mod producer_tests {
bc.set_target_url("https://example.test/page".to_owned());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(bc);
@@ -4546,8 +4546,7 @@ mod producer_tests {
browser_context.set_target_url("https://example.test/page".to_owned());
browser_context.set_active_target_id("TID-child-delivery-route");
browser_context.attach_active_session("SID-child-delivery-route");
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(browser_context);
@@ -4639,7 +4638,7 @@ mod producer_tests {
bc.set_target_url("about:blank".to_owned());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
conn.browser_context = Some(bc);
@@ -4783,8 +4782,7 @@ mod producer_tests {
conn.browser_context
.as_ref()
.unwrap()
- .background_targets
- .len(),
+ .background_target_count(),
1,
"prepared popup should create the owner popup target without reading a loaded page"
);
@@ -4792,8 +4790,8 @@ mod producer_tests {
conn.browser_context
.as_ref()
.unwrap()
- .background_targets
- .first()
+ .background_targets()
+ .next()
.and_then(|target| target.loaded_page())
.is_some_and(|page| moli_url::is_about_blank(page.final_url())),
"target creation should install only the initial empty Document"
diff --git a/moli-protocol/src/domains/page/popup.rs b/moli-protocol/src/domains/page/popup.rs
index 2db7b80e7..8d123dc07 100644
--- a/moli-protocol/src/domains/page/popup.rs
+++ b/moli-protocol/src/domains/page/popup.rs
@@ -306,8 +306,7 @@ mod tests {
assert!(
conn.browser_context_by_id("BID-current")
.expect("current browser context")
- .background_targets
- .is_empty(),
+ .has_no_background_targets(),
"draining from another current session must not redirect the popup"
);
}
@@ -469,8 +468,7 @@ mod tests {
conn.browser_context
.as_ref()
.expect("current browser context")
- .background_targets
- .is_empty()
+ .has_no_background_targets()
);
}
}
diff --git a/moli-protocol/src/domains/page/preload.rs b/moli-protocol/src/domains/page/preload.rs
index f1281fe62..cec8cb33b 100644
--- a/moli-protocol/src/domains/page/preload.rs
+++ b/moli-protocol/src/domains/page/preload.rs
@@ -19,6 +19,7 @@ use crate::domains::runtime::bidi_preload_function_declaration_source;
use super::{PageCommandTaskStep, PendingPageCommandDispatch, PendingPageCommandKind};
use moli_core::page::{CompletedPageCommand, PendingPageCommand, RendererAgentAttachmentId};
+use moli_page_types::DevToolsSessionKey;
#[derive(Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
@@ -274,6 +275,7 @@ fn document_start_script_from_add_preload_command(
match &command.source {
DevToolsPreloadScriptSource::RawScript(source) => Ok(DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: source.clone(),
world_name: command.world_name.clone(),
has_bidi_channel_argument: false,
@@ -298,6 +300,7 @@ fn document_start_script_from_add_preload_command(
let has_bidi_channel_argument = !source.channel_handoffs.is_empty();
Ok(DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: source.source,
world_name: command.world_name.clone(),
has_bidi_channel_argument,
@@ -580,7 +583,8 @@ async fn execute_devtools_single_route_remove_preload_script_command(
});
let remove_result = conn.with_target_owner_state_for_session_mut(None, |owner_state| {
remove_stored_document_start_script_registry_key(
- &mut owner_state.document_start_scripts,
+ owner_state,
+ None,
&script_id,
target_registry_key.clone(),
)
@@ -589,6 +593,7 @@ async fn execute_devtools_single_route_remove_preload_script_command(
return Err(preload_missing_owner_error(conn));
};
if !removed
+ && protocol == DevToolsProtocol::WebDriverBidi
&& let Some((browser_context_id, _)) = owner_identity.as_ref()
&& let Some(browser_context) = conn.browser_context_by_id_mut(browser_context_id)
&& let Some(default_registry_key) =
@@ -1056,14 +1061,24 @@ fn start_devtools_remove_preload_script_command(
) -> PageCommandTaskStep {
let protocol = command.context.protocol;
let script_id = command.script_id.into_string();
+ let renderer_inspector_session_id =
+ conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);
+ let script_owner_session = (protocol == DevToolsProtocol::Cdp).then(|| {
+ DevToolsSessionKey::from_wire_session_id(renderer_inspector_session_id.as_deref())
+ });
let owner_identity = conn.target_owner_identity_for_session(command_session_id);
let target_registry_key = owner_identity.as_ref().map(|(_, target_id)| {
- BrowserContext::target_document_start_script_registry_key(target_id.as_deref(), &script_id)
+ target_document_start_script_registry_key_for_owner(
+ target_id.as_deref(),
+ script_owner_session.as_ref(),
+ &script_id,
+ )
});
let remove_result =
conn.with_target_owner_state_for_session_mut(command_session_id, |owner_state| {
remove_stored_document_start_script_registry_key(
- &mut owner_state.document_start_scripts,
+ owner_state,
+ script_owner_session.as_ref(),
&script_id,
target_registry_key.clone(),
)
@@ -1086,24 +1101,32 @@ fn start_devtools_remove_preload_script_command(
removed = true;
registry_key = Some(default_registry_key);
}
- if !removed && protocol == DevToolsProtocol::WebDriverBidi {
- return PageCommandTaskStep::Complete(CommandOutputPlan::error(-32000, "NoSuchScript"));
+ if !removed {
+ let message = match protocol {
+ DevToolsProtocol::Cdp => "Script not found",
+ DevToolsProtocol::WebDriverClassic | DevToolsProtocol::WebDriverBidi => "NoSuchScript",
+ };
+ return PageCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message));
}
start_document_start_script_remove(conn, command_id, command_session_id, registry_key)
}
fn remove_stored_document_start_script_registry_key(
- scripts: &mut Vec<(String, DocumentStartScript)>,
+ owner_state: &mut crate::conn::TargetOwnerState,
+ owner_session: Option<&DevToolsSessionKey>,
script_id: &str,
fallback_registry_key: Option<String>,
) -> (bool, Option<String>) {
- let Some(index) = scripts
+ let Some(index) = owner_state
+ .document_start_scripts
.iter()
- .position(|(identifier, _)| identifier == script_id)
+ .position(|(identifier, script)| {
+ identifier == script_id && script.devtools_session.as_ref() == owner_session
+ })
else {
return (false, None);
};
- let (_, script) = scripts.remove(index);
+ let (_, script) = owner_state.document_start_scripts.remove(index);
(true, script.registry_key.or(fallback_registry_key))
}
@@ -1409,14 +1432,42 @@ fn restart_create_isolated_world_after_stale_renderer_completion(
fn record_document_start_script(
owner_state: &mut crate::conn::TargetOwnerState,
target_id: Option<&str>,
+ owner_session: Option<&DevToolsSessionKey>,
script: &DocumentStartScript,
) -> RecordedDocumentStartScript {
+ if let Some(owner_session) = owner_session {
+ let identifier = owner_state
+ .document_start_scripts
+ .iter()
+ .filter(|(_, script)| script.devtools_session.as_ref() == Some(owner_session))
+ .filter_map(|(identifier, _)| identifier.parse::<u32>().ok())
+ .max()
+ .unwrap_or(0)
+ .wrapping_add(1)
+ .to_string();
+ let script = script
+ .with_devtools_session(owner_session.clone())
+ .with_registry_key(target_document_start_script_registry_key_for_owner(
+ target_id,
+ Some(owner_session),
+ &identifier,
+ ));
+ owner_state
+ .document_start_scripts
+ .push((identifier.clone(), script.clone()));
+ return RecordedDocumentStartScript {
+ identifier,
+ script,
+ inserted: true,
+ };
+ }
if owner_state.next_document_start_script_id == 0
&& !owner_state.document_start_scripts.is_empty()
{
let max_existing_id = owner_state
.document_start_scripts
.iter()
+ .filter(|(_, script)| script.devtools_session.is_none())
.filter_map(|(identifier, _)| identifier.parse::<u32>().ok())
.max()
.unwrap_or(0);
@@ -1426,7 +1477,9 @@ fn record_document_start_script(
.document_start_scripts
.iter_mut()
.find(|(_, existing)| {
- existing.source == script.source && existing.world_name == script.world_name
+ existing.devtools_session.is_none()
+ && existing.source == script.source
+ && existing.world_name == script.world_name
})
{
let registry_key = existing.registry_key.clone().unwrap_or_else(|| {
@@ -1446,9 +1499,14 @@ fn record_document_start_script(
owner_state.next_document_start_script_id =
owner_state.next_document_start_script_id.wrapping_add(1);
let identifier = owner_state.next_document_start_script_id.to_string();
- let script = script.with_registry_key(
- BrowserContext::target_document_start_script_registry_key(target_id, &identifier),
- );
+ let script = owner_session
+ .map(|owner| script.with_devtools_session(owner.clone()))
+ .unwrap_or_else(|| script.clone())
+ .with_registry_key(target_document_start_script_registry_key_for_owner(
+ target_id,
+ owner_session,
+ &identifier,
+ ));
owner_state
.document_start_scripts
.push((identifier.clone(), script.clone()));
@@ -1459,6 +1517,23 @@ fn record_document_start_script(
}
}
+fn target_document_start_script_registry_key_for_owner(
+ target_id: Option<&str>,
+ owner_session: Option<&DevToolsSessionKey>,
+ identifier: &str,
+) -> String {
+ match owner_session.and_then(DevToolsSessionKey::wire_session_id) {
+ Some(owner_session_id) => {
+ BrowserContext::target_session_document_start_script_registry_key(
+ target_id,
+ owner_session_id,
+ identifier,
+ )
+ }
+ None => BrowserContext::target_document_start_script_registry_key(target_id, identifier),
+ }
+}
+
pub(super) async fn complete_pending_create_isolated_world_command(
conn: &mut CdpConnection,
command_id: Option<u64>,
@@ -1658,11 +1733,21 @@ async fn add_script_to_evaluate_on_new_document_direct_async(
command_context: &mut CommandDispatchContext,
) -> Result<String, DevToolsError> {
let script = document_start_script_from_add_preload_command(&command)?;
+ let renderer_inspector_session_id =
+ conn.target_renderer_runtime_inspector_session_id_for_session(session_id);
+ let script_owner_session = (command.context.protocol == DevToolsProtocol::Cdp).then(|| {
+ DevToolsSessionKey::from_wire_session_id(renderer_inspector_session_id.as_deref())
+ });
let target_id = conn
.target_owner_identity_for_session(session_id)
.and_then(|(_, target_id)| target_id);
let Some(recorded) = conn.with_target_owner_state_for_session_mut(session_id, |owner_state| {
- record_document_start_script(owner_state, target_id.as_deref(), &script)
+ record_document_start_script(
+ owner_state,
+ target_id.as_deref(),
+ script_owner_session.as_ref(),
+ &script,
+ )
}) else {
return Err(preload_missing_owner_error(conn));
};
@@ -1672,8 +1757,7 @@ async fn add_script_to_evaluate_on_new_document_direct_async(
return Ok(identifier);
}
let pending_run_immediately = {
- let renderer_runtime_inspector_session_id =
- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);
+ let renderer_runtime_inspector_session_id = renderer_inspector_session_id;
let slot = match conn.runtime_session_owner_slot_mut(session_id) {
Ok(slot) => slot,
Err(error) => return Err(devtools_preload_internal_error(error)),
@@ -1846,50 +1930,60 @@ mod protocol_neutral_tests {
#[test]
fn target_preload_remove_prefers_stored_registry_key() {
- let mut scripts = vec![(
- "1".to_owned(),
- DocumentStartScript {
- registry_key: Some("target:legacy-active:1".to_owned()),
- source: "globalThis.ready = true;".to_owned(),
- world_name: None,
- has_bidi_channel_argument: false,
- bidi_channel_handoffs: Vec::new(),
- },
- )];
+ let mut owner_state = TargetOwnerState {
+ document_start_scripts: vec![(
+ "1".to_owned(),
+ DocumentStartScript {
+ registry_key: Some("target:legacy-active:1".to_owned()),
+ devtools_session: None,
+ source: "globalThis.ready = true;".to_owned(),
+ world_name: None,
+ has_bidi_channel_argument: false,
+ bidi_channel_handoffs: Vec::new(),
+ },
+ )],
+ ..Default::default()
+ };
let (removed, registry_key) = super::remove_stored_document_start_script_registry_key(
- &mut scripts,
+ &mut owner_state,
+ None,
"1",
Some("target:TID-current:1".to_owned()),
);
assert!(removed);
assert_eq!(registry_key.as_deref(), Some("target:legacy-active:1"));
- assert!(scripts.is_empty());
+ assert!(owner_state.document_start_scripts.is_empty());
}
#[test]
fn target_preload_remove_falls_back_for_legacy_unkeyed_script() {
- let mut scripts = vec![(
- "1".to_owned(),
- DocumentStartScript {
- registry_key: None,
- source: "globalThis.ready = true;".to_owned(),
- world_name: None,
- has_bidi_channel_argument: false,
- bidi_channel_handoffs: Vec::new(),
- },
- )];
+ let mut owner_state = TargetOwnerState {
+ document_start_scripts: vec![(
+ "1".to_owned(),
+ DocumentStartScript {
+ registry_key: None,
+ devtools_session: None,
+ source: "globalThis.ready = true;".to_owned(),
+ world_name: None,
+ has_bidi_channel_argument: false,
+ bidi_channel_handoffs: Vec::new(),
+ },
+ )],
+ ..Default::default()
+ };
let (removed, registry_key) = super::remove_stored_document_start_script_registry_key(
- &mut scripts,
+ &mut owner_state,
+ None,
"1",
Some("target:TID-current:1".to_owned()),
);
assert!(removed);
assert_eq!(registry_key.as_deref(), Some("target:TID-current:1"));
- assert!(scripts.is_empty());
+ assert!(owner_state.document_start_scripts.is_empty());
}
#[test]
@@ -1899,6 +1993,7 @@ mod protocol_neutral_tests {
"1".to_owned(),
DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.ready = true;".to_owned(),
world_name: Some("utility".to_owned()),
has_bidi_channel_argument: false,
@@ -1907,14 +2002,19 @@ mod protocol_neutral_tests {
));
let script = DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.ready = true;".to_owned(),
world_name: Some("utility".to_owned()),
has_bidi_channel_argument: false,
bidi_channel_handoffs: Vec::new(),
};
- let recorded =
- super::record_document_start_script(&mut owner_state, Some("TID-current"), &script);
+ let recorded = super::record_document_start_script(
+ &mut owner_state,
+ Some("TID-current"),
+ None,
+ &script,
+ );
assert!(!recorded.inserted);
assert_eq!(recorded.identifier, "1");
@@ -1938,6 +2038,7 @@ mod protocol_neutral_tests {
"1".to_owned(),
DocumentStartScript {
registry_key: Some("target:legacy-active:1".to_owned()),
+ devtools_session: None,
source: "globalThis.ready = true;".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -1946,14 +2047,19 @@ mod protocol_neutral_tests {
));
let script = DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.ready = true;".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
bidi_channel_handoffs: Vec::new(),
};
- let recorded =
- super::record_document_start_script(&mut owner_state, Some("TID-current"), &script);
+ let recorded = super::record_document_start_script(
+ &mut owner_state,
+ Some("TID-current"),
+ None,
+ &script,
+ );
assert!(!recorded.inserted);
assert_eq!(
@@ -2049,4 +2155,36 @@ mod protocol_neutral_tests {
assert_eq!(out[0]["id"], json!(43));
assert_eq!(out[0]["error"]["message"], json!("BrowserContextNotLoaded"));
}
+
+ #[test]
+ fn primary_cdp_preload_retains_typed_session_ownership() {
+ let mut owner_state = TargetOwnerState::default();
+ let script = DocumentStartScript {
+ registry_key: None,
+ devtools_session: None,
+ source: "globalThis.primaryReady = true;".to_owned(),
+ world_name: Some("utility".to_owned()),
+ has_bidi_channel_argument: false,
+ bidi_channel_handoffs: Vec::new(),
+ };
+ let primary = moli_page_types::DevToolsSessionKey::Primary;
+
+ let recorded = super::record_document_start_script(
+ &mut owner_state,
+ Some("TID-primary"),
+ Some(&primary),
+ &script,
+ );
+
+ assert!(recorded.inserted);
+ assert_eq!(recorded.script.devtools_session.as_ref(), Some(&primary));
+ assert!(
+ owner_state
+ .document_start_scripts
+ .iter()
+ .any(|(identifier, script)| {
+ identifier == "1" && script.devtools_session.as_ref() == Some(&primary)
+ })
+ );
+ }
}
diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rs
index f190a954a..69873989b 100644
--- a/moli-protocol/src/domains/page/tests/capture.rs
+++ b/moli-protocol/src/domains/page/tests/capture.rs
@@ -487,7 +487,7 @@ async fn capture_screenshot_uses_emulated_device_metrics() {
#[tokio::test(flavor = "multi_thread")]
async fn capture_screenshot_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -496,7 +496,7 @@ async fn capture_screenshot_targets_loaded_background_owner_without_promotion()
let mut bc = BrowserContext::new("BID-screenshot-background".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<title>Background Screenshot</title><main>background</main>",
@@ -513,19 +513,15 @@ async fn capture_screenshot_targets_loaded_background_owner_without_promotion()
.browser_context
.as_mut()
.expect("browser context")
- .replace_parked_page_session_state(
- "TID-background".to_owned(),
- crate::conn::ParkedPageSessionState {
- emulated_device_metrics: Some(EmulatedDeviceMetrics {
- width: 320,
- height: 240,
- device_scale_factor: 2.0,
- screen_width: 320,
- screen_height: 240,
- }),
- ..Default::default()
- },
- );
+ .mutate_parked_page_session_state("TID-background", |state| {
+ state.emulated_device_metrics = Some(EmulatedDeviceMetrics {
+ width: 320,
+ height: 240,
+ device_scale_factor: 2.0,
+ screen_width: 320,
+ screen_height: 240,
+ });
+ });
ctx.process_async(json!({
"id": 114,
@@ -952,7 +948,7 @@ async fn get_layout_metrics_queries_live_renderer_for_loaded_pages() {
async fn get_layout_metrics_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let page_url = "data:text/html,<html style='width:2300px;height:1700px'><body style='margin:0;width:2300px;height:1700px'><div style='width:2300px;height:1700px'></div></body></html>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -962,7 +958,7 @@ async fn get_layout_metrics_targets_loaded_background_owner_without_promotion()
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<body>active</body>".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-background"))
.await;
diff --git a/moli-protocol/src/domains/page/tests/dialog.rs b/moli-protocol/src/domains/page/tests/dialog.rs
index 4446c593a..4534f6979 100644
--- a/moli-protocol/src/domains/page/tests/dialog.rs
+++ b/moli-protocol/src/domains/page/tests/dialog.rs
@@ -136,23 +136,20 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {
{
let browser_context = ctx.conn.browser_context.as_mut().unwrap();
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.javascript_dialog_state
.push(dialog("TID-A", "a"));
- browser_context
- .background_targets
- .push(BackgroundTarget::new(
- "TID-B".to_owned(),
- Some("SID-B".to_owned()),
- crate::conn::TargetIdentityState::new(
- "about:blank".to_owned(),
- URL_BASE.to_owned(),
- "Secure".to_owned(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::new(
+ "TID-B".to_owned(),
+ Some("SID-B".to_owned()),
+ crate::conn::TargetIdentityState::new(
+ "about:blank".to_owned(),
+ URL_BASE.to_owned(),
+ "Secure".to_owned(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
assert!(
browser_context
.promote_background_target_to_active_slot_async("TID-B")
@@ -160,14 +157,12 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {
.unwrap()
);
assert!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.javascript_dialog_state
.is_empty()
);
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.javascript_dialog_state
.push(dialog("TID-B", "b"));
@@ -182,8 +177,7 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {
.unwrap()
);
assert_eq!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.javascript_dialog_state
.pending_dialogs(),
@@ -200,8 +194,7 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {
.unwrap()
);
assert_eq!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.javascript_dialog_state
.pending_dialogs(),
diff --git a/moli-protocol/src/domains/page/tests/frame_tree.rs b/moli-protocol/src/domains/page/tests/frame_tree.rs
index 38873f95e..b66c83ae7 100644
--- a/moli-protocol/src/domains/page/tests/frame_tree.rs
+++ b/moli-protocol/src/domains/page/tests/frame_tree.rs
@@ -553,7 +553,7 @@ async fn pending_get_frame_tree_after_page_unload_returns_empty_target_tree() {
async fn get_frame_tree_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let page_url = "data:text/html,<iframe name='background-child'></iframe>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -563,7 +563,7 @@ async fn get_frame_tree_targets_loaded_background_owner_without_promotion() {
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<body>active</body>".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-background"))
.await;
diff --git a/moli-protocol/src/domains/page/tests/lifecycle.rs b/moli-protocol/src/domains/page/tests/lifecycle.rs
index 7cfb51cfd..5f9d6c498 100644
--- a/moli-protocol/src/domains/page/tests/lifecycle.rs
+++ b/moli-protocol/src/domains/page/tests/lifecycle.rs
@@ -99,22 +99,19 @@ fn page_owner_state_commands_complete_through_command_dispatch() {
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_bypass_csp_enabled
);
assert_eq!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("standard"),
Some(&json!("Times New Roman"))
);
assert!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
);
@@ -124,7 +121,9 @@ fn page_owner_state_commands_complete_through_command_dispatch() {
browser_context
.renderer_runtime()
.set_javascript_dialog_handler_enabled(true);
- let page_session_state = &mut browser_context.devtools_session_state.page_session_state;
+ let page_session_state = &mut browser_context.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state;
page_session_state.page_domain_enabled = true;
page_session_state.page_lifecycle_events = true;
page_session_state.page_file_chooser_opened_event_enabled = true;
@@ -148,7 +147,10 @@ fn page_owner_state_commands_complete_through_command_dispatch() {
assert_eq!(messages[0]["result"], json!({}));
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
- assert_page_domain_disabled(&browser_context.devtools_session_state.page_session_state);
+ assert_page_domain_disabled(
+ &browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state,
+ );
assert!(
!browser_context
.renderer_runtime()
@@ -668,7 +670,7 @@ async fn enable_accepts_enable_file_chooser_opened_event_param() {
.await;
ctx.expect_result(101, json!({}), None);
assert!(ctx.conn.browser_context.as_ref().is_some_and(|bc| {
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_file_chooser_opened_event_enabled
}));
@@ -799,11 +801,8 @@ async fn set_lifecycle_events_enabled_sets_flag() {
.await;
ctx.expect_result(1, json!({}), None);
assert!(
- ctx.conn
- .browser_context
- .as_ref()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_ref().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
@@ -1053,8 +1052,7 @@ async fn set_lifecycle_events_enabled_is_session_local_for_active_auxiliary_sess
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
assert!(
- !browser_context
- .devtools_session_state
+ !browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events,
"primary page session should stay disabled"
@@ -1071,7 +1069,7 @@ async fn set_lifecycle_events_enabled_is_session_local_for_active_auxiliary_sess
#[tokio::test(flavor = "multi_thread")]
async fn set_lifecycle_events_enabled_is_session_local_for_background_auxiliary_session() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background-primary".to_owned()),
"about:blank".to_owned(),
@@ -1080,7 +1078,7 @@ async fn set_lifecycle_events_enabled_is_session_local_for_background_auxiliary_
let mut browser_context = BrowserContext::new("BID-background-aux-lifecycle".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context.background_targets.push(background);
+ browser_context.insert_page_target_host(background);
assert!(
browser_context
.assign_auxiliary_session_to_target("TID-background", "SID-background-aux".to_owned())
@@ -1126,8 +1124,7 @@ async fn set_lifecycle_events_enabled_is_session_local_for_background_auxiliary_
.parked_page_session_state("TID-background")
.expect("background target should retain parked page session state");
assert!(
- !parked
- .devtools_session_state
+ !parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events,
"background primary page session should stay disabled"
@@ -1152,7 +1149,10 @@ async fn page_disable_clears_page_handler_state_for_active_auxiliary_session() {
"about:blank",
);
let browser_context = ctx.conn.browser_context.as_mut().unwrap();
- mark_page_domain_enabled(&mut browser_context.devtools_session_state.page_session_state);
+ mark_page_domain_enabled(
+ &mut browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state,
+ );
assert!(browser_context.assign_auxiliary_session_to_target("TID-active", "SID-aux".to_owned()));
enable_page_domain_for_session(&mut ctx.conn, "SID-aux");
@@ -1171,7 +1171,10 @@ async fn page_disable_clears_page_handler_state_for_active_auxiliary_session() {
ctx.expect_result(22, json!({}), Some("SID-aux"));
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
- assert_page_domain_enabled(&browser_context.devtools_session_state.page_session_state);
+ assert_page_domain_enabled(
+ &browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state,
+ );
assert_page_domain_disabled(
ctx.conn
.target_page_session_state_for_session(Some("SID-aux"))
@@ -1182,7 +1185,7 @@ async fn page_disable_clears_page_handler_state_for_active_auxiliary_session() {
#[tokio::test(flavor = "multi_thread")]
async fn page_disable_clears_page_handler_state_for_background_auxiliary_session() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background-primary".to_owned()),
"about:blank#background".to_owned(),
@@ -1190,13 +1193,16 @@ async fn page_disable_clears_page_handler_state_for_background_auxiliary_session
let mut browser_context = BrowserContext::new("BID-background-page-disable".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context.background_targets.push(background);
+ browser_context.insert_page_target_host(background);
assert!(
browser_context
.assign_auxiliary_session_to_target("TID-background", "SID-background-aux".to_owned())
);
browser_context.mutate_parked_page_session_state("TID-background", |state| {
- mark_page_domain_enabled(&mut state.devtools_session_state.page_session_state);
+ mark_page_domain_enabled(
+ &mut state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state,
+ );
});
ctx.conn.browser_context = Some(browser_context);
@@ -1219,7 +1225,9 @@ async fn page_disable_clears_page_handler_state_for_background_auxiliary_session
let parked = browser_context
.parked_page_session_state("TID-background")
.expect("background target should retain parked page session state");
- assert_page_domain_enabled(&parked.devtools_session_state.page_session_state);
+ assert_page_domain_enabled(
+ &parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state,
+ );
assert_page_domain_disabled(
ctx.conn
.target_page_session_state_for_session(Some("SID-background-aux"))
@@ -2200,7 +2208,7 @@ async fn add_script_run_immediately_installs_matching_bindings_into_new_top_leve
#[tokio::test(flavor = "multi_thread")]
async fn document_start_script_run_immediately_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -2209,7 +2217,7 @@ async fn document_start_script_run_immediately_targets_loaded_background_owner_w
let mut bc = BrowserContext::new("BID-1".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<body>background</body>",
@@ -2221,8 +2229,7 @@ async fn document_start_script_run_immediately_targets_loaded_background_owner_w
.as_mut()
.expect("browser context")
.mutate_parked_page_session_state("TID-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
});
@@ -2566,13 +2573,13 @@ async fn crash_notifies_all_attached_sessions_and_marks_browser_context_crashed(
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert!(bc.active_target.owner_state.target_crash_state.is_crashed());
assert!(
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_target_crashed_delivered()
);
assert!(
- bc.auxiliary_devtools_session_states
- .get("SID-aux")
+ bc.devtools_sessions
+ .attached("SID-aux")
.is_some_and(|state| state
.runtime_session_state
.inspector_target_crashed_delivered())
@@ -2624,7 +2631,7 @@ async fn crash_targets_background_owner_without_promotion() {
.load_page_via_runtime_async("data:text/html,<body>background-crash</body>")
.await
.expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let mut background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
background_page.final_url().as_str().to_owned(),
@@ -2635,20 +2642,17 @@ async fn crash_targets_background_owner_without_promotion() {
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
- bc.background_targets.push(background);
- bc.replace_parked_page_session_state(
- "TID-background".to_owned(),
- crate::conn::ParkedPageSessionState {
- devtools_session_state: crate::conn::DevToolsSessionState {
+ bc.insert_page_target_host(background);
+ bc.mutate_parked_page_session_state("TID-background", |state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =
+ crate::conn::DevToolsSessionState {
runtime_session_state: crate::conn::TargetRuntimeSessionState {
inspector_enabled: true,
..Default::default()
},
..Default::default()
- },
- ..Default::default()
- },
- );
+ };
+ });
let background_document_token = bc
.start_document_navigation_for_target(
"TID-background",
@@ -2753,8 +2757,7 @@ async fn crash_aborts_background_paused_navigation_without_promotion() {
.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(BackgroundTarget::with_url(
+ .insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank#background".to_owned(),
@@ -2929,13 +2932,13 @@ async fn close_clears_loaded_page_state_and_emits_detached_events() {
.await
.expect("page should load");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -3021,66 +3024,14 @@ async fn close_clears_loaded_page_state_and_emits_detached_events() {
!bc.accepts_document_body_completion_event(&close_document_token),
"Page.close must reject late body completions for the closed document"
);
- assert_eq!(bc.target_url(), "about:blank");
- assert_eq!(bc.target_security_origin(), crate::conn::URL_BASE);
- assert_eq!(bc.target_secure_context_type(), "Secure");
- assert_eq!(bc.next_network_request_sequence_for_test(), 0);
- assert_eq!(bc.subresource_network_emitted_record_count_for_test(), 0);
- assert_eq!(bc.next_io_stream_sequence_for_test(), 0);
- assert_eq!(
- bc.active_target
- .runtime_slot
- .next_subresource_fetch_request_id_for_test(),
- 0
- );
- assert!(!bc.active_target.owner_state.target_crash_state.is_crashed());
- assert!(
- !bc.devtools_session_state
- .page_session_state
- .page_lifecycle_events
- );
- assert!(
- !bc.devtools_session_state
- .runtime_session_state
- .runtime_frontend_enabled
- );
- assert!(
- !bc.devtools_session_state
- .runtime_session_state
- .inspector_enabled
- );
- assert!(
- !bc.active_target
- .runtime_slot
- .primary_network_events_enabled()
- );
- assert!(!bc.network_policy.cache_disabled());
- assert!(!bc.network_policy.bypass_service_worker());
- assert!(!bc.css_enabled);
- assert!(!bc.active_target.fetch_owner.is_enabled());
- assert!(!bc.active_target.fetch_owner.handle_auth_requests());
- assert!(
- bc.active_target
- .fetch_owner
- .config_snapshot()
- .patterns()
- .is_empty()
- );
- assert!(bc.network_policy.extra_headers().is_empty());
- assert!(bc.captured_response_bodies_empty_for_test());
- assert!(bc.io_streams_empty_for_test());
- assert!(
- !bc.active_target
- .fetch_owner
- .has_pending_fetch_state_for_test()
- );
+ assert!(bc.page_target("TID-1").is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn close_aborts_paused_request_stage_navigation_and_clears_state() {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -3159,37 +3110,29 @@ async fn close_aborts_paused_request_stage_navigation_and_clears_state() {
assert!(!bc.has_active_target());
assert!(!bc.has_active_session());
assert!(!bc.has_loaded_page());
- assert!(
- !bc.active_target
- .fetch_owner
- .has_pending_fetch_state_for_test()
- );
- assert_eq!(bc.target_url(), "about:blank");
+ assert!(bc.page_target("TID-1").is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn close_aborts_background_paused_navigation_without_promotion() {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-active", "SID-active", "about:blank");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank#background".to_owned(),
));
assert!(bc.assign_auxiliary_session_to_target("TID-background", "SID-aux".to_owned()));
- bc.replace_parked_page_session_state(
- "TID-background".to_owned(),
- crate::conn::ParkedPageSessionState {
- devtools_session_state: crate::conn::DevToolsSessionState {
+ bc.mutate_parked_page_session_state("TID-background", |state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =
+ crate::conn::DevToolsSessionState {
runtime_session_state: crate::conn::TargetRuntimeSessionState {
inspector_enabled: true,
..Default::default()
},
..Default::default()
- },
- ..Default::default()
- },
- );
+ };
+ });
ctx.process_async(json!({
"id": 246,
@@ -3331,7 +3274,7 @@ async fn close_aborts_paused_auth_navigation_and_clears_state() {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -3552,7 +3495,7 @@ async fn set_bypass_csp_accepts_valid_params_and_returns_empty_result() {
.await;
ctx.expect_result(2, json!({}), None);
assert!(ctx.conn.browser_context.as_ref().is_some_and(|bc| {
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_bypass_csp_enabled
}));
@@ -3584,16 +3527,14 @@ async fn set_font_families_accepts_object_params_and_returns_empty_result() {
ctx.expect_result(4, json!({}), None);
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert_eq!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("standard"),
Some(&json!("Times New Roman"))
);
assert_eq!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("fixed"),
@@ -3632,7 +3573,7 @@ async fn set_intercept_file_chooser_dialog_accepts_valid_params_and_returns_empt
.await;
ctx.expect_result(51, json!({}), None);
assert!(ctx.conn.browser_context.as_ref().is_some_and(|bc| {
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
}));
@@ -4050,8 +3991,7 @@ async fn start_screencast_is_session_local_for_active_auxiliary_session() {
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
assert!(
- !browser_context
- .devtools_session_state
+ !browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_screencast
.is_active(),
@@ -4068,7 +4008,7 @@ async fn start_screencast_is_session_local_for_active_auxiliary_session() {
#[tokio::test(flavor = "multi_thread")]
async fn start_screencast_is_session_local_for_background_auxiliary_session() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background-primary".to_owned()),
"about:blank#background".to_owned(),
@@ -4076,7 +4016,7 @@ async fn start_screencast_is_session_local_for_background_auxiliary_session() {
let mut browser_context = BrowserContext::new("BID-background-screencast".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context.background_targets.push(background);
+ browser_context.insert_page_target_host(background);
assert!(
browser_context
.assign_auxiliary_session_to_target("TID-background", "SID-background-aux".to_owned())
@@ -4102,8 +4042,7 @@ async fn start_screencast_is_session_local_for_background_auxiliary_session() {
.parked_page_session_state("TID-background")
.expect("background target should retain parked page session state");
assert!(
- !parked
- .devtools_session_state
+ !parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_screencast
.is_active(),
diff --git a/moli-protocol/src/domains/page/tests/mod.rs b/moli-protocol/src/domains/page/tests/mod.rs
index 2926e750d..87bf3eb83 100644
--- a/moli-protocol/src/domains/page/tests/mod.rs
+++ b/moli-protocol/src/domains/page/tests/mod.rs
@@ -1,9 +1,8 @@
use super::{LOADER_ID, build_mhtml_snapshot, child_frame_security_identity};
-use crate::conn::DocumentStartScript;
use crate::conn::{
- BackgroundTarget, BrowserContext, CdpCommandTaskStep, CdpSchedulerEvent, EmulatedDeviceMetrics,
- FetchInterceptionPattern, FetchRequestStage, NETWORK_ERROR_PAGE_URL, PendingCdpCommandDispatch,
- ServiceWorkerTargetState, URL_BASE,
+ BrowserContext, CdpCommandTaskStep, CdpSchedulerEvent, EmulatedDeviceMetrics,
+ FetchInterceptionPattern, FetchRequestStage, NETWORK_ERROR_PAGE_URL, PageTargetHost,
+ PendingCdpCommandDispatch, ServiceWorkerTargetState, URL_BASE,
};
use crate::devtools_runtime::{
AutomationEvent, DevToolsCommand, DevToolsCommandContext, DevToolsCommandResult,
diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rs
index 0493218be..8aee16f58 100644
--- a/moli-protocol/src/domains/page/tests/navigation.rs
+++ b/moli-protocol/src/domains/page/tests/navigation.rs
@@ -1217,18 +1217,16 @@ async fn navigation_history_is_preserved_per_parked_target() {
{
let browser_context = ctx.conn.browser_context.as_mut().unwrap();
- browser_context
- .background_targets
- .push(BackgroundTarget::new(
- "TID-B".to_owned(),
- Some("SID-B".to_owned()),
- crate::conn::TargetIdentityState::new(
- "about:blank".to_owned(),
- URL_BASE.to_owned(),
- "Secure".to_owned(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ browser_context.insert_page_target_host(PageTargetHost::new(
+ "TID-B".to_owned(),
+ Some("SID-B".to_owned()),
+ crate::conn::TargetIdentityState::new(
+ "about:blank".to_owned(),
+ URL_BASE.to_owned(),
+ "Secure".to_owned(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
}
assert!(
ctx.conn
@@ -1294,7 +1292,7 @@ async fn navigation_history_is_preserved_per_parked_target() {
async fn get_navigation_history_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let background_url = "data:text/html,<title>Background History</title><main>background</main>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -1304,7 +1302,7 @@ async fn get_navigation_history_targets_loaded_background_owner_without_promotio
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(background_url, Some("SID-background"))
.await;
@@ -1339,7 +1337,7 @@ async fn reset_navigation_history_targets_loaded_background_owner_without_promot
let mut ctx = TestContext::new();
let background_url =
"data:text/html,<title>Background Reset History</title><main>background</main>";
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background-reset".to_owned(),
Some("SID-background-reset".to_owned()),
"about:blank".to_owned(),
@@ -1350,7 +1348,7 @@ async fn reset_navigation_history_targets_loaded_background_owner_without_promot
browser_context.attach_active_session("SID-active".to_owned());
browser_context
.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
- browser_context.background_targets.push(background);
+ browser_context.insert_page_target_host(background);
ctx.conn.browser_context = Some(browser_context);
ctx.install_navigation_fixture_for_session_owner(background_url, Some("SID-background-reset"))
.await;
@@ -1399,7 +1397,7 @@ async fn navigate_to_history_entry_targets_background_owner_without_promotion()
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -1584,7 +1582,7 @@ async fn navigate_targets_background_owner_without_promotion() {
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<body>active</body>".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -1843,11 +1841,8 @@ async fn navigate_with_runtime_frontend_enabled_network_child_playwright_style_u
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.enable_background_navigation_scheduler_for_test();
@@ -2628,11 +2623,8 @@ async fn navigate_with_lifecycle_events_enabled_emits_lifecycle_markers() {
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
ctx.enable_dom_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
@@ -2795,11 +2787,8 @@ async fn navigate_with_child_iframe_emits_child_frame_navigation_and_lifecycle_e
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
@@ -3115,11 +3104,8 @@ async fn navigate_with_nested_child_frame_reports_outer_parent_frame_id() {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
ctx.process_async(json!({
@@ -3206,12 +3192,10 @@ async fn navigate_with_runtime_frontend_enabled_emits_nested_child_default_conte
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
let browser_context = ctx.conn.browser_context.as_mut().unwrap();
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
@@ -3290,11 +3274,8 @@ async fn navigate_with_legacy_runtime_frontend_projection_emits_context_creation
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
ctx.enable_dom_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.enable_background_navigation_scheduler_for_test();
@@ -3579,11 +3560,8 @@ async fn navigate_with_runtime_frontend_enabled_emits_initial_console_before_dcl
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
@@ -3649,7 +3627,7 @@ async fn navigate_with_console_enabled_emits_initial_console_without_runtime_ena
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state
.v8_state
.is_none(),
@@ -3798,11 +3776,8 @@ async fn navigate_with_runtime_frontend_enabled_emits_child_default_execution_co
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
@@ -5140,10 +5115,10 @@ async fn navigate_failure_creates_runtime_context_and_completes_lifecycle() {
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
@@ -6038,7 +6013,7 @@ async fn reload_targets_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let page_url = format!("http://{addr}/page");
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
page_url.clone(),
@@ -6048,7 +6023,7 @@ async fn reload_targets_background_owner_without_promotion() {
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(&page_url, Some("SID-background"))
.await;
@@ -6059,7 +6034,7 @@ async fn reload_targets_background_owner_without_promotion() {
.and_then(|browser_context| {
browser_context
.background_target_mut("TID-background")
- .and_then(BackgroundTarget::loaded_page_mut)
+ .and_then(PageTargetHost::loaded_page_mut)
})
.expect("loaded background page")
.serialize_html_async()
@@ -6370,7 +6345,7 @@ async fn reload_after_crash_emits_target_reloaded_after_crash() {
"data:text/html,<body>reload-after-crash</body>",
);
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.record_inspector_target_crashed();
bc.active_target
@@ -6418,7 +6393,7 @@ async fn navigate_after_crash_emits_target_reloaded_after_crash() {
"data:text/html,<body>before-crash</body>",
);
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.record_inspector_target_crashed();
bc.active_target
diff --git a/moli-protocol/src/domains/page/tests/runtime.rs b/moli-protocol/src/domains/page/tests/runtime.rs
index cdc3307e1..99a860969 100644
--- a/moli-protocol/src/domains/page/tests/runtime.rs
+++ b/moli-protocol/src/domains/page/tests/runtime.rs
@@ -1113,11 +1113,8 @@ async fn runtime_evaluate_child_navigation_emits_child_frame_navigation_and_life
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
ctx.process_async(json!({
@@ -1165,11 +1162,8 @@ async fn runtime_evaluate_timeout_child_navigation_emits_child_frame_navigation_
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
ctx.process_async(json!({
@@ -1208,11 +1202,8 @@ async fn runtime_evaluate_child_location_navigation_emits_child_frame_navigation
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
ctx.process_async(json!({
@@ -1289,11 +1280,8 @@ async fn runtime_evaluate_child_history_back_emits_child_frame_navigation_and_li
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/page/tests/scripts.rs b/moli-protocol/src/domains/page/tests/scripts.rs
index 6bb6edeec..a7602a88c 100644
--- a/moli-protocol/src/domains/page/tests/scripts.rs
+++ b/moli-protocol/src/domains/page/tests/scripts.rs
@@ -180,46 +180,22 @@ async fn add_script_to_evaluate_on_new_document_invalid_call_does_not_advance_id
ctx.expect_result(38, json!({ "identifier": "2" }), Some("SID-1"));
}
#[tokio::test(flavor = "multi_thread")]
-async fn add_script_to_evaluate_on_new_document_reuses_identifier_for_duplicate_script() {
+async fn add_script_to_evaluate_on_new_document_keeps_duplicate_registrations_distinct() {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .document_start_scripts
- .push((
- "7".to_owned(),
- DocumentStartScript {
- registry_key: None,
- source: "globalThis.__lm_dedupe_count = (globalThis.__lm_dedupe_count || 0) + 1;"
- .to_owned(),
- world_name: None,
- has_bidi_channel_argument: false,
- bidi_channel_handoffs: Vec::new(),
- },
- ));
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .next_document_start_script_id = 0;
-
- ctx.process_async(json!({
- "id": 39,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": "SID-1",
- "params": {
- "source": "globalThis.__lm_dedupe_count = (globalThis.__lm_dedupe_count || 0) + 1;"
- }
- }))
- .await;
- ctx.expect_result(39, json!({ "identifier": "7" }), Some("SID-1"));
+ for (id, identifier) in [(39, "1"), (40, "2")] {
+ ctx.process_async(json!({
+ "id": id,
+ "method": "Page.addScriptToEvaluateOnNewDocument",
+ "sessionId": "SID-1",
+ "params": {
+ "source": "globalThis.__lm_duplicate_count = (globalThis.__lm_duplicate_count || 0) + 1;"
+ }
+ }))
+ .await;
+ ctx.expect_result(id, json!({ "identifier": identifier }), Some("SID-1"));
+ }
let script_count = ctx
.conn
@@ -231,140 +207,44 @@ async fn add_script_to_evaluate_on_new_document_reuses_identifier_for_duplicate_
.document_start_scripts
.len();
assert_eq!(
- script_count, 1,
- "duplicate preload script should reuse identifier instead of appending",
+ script_count, 2,
+ "each duplicate source registration must remain independently removable",
);
ctx.process_async(json!({
- "id": 40,
+ "id": 41,
"method": "Page.navigate",
"sessionId": "SID-1",
"params": {
- "url": "data:text/html,<body><script>document.body.textContent = String(globalThis.__lm_dedupe_count || 0);</script></body>"
+ "url": "data:text/html,<body><script>document.body.textContent = String(globalThis.__lm_duplicate_count || 0);</script></body>"
}
})).await;
let _ = ctx.take_all();
let html = loaded_page_html_for_test(&mut ctx).await;
assert!(
- html.contains(">1<"),
- "expected deduped preload script to execute once, got {html}"
+ html.contains(">2<"),
+ "expected both duplicate preload registrations to execute, got {html}"
);
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn add_script_to_evaluate_on_new_document_restored_scripts_bump_from_max_identifier() {
- let mut ctx = TestContext::new();
- load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
-
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .document_start_scripts
- .push((
- "123".to_owned(),
- DocumentStartScript {
- registry_key: None,
- source: "globalThis.__lm_preload = 'seed';".to_owned(),
- world_name: None,
- has_bidi_channel_argument: false,
- bidi_channel_handoffs: Vec::new(),
- },
- ));
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .next_document_start_script_id = 0;
-
- ctx.process_async(json!({
- "id": 41,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": "SID-1",
- "params": {
- "source": "globalThis.__lm_preload = 'new';"
- }
- }))
- .await;
- ctx.expect_result(41, json!({ "identifier": "124" }), Some("SID-1"));
-
- let identifier_count = ctx
- .conn
- .browser_context
- .as_ref()
- .expect("browser context")
- .active_target
- .owner_state
- .document_start_scripts
- .iter()
- .filter(|(identifier, _)| identifier == "123" || identifier == "124")
- .count();
- assert_eq!(
- identifier_count, 2,
- "restored max id should be used to generate next identifier"
- );
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn add_script_to_evaluate_on_new_document_bump_ignores_non_numeric_identifiers() {
- let mut ctx = TestContext::new();
- load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
-
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .document_start_scripts
- .push((
- "legacy-script".to_owned(),
- DocumentStartScript {
- registry_key: None,
- source: "globalThis.__lm_preload = 'legacy';".to_owned(),
- world_name: None,
- has_bidi_channel_argument: false,
- bidi_channel_handoffs: Vec::new(),
- },
- ));
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .document_start_scripts
- .push((
- "9".to_owned(),
- DocumentStartScript {
- registry_key: None,
- source: "globalThis.__lm_preload = 'seed';".to_owned(),
- world_name: None,
- has_bidi_channel_argument: false,
- bidi_channel_handoffs: Vec::new(),
- },
- ));
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .owner_state
- .next_document_start_script_id = 0;
+ for (id, identifier) in [(42, "1"), (43, "2")] {
+ ctx.process_async(json!({
+ "id": id,
+ "method": "Page.removeScriptToEvaluateOnNewDocument",
+ "sessionId": "SID-1",
+ "params": { "identifier": identifier }
+ }))
+ .await;
+ ctx.expect_result(id, json!({}), Some("SID-1"));
+ }
ctx.process_async(json!({
- "id": 41,
+ "id": 44,
"method": "Page.addScriptToEvaluateOnNewDocument",
"sessionId": "SID-1",
- "params": {
- "source": "globalThis.__lm_preload = 'new';"
- }
+ "params": { "source": "globalThis.__lm_reused_identifier = true;" }
}))
.await;
- ctx.expect_result(41, json!({ "identifier": "10" }), Some("SID-1"));
+ ctx.expect_result(44, json!({ "identifier": "1" }), Some("SID-1"));
}
#[tokio::test(flavor = "multi_thread")]
async fn add_script_to_evaluate_on_new_document_persists_across_multiple_navigations() {
@@ -1715,7 +1595,7 @@ async fn create_isolated_world_returns_unique_context_ids_and_emits_runtime_even
#[tokio::test(flavor = "multi_thread")]
async fn create_isolated_world_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -1724,7 +1604,7 @@ async fn create_isolated_world_targets_loaded_background_owner_without_promotion
let mut bc = BrowserContext::new("BID-1".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<body>background</body>",
@@ -1892,7 +1772,7 @@ async fn create_isolated_world_after_reactivating_browser_context_with_another_l
.active_target
.runtime_slot
.replace_loaded_page(Some(first_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = false;
}
@@ -1918,7 +1798,7 @@ async fn create_isolated_world_after_reactivating_browser_context_with_another_l
.active_target
.runtime_slot
.replace_loaded_page(Some(second_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = false;
}
diff --git a/moli-protocol/src/domains/performance.rs b/moli-protocol/src/domains/performance.rs
index 1b8d2e6cd..becdbec34 100644
--- a/moli-protocol/src/domains/performance.rs
+++ b/moli-protocol/src/domains/performance.rs
@@ -564,7 +564,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance;
assert!(performance.enabled());
@@ -643,7 +643,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance;
assert_eq!(performance.time_domain(), PerformanceTimeDomain::TimeTicks);
@@ -877,15 +877,14 @@ mod tests {
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- !browser_context
- .devtools_session_state
+ !browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled()
);
let auxiliary = browser_context
- .auxiliary_devtools_session_states
- .get("SID-aux")
+ .devtools_sessions
+ .attached("SID-aux")
.expect("auxiliary session state")
.page_session_state
.performance;
@@ -1110,8 +1109,7 @@ mod tests {
ctx.expect_result(5, json!({}), Some("SID-background"));
let active = ctx.conn.browser_context.as_ref().expect("browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled()
@@ -1119,8 +1117,8 @@ mod tests {
assert!(
active
.parked_page_session_state("TID-background")
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.performance
.enabled()),
diff --git a/moli-protocol/src/domains/profiler.rs b/moli-protocol/src/domains/profiler.rs
index 8280f20b0..09ad79acd 100644
--- a/moli-protocol/src/domains/profiler.rs
+++ b/moli-protocol/src/domains/profiler.rs
@@ -564,12 +564,13 @@ mod tests {
with_loaded_document_async(&mut ctx, "<!doctype html><body></body>").await;
{
let browser_context = ctx.conn.browser_context.as_mut().expect("browser context");
- browser_context.set_active_target_id("TID-profiler-isolation");
browser_context.attach_active_session("SID-profiler-primary");
- assert!(browser_context.assign_auxiliary_session_to_target(
- "TID-profiler-isolation",
- "SID-profiler-aux".to_owned()
- ));
+ assert!(
+ browser_context.assign_auxiliary_session_to_target(
+ "TID-profiler",
+ "SID-profiler-aux".to_owned()
+ )
+ );
}
let primary_enable = process_and_take_response(
@@ -582,7 +583,11 @@ mod tests {
37,
)
.await;
- assert_eq!(primary_enable["result"], json!({}));
+ assert_eq!(
+ primary_enable["result"],
+ json!({}),
+ "primary Profiler.enable response: {primary_enable:?}"
+ );
let aux_start_without_enable = process_and_take_response(
&mut ctx,
@@ -670,12 +675,13 @@ mod tests {
with_loaded_document_async(&mut ctx, "<!doctype html><body></body>").await;
{
let browser_context = ctx.conn.browser_context.as_mut().expect("browser context");
- browser_context.set_active_target_id("TID-profiler-coverage-isolation");
browser_context.attach_active_session("SID-profiler-primary");
- assert!(browser_context.assign_auxiliary_session_to_target(
- "TID-profiler-coverage-isolation",
- "SID-profiler-aux".to_owned()
- ));
+ assert!(
+ browser_context.assign_auxiliary_session_to_target(
+ "TID-profiler",
+ "SID-profiler-aux".to_owned()
+ )
+ );
}
let primary_enable = process_and_take_response(
@@ -809,10 +815,9 @@ mod tests {
with_loaded_document_async(&mut ctx, "<!doctype html><body></body>").await;
{
let browser_context = ctx.conn.browser_context.as_mut().expect("browser context");
- browser_context.set_active_target_id("TID-profiler-detach");
browser_context.attach_active_session("SID-profiler-old");
assert!(browser_context.assign_auxiliary_session_to_target(
- "TID-profiler-detach",
+ "TID-profiler",
"SID-profiler-aux-old".to_owned()
));
}
@@ -864,7 +869,7 @@ mod tests {
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert_eq!(browser_context.active_session_id(), None);
assert!(
- browser_context.auxiliary_devtools_session_states.is_empty(),
+ browser_context.devtools_sessions.attached_is_empty(),
"detaching the primary target session must drop active auxiliary inspector session state"
);
}
@@ -1574,7 +1579,7 @@ mod tests {
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state;
assert!(
inspector_state.v8_state.is_some(),
diff --git a/moli-protocol/src/domains/runtime/activity.rs b/moli-protocol/src/domains/runtime/activity.rs
index f83d6b477..990e63825 100644
--- a/moli-protocol/src/domains/runtime/activity.rs
+++ b/moli-protocol/src/domains/runtime/activity.rs
@@ -624,11 +624,13 @@ mod tests {
.browser_context
.as_mut()
.expect("browser context should be loaded");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
- bc.devtools_session_state.page_session_state.log_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .page_session_state
+ .log_enabled = true;
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn
diff --git a/moli-protocol/src/domains/runtime/dispatcher.rs b/moli-protocol/src/domains/runtime/dispatcher.rs
index e5d770e10..96fc0e727 100644
--- a/moli-protocol/src/domains/runtime/dispatcher.rs
+++ b/moli-protocol/src/domains/runtime/dispatcher.rs
@@ -354,10 +354,6 @@ impl RuntimeInspectorRoutedOutput {
.count()
}
- fn events_mut(&mut self) -> &mut Vec<BackgroundProtocolEvent> {
- &mut self.events
- }
-
fn take_events_ready_before_command_response(
&mut self,
command_id: Option<u64>,
@@ -8502,12 +8498,10 @@ async fn complete_pending_runtime_inspector_command(
);
}
if completed.action == "runIfWaitingForDebugger" {
- crate::domains::target::start_initial_document_target_url_navigation_if_needed_background_events_async(
+ crate::domains::target::schedule_initial_document_target_url_navigation_after_debugger_resume(
conn,
- routed_output.events_mut(),
completed.session_id(),
- )
- .await;
+ );
}
}
routed_output.push_ordered_into_plan(&mut plan, completed.command_id);
diff --git a/moli-protocol/src/domains/runtime/tests/bindings.rs b/moli-protocol/src/domains/runtime/tests/bindings.rs
index 24db2d6eb..358c36074 100644
--- a/moli-protocol/src/domains/runtime/tests/bindings.rs
+++ b/moli-protocol/src/domains/runtime/tests/bindings.rs
@@ -62,7 +62,7 @@ async fn runtime_disable_clears_stored_binding_definitions_when_enabled() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| binding.name == "bindingClearedOnDisable")
@@ -80,7 +80,7 @@ async fn runtime_disable_clears_stored_binding_definitions_when_enabled() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.is_empty(),
"Runtime.disable should clear stored binding definitions when the Runtime agent was enabled"
@@ -279,7 +279,7 @@ async fn add_binding_can_complete_through_multi_phase_pending_command_task() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| binding.name == "pendingBinding")
@@ -433,7 +433,7 @@ async fn add_binding_rejects_execution_context_id_with_context_name() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| binding.name == "invalidBinding"),
@@ -478,7 +478,7 @@ async fn remove_binding_deactivates_current_page_binding_and_removes_persisted_d
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "tempBinding")
@@ -542,7 +542,7 @@ async fn remove_binding_can_complete_through_multi_phase_pending_command_task()
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "pendingRemoveBinding")
@@ -827,7 +827,7 @@ async fn add_binding_without_runtime_enable_installs_current_main_world_and_pers
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| binding.name == "immediateBinding"
@@ -936,7 +936,7 @@ async fn add_binding_with_execution_context_id_targets_existing_isolated_world()
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "utilityBindingById"),
@@ -1023,7 +1023,7 @@ async fn add_binding_execution_context_id_completes_through_pending_command_task
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "pendingUtilityBindingById"),
@@ -1300,7 +1300,7 @@ async fn patchright_style_pre_document_add_binding_persists_until_navigation() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| {
@@ -1379,7 +1379,7 @@ async fn pre_document_add_binding_completes_through_command_task_without_live_pa
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| {
@@ -1441,7 +1441,7 @@ async fn patchright_style_pre_document_remove_binding_succeeds_before_navigation
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "temporaryPreDocumentBinding"),
@@ -1528,7 +1528,7 @@ async fn pre_document_remove_binding_completes_through_command_task_without_live
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "preDocumentRemoveTaskBinding"),
diff --git a/moli-protocol/src/domains/runtime/tests/console.rs b/moli-protocol/src/domains/runtime/tests/console.rs
index 66adf35f3..39a5f023e 100644
--- a/moli-protocol/src/domains/runtime/tests/console.rs
+++ b/moli-protocol/src/domains/runtime/tests/console.rs
@@ -53,7 +53,7 @@ async fn runtime_discard_console_entries_suppresses_buffered_runtime_events() {
#[tokio::test(flavor = "multi_thread")]
async fn runtime_discard_console_entries_is_page_target_local() {
let mut ctx = TestContext::new();
- let background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -62,7 +62,7 @@ async fn runtime_discard_console_entries_is_page_target_local() {
let mut browser_context = BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id("TID-active");
browser_context.attach_active_session("SID-active");
- browser_context.background_targets.push(background_target);
+ browser_context.insert_page_target_host(background_target);
ctx.conn.browser_context = Some(browser_context);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<script>console.log('active-discard-peer')</script>",
@@ -346,11 +346,6 @@ async fn heap_profiler_sampling_and_tracking_are_restored_on_replacement_page_is
"<!doctype html><script>globalThis.__heapBefore = []</script>",
)
.await;
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context should exist")
- .set_active_target_id("TID-heap-profiler-restore");
for command in [
json!({"id": 206_840, "method": "HeapProfiler.enable"}),
@@ -523,7 +518,7 @@ async fn deferred_heap_profiler_state_follows_renderer_owned_document_navigation
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state;
assert!(
inspector_state.v8_state.is_some(),
@@ -648,9 +643,9 @@ async fn heap_profiler_moli_diagnostics_reports_connection_state_without_loaded_
"diagnostics should not require a loaded target: {response:?}"
);
assert_eq!(
- connection["retainedBackgroundNavigationEngineCount"],
+ connection["pageNavigationEngineCount"],
json!(0),
- "fresh diagnostics should expose retained engine count: {response:?}"
+ "fresh diagnostics should expose page engine count: {response:?}"
);
let scheduler = &response["result"]["scheduler"];
assert_eq!(
@@ -838,7 +833,7 @@ async fn heap_profiler_moli_reset_idle_engine_only_resets_without_loaded_page()
.browser_context
.as_mut()
.expect("browser context")
- .reset_active_target_slot_to_empty_async()
+ .remove_active_page_target_async()
.await;
ctx.process_async(json!({"id": 206_819, "method": "HeapProfiler.moliResetIdleEngine"}))
diff --git a/moli-protocol/src/domains/runtime/tests/evaluate.rs b/moli-protocol/src/domains/runtime/tests/evaluate.rs
index 0c94b7e4b..f7fbb9bee 100644
--- a/moli-protocol/src/domains/runtime/tests/evaluate.rs
+++ b/moli-protocol/src/domains/runtime/tests/evaluate.rs
@@ -331,7 +331,7 @@ async fn loaded_page_runtime_enable_projection_waits_for_v8_success() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled,
"protocol Runtime.enabled projection must not flip before V8 Runtime.enable succeeds"
@@ -353,7 +353,7 @@ async fn loaded_page_runtime_enable_projection_waits_for_v8_success() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled,
"protocol Runtime.enabled projection should flip after V8 Runtime.enable succeeds"
@@ -517,11 +517,6 @@ async fn loaded_page_runtime_agent_state_commands_dispatch_after_runtime_enable(
async fn runtime_agent_configuration_is_restored_on_replacement_page_isolate() {
let mut ctx = TestContext::new();
with_loaded_document_async(&mut ctx, "<!doctype html><body>before</body>").await;
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context should exist")
- .set_active_target_id("TID-runtime-agent-restore");
enable_runtime_and_take_execution_context_id_async(&mut ctx, 11_016).await;
for (id, method, params) in [
@@ -555,8 +550,7 @@ async fn runtime_agent_configuration_is_restored_on_replacement_page_isolate() {
.as_ref()
.expect("browser context should exist");
assert!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state
.v8_state
.is_some(),
@@ -607,11 +601,6 @@ async fn runtime_agent_configuration_is_restored_on_replacement_page_isolate() {
async fn opaque_reattach_state_wins_over_conflicting_runtime_listener_configuration() {
let mut ctx = TestContext::new();
with_loaded_document_async(&mut ctx, "<!doctype html><body>before</body>").await;
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context should exist")
- .set_active_target_id("TID-runtime-reattach-precedence");
ctx.process_async(json!({"id": 11_023, "method": "Runtime.enable"}))
.await;
@@ -626,15 +615,13 @@ async fn opaque_reattach_state_wins_over_conflicting_runtime_listener_configurat
.as_mut()
.expect("browser context should exist");
assert!(
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.inspector_session_state
.v8_state
.is_some(),
"successful Runtime.disable must persist the disabled V8 agent cookie"
);
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
@@ -1709,7 +1696,7 @@ async fn enable_and_disable_update_browser_context_runtime_flag() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
@@ -1722,7 +1709,7 @@ async fn enable_and_disable_update_browser_context_runtime_flag() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
@@ -1735,7 +1722,7 @@ async fn enable_and_disable_update_browser_context_runtime_flag() {
.browser_context
.as_ref()
.expect("browser context should exist")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
@@ -1907,7 +1894,7 @@ async fn dom_get_document_rejects_while_main_document_navigation_is_pending() {
#[tokio::test]
async fn document_navigation_gate_is_scoped_to_background_target_owner() {
let mut ctx = TestContext::new();
- let background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -1916,11 +1903,10 @@ async fn document_navigation_gate_is_scoped_to_background_target_owner() {
let mut browser_context = BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id("TID-active");
browser_context.attach_active_session("SID-active");
- browser_context
- .devtools_session_state
+ browser_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- browser_context.background_targets.push(background_target);
+ browser_context.insert_page_target_host(background_target);
ctx.conn.browser_context = Some(browser_context);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<html><title>active</title></html>",
@@ -1934,8 +1920,7 @@ async fn document_navigation_gate_is_scoped_to_background_target_owner() {
.await;
let browser_context = ctx.conn.browser_context.as_mut().expect("browser context");
browser_context.mutate_parked_page_session_state("TID-background", |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
});
@@ -6621,7 +6606,7 @@ async fn registered_named_world_object_handles_remain_callable_after_navigation(
.expect("browser context should exist");
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
diff --git a/moli-protocol/src/domains/runtime/tests/inspector.rs b/moli-protocol/src/domains/runtime/tests/inspector.rs
index 03d74de1d..871e864f6 100644
--- a/moli-protocol/src/domains/runtime/tests/inspector.rs
+++ b/moli-protocol/src/domains/runtime/tests/inspector.rs
@@ -11,7 +11,7 @@ async fn isolated_inspector_context_lookup_does_not_issue_internal_runtime_enabl
.expect("browser context should exist");
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
let utility_context_id = create_isolated_world_async(&mut ctx, 14, "utility").await;
@@ -46,7 +46,7 @@ async fn isolated_inspector_context_lookup_does_not_collide_with_pending_inspect
.expect("browser context should exist");
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
let utility_context_id = create_isolated_world_async(&mut ctx, 15, "utility").await;
@@ -83,7 +83,7 @@ async fn runtime_evaluate_materializes_default_context_via_inspector_hook() {
.expect("browser context should exist");
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.sent.clear();
@@ -135,7 +135,7 @@ async fn pending_inspector_await_does_not_block_default_context_evaluate() {
.expect("browser context should exist");
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn
diff --git a/moli-protocol/src/domains/runtime/tests/mod.rs b/moli-protocol/src/domains/runtime/tests/mod.rs
index 5ec7fa13b..9e0ea14bc 100644
--- a/moli-protocol/src/domains/runtime/tests/mod.rs
+++ b/moli-protocol/src/domains/runtime/tests/mod.rs
@@ -152,8 +152,7 @@ async fn push_loaded_runtime_frontend_enabled_background_context_async(
.replace_loaded_page(Some(page));
background_context.set_active_target_id(target_id.to_owned());
background_context.attach_active_session(session_id.to_owned());
- background_context
- .devtools_session_state
+ background_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
ctx.conn.inactive_browser_contexts.push(background_context);
@@ -166,7 +165,7 @@ async fn with_loaded_runtime_frontend_enabled_background_target_async(
background_session_id: &str,
html: &str,
) {
- let background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::PageTargetHost::with_url(
background_target_id.to_owned(),
Some(background_session_id.to_owned()),
format!("data:text/html,{html}"),
@@ -175,10 +174,9 @@ async fn with_loaded_runtime_frontend_enabled_background_target_async(
let mut browser_context = crate::conn::BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id(active_target_id.to_owned());
browser_context.attach_active_session(active_session_id.to_owned());
- browser_context.background_targets.push(background_target);
+ browser_context.insert_page_target_host(background_target);
browser_context.mutate_parked_page_session_state(background_target_id, |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
});
diff --git a/moli-protocol/src/domains/runtime/tests/objects.rs b/moli-protocol/src/domains/runtime/tests/objects.rs
index 77912ef92..94802c97d 100644
--- a/moli-protocol/src/domains/runtime/tests/objects.rs
+++ b/moli-protocol/src/domains/runtime/tests/objects.rs
@@ -619,7 +619,7 @@ async fn runtime_disable_clears_background_child_default_context_emission_cursor
{
let mut ctx = TestContext::new();
let html = "<iframe srcdoc=\"<body>background child</body>\"></iframe>";
- let background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
format!("data:text/html,{html}"),
@@ -627,7 +627,7 @@ async fn runtime_disable_clears_background_child_default_context_emission_cursor
let mut browser_context = crate::conn::BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
browser_context.attach_active_session("SID-active".to_owned());
- browser_context.background_targets.push(background_target);
+ browser_context.insert_page_target_host(background_target);
ctx.conn.browser_context = Some(browser_context);
ctx.install_navigation_fixture_for_session_owner(
&format!("data:text/html,{html}"),
diff --git a/moli-protocol/src/domains/runtime/tests/shared_worker.rs b/moli-protocol/src/domains/runtime/tests/shared_worker.rs
index e3055c81f..5dbe9dca2 100644
--- a/moli-protocol/src/domains/runtime/tests/shared_worker.rs
+++ b/moli-protocol/src/domains/runtime/tests/shared_worker.rs
@@ -583,13 +583,13 @@ onconnect = event => {
.browser_context
.as_mut()
.expect("browser context should remain installed");
- let mut background = crate::conn::BackgroundTarget::with_url(
+ let mut background = crate::conn::PageTargetHost::with_url(
"TID-diagnostics-document-worker-bg".to_owned(),
Some("SID-diagnostics-document-worker-bg".to_owned()),
background_url.to_owned(),
);
background.replace_loaded_page(Some(background_page));
- browser_context.background_targets.push(background);
+ browser_context.insert_page_target_host(background);
ctx.sent.clear();
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/runtime_context_events.rs b/moli-protocol/src/domains/runtime_context_events.rs
index 3947e883b..cefa326b8 100644
--- a/moli-protocol/src/domains/runtime_context_events.rs
+++ b/moli-protocol/src/domains/runtime_context_events.rs
@@ -279,7 +279,7 @@ fn qualify_worker_runtime_context_event_for_session_owner(
| CdpSessionRoute::TabTarget { .. }
| CdpSessionRoute::ActiveTarget { .. }
| CdpSessionRoute::AuxiliaryTarget { .. }
- | CdpSessionRoute::BackgroundTarget { .. } => {}
+ | CdpSessionRoute::PageTargetHost { .. } => {}
}
}
diff --git a/moli-protocol/src/domains/service_worker.rs b/moli-protocol/src/domains/service_worker.rs
index 8b1dcbff5..0a22a63f4 100644
--- a/moli-protocol/src/domains/service_worker.rs
+++ b/moli-protocol/src/domains/service_worker.rs
@@ -569,7 +569,7 @@ fn page_target_ids_for_controlled_client_ids(
{
target_ids.insert(target_id.to_owned());
}
- for target in &context.background_targets {
+ for target in context.background_targets() {
let Some(page) = target.loaded_page() else {
continue;
};
@@ -600,7 +600,7 @@ mod tests {
use serde_json::json;
use crate::{
- conn::{BackgroundTarget, BrowserContext, ServiceWorkerTargetState},
+ conn::{BrowserContext, PageTargetHost, ServiceWorkerTargetState},
testing::TestContext,
};
@@ -642,13 +642,13 @@ mod tests {
context.set_target_url("data:text/html,<title>same-url</title>".to_owned());
let _ = context.replace_loaded_page(Some(active_page));
- let mut background = BackgroundTarget::with_url(
+ let mut background = PageTargetHost::with_url(
"TID-background".to_owned(),
None,
"data:text/html,<title>same-url</title>".to_owned(),
);
let _ = background.replace_loaded_page(Some(background_page));
- context.background_targets.push(background);
+ context.insert_page_target_host(background);
assert_eq!(
super::page_target_ids_for_controlled_client_ids(&context, &[background_client_id]),
diff --git a/moli-protocol/src/domains/storage/ops.rs b/moli-protocol/src/domains/storage/ops.rs
index 0c47de543..de6be03ea 100644
--- a/moli-protocol/src/domains/storage/ops.rs
+++ b/moli-protocol/src/domains/storage/ops.rs
@@ -660,7 +660,11 @@ fn start_devtools_set_cookies_result(
"UnknownBrowserContextId",
)));
};
- let Some(page) = browser_context.active_target.runtime_slot.loaded_page_mut() else {
+ let Some(page) = browser_context
+ .page_targets
+ .active_mut()
+ .and_then(|target| target.runtime_slot.loaded_page_mut())
+ else {
let manager_surface = browser_context.cookie_manager_surface_snapshot_without_live_page();
let reports = set_cookies_with_manager_surface(browser_context, &manager_surface, cookies);
return DevToolsSetCookiesTaskStep::Complete(Ok(set_cookie_reports_result(&reports)));
@@ -708,7 +712,7 @@ fn effective_storage_browser_context_id(
| Some(crate::conn::CdpSessionRoute::AuxiliaryTarget {
browser_context_id, ..
})
- | Some(crate::conn::CdpSessionRoute::BackgroundTarget {
+ | Some(crate::conn::CdpSessionRoute::PageTargetHost {
browser_context_id, ..
}) => Ok(browser_context_id),
Some(crate::conn::CdpSessionRoute::Browser) => conn
@@ -878,7 +882,11 @@ fn complete_set_cookies_result(
));
};
let owner = {
- let Some(page) = browser_context.active_target.runtime_slot.loaded_page_mut() else {
+ let Some(page) = browser_context
+ .page_targets
+ .active_mut()
+ .and_then(|target| target.runtime_slot.loaded_page_mut())
+ else {
return Err(DevToolsError::new(
DevToolsErrorKind::Internal,
"NoDocumentLoaded",
diff --git a/moli-protocol/src/domains/storage/tests.rs b/moli-protocol/src/domains/storage/tests.rs
index 369a9f441..4af7a9d22 100644
--- a/moli-protocol/src/domains/storage/tests.rs
+++ b/moli-protocol/src/domains/storage/tests.rs
@@ -12,7 +12,7 @@ use url::Url;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use crate::{
- conn::{BackgroundTarget, BrowserContext, CdpCommandTaskStep},
+ conn::{BrowserContext, CdpCommandTaskStep, PageTargetHost},
domains::page::LOADER_ID,
testing::{TestContext, wait_until_message, wait_until_renderer_document_load},
};
@@ -774,7 +774,7 @@ async fn storage_key_targets_loaded_background_owner_without_promotion() {
.expect("page url should parse")
.origin()
.ascii_serialization();
- let background = BackgroundTarget::with_url(
+ let background = PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
@@ -783,7 +783,7 @@ async fn storage_key_targets_loaded_background_owner_without_promotion() {
let mut bc = BrowserContext::new("BID-SK-BG".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(&page_url, Some("SID-background"))
.await;
@@ -858,7 +858,7 @@ async fn pending_storage_key_keeps_background_owner_route_across_completion() {
.await
.expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let mut background = PageTargetHost::with_url(
"TID-storage-background".to_owned(),
None,
background_page.final_url().as_str().to_owned(),
@@ -871,7 +871,7 @@ async fn pending_storage_key_keeps_background_owner_route_across_completion() {
bc.active_target
.runtime_slot
.set_loaded_page_for_test(active_page);
- bc.background_targets.push(background);
+ bc.insert_page_target_host(background);
ctx.conn.browser_context = Some(bc);
let background_route = ctx
diff --git a/moli-protocol/src/domains/target.rs b/moli-protocol/src/domains/target.rs
index 8de247378..8b3f64baf 100644
--- a/moli-protocol/src/domains/target.rs
+++ b/moli-protocol/src/domains/target.rs
@@ -35,7 +35,7 @@ pub(crate) use popup::{
complete_popup_target_navigation_owner_action_async,
create_popup_target_from_renderer_output_background_events_async,
emit_target_info_changed_for_session_owner_background_event,
- start_initial_document_target_url_navigation_if_needed_background_events_async,
+ schedule_initial_document_target_url_navigation_after_debugger_resume,
};
pub(crate) fn popup_activation_creates_new_target(
conn: &CdpConnection,
@@ -1089,8 +1089,8 @@ fn select_browser_context_for_target(
return Err("BrowserContextNotLoaded");
}
if !conn.browser_contexts().any(|bc| {
- bc.has_active_target()
- || !bc.background_targets.is_empty()
+ bc.active_target_id().is_some()
+ || !bc.has_no_background_targets()
|| bc.has_any_shared_worker_targets()
|| bc.has_any_dedicated_worker_targets()
|| bc.has_any_service_worker_targets()
diff --git a/moli-protocol/src/domains/target/activation.rs b/moli-protocol/src/domains/target/activation.rs
index 4a4951677..32f5a7123 100644
--- a/moli-protocol/src/domains/target/activation.rs
+++ b/moli-protocol/src/domains/target/activation.rs
@@ -109,7 +109,7 @@ pub(super) async fn execute_devtools_activate_target_command_async(
);
return Ok(Vec::new());
}
- if !bc.has_active_target() && bc.background_targets.is_empty() {
+ if bc.active_target_id().is_none() && bc.has_no_background_targets() {
restore_previously_active_browser_context(
conn,
previously_active_browser_context_id.as_deref(),
diff --git a/moli-protocol/src/domains/target/attachment.rs b/moli-protocol/src/domains/target/attachment.rs
index 7ab14237c..305305453 100644
--- a/moli-protocol/src/domains/target/attachment.rs
+++ b/moli-protocol/src/domains/target/attachment.rs
@@ -172,7 +172,7 @@ fn do_attach(conn: &mut CdpConnection, cmd: &Cmd<'_>, target_id: &str) -> Target
if bc.has_service_worker_target(target_id) {
return do_attach_service_worker_target(conn, cmd.session_id, target_id);
}
- if !bc.has_active_target() && bc.background_targets.is_empty() {
+ if bc.active_target_id().is_none() && bc.has_no_background_targets() {
if let Some(restore_browser_context_id) = restore_browser_context_id.as_ref() {
restore_previously_active_browser_context(conn, restore_browser_context_id.as_deref());
}
@@ -652,7 +652,7 @@ async fn detach_from_target_inner_async(
let _ = conn
.detach_runtime_inspector_session_for_session_owner_async(Some(session_id))
.await;
- super::auto_attach::clear_emulated_media_for_detached_session_best_effort(conn, session_id)
+ super::auto_attach::clear_detached_session_target_overrides_best_effort(conn, session_id)
.await;
super::clear_detached_target_fetch_state_background_events_async(
conn,
@@ -785,8 +785,7 @@ async fn detach_from_target_inner_async(
}
if let Some(session_id) = params.session_id.as_deref() {
let background_target_id = conn.browser_context.as_ref().and_then(|bc| {
- bc.background_targets
- .iter()
+ bc.background_targets()
.find(|target| target.is_session(session_id))
.map(|target| target.target_id().to_owned())
});
@@ -1068,7 +1067,7 @@ fn detach_session_route_target_id(route: &crate::conn::CdpSessionRoute) -> Optio
crate::conn::CdpSessionRoute::TabTarget { tab_target_id, .. } => Some(tab_target_id),
crate::conn::CdpSessionRoute::ActiveTarget { target_id, .. } => target_id.as_deref(),
crate::conn::CdpSessionRoute::AuxiliaryTarget { target_id, .. }
- | crate::conn::CdpSessionRoute::BackgroundTarget { target_id, .. }
+ | crate::conn::CdpSessionRoute::PageTargetHost { target_id, .. }
| crate::conn::CdpSessionRoute::SharedWorkerTarget { target_id, .. }
| crate::conn::CdpSessionRoute::DedicatedWorkerTarget { target_id, .. }
| crate::conn::CdpSessionRoute::ServiceWorkerTarget { target_id, .. } => Some(target_id),
diff --git a/moli-protocol/src/domains/target/auto_attach.rs b/moli-protocol/src/domains/target/auto_attach.rs
index 0d84c2aac..ce08ade63 100644
--- a/moli-protocol/src/domains/target/auto_attach.rs
+++ b/moli-protocol/src/domains/target/auto_attach.rs
@@ -188,7 +188,7 @@ fn owner_already_auto_attached_to_page_target(
.and_then(BrowserContext::active_target_id)
== Some(target_id)
}
- Some(crate::conn::CdpSessionRoute::BackgroundTarget {
+ Some(crate::conn::CdpSessionRoute::PageTargetHost {
target_id: route_target_id,
..
})
@@ -275,7 +275,7 @@ fn page_session_route_matches_target(
.and_then(BrowserContext::active_target_id)
== Some(target_id)
}
- Some(crate::conn::CdpSessionRoute::BackgroundTarget {
+ Some(crate::conn::CdpSessionRoute::PageTargetHost {
target_id: route_target_id,
..
})
@@ -481,8 +481,7 @@ async fn set_auto_attach_inner_async(
target_ids.push(target_id);
}
target_ids.extend(
- bc.background_targets
- .iter()
+ bc.background_targets()
.filter(|target| {
should_auto_attach_page_target_for_owner(
conn,
@@ -516,7 +515,7 @@ async fn set_auto_attach_inner_async(
{
tab_target_ids.push(tab_target_id.to_owned());
}
- tab_target_ids.extend(bc.background_targets.iter().filter_map(|target| {
+ tab_target_ids.extend(bc.background_targets().filter_map(|target| {
let tab_target_id =
conn.tab_target_id_for_page_target_id(target.target_id())?;
should_auto_attach_tab_target_for_owner(
@@ -624,13 +623,12 @@ async fn set_auto_attach_inner_async(
if !attach_page_targets || bc.has_loaded_page() {
None
} else {
- bc.background_targets
- .iter()
- .rposition(|target| !target.has_session() && target.has_loaded_page())
- .map(|index| bc.background_targets[index].target_id().to_owned())
+ bc.background_targets()
+ .rev()
+ .find(|target| !target.has_session() && target.has_loaded_page())
+ .map(|target| target.target_id().to_owned())
.or_else(|| {
- bc.background_targets
- .iter()
+ bc.background_targets()
.find(|target| !target.has_session())
.map(|target| target.target_id().to_owned())
})
@@ -1103,7 +1101,7 @@ pub(super) async fn release_attached_sessions_for_root_frontend_async(
let _ = conn
.detach_runtime_inspector_session_for_session_owner_async(Some(&session_id))
.await;
- clear_emulated_media_for_detached_session_best_effort(conn, &session_id).await;
+ clear_detached_session_target_overrides_best_effort(conn, &session_id).await;
if !conn.release_primary_target_session_binding_without_event(&session_id) {
conn.rollback_auto_attached_session_detach_plan_without_event(&detach_plan);
}
@@ -1193,7 +1191,7 @@ async fn detach_attached_session_for_owner_async(
let _ = conn
.detach_runtime_inspector_session_for_session_owner_async(Some(session_id))
.await;
- clear_emulated_media_for_detached_session_best_effort(conn, session_id).await;
+ clear_detached_session_target_overrides_best_effort(conn, session_id).await;
super::clear_detached_target_fetch_state_background_events_async(
conn,
out.background_events_mut(),
@@ -1221,7 +1219,7 @@ async fn detach_attached_session_for_owner_async(
let _ = conn
.detach_runtime_inspector_session_for_session_owner_async(Some(session_id))
.await;
- clear_emulated_media_for_detached_session_best_effort(conn, session_id).await;
+ clear_detached_session_target_overrides_best_effort(conn, session_id).await;
let event_plan = conn
.detach_session_with_binding_cleanup_event_plan_async(
crate::conn::TargetSessionDetachCleanupPlan::new(
@@ -1327,7 +1325,7 @@ async fn detach_attached_session_for_owner_async(
}
}
-pub(super) async fn clear_emulated_media_for_detached_session_best_effort(
+pub(super) async fn clear_detached_session_target_overrides_best_effort(
conn: &mut CdpConnection,
session_id: &str,
) {
@@ -1341,6 +1339,13 @@ pub(super) async fn clear_emulated_media_for_detached_session_best_effort(
"failed to clear emulated media while detaching target session"
);
}
+ if let Err(error) = conn.clear_target_session_overrides_async(session_id).await {
+ tracing::warn!(
+ session_id,
+ error,
+ "failed to restore target overrides while detaching target session"
+ );
+ }
}
async fn ensure_initial_document_for_attached_page_targets_async(
diff --git a/moli-protocol/src/domains/target/browser_context.rs b/moli-protocol/src/domains/target/browser_context.rs
index 8d4058529..ae6a5c2a0 100644
--- a/moli-protocol/src/domains/target/browser_context.rs
+++ b/moli-protocol/src/domains/target/browser_context.rs
@@ -230,8 +230,7 @@ pub(in crate::domains) fn devtools_client_window_info_for_target(
));
}
if browser_context
- .background_targets
- .iter()
+ .background_targets()
.any(|target| target.target_id() == target_id.as_str())
{
return Some(devtools_client_window_info_from_owner_state(
@@ -306,9 +305,10 @@ pub(super) fn execute_devtools_create_browser_context_command(
}
let mut browser_context = conn.new_ephemeral_browser_context(id.clone());
- browser_context.tls_verify_host_override = command.accept_insecure_certs.map(|accept| !accept);
- browser_context.http_proxy_override = command.proxy_server;
- browser_context.http_no_proxy_override =
+ browser_context.default_tls_verify_host_override =
+ command.accept_insecure_certs.map(|accept| !accept);
+ browser_context.default_http_proxy_override = command.proxy_server;
+ browser_context.default_http_no_proxy_override =
normalize_proxy_bypass_list_for_loader(command.proxy_bypass_list.as_deref());
browser_context.proxy_autoconfig_url = command.proxy_autoconfig_url;
browser_context.proxy_socks_version = command.proxy_socks_version;
@@ -524,8 +524,8 @@ pub(super) fn create_browser_context(conn: &mut CdpConnection, cmd: &Cmd<'_>) ->
}
let id = conn.gen_bc_id();
let mut browser_context = conn.new_ephemeral_browser_context(id.clone());
- browser_context.http_proxy_override = params.proxy_server;
- browser_context.http_no_proxy_override =
+ browser_context.default_http_proxy_override = params.proxy_server;
+ browser_context.default_http_no_proxy_override =
normalize_proxy_bypass_list_for_loader(params.proxy_bypass_list.as_deref());
conn.insert_browser_context(browser_context);
CommandOutputPlan::result(json!({ "browserContextId": id }))
diff --git a/moli-protocol/src/domains/target/browser_context_disposal.rs b/moli-protocol/src/domains/target/browser_context_disposal.rs
index c4267b33c..f176b04ce 100644
--- a/moli-protocol/src/domains/target/browser_context_disposal.rs
+++ b/moli-protocol/src/domains/target/browser_context_disposal.rs
@@ -29,8 +29,7 @@ impl BrowserContextDisposal {
let active_page_target_id = browser_context.active_target_id().map(str::to_owned);
let mut page_target_ids = browser_context
- .background_targets
- .iter()
+ .background_targets()
.rev()
.map(|target| target.target_id().to_owned())
.collect::<Vec<_>>();
@@ -78,7 +77,8 @@ impl BrowserContextDisposal {
.collect::<Vec<_>>();
let mut pending_inspector_session_owners = browser_context
- .has_active_target()
+ .active_target_id()
+ .is_some()
.then_some(None)
.into_iter()
.collect::<Vec<_>>();
diff --git a/moli-protocol/src/domains/target/closing.rs b/moli-protocol/src/domains/target/closing.rs
index e12c4ddb2..9aac92244 100644
--- a/moli-protocol/src/domains/target/closing.rs
+++ b/moli-protocol/src/domains/target/closing.rs
@@ -198,7 +198,7 @@ async fn close_target_inner_async(
let session_id = match conn.browser_context.as_ref() {
Some(bc) => {
- if !bc.has_active_target() && bc.background_targets.is_empty() {
+ if bc.active_target_id().is_none() && bc.has_no_background_targets() {
return Err(DevToolsError::new(
DevToolsErrorKind::NoSuchTarget,
"TargetNotLoaded",
diff --git a/moli-protocol/src/domains/target/creation.rs b/moli-protocol/src/domains/target/creation.rs
index 23633b902..ea681abeb 100644
--- a/moli-protocol/src/domains/target/creation.rs
+++ b/moli-protocol/src/domains/target/creation.rs
@@ -297,6 +297,8 @@ pub(super) fn execute_devtools_create_target_command(
browser_context.active_target_id_owned(),
)
};
+ let claims_default_placeholder =
+ !has_active_target && previous_active_target_id.as_deref() == Some(default_target_id);
let auto_attach_page_owners = top_level_page_auto_attach_owner_sessions(conn);
let auto_attach_tab_owners = top_level_tab_auto_attach_owner_sessions(conn);
let auto_attached_page_sessions = auto_attach_page_owners
@@ -319,9 +321,6 @@ pub(super) fn execute_devtools_create_target_command(
let activation = activating_created_target
.then(|| TargetActivationTransition::new(target_id.clone(), previous_active_target_id));
let initial_empty_document_url = create_target_initial_empty_document_url(&command.url);
- if activating_created_target {
- conn.handoff_navigation_engine_for_active_target_demotion();
- }
{
let bc = conn.browser_context.as_mut().unwrap();
if creating_background_target {
@@ -340,7 +339,11 @@ pub(super) fn execute_devtools_create_target_command(
Some(initial_empty_document_url.clone()),
);
} else {
- bc.set_active_target_id(target_id.clone());
+ let claimed_default_placeholder =
+ claims_default_placeholder && bc.rekey_active_target(target_id.clone());
+ if !claimed_default_placeholder {
+ bc.set_active_target_id(target_id.clone());
+ }
bc.set_target_url(command.url.clone());
bc.begin_active_target_initial_empty_document(initial_empty_document_url.clone());
bc.active_target.owner_state.target_crash_state.clear();
diff --git a/moli-protocol/src/domains/target/info.rs b/moli-protocol/src/domains/target/info.rs
index 1e3334595..109b607e1 100644
--- a/moli-protocol/src/domains/target/info.rs
+++ b/moli-protocol/src/domains/target/info.rs
@@ -107,8 +107,8 @@ pub(super) fn execute_devtools_get_target_info_command(
));
}
let target_exists = conn.browser_contexts().any(|bc| {
- bc.has_active_target()
- || !bc.background_targets.is_empty()
+ bc.active_target_id().is_some()
+ || !bc.has_no_background_targets()
|| bc.has_any_shared_worker_targets()
|| bc.has_any_dedicated_worker_targets()
|| bc.has_any_service_worker_targets()
diff --git a/moli-protocol/src/domains/target/popup.rs b/moli-protocol/src/domains/target/popup.rs
index 4c7dd684c..e942a2dea 100644
--- a/moli-protocol/src/domains/target/popup.rs
+++ b/moli-protocol/src/domains/target/popup.rs
@@ -452,6 +452,34 @@ pub(crate) async fn start_initial_document_target_url_navigation_if_needed_backg
true
}
+pub(crate) fn schedule_initial_document_target_url_navigation_after_debugger_resume(
+ conn: &mut CdpConnection,
+ session_id: Option<&str>,
+) -> bool {
+ if !conn.runtime_session_owner_should_start_initial_document_navigation(session_id) {
+ return false;
+ }
+ let Some(target_url) = conn.runtime_session_owner_target_url(session_id) else {
+ return false;
+ };
+ let Some((browser_context_id, Some(target_id))) =
+ conn.target_owner_identity_for_session(session_id)
+ else {
+ return false;
+ };
+ let Some(action) = PopupTargetNavigationOwnerAction::capture(
+ conn,
+ &browser_context_id,
+ &target_id,
+ target_url,
+ PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume,
+ ) else {
+ return false;
+ };
+ conn.publish_popup_target_navigation_owner_action(action);
+ true
+}
+
fn popup_target_has_loaded_page(
conn: &CdpConnection,
browser_context_id: &str,
@@ -497,7 +525,8 @@ pub(crate) async fn complete_popup_target_navigation_owner_action_async(
let mut protocol_events = Vec::new();
match kind {
- PopupTargetNavigationKind::InitialDocument => {
+ PopupTargetNavigationKind::InitialDocument
+ | PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume => {
if !conn.runtime_session_owner_should_start_initial_document_navigation(None) {
return crate::conn::CdpTurnOutcome::new_with_protocol_events(
Vec::new(),
@@ -514,7 +543,11 @@ pub(crate) async fn complete_popup_target_navigation_owner_action_async(
&url,
)
.await;
- if kind == PopupTargetNavigationKind::InitialDocument {
+ if matches!(
+ kind,
+ PopupTargetNavigationKind::InitialDocument
+ | PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume
+ ) {
emit_target_info_changed_for_target_background_event(
conn,
&mut protocol_events,
diff --git a/moli-protocol/src/domains/target/tests/test_support.rs b/moli-protocol/src/domains/target/tests/test_support.rs
index 31f867763..1dddda975 100644
--- a/moli-protocol/src/domains/target/tests/test_support.rs
+++ b/moli-protocol/src/domains/target/tests/test_support.rs
@@ -32,17 +32,16 @@ pub(super) fn push_background_target(
.browser_context
.as_mut()
.expect("browser context must exist before adding background target");
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- target_id.to_owned(),
- session_id.map(str::to_owned),
- crate::conn::TargetIdentityState::new(
- url.to_owned(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ target_id.to_owned(),
+ session_id.map(str::to_owned),
+ crate::conn::TargetIdentityState::new(
+ url.to_owned(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
}
pub(super) fn loaded_page_for_target<'a>(
@@ -54,7 +53,7 @@ pub(super) fn loaded_page_for_target<'a>(
} else {
browser_context
.background_target(target_id)
- .and_then(crate::conn::BackgroundTarget::loaded_page)
+ .and_then(crate::conn::PageTargetHost::loaded_page)
}
}
diff --git a/moli-protocol/src/domains/target/tests/tests_background_auto_attach.rs b/moli-protocol/src/domains/target/tests/tests_background_auto_attach.rs
index bf0cceac8..0f8b77217 100644
--- a/moli-protocol/src/domains/target/tests/tests_background_auto_attach.rs
+++ b/moli-protocol/src/domains/target/tests/tests_background_auto_attach.rs
@@ -102,17 +102,16 @@ async fn set_auto_attach_true_still_reports_transient_no_page_target_like_chromi
.attach_active_session("SID-active");
{
let bc = ctx.conn.browser_context.as_mut().expect("browser context");
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-background-in-transit".to_owned(),
- None,
- crate::conn::TargetIdentityState::new(
- "https://example.test/in-transit".to_owned(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-background-in-transit".to_owned(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "https://example.test/in-transit".to_owned(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
}
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
index 63811bdfe..9378b2ee1 100644
--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs
+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
@@ -158,7 +158,7 @@ async fn same_context_background_session_can_stage_its_own_pre_document_state_be
let staged_devtools_state = active
.parked_page_session_state(staged.target_id())
.expect("staged page session state")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.as_slice();
assert_eq!(staged_devtools_state.len(), 1);
@@ -178,7 +178,9 @@ async fn same_context_background_session_can_stage_its_own_pre_document_state_be
script_id
);
assert!(
- active.devtools_session_state.runtime_bindings.is_empty(),
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .is_empty(),
"active target DevTools session must not inherit staged target binding"
);
assert!(
@@ -356,7 +358,7 @@ async fn same_context_background_session_can_stage_its_own_utility_pre_document_
let staged_devtools_state = active
.parked_page_session_state(staged.target_id())
.expect("staged page session state")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.as_slice();
assert_eq!(staged_devtools_state.len(), 1);
@@ -383,7 +385,9 @@ async fn same_context_background_session_can_stage_its_own_utility_pre_document_
script_id
);
assert!(
- active.devtools_session_state.runtime_bindings.is_empty(),
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .is_empty(),
"active target DevTools session must not inherit staged target binding"
);
assert!(
@@ -609,7 +613,11 @@ async fn same_context_background_session_can_remove_its_own_binding_before_promo
.expect("staged background target");
let staged_bindings_empty = active
.parked_page_session_state(staged.target_id())
- .is_none_or(|state| state.devtools_session_state.runtime_bindings.is_empty());
+ .is_none_or(|state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .is_empty()
+ });
assert!(
staged_bindings_empty,
"removed binding should be cleared from parked DevTools session"
@@ -768,7 +776,7 @@ async fn same_context_background_session_can_remove_its_own_preload_before_promo
let staged_bindings = &active
.parked_page_session_state(staged.target_id())
.expect("staged page session state")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings;
assert_eq!(staged_bindings.len(), 1);
assert!(
@@ -919,7 +927,11 @@ async fn same_context_background_session_can_remove_its_own_utility_binding_befo
.expect("staged background target");
let staged_bindings_empty = active
.parked_page_session_state(staged.target_id())
- .is_none_or(|state| state.devtools_session_state.runtime_bindings.is_empty());
+ .is_none_or(|state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .is_empty()
+ });
assert!(
staged_bindings_empty,
"removed utility binding should be cleared from parked DevTools session"
@@ -1103,7 +1115,7 @@ async fn same_context_background_session_can_remove_its_own_utility_preload_befo
let staged_bindings = &active
.parked_page_session_state(staged.target_id())
.expect("staged page session state")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings;
assert_eq!(staged_bindings.len(), 1);
assert_eq!(
@@ -2613,7 +2625,7 @@ async fn same_context_background_session_can_clear_its_own_user_agent_before_pro
}
#[tokio::test(flavor = "multi_thread")]
-async fn same_context_background_session_can_stage_its_own_locale_and_timezone_before_promotion() {
+async fn same_context_background_session_stages_locale_without_changing_request_language() {
async fn handler(
State(seen): State<Arc<Mutex<Vec<(String, Option<String>)>>>>,
headers: HeaderMap,
@@ -2765,7 +2777,7 @@ async fn same_context_background_session_can_stage_its_own_locale_and_timezone_b
"method": "Runtime.evaluate",
"sessionId": "SID-active",
"params": {
- "expression": "JSON.stringify({ lang: navigator.language, tz: Intl.DateTimeFormat().resolvedOptions().timeZone })"
+ "expression": "JSON.stringify({ lang: navigator.language, locale: Intl.DateTimeFormat().resolvedOptions().locale, tz: Intl.DateTimeFormat().resolvedOptions().timeZone })"
}
}))
.await;
@@ -2775,7 +2787,8 @@ async fn same_context_background_session_can_stage_its_own_locale_and_timezone_b
.expect("active payload should be string");
let active_payload: serde_json::Value =
serde_json::from_str(active_payload).expect("active payload should be valid json");
- assert_eq!(active_payload["lang"], json!("en-GB"));
+ assert_eq!(active_payload["lang"], json!("en-US"));
+ assert_eq!(active_payload["locale"], json!("en-GB"));
assert_eq!(active_payload["tz"], json!("UTC"));
ctx.process_async(json!({
@@ -2809,7 +2822,7 @@ async fn same_context_background_session_can_stage_its_own_locale_and_timezone_b
"method": "Runtime.evaluate",
"sessionId": second_session_id,
"params": {
- "expression": "JSON.stringify({ lang: navigator.language, tz: Intl.DateTimeFormat().resolvedOptions().timeZone })"
+ "expression": "JSON.stringify({ lang: navigator.language, locale: Intl.DateTimeFormat().resolvedOptions().locale, tz: Intl.DateTimeFormat().resolvedOptions().timeZone })"
}
}))
.await;
@@ -2819,15 +2832,16 @@ async fn same_context_background_session_can_stage_its_own_locale_and_timezone_b
.expect("promoted payload should be string");
let promoted_payload: serde_json::Value =
serde_json::from_str(promoted_payload).expect("promoted payload should be valid json");
- assert_eq!(promoted_payload["lang"], json!("fr-FR"));
+ assert_eq!(promoted_payload["lang"], json!("en-US"));
+ assert_eq!(promoted_payload["locale"], json!("fr-FR"));
assert_eq!(promoted_payload["tz"], json!("Asia/Shanghai"));
let seen = seen.lock().clone();
assert_eq!(
seen,
vec![
- ("/page-a".to_owned(), Some("en-GB".to_owned())),
- ("/page-b".to_owned(), Some("fr-FR".to_owned()))
+ ("/page-a".to_owned(), Some("en-US,en;q=0.9".to_owned())),
+ ("/page-b".to_owned(), Some("en-US,en;q=0.9".to_owned()))
]
);
@@ -2957,7 +2971,10 @@ async fn same_context_background_session_can_clear_its_own_locale_before_promoti
.and_then(|tail| tail.split("</body>").next())
.expect("active payload should be embedded in body")
.to_owned();
- assert_ne!(active_surface, "fr-FR|fr-FR");
+ assert!(
+ active_surface.starts_with("en-US|en-US,en;q=0.9"),
+ "active target should retain the default navigator and request languages: {active_surface}"
+ );
ctx.process_async(json!({
"id": 104194806,
@@ -2992,10 +3009,6 @@ async fn same_context_background_session_can_clear_its_own_locale_before_promoti
promoted_surface, active_surface,
"promoted target should observe default locale surface after clearing its staged override"
);
- assert_ne!(
- promoted_surface, "fr-FR|fr-FR",
- "promoted target should not retain the staged locale override"
- );
server.abort();
}
@@ -3490,30 +3503,26 @@ async fn same_context_background_session_can_stage_its_own_page_settings_before_
.parked_page_session_state(&second_target_id)
.expect("staged page settings for background target");
assert!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_bypass_csp_enabled
);
assert_eq!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("standard"),
Some(&json!("Georgia"))
);
assert_eq!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("fixed"),
Some(&json!("Fira Code"))
);
assert!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
);
@@ -3534,30 +3543,26 @@ async fn same_context_background_session_can_stage_its_own_page_settings_before_
.expect("promoted browser context");
assert_eq!(active.active_target_id(), Some(second_target_id.as_str()));
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_bypass_csp_enabled
);
assert_eq!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("standard"),
Some(&json!("Georgia"))
);
assert_eq!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_font_families
.get("fixed"),
Some(&json!("Fira Code"))
);
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_intercept_file_chooser_dialog_enabled
);
@@ -4299,8 +4304,7 @@ async fn same_context_background_session_can_stage_its_own_lifecycle_events_befo
.as_ref()
.expect("active browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
@@ -4308,8 +4312,7 @@ async fn same_context_background_session_can_stage_its_own_lifecycle_events_befo
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
assert!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
@@ -4477,8 +4480,7 @@ async fn same_context_background_session_can_disable_its_own_lifecycle_events_be
.as_ref()
.expect("active browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
@@ -4615,8 +4617,7 @@ async fn same_context_background_session_can_stage_its_own_runtime_enable_before
.as_ref()
.expect("active browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
@@ -4624,8 +4625,7 @@ async fn same_context_background_session_can_stage_its_own_runtime_enable_before
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
assert!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
@@ -4844,8 +4844,8 @@ async fn same_context_loaded_background_session_runtime_enable_replays_context_w
);
assert!(
bc.parked_page_session_state(&second_target_id)
- .is_some_and(|state| state
- .devtools_session_state
+ .is_some_and(|state| state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled),
"Runtime.enable should be staged on the background target owner"
@@ -5543,8 +5543,7 @@ async fn same_context_background_session_can_disable_its_own_runtime_before_prom
.as_ref()
.expect("active browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
@@ -5691,8 +5690,7 @@ async fn same_context_background_session_can_stage_its_own_inspector_enable_befo
.is_crashed()
);
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -5700,8 +5698,7 @@ async fn same_context_background_session_can_stage_its_own_inspector_enable_befo
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
assert!(
- staged
- .devtools_session_state
+ staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -5834,8 +5831,7 @@ async fn same_context_background_session_can_disable_its_own_inspector_before_pr
.as_ref()
.expect("active browser context");
assert!(
- !active
- .devtools_session_state
+ !active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -6223,15 +6219,18 @@ async fn same_context_background_session_can_stage_its_own_fetch_enable_before_p
let staged = active
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
- assert!(staged.fetch_config.is_enabled());
- assert_eq!(staged.fetch_config.patterns().len(), 1);
- assert_eq!(staged.fetch_config.patterns()[0].url_pattern, "*");
+ assert!(staged.fetch_owner.config_snapshot().is_enabled());
+ assert_eq!(staged.fetch_owner.config_snapshot().patterns().len(), 1);
+ assert_eq!(
+ staged.fetch_owner.config_snapshot().patterns()[0].url_pattern,
+ "*"
+ );
assert_eq!(
- staged.fetch_config.patterns()[0].resource_type_filter,
+ staged.fetch_owner.config_snapshot().patterns()[0].resource_type_filter,
Some(crate::conn::FetchResourceTypeFilter::Document)
);
assert_eq!(
- staged.fetch_config.patterns()[0].request_stage,
+ staged.fetch_owner.config_snapshot().patterns()[0].request_stage,
crate::conn::FetchRequestStage::Request
);
}
@@ -6554,8 +6553,8 @@ async fn same_context_background_session_can_stage_its_own_fetch_auth_handling_b
let staged = active
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
- assert!(staged.fetch_config.is_enabled());
- assert!(staged.fetch_config.handle_auth_requests());
+ assert!(staged.fetch_owner.config_snapshot().is_enabled());
+ assert!(staged.fetch_owner.config_snapshot().handle_auth_requests());
}
ctx.process_async(json!({
@@ -6909,7 +6908,7 @@ async fn same_context_background_session_can_stage_its_own_network_enable_before
let staged = active
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
- assert!(staged.network_enabled);
+ assert!(staged.runtime_slot.primary_network_events_enabled());
}
ctx.process_async(json!({
@@ -7106,7 +7105,11 @@ async fn same_context_background_session_can_disable_its_own_network_before_prom
"network disable should collapse staged parked state back to default"
);
assert!(
- active.parked_network_artifacts(&second_target_id).is_none(),
+ active
+ .background_target(&second_target_id)
+ .expect("background target")
+ .runtime_slot
+ .network_artifacts_are_default_for_test(),
"network disable should clear staged parked network artifacts"
);
}
@@ -7296,7 +7299,7 @@ async fn same_context_background_session_can_stage_its_own_cache_and_service_wor
let staged = active
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
- assert!(staged.network_enabled);
+ assert!(staged.runtime_slot.primary_network_events_enabled());
assert!(staged.network_policy.cache_disabled());
assert!(staged.network_policy.bypass_service_worker());
}
@@ -7537,7 +7540,7 @@ async fn same_context_background_session_can_disable_its_own_cache_and_service_w
let staged = active
.parked_page_session_state(&second_target_id)
.expect("second target should have staged parked page session state");
- assert!(staged.network_enabled);
+ assert!(staged.runtime_slot.primary_network_events_enabled());
assert!(!staged.network_policy.cache_disabled());
assert!(!staged.network_policy.bypass_service_worker());
}
diff --git a/moli-protocol/src/domains/target/tests/tests_browser_context.rs b/moli-protocol/src/domains/target/tests/tests_browser_context.rs
index a13e4c745..b424b90ae 100644
--- a/moli-protocol/src/domains/target/tests/tests_browser_context.rs
+++ b/moli-protocol/src/domains/target/tests/tests_browser_context.rs
@@ -112,7 +112,7 @@ async fn dispose_browser_context_emits_detached_events_for_attached_target() {
let mut bc = BrowserContext::new("BID-20".into());
bc.set_active_target_id("TID-000000000A");
bc.attach_active_session("SID-000000000A");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
ctx.conn.browser_context = Some(bc);
@@ -784,7 +784,7 @@ async fn dispose_browser_context_aborts_paused_request_stage_navigation() {
let mut bc = BrowserContext::new("BID-9".into());
bc.set_active_target_id("TID-000000000A");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/browser_target.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/browser_target.rs
index 0374a139b..8d2a8c28d 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/browser_target.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/browser_target.rs
@@ -425,7 +425,7 @@ async fn rust_cdp_capability_target_browser_context_proxy_and_enumeration() {
ctx.conn
.browser_context
.as_ref()
- .and_then(|context| context.http_proxy_override.as_deref()),
+ .and_then(|context| context.default_http_proxy_override.as_deref()),
Some("http://proxy.example:8080")
);
}
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_contexts.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_contexts.rs
index f7be67880..00dac7332 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_contexts.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_contexts.rs
@@ -168,7 +168,7 @@ async fn rust_cdp_chromium_target_create_browser_context_proxy_server_is_recorde
assert_eq!(
ctx.conn
.browser_context_by_id(&browser_context_id)
- .and_then(|context| context.http_proxy_override.as_deref()),
+ .and_then(|context| context.default_http_proxy_override.as_deref()),
Some("http://proxy.example:8080")
);
}
@@ -196,7 +196,7 @@ async fn rust_cdp_chromium_target_create_browser_context_proxy_bypass_normalizes
assert_eq!(
ctx.conn
.browser_context_by_id(&browser_context_id)
- .and_then(|context| context.http_no_proxy_override.as_deref()),
+ .and_then(|context| context.default_http_no_proxy_override.as_deref()),
Some("localhost,.example.com")
);
}
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs
index 4d564b0bb..f4ec33276 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs
@@ -542,9 +542,9 @@ async fn rust_cdp_chromium_target_second_create_target_activates_new_target_by_d
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert_eq!(browser_context.active_target_id(), Some(target_id.as_str()));
- assert_eq!(browser_context.background_targets.len(), 1);
+ assert_eq!(browser_context.background_target_count(), 1);
assert_eq!(
- browser_context.background_targets[0].target_id(),
+ browser_context.background_target_at(0).unwrap().target_id(),
"TID-000000000A"
);
@@ -784,19 +784,31 @@ async fn rust_cdp_chromium_target_window_open_auto_attached_popup_materializes_i
async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_document_after_resume() {
let fixture = SmokeFixtureServer::start().await;
let mut ctx = TestContext::new_with_target_discovery(false);
+ ctx.enable_background_navigation_scheduler_for_test();
+ tokio::task::LocalSet::new()
+ .run_until(run_waiting_popup_initial_document_after_resume(
+ &mut ctx, &fixture,
+ ))
+ .await;
+}
+
+async fn run_waiting_popup_initial_document_after_resume(
+ ctx: &mut TestContext,
+ fixture: &SmokeFixtureServer,
+) {
load_bc_with_titled_page_async(
- &mut ctx,
+ ctx,
"BID-popup-wait-route",
"TID-wait-route-opener",
"<main>opener</main>",
)
.await;
- set_auto_attach_waiting_for_debugger(&mut ctx, 260_215).await;
+ set_auto_attach_waiting_for_debugger(ctx, 260_215).await;
ctx.take_all();
let popup_url = fixture.url("/plain?popup=wait-route");
let messages = open_popup_from_runtime(
- &mut ctx,
+ ctx,
260_216,
&format!("window.open('{popup_url}', '_blank') !== null"),
)
@@ -816,7 +828,7 @@ async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_docum
"sessionId": popup_session_id
}))
.await;
- take_response_by_id(&mut ctx, 260_217);
+ take_response_by_id(ctx, 260_217);
assert!(
ctx.conn
.browser_context
@@ -859,7 +871,28 @@ async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_docum
"sessionId": popup_session_id
}))
.await;
- take_response_by_id(&mut ctx, 260_219);
+ crate::testing::wait_until_scheduler_message(
+ ctx,
+ "popup document request after debugger resume",
+ |message| message["method"] == json!("Fetch.requestPaused"),
+ )
+ .await;
+ let response_index = ctx
+ .sent
+ .iter()
+ .position(|message| message["id"] == json!(260_219))
+ .expect("runIfWaitingForDebugger terminal response");
+ let request_index = ctx
+ .sent
+ .iter()
+ .position(|message| message["method"] == json!("Fetch.requestPaused"))
+ .expect("popup document request");
+ assert!(
+ response_index < request_index,
+ "the debugger-resume response must cross the frontend before its initial navigation can replace about:blank: {:?}",
+ ctx.sent
+ );
+ take_response_by_id(ctx, 260_219);
let paused = ctx
.sent
.iter()
@@ -900,7 +933,7 @@ async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_docum
}
}))
.await;
- let isolated = take_response_by_id(&mut ctx, 260_220);
+ let isolated = take_response_by_id(ctx, 260_220);
assert!(
isolated["result"]["executionContextId"].as_i64().is_some(),
"createIsolatedWorld should resolve while popup initial document is paused: {isolated:?}"
@@ -928,14 +961,10 @@ async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_docum
}))
.await;
ctx.expect_result(260_221, json!({}), Some(popup_session_id));
- crate::testing::wait_until_scheduler_message(
- &mut ctx,
- "resumed popup load lifecycle",
- |message| {
- message["method"] == json!("Page.loadEventFired")
- && message["sessionId"] == json!(popup_session_id)
- },
- )
+ crate::testing::wait_until_scheduler_message(ctx, "resumed popup load lifecycle", |message| {
+ message["method"] == json!("Page.loadEventFired")
+ && message["sessionId"] == json!(popup_session_id)
+ })
.await;
assert!(
ctx.sent.iter().any(|message| {
@@ -958,7 +987,7 @@ async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_docum
}))
.await;
assert_eq!(
- take_response_by_id(&mut ctx, 260_222)["result"]["result"]["value"],
+ take_response_by_id(ctx, 260_222)["result"]["result"]["value"],
"routed-popup"
);
}
@@ -1190,7 +1219,7 @@ async fn rust_cdp_chromium_target_resetting_opener_clears_popup_opener_reference
.browser_context
.as_mut()
.unwrap()
- .reset_active_target_slot_to_empty_async()
+ .remove_active_page_target_async()
.await;
assert!(
diff --git a/moli-protocol/src/domains/target/tests/tests_control_plane.rs b/moli-protocol/src/domains/target/tests/tests_control_plane.rs
index 5581eccb4..c061e67f2 100644
--- a/moli-protocol/src/domains/target/tests/tests_control_plane.rs
+++ b/moli-protocol/src/domains/target/tests/tests_control_plane.rs
@@ -1088,8 +1088,7 @@ async fn set_auto_attach_true_attaches_existing_background_targets() {
.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(crate::conn::BackgroundTarget::new(
+ .insert_page_target_host(crate::conn::PageTargetHost::new(
"TID-000000000F".into(),
None,
crate::conn::TargetIdentityState::new(
@@ -1145,8 +1144,7 @@ async fn set_auto_attach_promotes_existing_background_target_when_active_target_
.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(crate::conn::BackgroundTarget::new(
+ .insert_page_target_host(crate::conn::PageTargetHost::new(
"TID-000000000F".into(),
None,
crate::conn::TargetIdentityState::new(
@@ -1230,28 +1228,26 @@ async fn set_auto_attach_sweep_chain_promotes_multiple_existing_background_targe
let mut ctx = TestContext::new();
load_bc_with_target(&mut ctx, "BID-9", "TID-000000000E");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000F".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#second".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-0000000010".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#third".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000F".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#second".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-0000000010".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#third".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
ctx.process_async(json!({
"id": 17018,
@@ -1364,17 +1360,16 @@ async fn set_auto_attach_prefers_existing_background_target_with_parked_loaded_r
load_bc_with_target(&mut ctx, "BID-9", "TID-000000000E");
{
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000F".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#metadata-only".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000F".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#metadata-only".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
bc.stage_active_target_demoting_current(
"TID-0000000010".into(),
None,
@@ -1473,8 +1468,7 @@ async fn activate_target_promotes_set_auto_attach_background_session_into_page_r
.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(crate::conn::BackgroundTarget::new(
+ .insert_page_target_host(crate::conn::PageTargetHost::new(
"TID-000000000F".into(),
None,
crate::conn::TargetIdentityState::new(
@@ -1555,28 +1549,26 @@ async fn activate_target_chain_switches_between_multiple_attached_background_tar
load_bc_with_target(&mut ctx, "BID-9", "TID-000000000E");
let bc = ctx.conn.browser_context.as_mut().unwrap();
bc.attach_active_session("SID-active");
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000F".into(),
- Some("SID-second".into()),
- crate::conn::TargetIdentityState::new(
- "about:blank#second".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-0000000010".into(),
- Some("SID-third".into()),
- crate::conn::TargetIdentityState::new(
- "about:blank#third".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000F".into(),
+ Some("SID-second".into()),
+ crate::conn::TargetIdentityState::new(
+ "about:blank#second".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-0000000010".into(),
+ Some("SID-third".into()),
+ crate::conn::TargetIdentityState::new(
+ "about:blank#third".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
ctx.process_async(json!({
"id": 17030,
@@ -1656,8 +1648,7 @@ async fn set_auto_attach_false_detaches_existing_background_targets() {
.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(crate::conn::BackgroundTarget::new(
+ .insert_page_target_host(crate::conn::PageTargetHost::new(
"TID-000000000F".into(),
Some("SID-bg".into()),
crate::conn::TargetIdentityState::new(
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/binding_isolation.rs b/moli-protocol/src/domains/target/tests/tests_patchright/binding_isolation.rs
index b7935dd4f..848bc18bc 100644
--- a/moli-protocol/src/domains/target/tests/tests_patchright/binding_isolation.rs
+++ b/moli-protocol/src/domains/target/tests/tests_patchright/binding_isolation.rs
@@ -1548,1636 +1548,3 @@ async fn patchright_over_cdp_same_named_handle_binding_in_main_and_utility_world
})
.await;
}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_same_named_dual_world_handle_binding_keeps_same_seq_isolated_by_execution_context()
- {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 363, 364, 365).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 366, 367, 368).await;
-
- for (id, session_id, label, main_handle_id, utility_handle_id) in [
- (
- 369_u64,
- first.session_id.as_str(),
- "first-page",
- "first-main-handle",
- "first-utility-handle",
- ),
- (
- 372_u64,
- second.session_id.as_str(),
- "second-page",
- "second-main-handle",
- "second-utility-handle",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedDualWorldHandleBinding"
- }
- }))
- .await;
- let add_main_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_main_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedDualWorldHandleBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_utility_binding = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(add_utility_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!(
- "data:text/html,<body><div id='page'>{label}</div><div id='{main_handle_id}'>main-{label}</div><div id='{utility_handle_id}'>utility-{label}</div></body>"
- )
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (375_u64, first.target_id.as_str(), first.session_id.as_str()),
- (
- 376_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 377,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(377, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 378_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 379_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- let handle_wrapper_source = r#"
- (() => {
- function addHandleBinding(bindingName) {
- const binding = globalThis[bindingName];
- globalThis[bindingName] = (...args) => {
- const me = globalThis[bindingName];
- let callbacks = me.callbacks;
- if (!callbacks) {
- callbacks = new Map();
- me.callbacks = callbacks;
- }
- let handles = me.handles;
- if (!handles) {
- handles = new Map();
- me.handles = handles;
- }
- const seq = (me.lastSeq || 0) + 1;
- me.lastSeq = seq;
- handles.set(seq, args[0]);
- const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));
- binding(JSON.stringify({ name: bindingName, seq }));
- return promise;
- };
- }
- function takeBindingHandle(arg) {
- const handles = globalThis[arg.name].handles;
- const handle = handles.get(arg.seq);
- handles.delete(arg.seq);
- return handle;
- }
- function deliverBindingResult(arg) {
- const callbacks = globalThis[arg.name].callbacks;
- if ('error' in arg)
- callbacks.get(arg.seq).reject(arg.error);
- else
- callbacks.get(arg.seq).resolve(arg.result);
- callbacks.delete(arg.seq);
- }
- addHandleBinding('sharedDualWorldHandleBinding');
- globalThis.__lm_shared_dual_world_take_handle = takeBindingHandle;
- globalThis.__lm_shared_dual_world_deliver_handle = deliverBindingResult;
- return typeof globalThis.sharedDualWorldHandleBinding;
- })()
- "#;
-
- for (id, session_id) in [
- (380_u64, first_auto_session.as_str()),
- (382_u64, second_auto_session.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": handle_wrapper_source
- }
- }))
- .await;
- let install_main_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_main_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- for (id, session_id, utility_context) in [
- (381_u64, first_auto_session.as_str(), first_utility_context),
- (
- 383_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": handle_wrapper_source
- }
- }))
- .await;
- let install_utility_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_utility_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- let mut first_main_seq = 0_i64;
- let mut first_main_context = 0_i64;
- let mut first_utility_seq = 0_i64;
- let mut second_main_seq = 0_i64;
- let mut second_main_context = 0_i64;
- let mut second_utility_seq = 0_i64;
- for (
- id,
- session_id,
- context_id,
- expression,
- expected_name,
- expected_text,
- seq_out,
- main_context_out,
- ) in [
- (
- 384_u64,
- first_auto_session.as_str(),
- None,
- "globalThis.__lm_first_main_handle_promise = sharedDualWorldHandleBinding(document.getElementById('first-main-handle')); 'scheduled-first-main'",
- "first-main-handle",
- "main-first-page",
- &mut first_main_seq,
- Some(&mut first_main_context),
- ),
- (
- 385_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- "globalThis.__lm_first_utility_handle_promise = sharedDualWorldHandleBinding(document.getElementById('first-utility-handle')); 'scheduled-first-utility'",
- "first-utility-handle",
- "utility-first-page",
- &mut first_utility_seq,
- None,
- ),
- (
- 386_u64,
- second_auto_session.as_str(),
- None,
- "globalThis.__lm_second_main_handle_promise = sharedDualWorldHandleBinding(document.getElementById('second-main-handle')); 'scheduled-second-main'",
- "second-main-handle",
- "main-second-page",
- &mut second_main_seq,
- Some(&mut second_main_context),
- ),
- (
- 387_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- "globalThis.__lm_second_utility_handle_promise = sharedDualWorldHandleBinding(document.getElementById('second-utility-handle')); 'scheduled-second-utility'",
- "second-utility-handle",
- "utility-second-page",
- &mut second_utility_seq,
- None,
- ),
- ] {
- let mut params = json!({ "expression": expression });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- let scheduled = take_response_by_id(&mut ctx, id);
- assert!(
- scheduled["result"]["result"]["value"]
- .as_str()
- .expect("scheduled value")
- .starts_with("scheduled-")
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedDualWorldHandleBinding")
- })
- .cloned()
- .expect("dual-world handle binding should emit Runtime.bindingCalled");
- let execution_context_id = binding_called["params"]["executionContextId"]
- .as_i64()
- .expect("execution context id");
- if let Some(main_context_out) = main_context_out {
- *main_context_out = execution_context_id;
- } else {
- assert_eq!(
- execution_context_id,
- context_id.expect("utility context id")
- );
- }
- let payload = binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let payload: serde_json::Value =
- serde_json::from_str(payload).expect("binding payload should be valid json");
- assert_eq!(payload["name"], json!("sharedDualWorldHandleBinding"));
- *seq_out = payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(*seq_out, 1);
- ctx.sent.clear();
-
- let mut take_params = json!({
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_shared_dual_world_take_handle({{ name: 'sharedDualWorldHandleBinding', seq: {} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_shared_dual_world_take_handle({{ name: 'sharedDualWorldHandleBinding', seq: {} }})]); }})()",
- *seq_out, *seq_out
- )
- });
- if let Some(context_id) = context_id {
- take_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id + 10,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": take_params
- }))
- .await;
- let taken = take_response_by_id(&mut ctx, id + 10);
- let taken_value = taken["result"]["result"]["value"]
- .as_str()
- .expect("handle take should serialize");
- let taken_value: serde_json::Value =
- serde_json::from_str(taken_value).expect("taken handle json");
- assert_eq!(
- taken_value,
- json!([expected_name, expected_text, "undefined"])
- );
- }
-
- assert_ne!(first_main_context, first_utility_context);
- assert_ne!(second_main_context, second_utility_context);
-
- for (id, session_id, context_id, seq, result, promise_name) in [
- (
- 398_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- second_utility_seq,
- "second-utility-resolved",
- "__lm_second_utility_handle_promise",
- ),
- (
- 399_u64,
- first_auto_session.as_str(),
- None,
- first_main_seq,
- "first-main-resolved",
- "__lm_first_main_handle_promise",
- ),
- (
- 400_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- first_utility_seq,
- "first-utility-resolved",
- "__lm_first_utility_handle_promise",
- ),
- (
- 401_u64,
- second_auto_session.as_str(),
- None,
- second_main_seq,
- "second-main-resolved",
- "__lm_second_main_handle_promise",
- ),
- ] {
- let mut deliver_params = json!({
- "expression": format!(
- "globalThis.__lm_shared_dual_world_deliver_handle({{ name: 'sharedDualWorldHandleBinding', seq: {seq}, result: '{result}' }}); 'delivered'"
- )
- });
- if let Some(context_id) = context_id {
- deliver_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": deliver_params
- }))
- .await;
- let delivered = take_response_by_id(&mut ctx, id);
- assert_eq!(delivered["result"]["result"]["value"], json!("delivered"));
-
- let mut promise_params = json!({
- "expression": format!("globalThis.{promise_name}"),
- "awaitPromise": true
- });
- if let Some(context_id) = context_id {
- promise_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id + 10,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": promise_params
- }))
- .await;
- let resolved = take_response_by_id(&mut ctx, id + 10);
- assert_eq!(resolved["result"]["result"]["value"], json!(result));
- }
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_same_named_dual_world_page_binding_keeps_same_seq_isolated_by_execution_context()
- {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 402, 403, 404).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 405, 406, 407).await;
-
- for (id, session_id, label) in [
- (408_u64, first.session_id.as_str(), "first-page"),
- (411_u64, second.session_id.as_str(), "second-page"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedDualWorldBinding"
- }
- }))
- .await;
- let add_main_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_main_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedDualWorldBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_utility_binding = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(add_utility_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (414_u64, first.target_id.as_str(), first.session_id.as_str()),
- (
- 415_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 416,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(416, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 417_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 418_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- let wrapper_source = r#"
- (() => {
- function addPageBinding(bindingName) {
- const binding = globalThis[bindingName];
- globalThis[bindingName] = (...args) => {
- const me = globalThis[bindingName];
- let callbacks = me.callbacks;
- if (!callbacks) {
- callbacks = new Map();
- me.callbacks = callbacks;
- }
- const seq = (me.lastSeq || 0) + 1;
- me.lastSeq = seq;
- const payload = { name: bindingName, seq, serializedArgs: args };
- const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));
- binding(JSON.stringify(payload));
- return promise;
- };
- }
- function deliverBindingResult(arg) {
- const callbacks = globalThis[arg.name].callbacks;
- if ('error' in arg)
- callbacks.get(arg.seq).reject(arg.error);
- else
- callbacks.get(arg.seq).resolve(arg.result);
- callbacks.delete(arg.seq);
- }
- addPageBinding('sharedDualWorldBinding');
- globalThis.__lm_shared_dual_world_deliver = deliverBindingResult;
- return typeof globalThis.sharedDualWorldBinding;
- })()
- "#;
-
- for (id, session_id) in [
- (419_u64, first_auto_session.as_str()),
- (421_u64, second_auto_session.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": wrapper_source
- }
- }))
- .await;
- let install_main_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_main_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- for (id, session_id, utility_context) in [
- (420_u64, first_auto_session.as_str(), first_utility_context),
- (
- 422_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": wrapper_source
- }
- }))
- .await;
- let install_utility_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_utility_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- let mut first_main_seq = 0_i64;
- let mut first_main_context = 0_i64;
- let mut first_utility_seq = 0_i64;
- let mut second_main_seq = 0_i64;
- let mut second_main_context = 0_i64;
- let mut second_utility_seq = 0_i64;
- for (id, session_id, context_id, expression, serialized_arg, seq_out, main_context_out) in [
- (
- 423_u64,
- first_auto_session.as_str(),
- None,
- "globalThis.__lm_first_main_binding_promise = sharedDualWorldBinding('from-first-main'); 'scheduled-first-main'",
- "from-first-main",
- &mut first_main_seq,
- Some(&mut first_main_context),
- ),
- (
- 424_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- "globalThis.__lm_first_utility_binding_promise = sharedDualWorldBinding('from-first-utility'); 'scheduled-first-utility'",
- "from-first-utility",
- &mut first_utility_seq,
- None,
- ),
- (
- 425_u64,
- second_auto_session.as_str(),
- None,
- "globalThis.__lm_second_main_binding_promise = sharedDualWorldBinding('from-second-main'); 'scheduled-second-main'",
- "from-second-main",
- &mut second_main_seq,
- Some(&mut second_main_context),
- ),
- (
- 426_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- "globalThis.__lm_second_utility_binding_promise = sharedDualWorldBinding('from-second-utility'); 'scheduled-second-utility'",
- "from-second-utility",
- &mut second_utility_seq,
- None,
- ),
- ] {
- let mut params = json!({ "expression": expression });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- let scheduled = take_response_by_id(&mut ctx, id);
- assert!(
- scheduled["result"]["result"]["value"]
- .as_str()
- .expect("scheduled value")
- .starts_with("scheduled-")
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedDualWorldBinding")
- })
- .cloned()
- .expect("dual-world page binding should emit Runtime.bindingCalled");
- let execution_context_id = binding_called["params"]["executionContextId"]
- .as_i64()
- .expect("execution context id");
- if let Some(main_context_out) = main_context_out {
- *main_context_out = execution_context_id;
- } else {
- assert_eq!(
- execution_context_id,
- context_id.expect("utility context id")
- );
- }
- let payload = binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let payload: serde_json::Value = serde_json::from_str(payload).unwrap_or_else(|error| {
- panic!(
- "binding payload should be valid json: {error}; payload={payload:?}; event={binding_called:?}"
- )
- });
- assert_eq!(payload["name"], json!("sharedDualWorldBinding"));
- assert_eq!(payload["serializedArgs"], json!([serialized_arg]));
- *seq_out = payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(*seq_out, 1);
- ctx.sent.clear();
- }
-
- assert_ne!(first_main_context, first_utility_context);
- assert_ne!(second_main_context, second_utility_context);
-
- for (id, session_id, context_id, seq, result, promise_name) in [
- (
- 427_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- second_utility_seq,
- "second-utility-resolved",
- "__lm_second_utility_binding_promise",
- ),
- (
- 428_u64,
- first_auto_session.as_str(),
- None,
- first_main_seq,
- "first-main-resolved",
- "__lm_first_main_binding_promise",
- ),
- (
- 429_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- first_utility_seq,
- "first-utility-resolved",
- "__lm_first_utility_binding_promise",
- ),
- (
- 430_u64,
- second_auto_session.as_str(),
- None,
- second_main_seq,
- "second-main-resolved",
- "__lm_second_main_binding_promise",
- ),
- ] {
- let mut deliver_params = json!({
- "expression": format!(
- "globalThis.__lm_shared_dual_world_deliver({{ name: 'sharedDualWorldBinding', seq: {seq}, result: '{result}' }}); 'delivered'"
- )
- });
- if let Some(context_id) = context_id {
- deliver_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": deliver_params
- }))
- .await;
- let delivered = take_response_by_id(&mut ctx, id);
- assert_eq!(delivered["result"]["result"]["value"], json!("delivered"));
-
- let mut promise_params = json!({
- "expression": format!("globalThis.{promise_name}"),
- "awaitPromise": true
- });
- if let Some(context_id) = context_id {
- promise_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id + 10,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": promise_params
- }))
- .await;
- let resolved = take_response_by_id(&mut ctx, id + 10);
- assert_eq!(resolved["result"]["result"]["value"], json!(result));
- }
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_same_named_dual_world_page_binding_keeps_serialized_object_args_isolated_by_execution_context()
- {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 3431, 3432, 3433).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 3434, 3435, 3436).await;
-
- for (id, session_id, label) in [
- (3437_u64, first.session_id.as_str(), "first-object-page"),
- (3440_u64, second.session_id.as_str(), "second-object-page"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedDualWorldObjectBinding"
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedDualWorldObjectBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id + 1)["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 3443_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 3444_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 3445,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(3445, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 3446_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 3447_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- let wrapper_source = patchright_page_binding_wrapper_source(
- "sharedDualWorldObjectBinding",
- "__lm_shared_dual_world_object_deliver",
- None,
- false,
- );
-
- for (id, session_id) in [
- (3448_u64, first_auto_session.as_str()),
- (3450_u64, second_auto_session.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": &wrapper_source
- }
- }))
- .await;
- let install_main_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_main_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- for (id, session_id, utility_context) in [
- (3449_u64, first_auto_session.as_str(), first_utility_context),
- (
- 3451_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": &wrapper_source
- }
- }))
- .await;
- let install_utility_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_utility_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- let mut first_main_seq = 0_i64;
- let mut first_utility_seq = 0_i64;
- let mut second_main_seq = 0_i64;
- let mut second_utility_seq = 0_i64;
- let mut first_main_context = 0_i64;
- let mut second_main_context = 0_i64;
- for (id, session_id, context_id, expression, serialized_arg, seq_out, main_context_out) in [
- (
- 3452_u64,
- first_auto_session.as_str(),
- None,
- "globalThis.__lm_first_main_object_promise = sharedDualWorldObjectBinding({ source: 'first-main', nested: { count: 1, values: ['a', 2, true] } }); 'scheduled-first-main'",
- json!([{
- "source": "first-main",
- "nested": { "count": 1, "values": ["a", 2, true] }
- }]),
- &mut first_main_seq,
- Some(&mut first_main_context),
- ),
- (
- 3453_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- "globalThis.__lm_first_utility_object_promise = sharedDualWorldObjectBinding({ source: 'first-utility', nested: { count: 2, values: ['b', 3, false] } }); 'scheduled-first-utility'",
- json!([{
- "source": "first-utility",
- "nested": { "count": 2, "values": ["b", 3, false] }
- }]),
- &mut first_utility_seq,
- None,
- ),
- (
- 3454_u64,
- second_auto_session.as_str(),
- None,
- "globalThis.__lm_second_main_object_promise = sharedDualWorldObjectBinding({ source: 'second-main', nested: { count: 3, values: ['c', 4, true] } }); 'scheduled-second-main'",
- json!([{
- "source": "second-main",
- "nested": { "count": 3, "values": ["c", 4, true] }
- }]),
- &mut second_main_seq,
- Some(&mut second_main_context),
- ),
- (
- 3455_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- "globalThis.__lm_second_utility_object_promise = sharedDualWorldObjectBinding({ source: 'second-utility', nested: { count: 4, values: ['d', 5, false] } }); 'scheduled-second-utility'",
- json!([{
- "source": "second-utility",
- "nested": { "count": 4, "values": ["d", 5, false] }
- }]),
- &mut second_utility_seq,
- None,
- ),
- ] {
- let mut params = json!({ "expression": expression });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- let scheduled = take_response_by_id(&mut ctx, id);
- assert!(
- scheduled["result"]["result"]["value"]
- .as_str()
- .expect("scheduled value")
- .starts_with("scheduled-")
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedDualWorldObjectBinding")
- })
- .cloned()
- .expect("dual-world object binding should emit Runtime.bindingCalled");
- let execution_context_id = binding_called["params"]["executionContextId"]
- .as_i64()
- .expect("execution context id");
- if let Some(main_context_out) = main_context_out {
- *main_context_out = execution_context_id;
- } else {
- assert_eq!(
- execution_context_id,
- context_id.expect("utility context id")
- );
- }
- let payload = binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let payload: serde_json::Value = serde_json::from_str(payload).unwrap_or_else(|error| {
- panic!(
- "binding payload should be valid json: {error}; payload={payload:?}; event={binding_called:?}"
- )
- });
- assert_eq!(payload["name"], json!("sharedDualWorldObjectBinding"));
- assert_eq!(payload["serializedArgs"], serialized_arg);
- *seq_out = payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(*seq_out, 1);
- ctx.sent.clear();
- }
-
- assert_ne!(first_main_context, first_utility_context);
- assert_ne!(second_main_context, second_utility_context);
-
- for (id, session_id, context_id, seq, result, promise_name) in [
- (
- 3456_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- second_utility_seq,
- "second-utility-object-resolved",
- "__lm_second_utility_object_promise",
- ),
- (
- 3457_u64,
- first_auto_session.as_str(),
- None,
- first_main_seq,
- "first-main-object-resolved",
- "__lm_first_main_object_promise",
- ),
- (
- 3458_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- first_utility_seq,
- "first-utility-object-resolved",
- "__lm_first_utility_object_promise",
- ),
- (
- 3459_u64,
- second_auto_session.as_str(),
- None,
- second_main_seq,
- "second-main-object-resolved",
- "__lm_second_main_object_promise",
- ),
- ] {
- let mut deliver_params = json!({
- "expression": format!(
- "globalThis.__lm_shared_dual_world_object_deliver({{ name: 'sharedDualWorldObjectBinding', seq: {seq}, result: '{result}' }}); 'delivered'"
- )
- });
- if let Some(context_id) = context_id {
- deliver_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": deliver_params
- }))
- .await;
- let delivered = take_response_by_id(&mut ctx, id);
- assert_eq!(delivered["result"]["result"]["value"], json!("delivered"));
-
- let mut promise_params = json!({
- "expression": format!("globalThis.{promise_name}"),
- "awaitPromise": true
- });
- if let Some(context_id) = context_id {
- promise_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id + 10,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": promise_params
- }))
- .await;
- let resolved = take_response_by_id(&mut ctx, id + 10);
- assert_eq!(resolved["result"]["result"]["value"], json!(result));
- }
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_same_named_dual_world_page_binding_rejection_keeps_same_seq_isolated_by_execution_context()
- {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 431, 432, 433).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 434, 435, 436).await;
-
- for (id, session_id, label) in [
- (437_u64, first.session_id.as_str(), "first-page"),
- (440_u64, second.session_id.as_str(), "second-page"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedRejectingDualWorldBinding"
- }
- }))
- .await;
- let add_main_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_main_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedRejectingDualWorldBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_utility_binding = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(add_utility_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (443_u64, first.target_id.as_str(), first.session_id.as_str()),
- (
- 444_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 445,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(445, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 446_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 447_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- let wrapper_source = r#"
- (() => {
- function addPageBinding(bindingName) {
- const binding = globalThis[bindingName];
- globalThis[bindingName] = (...args) => {
- const me = globalThis[bindingName];
- let callbacks = me.callbacks;
- if (!callbacks) {
- callbacks = new Map();
- me.callbacks = callbacks;
- }
- const seq = (me.lastSeq || 0) + 1;
- me.lastSeq = seq;
- const payload = { name: bindingName, seq, serializedArgs: args };
- const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));
- binding(JSON.stringify(payload));
- return promise;
- };
- }
- function deliverBindingResult(arg) {
- const callbacks = globalThis[arg.name].callbacks;
- if ('error' in arg)
- callbacks.get(arg.seq).reject(arg.error);
- else
- callbacks.get(arg.seq).resolve(arg.result);
- callbacks.delete(arg.seq);
- }
- addPageBinding('sharedRejectingDualWorldBinding');
- globalThis.__lm_shared_rejecting_dual_world_deliver = deliverBindingResult;
- return typeof globalThis.sharedRejectingDualWorldBinding;
- })()
- "#;
-
- for (id, session_id) in [
- (448_u64, first_auto_session.as_str()),
- (450_u64, second_auto_session.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": wrapper_source
- }
- }))
- .await;
- let install_main_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_main_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- for (id, session_id, utility_context) in [
- (449_u64, first_auto_session.as_str(), first_utility_context),
- (
- 451_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": wrapper_source
- }
- }))
- .await;
- let install_utility_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_utility_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- let mut first_main_seq = 0_i64;
- let mut first_main_context = 0_i64;
- let mut first_utility_seq = 0_i64;
- let mut second_main_seq = 0_i64;
- let mut second_main_context = 0_i64;
- let mut second_utility_seq = 0_i64;
- for (id, session_id, context_id, expression, serialized_arg, seq_out, main_context_out) in [
- (
- 452_u64,
- first_auto_session.as_str(),
- None,
- "globalThis.__lm_first_main_binding_promise = sharedRejectingDualWorldBinding('from-first-main').then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-first-main'",
- "from-first-main",
- &mut first_main_seq,
- Some(&mut first_main_context),
- ),
- (
- 453_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- "globalThis.__lm_first_utility_binding_promise = sharedRejectingDualWorldBinding('from-first-utility').then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-first-utility'",
- "from-first-utility",
- &mut first_utility_seq,
- None,
- ),
- (
- 454_u64,
- second_auto_session.as_str(),
- None,
- "globalThis.__lm_second_main_binding_promise = sharedRejectingDualWorldBinding('from-second-main').then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-second-main'",
- "from-second-main",
- &mut second_main_seq,
- Some(&mut second_main_context),
- ),
- (
- 455_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- "globalThis.__lm_second_utility_binding_promise = sharedRejectingDualWorldBinding('from-second-utility').then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-second-utility'",
- "from-second-utility",
- &mut second_utility_seq,
- None,
- ),
- ] {
- let mut params = json!({ "expression": expression });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- let scheduled = take_response_by_id(&mut ctx, id);
- assert!(
- scheduled["result"]["result"]["value"]
- .as_str()
- .expect("scheduled value")
- .starts_with("scheduled-")
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedRejectingDualWorldBinding")
- })
- .cloned()
- .expect("rejecting dual-world page binding should emit Runtime.bindingCalled");
- let execution_context_id = binding_called["params"]["executionContextId"]
- .as_i64()
- .expect("execution context id");
- if let Some(main_context_out) = main_context_out {
- *main_context_out = execution_context_id;
- } else {
- assert_eq!(
- execution_context_id,
- context_id.expect("utility context id")
- );
- }
- let payload = binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let payload: serde_json::Value =
- serde_json::from_str(payload).expect("binding payload should be valid json");
- assert_eq!(payload["name"], json!("sharedRejectingDualWorldBinding"));
- assert_eq!(payload["serializedArgs"], json!([serialized_arg]));
- *seq_out = payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(*seq_out, 1);
- ctx.sent.clear();
- }
-
- assert_ne!(first_main_context, first_utility_context);
- assert_ne!(second_main_context, second_utility_context);
-
- for (id, session_id, context_id, seq, error, promise_name) in [
- (
- 456_u64,
- second_auto_session.as_str(),
- Some(second_utility_context),
- second_utility_seq,
- "second-utility-rejected",
- "__lm_second_utility_binding_promise",
- ),
- (
- 457_u64,
- first_auto_session.as_str(),
- None,
- first_main_seq,
- "first-main-rejected",
- "__lm_first_main_binding_promise",
- ),
- (
- 458_u64,
- first_auto_session.as_str(),
- Some(first_utility_context),
- first_utility_seq,
- "first-utility-rejected",
- "__lm_first_utility_binding_promise",
- ),
- (
- 459_u64,
- second_auto_session.as_str(),
- None,
- second_main_seq,
- "second-main-rejected",
- "__lm_second_main_binding_promise",
- ),
- ] {
- let mut deliver_params = json!({
- "expression": format!(
- "globalThis.__lm_shared_rejecting_dual_world_deliver({{ name: 'sharedRejectingDualWorldBinding', seq: {seq}, error: '{error}' }}); 'delivered'"
- )
- });
- if let Some(context_id) = context_id {
- deliver_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": deliver_params
- }))
- .await;
- let delivered = take_response_by_id(&mut ctx, id);
- assert_eq!(delivered["result"]["result"]["value"], json!("delivered"));
-
- let mut promise_params = json!({
- "expression": format!("globalThis.{promise_name}"),
- "awaitPromise": true
- });
- if let Some(context_id) = context_id {
- promise_params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id + 10,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": promise_params
- }))
- .await;
- let rejected = take_response_by_id(&mut ctx, id + 10);
- assert_eq!(
- rejected["result"]["result"]["value"],
- json!(format!("rejected:{error}"))
- );
- }
-}
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/cleanup_isolation.rs b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/cleanup_isolation.rs
deleted file mode 100644
index c63bc99b3..000000000
--- a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/cleanup_isolation.rs
+++ /dev/null
@@ -1,2576 +0,0 @@
-use super::*;
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_rehydrates_existing_targets_without_runtime_enable_and_keeps_context_isolation()
- {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2262, 2263, 2264).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2265, 2266, 2267).await;
-
- for (id, session_id, source, binding_name, label) in [
- (
- 2268_u64,
- first.session_id.as_str(),
- "globalThis.__lm_auto_attach_sweep_marker = 'first';",
- "autoAttachSweepBindingFirst",
- "first-page",
- ),
- (
- 2271_u64,
- second.session_id.as_str(),
- "globalThis.__lm_auto_attach_sweep_marker = 'second';",
- "autoAttachSweepBindingSecond",
- "second-page",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": {
- "source": source,
- "worldName": "utility"
- }
- }))
- .await;
- let preload = take_response_by_id(&mut ctx, id);
- assert_eq!(preload["sessionId"], json!(session_id));
- assert!(preload["result"]["identifier"].is_string());
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": binding_name,
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(add_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 2274_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 2275_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- assert_eq!(
- ctx.conn
- .browser_contexts()
- .filter(|bc| !bc.has_active_session())
- .count(),
- 2,
- "both targets should be sessionless before auto-attach sweep"
- );
-
- ctx.process_async(json!({
- "id": 2276,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2276, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_attached_event = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .expect("first target auto-attach event");
- let second_attached_event = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .expect("second target auto-attach event");
- let first_auto_session = first_attached_event["params"]["sessionId"]
- .as_str()
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = second_attached_event["params"]["sessionId"]
- .as_str()
- .expect("second auto-attached session id")
- .to_owned();
- assert_ne!(first_auto_session, first.session_id);
- assert_ne!(second_auto_session, second.session_id);
- assert_ne!(first_auto_session, second_auto_session);
-
- for (id, session_id, target_id, binding_name, expected_marker, expected_text) in [
- (
- 2277_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- "autoAttachSweepBindingFirst",
- "first",
- "first-page",
- ),
- (
- 2279_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- "autoAttachSweepBindingSecond",
- "second",
- "second-page",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach sweep");
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("{binding_name}('payload-{expected_marker}'); JSON.stringify([typeof globalThis.{binding_name}, globalThis.__lm_auto_attach_sweep_marker, document.querySelector('#page').textContent])")
- }
- })).await;
- let evaluation = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(
- evaluation["result"]["result"]["value"],
- json!(format!(
- "[\"function\",\"{expected_marker}\",\"{expected_text}\"]"
- ))
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!(binding_name)
- })
- .cloned()
- .expect("auto-attached utility world should emit bindingCalled");
- assert_eq!(
- binding_called["params"]["payload"],
- json!(format!("payload-{expected_marker}"))
- );
- assert_eq!(
- binding_called["params"]["executionContextId"],
- json!(utility_context)
- );
- ctx.sent.clear();
- }
-
- let first_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == first.browser_context_id)
- .expect("first browser context should exist");
- assert_eq!(
- first_context
- .active_target
- .owner_state
- .document_start_scripts
- .len(),
- 1
- );
- assert!(
- first_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "autoAttachSweepBindingFirst"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "first browser context should retain its utility-world binding definition"
- );
-
- let second_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .expect("second browser context should exist");
- assert_eq!(
- second_context
- .active_target
- .owner_state
- .document_start_scripts
- .len(),
- 1
- );
- assert!(
- second_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "autoAttachSweepBindingSecond"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "second browser context should retain its utility-world binding definition"
- );
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_cleanup_stays_isolated_per_browser_context() {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2281, 2282, 2283).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2284, 2285, 2286).await;
-
- let mut first_preload_identifier = String::new();
- let mut second_preload_identifier = String::new();
- for (id, session_id, source, binding_name, label, preload_identifier) in [
- (
- 2287_u64,
- first.session_id.as_str(),
- "globalThis.__lm_auto_attach_cleanup_marker = 'first';",
- "autoAttachCleanupBindingFirst",
- "first-page",
- &mut first_preload_identifier,
- ),
- (
- 2290_u64,
- second.session_id.as_str(),
- "globalThis.__lm_auto_attach_cleanup_marker = 'second';",
- "autoAttachCleanupBindingSecond",
- "second-page",
- &mut second_preload_identifier,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": {
- "source": source,
- "worldName": "utility"
- }
- }))
- .await;
- let preload = take_response_by_id(&mut ctx, id);
- assert_eq!(preload["sessionId"], json!(session_id));
- *preload_identifier = preload["result"]["identifier"]
- .as_str()
- .expect("preload identifier")
- .to_owned();
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": binding_name,
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(add_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 2293_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 2294_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 2295,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2295, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2296_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 2297_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after auto-attach sweep");
- ctx.take_all();
- }
-
- ctx.process_async(json!({
- "id": 2298,
- "method": "Runtime.removeBinding",
- "sessionId": first_auto_session,
- "params": {
- "name": "autoAttachCleanupBindingFirst"
- }
- }))
- .await;
- let remove_binding = take_response_by_id(&mut ctx, 2298);
- assert_eq!(remove_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": 2299,
- "method": "Page.removeScriptToEvaluateOnNewDocument",
- "sessionId": first_auto_session,
- "params": {
- "identifier": first_preload_identifier
- }
- }))
- .await;
- let remove_preload = take_response_by_id(&mut ctx, 2299);
- assert_eq!(remove_preload["result"], json!({}));
-
- for (id, session_id, utility_context, binding_name, expected_snapshot) in [
- (
- 2300_u64,
- first_auto_session.as_str(),
- first_utility_context,
- "autoAttachCleanupBindingFirst",
- "[\"undefined\",\"first\",\"first-page\"]",
- ),
- (
- 2301_u64,
- second_auto_session.as_str(),
- second_utility_context,
- "autoAttachCleanupBindingSecond",
- "[\"function\",\"second\",\"second-page\"]",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("JSON.stringify([typeof globalThis.{binding_name}, globalThis.__lm_auto_attach_cleanup_marker, document.querySelector('#page').textContent])")
- }
- })).await;
- let evaluation = take_response_by_id(&mut ctx, id);
- assert_eq!(
- evaluation["result"]["result"]["value"],
- json!(expected_snapshot)
- );
- }
-
- for (id, session_id, label) in [
- (2302_u64, first_auto_session.as_str(), "first-page-replay"),
- (2303_u64, second_auto_session.as_str(), "second-page-replay"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2304_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 2305_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after replay navigation");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context, binding_name, expected_snapshot) in [
- (
- 2306_u64,
- first_auto_session.as_str(),
- first_replay_utility_context,
- "autoAttachCleanupBindingFirst",
- "[\"undefined\",null,\"first-page-replay\"]",
- ),
- (
- 2307_u64,
- second_auto_session.as_str(),
- second_replay_utility_context,
- "autoAttachCleanupBindingSecond",
- "[\"function\",\"second\",\"second-page-replay\"]",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("JSON.stringify([typeof globalThis.{binding_name}, globalThis.__lm_auto_attach_cleanup_marker, document.querySelector('#page').textContent])")
- }
- })).await;
- let evaluation = take_response_by_id(&mut ctx, id);
- assert_eq!(
- evaluation["result"]["result"]["value"],
- json!(expected_snapshot)
- );
- }
-
- let first_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == first.browser_context_id)
- .expect("first browser context should still exist");
- assert!(
- !first_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "autoAttachCleanupBindingFirst"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "first browser context binding definition should be removed after cleanup"
- );
- assert!(
- !first_context
- .active_target
- .owner_state
- .document_start_scripts
- .iter()
- .any(|script| script.0 == first_preload_identifier),
- "first browser context preload definition should be removed after cleanup"
- );
-
- let second_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .expect("second browser context should still exist");
- assert!(
- second_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "autoAttachCleanupBindingSecond"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "second browser context binding definition should remain intact"
- );
- assert!(
- second_context
- .active_target
- .owner_state
- .document_start_scripts
- .iter()
- .any(|script| script.0 == second_preload_identifier),
- "second browser context preload definition should remain intact"
- );
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_page_binding_cleanup_with_same_name_stays_isolated_per_browser_context()
- {
- super::super::patchright_8mb_stack(
- "patchright-utility-page-binding-cleanup-same-name",
- || async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2308, 2309, 2310).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2311, 2312, 2313).await;
-
- for (id, session_id, label) in [
- (2314_u64, first.session_id.as_str(), "first-page"),
- (2316_u64, second.session_id.as_str(), "second-page"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedPatchedBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 2318_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 2319_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 2320,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2320, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2321_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 2322_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- let shared_wrapper_source = patchright_page_binding_wrapper_source(
- "sharedPatchedBinding",
- "__lm_deliverSharedPatchedBindingResult",
- None,
- false,
- );
-
- for (id, session_id, utility_context) in [
- (2323_u64, first_auto_session.as_str(), first_utility_context),
- (
- 2324_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": &shared_wrapper_source
- }
- }))
- .await;
- let install_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- for (id, session_id, utility_context, payload, expected_text) in [
- (
- 2325_u64,
- first_auto_session.as_str(),
- first_utility_context,
- "payload-first",
- "first-page",
- ),
- (
- 2328_u64,
- second_auto_session.as_str(),
- second_utility_context,
- "payload-second",
- "second-page",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("globalThis.__lm_bindingPromise = sharedPatchedBinding('{payload}'); JSON.stringify([typeof globalThis.sharedPatchedBinding, document.querySelector('#page').textContent])")
- }
- })).await;
- let scheduled = take_response_by_id(&mut ctx, id);
- assert_eq!(
- scheduled["result"]["result"]["value"],
- json!(format!("[\"function\",\"{expected_text}\"]"))
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedPatchedBinding")
- && message["params"]["executionContextId"] == json!(utility_context)
- })
- .cloned()
- .expect("shared page binding wrapper should emit Runtime.bindingCalled");
- let binding_payload = binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let binding_payload: serde_json::Value =
- serde_json::from_str(binding_payload).expect("binding payload should be valid json");
- let seq = binding_payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(binding_payload["name"], json!("sharedPatchedBinding"));
- assert_eq!(binding_payload["serializedArgs"], json!([payload]));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("globalThis.__lm_deliverSharedPatchedBindingResult({{ name: 'sharedPatchedBinding', seq: {seq}, result: 'ok-{payload}' }}); 'delivered'")
- }
- })).await;
- let delivered = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(delivered["result"]["result"]["value"], json!("delivered"));
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": "globalThis.__lm_bindingPromise",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(
- resolved["result"]["result"]["value"],
- json!(format!("ok-{payload}"))
- );
- }
-
- ctx.process_async(json!({
- "id": 2331,
- "method": "Runtime.removeBinding",
- "sessionId": first_auto_session,
- "params": {
- "name": "sharedPatchedBinding"
- }
- }))
- .await;
- let remove_binding = take_response_by_id(&mut ctx, 2331);
- assert_eq!(remove_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": 2332,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedPatchedBinding"
- }
- }))
- .await;
- let first_removed = take_response_by_id(&mut ctx, 2332);
- assert_eq!(
- first_removed["result"]["result"]["value"],
- json!("undefined")
- );
-
- ctx.sent.clear();
- ctx.process_async(json!({
- "id": 2333,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedPatchedBinding === 'function' ? sharedPatchedBinding('unexpected') : 'absent'"
- }
- })).await;
- let first_guarded = take_response_by_id(&mut ctx, 2333);
- assert_eq!(first_guarded["result"]["result"]["value"], json!("absent"));
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedPatchedBinding")
- }),
- "removed shared page-binding wrapper should no longer emit bindingCalled in the cleaned-up context"
- );
-
- ctx.process_async(json!({
- "id": 2334,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_bindingPromiseAfterCleanup = sharedPatchedBinding('payload-second-after-cleanup'); JSON.stringify([typeof globalThis.sharedPatchedBinding, document.querySelector('#page').textContent])"
- }
- })).await;
- let second_scheduled = take_response_by_id(&mut ctx, 2334);
- assert_eq!(
- second_scheduled["result"]["result"]["value"],
- json!("[\"function\",\"second-page\"]")
- );
- let second_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedPatchedBinding")
- && message["params"]["executionContextId"] == json!(second_utility_context)
- })
- .cloned()
- .expect("second context should still emit bindingCalled after first-context cleanup");
- let second_binding_payload = second_binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let second_binding_payload: serde_json::Value =
- serde_json::from_str(second_binding_payload).expect("binding payload should be valid json");
- let second_seq = second_binding_payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(
- second_binding_payload["serializedArgs"],
- json!(["payload-second-after-cleanup"])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 2335,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": format!("globalThis.__lm_deliverSharedPatchedBindingResult({{ name: 'sharedPatchedBinding', seq: {second_seq}, result: 'ok-second-after-cleanup' }}); 'delivered'")
- }
- })).await;
- let second_delivered = take_response_by_id(&mut ctx, 2335);
- assert_eq!(
- second_delivered["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 2336,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_bindingPromiseAfterCleanup",
- "awaitPromise": true
- }
- }))
- .await;
- let second_resolved = take_response_by_id(&mut ctx, 2336);
- assert_eq!(
- second_resolved["result"]["result"]["value"],
- json!("ok-second-after-cleanup")
- );
-
- for (id, session_id, label) in [
- (2337_u64, first_auto_session.as_str(), "first-page-replay"),
- (2338_u64, second_auto_session.as_str(), "second-page-replay"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2339_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 2340_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after replay navigation");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context, expected_type) in [
- (
- 2341_u64,
- first_auto_session.as_str(),
- first_replay_utility_context,
- "undefined",
- ),
- (
- 2342_u64,
- second_auto_session.as_str(),
- second_replay_utility_context,
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": "typeof globalThis.sharedPatchedBinding"
- }
- }))
- .await;
- let replay_state = take_response_by_id(&mut ctx, id);
- assert_eq!(
- replay_state["result"]["result"]["value"],
- json!(expected_type)
- );
- }
-
- let first_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == first.browser_context_id)
- .expect("first browser context should still exist");
- assert!(
- !first_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedPatchedBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "first browser context should no longer retain the shared binding definition"
- );
-
- let second_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .expect("second browser context should still exist");
- assert!(
- second_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedPatchedBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "second browser context should retain the shared binding definition"
- );
- },
- )
- .await;
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_page_binding_rejection_with_same_name_stays_isolated_per_browser_context()
- {
- super::super::patchright_8mb_stack(
- "patchright-utility-cleanup-rejecting-binding",
- || async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2411, 2412, 2413).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2414, 2415, 2416).await;
-
- for (id, session_id, label) in [
- (2417_u64, first.session_id.as_str(), "first-page"),
- (2419_u64, second.session_id.as_str(), "second-page"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedRejectingBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 2421_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 2422_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 2423,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2423, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2424_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 2425_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- let shared_rejecting_wrapper_source = patchright_page_binding_wrapper_source(
- "sharedRejectingBinding",
- "__lm_deliverSharedRejectingBindingResult",
- None,
- false,
- );
-
- for (id, session_id, utility_context) in [
- (2426_u64, first_auto_session.as_str(), first_utility_context),
- (
- 2427_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": &shared_rejecting_wrapper_source
- }
- }))
- .await;
- let install_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- ctx.process_async(json!({
- "id": 2428,
- "method": "Runtime.removeBinding",
- "sessionId": first_auto_session,
- "params": {
- "name": "sharedRejectingBinding"
- }
- }))
- .await;
- let remove_binding = take_response_by_id(&mut ctx, 2428);
- assert_eq!(remove_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": 2429,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedRejectingBinding"
- }
- }))
- .await;
- let first_removed = take_response_by_id(&mut ctx, 2429);
- assert_eq!(
- first_removed["result"]["result"]["value"],
- json!("undefined")
- );
-
- ctx.sent.clear();
- ctx.process_async(json!({
- "id": 2430,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedRejectingBinding === 'function' ? sharedRejectingBinding('unexpected') : 'absent'"
- }
- })).await;
- let first_guarded = take_response_by_id(&mut ctx, 2430);
- assert_eq!(first_guarded["result"]["result"]["value"], json!("absent"));
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedRejectingBinding")
- }),
- "removed shared rejecting page-binding wrapper should not emit bindingCalled in the cleaned-up context"
- );
-
- ctx.process_async(json!({
- "id": 2431,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_bindingPromiseAfterCleanup = sharedRejectingBinding('payload-second-after-cleanup').then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled'"
- }
- })).await;
- let second_scheduled = take_response_by_id(&mut ctx, 2431);
- assert_eq!(
- second_scheduled["result"]["result"]["value"],
- json!("scheduled")
- );
- let second_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedRejectingBinding")
- && message["params"]["executionContextId"] == json!(second_utility_context)
- })
- .cloned()
- .expect("second context should still emit bindingCalled after first-context cleanup");
- let second_binding_payload = second_binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let second_binding_payload: serde_json::Value =
- serde_json::from_str(second_binding_payload).expect("binding payload should be valid json");
- let second_seq = second_binding_payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(
- second_binding_payload["serializedArgs"],
- json!(["payload-second-after-cleanup"])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 2432,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": format!("globalThis.__lm_deliverSharedRejectingBindingResult({{ name: 'sharedRejectingBinding', seq: {second_seq}, error: 'rejected-second-after-cleanup' }}); 'delivered'")
- }
- })).await;
- let second_delivered = take_response_by_id(&mut ctx, 2432);
- assert_eq!(
- second_delivered["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 2433,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_bindingPromiseAfterCleanup",
- "awaitPromise": true
- }
- }))
- .await;
- let second_rejected = take_response_by_id(&mut ctx, 2433);
- assert_eq!(
- second_rejected["result"]["result"]["value"],
- json!("rejected:rejected-second-after-cleanup")
- );
-
- for (id, session_id, label) in [
- (2434_u64, first_auto_session.as_str(), "first-page-replay"),
- (2435_u64, second_auto_session.as_str(), "second-page-replay"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id=page>{label}</div></body>")
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2436_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 2437_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after replay navigation");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context, expected_type) in [
- (
- 2438_u64,
- first_auto_session.as_str(),
- first_replay_utility_context,
- "undefined",
- ),
- (
- 2439_u64,
- second_auto_session.as_str(),
- second_replay_utility_context,
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": "typeof globalThis.sharedRejectingBinding"
- }
- }))
- .await;
- let replay_state = take_response_by_id(&mut ctx, id);
- assert_eq!(
- replay_state["result"]["result"]["value"],
- json!(expected_type)
- );
- }
-
- let first_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == first.browser_context_id)
- .expect("first browser context should still exist");
- assert!(
- !first_context
- .devtools_session_state
-
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedRejectingBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "first browser context should no longer retain the shared rejecting binding definition"
- );
-
- let second_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .expect("second browser context should still exist");
- assert!(
- second_context
- .devtools_session_state
-
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedRejectingBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "second browser context should retain the shared rejecting binding definition"
- );
- },
- )
- .await;
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_handle_page_binding_cleanup_with_same_name_stays_isolated_per_browser_context()
- {
- super::super::patchright_8mb_stack(
- "patchright-utility-cleanup-same-name",
- || async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2343, 2344, 2345).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2346, 2347, 2348).await;
-
- for (id, session_id, label, handle_id) in [
- (
- 2349_u64,
- first.session_id.as_str(),
- "first-page",
- "first-handle",
- ),
- (
- 2351_u64,
- second.session_id.as_str(),
- "second-page",
- "second-handle",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedHandleBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div><div id='{handle_id}'>node</div></body>")
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 2353_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 2354_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 2355,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2355, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2356_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 2357_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context) in [
- (2358_u64, first_auto_session.as_str(), first_utility_context),
- (
- 2359_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": r#"
- (() => {
- function addHandleBinding(bindingName) {
- const binding = globalThis[bindingName];
- globalThis[bindingName] = (...args) => {
- const me = globalThis[bindingName];
- let callbacks = me.callbacks;
- if (!callbacks) {
- callbacks = new Map();
- me.callbacks = callbacks;
- }
- let handles = me.handles;
- if (!handles) {
- handles = new Map();
- me.handles = handles;
- }
- const seq = (me.lastSeq || 0) + 1;
- me.lastSeq = seq;
- handles.set(seq, args[0]);
- const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));
- binding(JSON.stringify({ name: bindingName, seq }));
- return promise;
- };
- }
- function takeBindingHandle(arg) {
- const handles = globalThis[arg.name].handles;
- const handle = handles.get(arg.seq);
- handles.delete(arg.seq);
- return handle;
- }
- function deliverBindingResult(arg) {
- const callbacks = globalThis[arg.name].callbacks;
- if ('error' in arg)
- callbacks.get(arg.seq).reject(arg.error);
- else
- callbacks.get(arg.seq).resolve(arg.result);
- callbacks.delete(arg.seq);
- }
- addHandleBinding('sharedHandleBinding');
- globalThis.__lm_takeSharedHandleBindingHandle = takeBindingHandle;
- globalThis.__lm_deliverSharedHandleBindingResult = deliverBindingResult;
- return typeof globalThis.sharedHandleBinding;
- })()
- "#
- }
- })).await;
- let install_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- for (id, session_id, utility_context, handle_id, expected_tag) in [
- (
- 2360_u64,
- first_auto_session.as_str(),
- first_utility_context,
- "first-handle",
- "FIRST-HANDLE",
- ),
- (
- 2364_u64,
- second_auto_session.as_str(),
- second_utility_context,
- "second-handle",
- "SECOND-HANDLE",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("globalThis.__lm_handlePromise = sharedHandleBinding(document.getElementById('{handle_id}')); 'scheduled'")
- }
- })).await;
- let scheduled = take_response_by_id(&mut ctx, id);
- assert_eq!(scheduled["result"]["result"]["value"], json!("scheduled"));
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedHandleBinding")
- && message["params"]["executionContextId"] == json!(utility_context)
- })
- .cloned()
- .expect("shared handle binding wrapper should emit Runtime.bindingCalled");
- let binding_payload = binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let binding_payload: serde_json::Value =
- serde_json::from_str(binding_payload).expect("binding payload should be valid json");
- let seq = binding_payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- assert_eq!(binding_payload["name"], json!("sharedHandleBinding"));
- assert_eq!(
- binding_payload,
- json!({
- "name": "sharedHandleBinding",
- "seq": binding_payload["seq"],
- })
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_takeSharedHandleBindingHandle({{ name: 'sharedHandleBinding', seq: {seq} }}); return JSON.stringify([handle.id, typeof globalThis.__lm_takeSharedHandleBindingHandle({{ name: 'sharedHandleBinding', seq: {seq} }})]); }})()")
- }
- })).await;
- let taken_handle = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(
- taken_handle["result"]["result"]["value"],
- json!(format!("[\"{handle_id}\",\"undefined\"]"))
- );
-
- ctx.process_async(json!({
- "id": id + 2,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": format!("globalThis.__lm_deliverSharedHandleBindingResult({{ name: 'sharedHandleBinding', seq: {seq}, result: '{expected_tag}' }}); 'delivered'")
- }
- })).await;
- let delivered = take_response_by_id(&mut ctx, id + 2);
- assert_eq!(delivered["result"]["result"]["value"], json!("delivered"));
-
- ctx.process_async(json!({
- "id": id + 3,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": "globalThis.__lm_handlePromise",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved = take_response_by_id(&mut ctx, id + 3);
- assert_eq!(resolved["result"]["result"]["value"], json!(expected_tag));
- }
-
- ctx.process_async(json!({
- "id": 2368,
- "method": "Runtime.removeBinding",
- "sessionId": first_auto_session,
- "params": {
- "name": "sharedHandleBinding"
- }
- }))
- .await;
- let remove_binding = take_response_by_id(&mut ctx, 2368);
- assert_eq!(remove_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": 2369,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedHandleBinding"
- }
- }))
- .await;
- let first_removed = take_response_by_id(&mut ctx, 2369);
- assert_eq!(
- first_removed["result"]["result"]["value"],
- json!("undefined")
- );
-
- ctx.sent.clear();
- ctx.process_async(json!({
- "id": 2370,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedHandleBinding === 'function' ? sharedHandleBinding(document.getElementById('first-handle')) : 'absent'"
- }
- })).await;
- let first_guarded = take_response_by_id(&mut ctx, 2370);
- assert_eq!(first_guarded["result"]["result"]["value"], json!("absent"));
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedHandleBinding")
- }),
- "removed shared handle-binding wrapper should no longer emit bindingCalled in the cleaned-up context"
- );
-
- ctx.process_async(json!({
- "id": 2371,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_handlePromiseAfterCleanup = sharedHandleBinding(document.getElementById('second-handle')); 'scheduled'"
- }
- })).await;
- let second_scheduled = take_response_by_id(&mut ctx, 2371);
- assert_eq!(
- second_scheduled["result"]["result"]["value"],
- json!("scheduled")
- );
- let second_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedHandleBinding")
- && message["params"]["executionContextId"] == json!(second_utility_context)
- })
- .cloned()
- .expect("second context should still emit bindingCalled after first-context cleanup");
- let second_binding_payload = second_binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let second_binding_payload: serde_json::Value =
- serde_json::from_str(second_binding_payload).expect("binding payload should be valid json");
- let second_seq = second_binding_payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 2372,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_takeSharedHandleBindingHandle({{ name: 'sharedHandleBinding', seq: {second_seq} }}); return JSON.stringify([handle.id, typeof globalThis.__lm_takeSharedHandleBindingHandle({{ name: 'sharedHandleBinding', seq: {second_seq} }})]); }})()")
- }
- })).await;
- let second_taken_handle = take_response_by_id(&mut ctx, 2372);
- assert_eq!(
- second_taken_handle["result"]["result"]["value"],
- json!("[\"second-handle\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 2373,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": format!("globalThis.__lm_deliverSharedHandleBindingResult({{ name: 'sharedHandleBinding', seq: {second_seq}, result: 'SECOND-HANDLE-AFTER-CLEANUP' }}); 'delivered'")
- }
- })).await;
- let second_delivered = take_response_by_id(&mut ctx, 2373);
- assert_eq!(
- second_delivered["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 2374,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_handlePromiseAfterCleanup",
- "awaitPromise": true
- }
- }))
- .await;
- let second_resolved = take_response_by_id(&mut ctx, 2374);
- assert_eq!(
- second_resolved["result"]["result"]["value"],
- json!("SECOND-HANDLE-AFTER-CLEANUP")
- );
-
- for (id, session_id, label, handle_id) in [
- (
- 2375_u64,
- first_auto_session.as_str(),
- "first-page-replay",
- "first-replay-handle",
- ),
- (
- 2376_u64,
- second_auto_session.as_str(),
- "second-page-replay",
- "second-replay-handle",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div><div id='{handle_id}'>node</div></body>")
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2377_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 2378_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after replay navigation");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context, expected_type) in [
- (
- 2379_u64,
- first_auto_session.as_str(),
- first_replay_utility_context,
- "undefined",
- ),
- (
- 2380_u64,
- second_auto_session.as_str(),
- second_replay_utility_context,
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": "typeof globalThis.sharedHandleBinding"
- }
- }))
- .await;
- let replay_state = take_response_by_id(&mut ctx, id);
- assert_eq!(
- replay_state["result"]["result"]["value"],
- json!(expected_type)
- );
- }
-
- let first_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == first.browser_context_id)
- .expect("first browser context should still exist");
- assert!(
- !first_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedHandleBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "first browser context should no longer retain the shared handle binding definition"
- );
-
- let second_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .expect("second browser context should still exist");
- assert!(
- second_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedHandleBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "second browser context should retain the shared handle binding definition"
- );
- },
- )
- .await;
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_handle_page_binding_rejection_with_same_name_stays_isolated_per_browser_context()
- {
- super::super::patchright_8mb_stack(
- "patchright-utility-handle-rejection-cleanup-same-name",
- run_patchright_over_cdp_auto_attach_sweep_handle_page_binding_rejection_with_same_name_stays_isolated_per_browser_context,
- )
- .await;
-}
-
-async fn run_patchright_over_cdp_auto_attach_sweep_handle_page_binding_rejection_with_same_name_stays_isolated_per_browser_context()
- {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2381, 2382, 2383).await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2384, 2385, 2386).await;
-
- for (id, session_id, label, handle_id) in [
- (
- 2387_u64,
- first.session_id.as_str(),
- "first-page",
- "first-handle",
- ),
- (
- 2389_u64,
- second.session_id.as_str(),
- "second-page",
- "second-handle",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": "sharedRejectingHandleBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, id);
- assert_eq!(add_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": id + 1,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div><div id='{handle_id}'>node</div></body>")
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, id + 1);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 2391_u64,
- first.target_id.as_str(),
- first.session_id.as_str(),
- ),
- (
- 2392_u64,
- second.target_id.as_str(),
- second.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 2393,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2393, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(
- attached_events.len(),
- 2,
- "auto-attach sweep should attach both targets"
- );
- let first_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(first.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first auto-attached session id")
- .to_owned();
- let second_auto_session = attached_events
- .iter()
- .find(|event| event["params"]["targetInfo"]["targetId"] == json!(second.target_id))
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second auto-attached session id")
- .to_owned();
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2394_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 2395_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context id after auto-attach");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context) in [
- (2396_u64, first_auto_session.as_str(), first_utility_context),
- (
- 2397_u64,
- second_auto_session.as_str(),
- second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": r#"
- (() => {
- function addHandleBinding(bindingName) {
- const binding = globalThis[bindingName];
- globalThis[bindingName] = (...args) => {
- const me = globalThis[bindingName];
- let callbacks = me.callbacks;
- if (!callbacks) {
- callbacks = new Map();
- me.callbacks = callbacks;
- }
- let handles = me.handles;
- if (!handles) {
- handles = new Map();
- me.handles = handles;
- }
- const seq = (me.lastSeq || 0) + 1;
- me.lastSeq = seq;
- handles.set(seq, args[0]);
- const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));
- binding(JSON.stringify({ name: bindingName, seq }));
- return promise;
- };
- }
- function takeBindingHandle(arg) {
- const handles = globalThis[arg.name].handles;
- const handle = handles.get(arg.seq);
- handles.delete(arg.seq);
- return handle;
- }
- function deliverBindingResult(arg) {
- const callbacks = globalThis[arg.name].callbacks;
- if ('error' in arg)
- callbacks.get(arg.seq).reject(arg.error);
- else
- callbacks.get(arg.seq).resolve(arg.result);
- callbacks.delete(arg.seq);
- }
- addHandleBinding('sharedRejectingHandleBinding');
- globalThis.__lm_takeSharedRejectingHandleBindingHandle = takeBindingHandle;
- globalThis.__lm_deliverSharedRejectingHandleBindingResult = deliverBindingResult;
- return typeof globalThis.sharedRejectingHandleBinding;
- })()
- "#
- }
- })).await;
- let install_wrapper = take_response_by_id(&mut ctx, id);
- assert_eq!(
- install_wrapper["result"]["result"]["value"],
- json!("function")
- );
- }
-
- ctx.process_async(json!({
- "id": 2398,
- "method": "Runtime.removeBinding",
- "sessionId": first_auto_session,
- "params": {
- "name": "sharedRejectingHandleBinding"
- }
- }))
- .await;
- let remove_binding = take_response_by_id(&mut ctx, 2398);
- assert_eq!(remove_binding["result"], json!({}));
-
- ctx.process_async(json!({
- "id": 2399,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedRejectingHandleBinding"
- }
- }))
- .await;
- let first_removed = take_response_by_id(&mut ctx, 2399);
- assert_eq!(
- first_removed["result"]["result"]["value"],
- json!("undefined")
- );
-
- ctx.sent.clear();
- ctx.process_async(json!({
- "id": 2400,
- "method": "Runtime.evaluate",
- "sessionId": first_auto_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "typeof globalThis.sharedRejectingHandleBinding === 'function' ? sharedRejectingHandleBinding(document.getElementById('first-handle')) : 'absent'"
- }
- })).await;
- let first_guarded = take_response_by_id(&mut ctx, 2400);
- assert_eq!(first_guarded["result"]["result"]["value"], json!("absent"));
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedRejectingHandleBinding")
- }),
- "removed shared rejecting handle-binding wrapper should no longer emit bindingCalled in the cleaned-up context"
- );
-
- ctx.process_async(json!({
- "id": 2401,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_handlePromiseAfterCleanup = sharedRejectingHandleBinding(document.getElementById('second-handle')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled'"
- }
- })).await;
- let second_scheduled = take_response_by_id(&mut ctx, 2401);
- assert_eq!(
- second_scheduled["result"]["result"]["value"],
- json!("scheduled")
- );
- let second_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("sharedRejectingHandleBinding")
- && message["params"]["executionContextId"] == json!(second_utility_context)
- })
- .cloned()
- .expect("second context should still emit bindingCalled after first-context cleanup");
- let second_binding_payload = second_binding_called["params"]["payload"]
- .as_str()
- .expect("binding payload should be a json string");
- let second_binding_payload: serde_json::Value =
- serde_json::from_str(second_binding_payload).expect("binding payload should be valid json");
- let second_seq = second_binding_payload["seq"]
- .as_i64()
- .expect("binding payload seq should be an integer");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 2402,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_takeSharedRejectingHandleBindingHandle({{ name: 'sharedRejectingHandleBinding', seq: {second_seq} }}); return JSON.stringify([handle.id, typeof globalThis.__lm_takeSharedRejectingHandleBindingHandle({{ name: 'sharedRejectingHandleBinding', seq: {second_seq} }})]); }})()")
- }
- })).await;
- let second_taken_handle = take_response_by_id(&mut ctx, 2402);
- assert_eq!(
- second_taken_handle["result"]["result"]["value"],
- json!("[\"second-handle\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 2403,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": format!("globalThis.__lm_deliverSharedRejectingHandleBindingResult({{ name: 'sharedRejectingHandleBinding', seq: {second_seq}, error: 'reject-second-after-cleanup' }}); 'delivered'")
- }
- })).await;
- let second_delivered = take_response_by_id(&mut ctx, 2403);
- assert_eq!(
- second_delivered["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 2404,
- "method": "Runtime.evaluate",
- "sessionId": second_auto_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_handlePromiseAfterCleanup",
- "awaitPromise": true
- }
- }))
- .await;
- let second_rejected = take_response_by_id(&mut ctx, 2404);
- assert_eq!(
- second_rejected["result"]["result"]["value"],
- json!("rejected:reject-second-after-cleanup")
- );
-
- for (id, session_id, label, handle_id) in [
- (
- 2405_u64,
- first_auto_session.as_str(),
- "first-page-replay",
- "first-replay-handle",
- ),
- (
- 2406_u64,
- second_auto_session.as_str(),
- "second-page-replay",
- "second-replay-handle",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": {
- "url": format!("data:text/html,<body><div id='page'>{label}</div><div id='{handle_id}'>node</div></body>")
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, utility_context) in [
- (
- 2407_u64,
- first_auto_session.as_str(),
- first.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 2408_u64,
- second_auto_session.as_str(),
- second.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *utility_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after replay navigation");
- ctx.take_all();
- }
-
- for (id, session_id, utility_context, expected_type) in [
- (
- 2409_u64,
- first_auto_session.as_str(),
- first_replay_utility_context,
- "undefined",
- ),
- (
- 2410_u64,
- second_auto_session.as_str(),
- second_replay_utility_context,
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context,
- "expression": "typeof globalThis.sharedRejectingHandleBinding"
- }
- }))
- .await;
- let replay_state = take_response_by_id(&mut ctx, id);
- assert_eq!(
- replay_state["result"]["result"]["value"],
- json!(expected_type)
- );
- }
-
- let first_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == first.browser_context_id)
- .expect("first browser context should still exist");
- assert!(
- !first_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedRejectingHandleBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "first browser context should no longer retain the shared rejecting handle binding definition"
- );
-
- let second_context = ctx
- .conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .expect("second browser context should still exist");
- assert!(
- second_context
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "sharedRejectingHandleBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "second browser context should retain the shared rejecting handle binding definition"
- );
-}
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/mod.rs b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/mod.rs
index 10593e659..ec1d37d87 100644
--- a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/mod.rs
+++ b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/mod.rs
@@ -1,5 +1,4 @@
use super::*;
-mod cleanup_isolation;
mod preload_runtime;
mod replacement_targets;
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/preload_runtime.rs b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/preload_runtime.rs
index 9f91a47dc..ae55e6157 100644
--- a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/preload_runtime.rs
+++ b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/preload_runtime.rs
@@ -199,8 +199,7 @@ async fn patchright_over_cdp_utility_world_binding_and_preload_stay_isolated_per
1
);
assert!(
- first_context
- .devtools_session_state
+ first_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| {
@@ -584,7 +583,7 @@ async fn patchright_over_cdp_existing_utility_world_binding_install_by_execution
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "utilityBindingById"),
@@ -786,7 +785,7 @@ async fn patchright_over_cdp_pre_document_remove_binding_prevents_first_navigati
.browser_context
.as_ref()
.expect("browser context")
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.all(|binding| binding.name != "temporaryPreDocumentBinding"),
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/crpage.rs b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/crpage.rs
deleted file mode 100644
index 868a03b20..000000000
--- a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/crpage.rs
+++ /dev/null
@@ -1,3400 +0,0 @@
-use super::*;
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_utility_world_init_persists_across_targets_without_runtime_enable() {
- let mut ctx = TestContext::new();
-
- ctx.process_async(json!({
- "id": 211,
- "method": "Target.createBrowserContext"
- }))
- .await;
- let browser_context_id = ctx
- .conn
- .browser_context
- .as_ref()
- .expect("browser context should exist")
- .id
- .clone();
- ctx.expect_result(211, json!({ "browserContextId": browser_context_id }), None);
-
- ctx.process_async(json!({
- "id": 212,
- "method": "Target.createTarget",
- "params": {
- "browserContextId": browser_context_id,
- "url": "about:blank"
- }
- }))
- .await;
- let first_target = take_response_by_id(&mut ctx, 212)["result"]["targetId"]
- .as_str()
- .expect("first target id")
- .to_owned();
- ctx.expect_event(
- "Target.targetCreated",
- Some(&json!({
- "targetInfo": {
- "targetId": first_target,
- "browserContextId": browser_context_id,
- }
- })),
- );
-
- ctx.process_async(json!({
- "id": 213,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": first_target,
- "flatten": true
- }
- }))
- .await;
- let first_session = ctx
- .conn
- .browser_context
- .as_ref()
- .and_then(|bc| bc.active_session_id_owned())
- .expect("first session id should exist");
- ctx.expect_result(213, json!({ "sessionId": first_session }), None);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": first_session,
- "targetInfo": {
- "targetId": first_target,
- "browserContextId": browser_context_id,
- }
- })),
- );
-
- ctx.process_async(json!({
- "id": 214,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": first_session,
- "params": {
- "source": "globalThis.__lm_patchright_target_preload = 'ready';",
- "worldName": "utility"
- }
- }))
- .await;
- let preload = take_response_by_id(&mut ctx, 214);
- assert_eq!(preload["sessionId"], json!(first_session));
- assert!(preload["result"]["identifier"].is_string());
-
- ctx.process_async(json!({
- "id": 215,
- "method": "Runtime.addBinding",
- "sessionId": first_session,
- "params": {
- "name": "utilityBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, 215);
- assert!(add_binding.get("error").is_none());
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.executionContextCreated")
- || message["method"] == json!("Runtime.executionContextsCleared")
- }),
- "Patchright-style setup should stay off Runtime.enable surfaces"
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 216,
- "method": "Page.navigate",
- "sessionId": first_session,
- "params": {
- "url": "data:text/html,<body>first</body>"
- }
- }))
- .await;
- let first_navigation = take_response_by_id(&mut ctx, 216);
- assert_eq!(first_navigation["sessionId"], json!(first_session));
- assert!(
- ctx.sent.iter().all(|message| {
- message.get("error").is_none()
- && message["method"] != json!("Runtime.executionContextCreated")
- && message["method"] != json!("Runtime.executionContextsCleared")
- }),
- "unexpected protocol/runtime event during first navigation: {:?}",
- ctx.sent
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 217,
- "method": "Page.createIsolatedWorld",
- "sessionId": first_session,
- "params": {
- "frameId": first_target,
- "worldName": "utility"
- }
- }))
- .await;
- let first_utility_context = take_response_by_id(&mut ctx, 217)["result"]["executionContextId"]
- .as_i64()
- .expect("first utility context id");
-
- ctx.process_async(json!({
- "id": 218,
- "method": "Runtime.evaluate",
- "sessionId": first_session,
- "params": {
- "contextId": first_utility_context,
- "expression": "utilityBinding('payload-first'); JSON.stringify([typeof globalThis.utilityBinding, globalThis.__lm_patchright_target_preload])"
- }
- })).await;
- let first_eval = take_response_by_id(&mut ctx, 218);
- assert_eq!(
- first_eval["result"]["result"]["value"],
- json!("[\"function\",\"ready\"]")
- );
- let first_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("utilityBinding")
- })
- .cloned()
- .expect("first utility world binding call");
- assert_eq!(
- first_binding_called["params"]["payload"],
- json!("payload-first")
- );
- assert_eq!(
- first_binding_called["params"]["executionContextId"],
- json!(first_utility_context)
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 219,
- "method": "Target.closeTarget",
- "params": { "targetId": first_target }
- }))
- .await;
- ctx.expect_result(219, json!({ "success": true }), None);
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 220,
- "method": "Target.createTarget",
- "params": {
- "browserContextId": browser_context_id,
- "url": "about:blank"
- }
- }))
- .await;
- let second_target = take_response_by_id(&mut ctx, 220)["result"]["targetId"]
- .as_str()
- .expect("second target id")
- .to_owned();
- ctx.expect_event(
- "Target.targetCreated",
- Some(&json!({
- "targetInfo": {
- "targetId": second_target,
- "browserContextId": browser_context_id,
- }
- })),
- );
-
- ctx.process_async(json!({
- "id": 221,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second_target,
- "flatten": true
- }
- }))
- .await;
- let second_session = ctx
- .conn
- .browser_context
- .as_ref()
- .and_then(|bc| bc.active_session_id_owned())
- .expect("second session id should exist");
- ctx.expect_result(221, json!({ "sessionId": second_session }), None);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": second_session,
- "targetInfo": {
- "targetId": second_target,
- "browserContextId": browser_context_id,
- }
- })),
- );
-
- ctx.process_async(json!({
- "id": 222,
- "method": "Page.navigate",
- "sessionId": second_session,
- "params": {
- "url": "data:text/html,<body>second</body>"
- }
- }))
- .await;
- let second_navigation = take_response_by_id(&mut ctx, 222);
- assert_eq!(second_navigation["sessionId"], json!(second_session));
- assert!(
- ctx.sent.iter().all(|message| {
- message.get("error").is_none()
- && message["method"] != json!("Runtime.executionContextCreated")
- && message["method"] != json!("Runtime.executionContextsCleared")
- }),
- "unexpected protocol/runtime event during second navigation: {:?}",
- ctx.sent
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 223,
- "method": "Page.createIsolatedWorld",
- "sessionId": second_session,
- "params": {
- "frameId": second_target,
- "worldName": "utility"
- }
- }))
- .await;
- let second_utility_context = take_response_by_id(&mut ctx, 223)["result"]["executionContextId"]
- .as_i64()
- .expect("second utility context id");
-
- ctx.process_async(json!({
- "id": 224,
- "method": "Runtime.evaluate",
- "sessionId": second_session,
- "params": {
- "contextId": second_utility_context,
- "expression": "utilityBinding('payload-second'); JSON.stringify([typeof globalThis.utilityBinding, globalThis.__lm_patchright_target_preload])"
- }
- })).await;
- let second_eval = take_response_by_id(&mut ctx, 224);
- assert_eq!(
- second_eval["result"]["result"]["value"],
- json!("[\"function\",\"ready\"]")
- );
- let second_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("utilityBinding")
- })
- .cloned()
- .expect("second utility world binding call");
- assert_eq!(
- second_binding_called["params"]["payload"],
- json!("payload-second")
- );
- assert_eq!(
- second_binding_called["params"]["executionContextId"],
- json!(second_utility_context)
- );
-
- let active = ctx
- .conn
- .browser_context
- .as_ref()
- .expect("active browser context");
- assert_eq!(active.id, browser_context_id);
- assert_eq!(active.active_target_id(), Some(second_target.as_str()));
- assert_eq!(active.active_session_id(), Some(second_session.as_str()));
- assert_eq!(
- active
- .active_target
- .owner_state
- .document_start_scripts
- .len(),
- 1
- );
- assert!(
- active
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "utilityBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "utility binding should persist on the browser context"
- );
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_crpage_replacement_targets_keep_cleanup_isolated_per_browser_context_without_runtime_enable()
- {
- patchright_replacement_targets_large_stack(|| async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 35400, 35401, 35402)
- .await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 35403, 35404, 35405)
- .await;
-
- for (id, session_id, html) in [
- (
- 35406_u64,
- first.session_id.as_str(),
- "<body><div id='utility-handle-a'>first-a</div><div id='utility-handle-b'>first-b</div></body>",
- ),
- (
- 35407_u64,
- second.session_id.as_str(),
- "<body><div id='utility-handle-a'>second-a</div><div id='utility-handle-b'>second-b</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35408_u64,
- first.session_id.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 35409_u64,
- second.session_id.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("initial utility context id");
- ctx.take_all();
- }
-
- let custom_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customBindingB",
- "__lm_custom_binding_b_deliver",
- None,
- false,
- );
- let custom_handle_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptHandleBinding",
- "__lm_pw_kept_handle_binding_deliver",
- Some("__lm_pw_kept_handle_binding_take"),
- true,
- );
-
- for (session_id, utility_context_id, id_base) in [
- (first.session_id.as_str(), first_utility_context, 35410_u64),
- (
- second.session_id.as_str(),
- second_utility_context,
- 35430_u64,
- ),
- ] {
- for (binding_name, source, offset) in [
- ("customBindingA", custom_wrapper_a_source.as_str(), 0_u64),
- ("customBindingB", custom_wrapper_b_source.as_str(), 4_u64),
- (
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- 8_u64,
- ),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- 12_u64,
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + offset,
- id_base + offset + 1,
- id_base + offset + 2,
- id_base + offset + 3,
- binding_name,
- source,
- )
- .await;
- }
- }
-
- for (session_id, id_base) in [
- (first.session_id.as_str(), 35450_u64),
- (second.session_id.as_str(), 35460_u64),
- ] {
- for (source, world_name, offset) in [
- (custom_wrapper_a_source.as_str(), None, 0_u64),
- (custom_wrapper_b_source.as_str(), None, 1_u64),
- (custom_handle_wrapper_a_source.as_str(), None, 2_u64),
- (retained_handle_wrapper_source.as_str(), None, 3_u64),
- (custom_wrapper_a_source.as_str(), Some("utility"), 4_u64),
- (custom_wrapper_b_source.as_str(), Some("utility"), 5_u64),
- (
- custom_handle_wrapper_a_source.as_str(),
- Some("utility"),
- 6_u64,
- ),
- (
- retained_handle_wrapper_source.as_str(),
- Some("utility"),
- 7_u64,
- ),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id_base + offset,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id_base + offset)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
- }
-
- for (id, binding_name) in [
- (35470_u64, "customBindingA"),
- (35471_u64, "customHandleBindingA"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": binding_name }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- for (id, target_id) in [
- (35472_u64, first.target_id.as_str()),
- (35473_u64, second.target_id.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.closeTarget",
- "params": { "targetId": target_id }
- }))
- .await;
- ctx.expect_result(id, json!({ "success": true }), None);
- ctx.take_all();
- }
-
- let first_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 35474,
- 35475,
- )
- .await;
- let second_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &second.browser_context_id,
- 35476,
- 35477,
- )
- .await;
-
- for (id, session_id, html) in [
- (
- 35478_u64,
- first_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>first-replacement-a</div><div id='utility-handle-b'>first-replacement-b</div></body>",
- ),
- (
- 35479_u64,
- second_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>second-replacement-a</div><div id='utility-handle-b'>second-replacement-b</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, session_id, expected_state) in [
- (
- 35480_u64,
- first_replacement.session_id.as_str(),
- json!("[\"undefined\",\"function\",\"undefined\",\"function\"]"),
- ),
- (
- 35481_u64,
- second_replacement.session_id.as_str(),
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": format!(
- "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- )
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- for (id, target_id, session_id) in [
- (
- 35482_u64,
- first_replacement.target_id.as_str(),
- first_replacement.session_id.as_str(),
- ),
- (
- 35483_u64,
- second_replacement.target_id.as_str(),
- second_replacement.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 35484,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(35484, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(attached_events.len(), 2);
- let first_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(first_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("first replacement re-auto-attached session")
- .to_owned();
- let second_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(second_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("second replacement re-auto-attached session")
- .to_owned();
-
- for (id, session_id, expected_state) in [
- (
- 35485_u64,
- first_reauto_session.as_str(),
- json!("[\"undefined\",\"function\",\"undefined\",\"function\"]"),
- ),
- (
- 35486_u64,
- second_reauto_session.as_str(),
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- let mut first_reauto_utility_context = 0_i64;
- let mut second_reauto_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35487_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_reauto_utility_context,
- ),
- (
- 35488_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_reauto_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("re-auto-attached utility context id");
- ctx.take_all();
- }
-
- for (session_id, utility_context_id, add_base, eval_base, cleaned) in [
- (
- first_reauto_session.as_str(),
- first_reauto_utility_context,
- 35489_u64,
- 35499_u64,
- true,
- ),
- (
- second_reauto_session.as_str(),
- second_reauto_utility_context,
- 35509_u64,
- 35519_u64,
- false,
- ),
- ] {
- let bindings = if cleaned {
- vec![
- ("customBindingB", custom_wrapper_b_source.as_str()),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ]
- } else {
- vec![
- ("customBindingA", custom_wrapper_a_source.as_str()),
- ("customBindingB", custom_wrapper_b_source.as_str()),
- (
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- ),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ]
- };
-
- for (offset, (binding_name, source)) in bindings.iter().enumerate() {
- let add_id = add_base + offset as u64;
- let eval_id = eval_base + offset as u64;
- ctx.process_async(json!({
- "id": add_id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": binding_name,
- "executionContextId": utility_context_id
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, add_id)["result"], json!({}));
-
- ctx.process_async(json!({
- "id": eval_id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context_id,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, eval_id);
- assert_eq!(installed["result"]["result"]["value"], json!("function"));
- }
- }
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35529_u64,
- first_reauto_session.as_str(),
- first_reauto_utility_context,
- json!("[\"undefined\",\"function\",\"undefined\",\"function\"]"),
- ),
- (
- 35530_u64,
- second_reauto_session.as_str(),
- second_reauto_utility_context,
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": context_id,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- for (id, session_id, source, expected_type) in [
- (
- 35545_u64,
- first_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35546_u64,
- first_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "function",
- ),
- (
- 35547_u64,
- first_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35548_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 35549_u64,
- second_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35550_u64,
- second_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "function",
- ),
- (
- 35551_u64,
- second_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35552_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, id);
- assert_eq!(installed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35531,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_first_reauto_custom_b = customBindingB({ source: 'first-reauto-custom-b', nested: { count: 1, values: ['x', 2, true] } }); 'scheduled-first'"
- }
- })).await;
- let scheduled_first_custom = take_response_by_id(&mut ctx, 35531);
- assert!(
- scheduled_first_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled first custom")
- .starts_with("scheduled-")
- );
- let first_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("first cleaned replacement should emit customBindingB");
- let first_custom_payload: serde_json::Value = serde_json::from_str(
- first_custom_called["params"]["payload"]
- .as_str()
- .expect("first custom payload string"),
- )
- .expect("first custom payload json");
- let first_custom_seq = first_custom_payload["seq"]
- .as_i64()
- .expect("first custom seq");
- assert_eq!(
- first_custom_payload["serializedArgs"],
- json!([{ "source": "first-reauto-custom-b", "nested": { "count": 1, "values": ["x", 2, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35532,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_b_deliver({{ name: 'customBindingB', seq: {first_custom_seq}, result: 'first-reauto-custom-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35532)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35533,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_first_reauto_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35533)["result"]["result"]["value"],
- json!("first-reauto-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35534,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_second_reauto_custom_a = customBindingA({ source: 'second-reauto-custom-a', nested: { count: 2, values: ['y', 3, false] } }); 'scheduled-second'"
- }
- })).await;
- let scheduled_second_custom = take_response_by_id(&mut ctx, 35534);
- assert!(
- scheduled_second_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled second custom")
- .starts_with("scheduled-")
- );
- let second_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("second untouched replacement should emit customBindingA");
- let second_custom_payload: serde_json::Value = serde_json::from_str(
- second_custom_called["params"]["payload"]
- .as_str()
- .expect("second custom payload string"),
- )
- .expect("second custom payload json");
- let second_custom_seq = second_custom_payload["seq"]
- .as_i64()
- .expect("second custom seq");
- assert_eq!(
- second_custom_payload["serializedArgs"],
- json!([{ "source": "second-reauto-custom-a", "nested": { "count": 2, "values": ["y", 3, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35535,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {second_custom_seq}, result: 'second-reauto-custom-a-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35535)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35536,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_second_reauto_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35536)["result"]["result"]["value"],
- json!("second-reauto-custom-a-ok")
- );
-
- ctx.process_async(json!({
- "id": 35537,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_reauto_utility_context,
- "expression": "globalThis.__lm_first_reauto_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-first-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_handle = take_response_by_id(&mut ctx, 35537);
- assert!(
- scheduled_first_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled first handle")
- .starts_with("scheduled-")
- );
- let first_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(first_reauto_utility_context)
- })
- .cloned()
- .expect("first cleaned replacement should emit retained handle binding");
- let first_handle_payload: serde_json::Value = serde_json::from_str(
- first_handle_called["params"]["payload"]
- .as_str()
- .expect("first handle payload string"),
- )
- .expect("first handle payload json");
- let first_handle_seq = first_handle_payload["seq"]
- .as_i64()
- .expect("first handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35538,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_reauto_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35538)["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"first-replacement-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35539,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_reauto_utility_context,
- "expression": format!("globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {first_handle_seq}, error: 'first-reauto-pw-handle-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35539)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35540,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_reauto_utility_context,
- "expression": "globalThis.__lm_first_reauto_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35540)["result"]["result"]["value"],
- json!("rejected:first-reauto-pw-handle-error")
- );
-
- ctx.process_async(json!({
- "id": 35541,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_utility_context,
- "expression": "globalThis.__lm_second_reauto_custom_handle_a = customHandleBindingA(document.getElementById('utility-handle-a')); 'scheduled-second-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_second_handle = take_response_by_id(&mut ctx, 35541);
- assert!(
- scheduled_second_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled second handle")
- .starts_with("scheduled-")
- );
- let second_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customHandleBindingA")
- && message["params"]["executionContextId"] == json!(second_reauto_utility_context)
- })
- .cloned()
- .expect("second untouched replacement should emit custom handle binding");
- let second_handle_payload: serde_json::Value = serde_json::from_str(
- second_handle_called["params"]["payload"]
- .as_str()
- .expect("second handle payload string"),
- )
- .expect("second handle payload json");
- let second_handle_seq = second_handle_payload["seq"]
- .as_i64()
- .expect("second handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35542,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {second_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {second_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35542)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"second-replacement-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35543,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_a_deliver({{ name: 'customHandleBindingA', seq: {second_handle_seq}, result: 'second-reauto-custom-handle-a-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35543)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35544,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_utility_context,
- "expression": "globalThis.__lm_second_reauto_custom_handle_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35544)["result"]["result"]["value"],
- json!("second-reauto-custom-handle-a-ok")
- );
-
- for (id, session_id, html) in [
- (
- 35553_u64,
- first_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>first-reauto-replay-a</div><div id='utility-handle-b'>first-reauto-replay-b</div></body>",
- ),
- (
- 35554_u64,
- second_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>second-reauto-replay-a</div><div id='utility-handle-b'>second-reauto-replay-b</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, session_id, source, expected_type) in [
- (
- 35555_u64,
- first_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35556_u64,
- first_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "function",
- ),
- (
- 35557_u64,
- first_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35558_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 35559_u64,
- second_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35560_u64,
- second_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "function",
- ),
- (
- 35561_u64,
- second_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35562_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_reauto_replay_utility_context = 0_i64;
- let mut second_reauto_replay_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35563_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_reauto_replay_utility_context,
- ),
- (
- 35564_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_reauto_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("re-auto replay utility context id");
- ctx.take_all();
- }
-
- for (session_id, utility_context_id, add_base, eval_base, cleaned) in [
- (
- first_reauto_session.as_str(),
- first_reauto_replay_utility_context,
- 35565_u64,
- 35575_u64,
- true,
- ),
- (
- second_reauto_session.as_str(),
- second_reauto_replay_utility_context,
- 35585_u64,
- 35595_u64,
- false,
- ),
- ] {
- let bindings = if cleaned {
- vec![
- ("customBindingB", custom_wrapper_b_source.as_str()),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ]
- } else {
- vec![
- ("customBindingA", custom_wrapper_a_source.as_str()),
- ("customBindingB", custom_wrapper_b_source.as_str()),
- (
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- ),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ]
- };
-
- for (offset, (binding_name, source)) in bindings.iter().enumerate() {
- let add_id = add_base + offset as u64;
- let eval_id = eval_base + offset as u64;
- ctx.process_async(json!({
- "id": add_id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": binding_name,
- "executionContextId": utility_context_id
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, add_id)["result"], json!({}));
-
- ctx.process_async(json!({
- "id": eval_id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context_id,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, eval_id);
- assert_eq!(installed["result"]["result"]["value"], json!("function"));
- }
- }
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35605_u64,
- first_reauto_session.as_str(),
- first_reauto_replay_utility_context,
- json!("[\"undefined\",\"function\",\"undefined\",\"function\"]"),
- ),
- (
- 35606_u64,
- second_reauto_session.as_str(),
- second_reauto_replay_utility_context,
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": context_id,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- ctx.process_async(json!({
- "id": 35607,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_first_reauto_replay_custom_b = customBindingB({ source: 'first-reauto-replay-custom-b', nested: { count: 6, values: ['m', 7, true] } }); 'scheduled-first-replay'"
- }
- })).await;
- let scheduled_first_replay_custom = take_response_by_id(&mut ctx, 35607);
- assert!(
- scheduled_first_replay_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled first replay custom")
- .starts_with("scheduled-")
- );
- let first_replay_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("first replay custom bindingCalled");
- let first_replay_custom_payload: serde_json::Value = serde_json::from_str(
- first_replay_custom_called["params"]["payload"]
- .as_str()
- .expect("first replay custom payload string"),
- )
- .expect("first replay custom payload json");
- let first_replay_custom_seq = first_replay_custom_payload["seq"]
- .as_i64()
- .expect("first replay custom seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35608,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_b_deliver({{ name: 'customBindingB', seq: {first_replay_custom_seq}, result: 'first-reauto-replay-custom-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35608)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35609,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_first_reauto_replay_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35609)["result"]["result"]["value"],
- json!("first-reauto-replay-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35610,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_replay_utility_context,
- "expression": "globalThis.__lm_second_reauto_replay_custom_handle_a_reject = customHandleBindingA(document.getElementById('utility-handle-a')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-second-replay-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_second_replay_handle = take_response_by_id(&mut ctx, 35610);
- assert!(
- scheduled_second_replay_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled second replay handle")
- .starts_with("scheduled-")
- );
- let second_replay_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customHandleBindingA")
- && message["params"]["executionContextId"]
- == json!(second_reauto_replay_utility_context)
- })
- .cloned()
- .expect("second replay custom handle bindingCalled");
- let second_replay_handle_payload: serde_json::Value = serde_json::from_str(
- second_replay_handle_called["params"]["payload"]
- .as_str()
- .expect("second replay handle payload string"),
- )
- .expect("second replay handle payload json");
- let second_replay_handle_seq = second_replay_handle_payload["seq"]
- .as_i64()
- .expect("second replay handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35611,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {second_replay_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {second_replay_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35611)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"second-reauto-replay-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35612,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_a_deliver({{ name: 'customHandleBindingA', seq: {second_replay_handle_seq}, error: 'second-reauto-replay-custom-handle-a-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35612)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35613,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_reauto_replay_utility_context,
- "expression": "globalThis.__lm_second_reauto_replay_custom_handle_a_reject",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35613)["result"]["result"]["value"],
- json!("rejected:second-reauto-replay-custom-handle-a-error")
- );
-
- ctx.process_async(json!({
- "id": 35614,
- "method": "Runtime.removeBinding",
- "sessionId": first_reauto_session,
- "params": { "name": "customBindingB" }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, 35614)["result"], json!({}));
-
- for (id, session_id, expected_state) in [
- (
- 35615_u64,
- first_reauto_session.as_str(),
- json!("[\"undefined\",\"undefined\",\"undefined\",\"function\"]"),
- ),
- (
- 35616_u64,
- first_reauto_session.as_str(),
- json!("[\"undefined\",\"undefined\",\"undefined\",\"function\"]"),
- ),
- (
- 35617_u64,
- second_reauto_session.as_str(),
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- (
- 35618_u64,
- second_reauto_session.as_str(),
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let params = if id == 35615 || id == 35617 {
- json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- })
- } else {
- json!({
- "contextId": if id == 35616 {
- first_reauto_replay_utility_context
- } else {
- second_reauto_replay_utility_context
- },
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- })
- };
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- for (id, session_id, html) in [
- (
- 35619_u64,
- first_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>first-reauto-post-cleanup-a</div><div id='utility-handle-b'>first-reauto-post-cleanup-b</div></body>",
- ),
- (
- 35620_u64,
- second_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>second-reauto-post-cleanup-a</div><div id='utility-handle-b'>second-reauto-post-cleanup-b</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, session_id, source, expected_type) in [
- (
- 35621_u64,
- first_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35622_u64,
- first_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "undefined",
- ),
- (
- 35623_u64,
- first_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35624_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 35625_u64,
- second_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35626_u64,
- second_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "function",
- ),
- (
- 35627_u64,
- second_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35628_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_post_cleanup_utility_context = 0_i64;
- let mut second_post_cleanup_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35629_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_post_cleanup_utility_context,
- ),
- (
- 35630_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_post_cleanup_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("post-cleanup replay utility context id");
- ctx.take_all();
- }
-
- for (session_id, utility_context_id, add_base, eval_base, cleaned) in [
- (
- first_reauto_session.as_str(),
- first_post_cleanup_utility_context,
- 35631_u64,
- 35641_u64,
- true,
- ),
- (
- second_reauto_session.as_str(),
- second_post_cleanup_utility_context,
- 35651_u64,
- 35661_u64,
- false,
- ),
- ] {
- let bindings = if cleaned {
- vec![(
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- )]
- } else {
- vec![
- ("customBindingA", custom_wrapper_a_source.as_str()),
- ("customBindingB", custom_wrapper_b_source.as_str()),
- (
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- ),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ]
- };
-
- for (offset, (binding_name, source)) in bindings.iter().enumerate() {
- let add_id = add_base + offset as u64;
- let eval_id = eval_base + offset as u64;
- ctx.process_async(json!({
- "id": add_id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": binding_name,
- "executionContextId": utility_context_id
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, add_id)["result"], json!({}));
-
- ctx.process_async(json!({
- "id": eval_id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context_id,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, eval_id);
- assert_eq!(installed["result"]["result"]["value"], json!("function"));
- }
- }
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35671_u64,
- first_reauto_session.as_str(),
- first_post_cleanup_utility_context,
- json!("[\"undefined\",\"undefined\",\"undefined\",\"function\"]"),
- ),
- (
- 35672_u64,
- second_reauto_session.as_str(),
- second_post_cleanup_utility_context,
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": context_id,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- ctx.process_async(json!({
- "id": 35673,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_post_cleanup_utility_context,
- "expression": "globalThis.__lm_first_post_cleanup_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(value => `resolved:${value}`, error => `rejected:${error}`); 'scheduled-first-post-cleanup-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_post_cleanup_handle = take_response_by_id(&mut ctx, 35673);
- assert!(
- scheduled_first_post_cleanup_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled first post-cleanup handle")
- .starts_with("scheduled-")
- );
- let first_post_cleanup_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"]
- == json!(first_post_cleanup_utility_context)
- })
- .cloned()
- .expect("first post-cleanup retained handle bindingCalled");
- let first_post_cleanup_handle_payload: serde_json::Value = serde_json::from_str(
- first_post_cleanup_handle_called["params"]["payload"]
- .as_str()
- .expect("first post-cleanup handle payload string"),
- )
- .expect("first post-cleanup handle payload json");
- let first_post_cleanup_handle_seq = first_post_cleanup_handle_payload["seq"]
- .as_i64()
- .expect("first post-cleanup handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35674,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_post_cleanup_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_post_cleanup_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_post_cleanup_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35674)["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"first-reauto-post-cleanup-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35675,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_post_cleanup_utility_context,
- "expression": format!("globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {first_post_cleanup_handle_seq}, result: 'first-post-cleanup-pw-handle-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35675)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35676,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_post_cleanup_utility_context,
- "expression": "globalThis.__lm_first_post_cleanup_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35676)["result"]["result"]["value"],
- json!("resolved:first-post-cleanup-pw-handle-ok")
- );
-
- ctx.process_async(json!({
- "id": 35677,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_second_post_cleanup_custom_a = customBindingA({ source: 'second-post-cleanup-custom-a', nested: { count: 8, values: ['q', 9, false] } }); 'scheduled-second-post-cleanup-custom-a'"
- }
- })).await;
- let scheduled_second_post_cleanup_custom = take_response_by_id(&mut ctx, 35677);
- assert!(
- scheduled_second_post_cleanup_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled second post-cleanup custom")
- .starts_with("scheduled-")
- );
- let second_post_cleanup_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("second post-cleanup custom bindingCalled");
- let second_post_cleanup_custom_payload: serde_json::Value = serde_json::from_str(
- second_post_cleanup_custom_called["params"]["payload"]
- .as_str()
- .expect("second post-cleanup custom payload string"),
- )
- .expect("second post-cleanup custom payload json");
- let second_post_cleanup_custom_seq = second_post_cleanup_custom_payload["seq"]
- .as_i64()
- .expect("second post-cleanup custom seq");
- assert_eq!(
- second_post_cleanup_custom_payload["serializedArgs"],
- json!([{ "source": "second-post-cleanup-custom-a", "nested": { "count": 8, "values": ["q", 9, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35678,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {second_post_cleanup_custom_seq}, result: 'second-post-cleanup-custom-a-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35678)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35679,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_second_post_cleanup_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35679)["result"]["result"]["value"],
- json!("second-post-cleanup-custom-a-ok")
- );
-
- ctx.process_async(json!({
- "id": 35680,
- "method": "Runtime.removeBinding",
- "sessionId": second_reauto_session,
- "params": { "name": "customHandleBindingA" }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, 35680)["result"], json!({}));
-
- for (id, session_id, expected_state) in [
- (
- 35681_u64,
- first_reauto_session.as_str(),
- json!("[\"undefined\",\"undefined\",\"undefined\",\"function\"]"),
- ),
- (
- 35682_u64,
- second_reauto_session.as_str(),
- json!("[\"function\",\"function\",\"undefined\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35683_u64,
- first_reauto_session.as_str(),
- first_post_cleanup_utility_context,
- json!("[\"undefined\",\"undefined\",\"undefined\",\"function\"]"),
- ),
- (
- 35684_u64,
- second_reauto_session.as_str(),
- second_post_cleanup_utility_context,
- json!("[\"function\",\"function\",\"undefined\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": context_id,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- for (id, session_id, html) in [
- (
- 35685_u64,
- first_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>first-reauto-final-a</div><div id='utility-handle-b'>first-reauto-final-b</div></body>",
- ),
- (
- 35686_u64,
- second_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>second-reauto-final-a</div><div id='utility-handle-b'>second-reauto-final-b</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, session_id, source, expected_type) in [
- (
- 35687_u64,
- first_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35688_u64,
- first_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "undefined",
- ),
- (
- 35689_u64,
- first_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35690_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 35691_u64,
- second_reauto_session.as_str(),
- custom_wrapper_a_source.as_str(),
- "function",
- ),
- (
- 35692_u64,
- second_reauto_session.as_str(),
- custom_wrapper_b_source.as_str(),
- "function",
- ),
- (
- 35693_u64,
- second_reauto_session.as_str(),
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35694_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_final_utility_context = 0_i64;
- let mut second_final_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35695_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_final_utility_context,
- ),
- (
- 35696_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_final_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("final replay utility context id");
- ctx.take_all();
- }
-
- for (session_id, utility_context_id, add_base, eval_base, variant) in [
- (
- first_reauto_session.as_str(),
- first_final_utility_context,
- 35697_u64,
- 35707_u64,
- 0_u8,
- ),
- (
- second_reauto_session.as_str(),
- second_final_utility_context,
- 35717_u64,
- 35727_u64,
- 1_u8,
- ),
- ] {
- let bindings = match variant {
- 0 => vec![(
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- )],
- 1 => vec![
- ("customBindingA", custom_wrapper_a_source.as_str()),
- ("customBindingB", custom_wrapper_b_source.as_str()),
- (
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ],
- _ => unreachable!("variant"),
- };
-
- for (offset, (binding_name, source)) in bindings.iter().enumerate() {
- let add_id = add_base + offset as u64;
- let eval_id = eval_base + offset as u64;
- ctx.process_async(json!({
- "id": add_id,
- "method": "Runtime.addBinding",
- "sessionId": session_id,
- "params": {
- "name": binding_name,
- "executionContextId": utility_context_id
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, add_id)["result"], json!({}));
-
- ctx.process_async(json!({
- "id": eval_id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": utility_context_id,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, eval_id);
- assert_eq!(installed["result"]["result"]["value"], json!("function"));
- }
- }
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35737_u64,
- first_reauto_session.as_str(),
- first_final_utility_context,
- json!("[\"undefined\",\"undefined\",\"undefined\",\"function\"]"),
- ),
- (
- 35738_u64,
- second_reauto_session.as_str(),
- second_final_utility_context,
- json!("[\"function\",\"function\",\"undefined\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": context_id,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- ctx.process_async(json!({
- "id": 35739,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_second_final_custom_b = customBindingB({ source: 'second-final-custom-b', nested: { count: 10, values: ['z', 11, true] } }); 'scheduled-second-final-custom-b'"
- }
- })).await;
- let scheduled_second_final_custom = take_response_by_id(&mut ctx, 35739);
- assert!(
- scheduled_second_final_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled second final custom")
- .starts_with("scheduled-")
- );
- let second_final_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("second final custom bindingCalled");
- let second_final_custom_payload: serde_json::Value = serde_json::from_str(
- second_final_custom_called["params"]["payload"]
- .as_str()
- .expect("second final custom payload string"),
- )
- .expect("second final custom payload json");
- let second_final_custom_seq = second_final_custom_payload["seq"]
- .as_i64()
- .expect("second final custom seq");
- assert_eq!(
- second_final_custom_payload["serializedArgs"],
- json!([{ "source": "second-final-custom-b", "nested": { "count": 10, "values": ["z", 11, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35740,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_b_deliver({{ name: 'customBindingB', seq: {second_final_custom_seq}, result: 'second-final-custom-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35740)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35741,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_second_final_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35741)["result"]["result"]["value"],
- json!("second-final-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35742,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_final_utility_context,
- "expression": "globalThis.__lm_first_final_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-a')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-first-final-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_final_handle = take_response_by_id(&mut ctx, 35742);
- assert!(
- scheduled_first_final_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled first final handle")
- .starts_with("scheduled-")
- );
- let first_final_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(first_final_utility_context)
- })
- .cloned()
- .expect("first final retained handle bindingCalled");
- let first_final_handle_payload: serde_json::Value = serde_json::from_str(
- first_final_handle_called["params"]["payload"]
- .as_str()
- .expect("first final handle payload string"),
- )
- .expect("first final handle payload json");
- let first_final_handle_seq = first_final_handle_payload["seq"]
- .as_i64()
- .expect("first final handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35743,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_final_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_final_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_final_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35743)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"first-reauto-final-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35744,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_final_utility_context,
- "expression": format!("globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {first_final_handle_seq}, error: 'first-final-pw-handle-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35744)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35745,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_final_utility_context,
- "expression": "globalThis.__lm_first_final_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35745)["result"]["result"]["value"],
- json!("rejected:first-final-pw-handle-error")
- );
- })
- .await;
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_replacement_targets_keep_thin_crpage_cleanup_isolated_per_browser_context_without_runtime_enable()
- {
- patchright_replacement_targets_large_stack(|| async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 35750, 35751, 35752)
- .await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 35753, 35754, 35755)
- .await;
-
- for (id, session_id, html) in [
- (
- 35756_u64,
- first.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-first-a</div></body>",
- ),
- (
- 35757_u64,
- second.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-second-a</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35758_u64,
- first.session_id.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 35759_u64,
- second.session_id.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin initial utility context id");
- ctx.take_all();
- }
-
- let custom_wrapper_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptHandleBinding",
- "__lm_pw_kept_handle_binding_deliver",
- Some("__lm_pw_kept_handle_binding_take"),
- true,
- );
-
- for (session_id, utility_context_id, id_base) in [
- (first.session_id.as_str(), first_utility_context, 35760_u64),
- (
- second.session_id.as_str(),
- second_utility_context,
- 35770_u64,
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base,
- id_base + 1,
- id_base + 2,
- id_base + 3,
- "customBindingA",
- &custom_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 4,
- id_base + 5,
- id_base + 6,
- id_base + 7,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
- }
-
- for (session_id, id_base) in [
- (first.session_id.as_str(), 35780_u64),
- (second.session_id.as_str(), 35790_u64),
- ] {
- for (source, world_name, offset) in [
- (custom_wrapper_source.as_str(), None, 0_u64),
- (retained_handle_wrapper_source.as_str(), None, 1_u64),
- (custom_wrapper_source.as_str(), Some("utility"), 2_u64),
- (
- retained_handle_wrapper_source.as_str(),
- Some("utility"),
- 3_u64,
- ),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id_base + offset,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id_base + offset)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
- }
-
- ctx.process_async(json!({
- "id": 35800,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": "customBindingA" }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, 35800)["result"], json!({}));
-
- for (id, target_id) in [
- (35801_u64, first.target_id.as_str()),
- (35802_u64, second.target_id.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.closeTarget",
- "params": { "targetId": target_id }
- }))
- .await;
- ctx.expect_result(id, json!({ "success": true }), None);
- ctx.take_all();
- }
-
- let first_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 35803,
- 35804,
- )
- .await;
- let second_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &second.browser_context_id,
- 35805,
- 35806,
- )
- .await;
-
- for (id, session_id, html) in [
- (
- 35807_u64,
- first_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-first-replacement-a</div></body>",
- ),
- (
- 35808_u64,
- second_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-second-replacement-a</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 35809_u64,
- first_replacement.target_id.as_str(),
- first_replacement.session_id.as_str(),
- ),
- (
- 35810_u64,
- second_replacement.target_id.as_str(),
- second_replacement.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 35811,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(35811, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(attached_events.len(), 2);
- let first_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(first_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin first replacement re-auto-attached session")
- .to_owned();
- let second_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(second_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin second replacement re-auto-attached session")
- .to_owned();
-
- for (id, session_id, source, expected_type) in [
- (
- 35812_u64,
- first_reauto_session.as_str(),
- custom_wrapper_source.as_str(),
- "undefined",
- ),
- (
- 35813_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 35814_u64,
- second_reauto_session.as_str(),
- custom_wrapper_source.as_str(),
- "function",
- ),
- (
- 35815_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, id);
- assert_eq!(installed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_reauto_utility_context = 0_i64;
- let mut second_reauto_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35816_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_reauto_utility_context,
- ),
- (
- 35817_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_reauto_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin re-auto utility context id");
- ctx.take_all();
- }
-
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_reauto_utility_context,
- 35818,
- 35819,
- 35820,
- 35821,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_reauto_utility_context,
- 35822,
- 35823,
- 35824,
- 35825,
- "customBindingA",
- &custom_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_reauto_utility_context,
- 35826,
- 35827,
- 35828,
- 35829,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35830_u64,
- first_reauto_session.as_str(),
- first_reauto_utility_context,
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 35831_u64,
- second_reauto_session.as_str(),
- second_reauto_utility_context,
- json!("[\"function\",\"function\"]"),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "contextId": context_id,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- for (id, session_id, html) in [
- (
- 35832_u64,
- first_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>thin-first-replay-a</div></body>",
- ),
- (
- 35833_u64,
- second_reauto_session.as_str(),
- "<body><div id='utility-handle-a'>thin-second-replay-a</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, session_id, source, expected_type) in [
- (
- 35834_u64,
- first_reauto_session.as_str(),
- custom_wrapper_source.as_str(),
- "undefined",
- ),
- (
- 35835_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 35836_u64,
- second_reauto_session.as_str(),
- custom_wrapper_source.as_str(),
- "function",
- ),
- (
- 35837_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 35838_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 35839_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin replay utility context id");
- ctx.take_all();
- }
-
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 35840,
- 35841,
- 35842,
- 35843,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 35844,
- 35845,
- 35846,
- 35847,
- "customBindingA",
- &custom_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 35848,
- 35849,
- 35850,
- 35851,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
-
- ctx.process_async(json!({
- "id": 35852,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_second_custom_a = customBindingA({ source: 'thin-second-custom-a', nested: { count: 12, values: ['thin', 13, true] } }); 'scheduled-thin-second-custom-a'"
- }
- })).await;
- let scheduled_second_custom = take_response_by_id(&mut ctx, 35852);
- assert!(
- scheduled_second_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin second custom")
- .starts_with("scheduled-")
- );
- let second_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin second custom bindingCalled");
- let second_custom_payload: serde_json::Value = serde_json::from_str(
- second_custom_called["params"]["payload"]
- .as_str()
- .expect("thin second custom payload string"),
- )
- .expect("thin second custom payload json");
- let second_custom_seq = second_custom_payload["seq"]
- .as_i64()
- .expect("thin second custom seq");
- assert_eq!(
- second_custom_payload["serializedArgs"],
- json!([{ "source": "thin-second-custom-a", "nested": { "count": 12, "values": ["thin", 13, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35853,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {second_custom_seq}, result: 'thin-second-custom-a-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35853)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35854,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_second_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35854)["result"]["result"]["value"],
- json!("thin-second-custom-a-ok")
- );
-
- ctx.process_async(json!({
- "id": 35855,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_first_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-a')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-first-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_handle = take_response_by_id(&mut ctx, 35855);
- assert!(
- scheduled_first_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin first handle")
- .starts_with("scheduled-")
- );
- let first_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin first retained handle bindingCalled");
- let first_handle_payload: serde_json::Value = serde_json::from_str(
- first_handle_called["params"]["payload"]
- .as_str()
- .expect("thin first handle payload string"),
- )
- .expect("thin first handle payload json");
- let first_handle_seq = first_handle_payload["seq"]
- .as_i64()
- .expect("thin first handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35856,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35856)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-first-replay-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35857,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {first_handle_seq}, error: 'thin-first-pw-handle-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35857)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35858,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_first_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35858)["result"]["result"]["value"],
- json!("rejected:thin-first-pw-handle-error")
- );
-
- for (id, session_id, target_id) in [
- (
- 35859_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- ),
- (
- 35860_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id,
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 35861,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": first_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let first_reattached_session = take_response_by_id(&mut ctx, 35861)["result"]["sessionId"]
- .as_str()
- .expect("thin first reattached session id")
- .to_owned();
- assert_ne!(first_reattached_session, first_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": first_reattached_session,
- "targetInfo": {
- "targetId": first_replacement.target_id,
- "browserContextId": first.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 35862,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let second_reattached_session = take_response_by_id(&mut ctx, 35862)["result"]["sessionId"]
- .as_str()
- .expect("thin second reattached session id")
- .to_owned();
- assert_ne!(second_reattached_session, second_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": second_reattached_session,
- "targetInfo": {
- "targetId": second_replacement.target_id,
- "browserContextId": second.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, session_id, context_id, expected_state) in [
- (
- 35863_u64,
- first_reattached_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 35864_u64,
- first_reattached_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 35865_u64,
- second_reattached_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\"]"),
- ),
- (
- 35866_u64,
- second_reattached_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.__pw_keptHandleBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 35867,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_reattached_second_custom_a = customBindingA({ source: 'thin-reattached-second-custom-a', nested: { count: 14, values: ['reattach', 15, true] } }); 'scheduled-thin-reattached-second-custom-a'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_custom = take_response_by_id(&mut ctx, 35867);
- assert!(
- scheduled_reattached_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin reattached second custom")
- .starts_with("scheduled-")
- );
- let reattached_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reattached_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin reattached second custom bindingCalled");
- let reattached_custom_payload: serde_json::Value = serde_json::from_str(
- reattached_custom_called["params"]["payload"]
- .as_str()
- .expect("thin reattached second custom payload string"),
- )
- .expect("thin reattached second custom payload json");
- let reattached_custom_seq = reattached_custom_payload["seq"]
- .as_i64()
- .expect("thin reattached second custom seq");
- assert_eq!(reattached_custom_seq, 2);
- assert_eq!(
- reattached_custom_payload["serializedArgs"],
- json!([{ "source": "thin-reattached-second-custom-a", "nested": { "count": 14, "values": ["reattach", 15, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35868,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_custom_binding_a_deliver({ name: 'customBindingA', seq: 2, result: 'thin-reattached-second-custom-a-ok' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35868)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35869,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_reattached_second_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35869)["result"]["result"]["value"],
- json!("thin-reattached-second-custom-a-ok")
- );
-
- ctx.process_async(json!({
- "id": 35870,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_reattached_first_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-a')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-reattached-first-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_handle = take_response_by_id(&mut ctx, 35870);
- assert!(
- scheduled_reattached_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin reattached first handle")
- .starts_with("scheduled-")
- );
- let reattached_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reattached_session)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin reattached first retained handle bindingCalled");
- let reattached_handle_payload: serde_json::Value = serde_json::from_str(
- reattached_handle_called["params"]["payload"]
- .as_str()
- .expect("thin reattached first handle payload string"),
- )
- .expect("thin reattached first handle payload json");
- let reattached_handle_seq = reattached_handle_payload["seq"]
- .as_i64()
- .expect("thin reattached first handle seq");
- assert_eq!(reattached_handle_seq, 2);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35871,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {reattached_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {reattached_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35871)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-first-replay-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35872,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {reattached_handle_seq}, error: 'thin-reattached-first-pw-handle-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35872)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35873,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_reattached_first_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 35873)["result"]["result"]["value"],
- json!("rejected:thin-reattached-first-pw-handle-error")
- );
- })
- .await;
-}
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/mod.rs b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/mod.rs
index 3a5ec00b9..84f22d87a 100644
--- a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/mod.rs
+++ b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/mod.rs
@@ -23,5 +23,4 @@ where
}
}
-mod crpage;
mod thin_variants;
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/thin_variants.rs b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/thin_variants.rs
index 728c74f7d..6a202db1c 100644
--- a/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/thin_variants.rs
+++ b/moli-protocol/src/domains/target/tests/tests_patchright/utility_world/replacement_targets/thin_variants.rs
@@ -1,3896 +1,5 @@
use super::*;
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_replacement_targets_keep_thin_handle_cleanup_isolated_per_browser_context_without_runtime_enable()
- {
- patchright_replacement_targets_large_stack(|| async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36000, 36001, 36002)
- .await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36003, 36004, 36005)
- .await;
-
- for (id, session_id, html) in [
- (
- 36006_u64,
- first.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-first-handle-a</div></body>",
- ),
- (
- 36007_u64,
- second.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-second-handle-a</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36008_u64,
- first.session_id.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 36009_u64,
- second.session_id.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin handle initial utility context id");
- ctx.take_all();
- }
-
- let custom_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
-
- for (session_id, utility_context_id, id_base) in [
- (first.session_id.as_str(), first_utility_context, 36010_u64),
- (
- second.session_id.as_str(),
- second_utility_context,
- 36020_u64,
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base,
- id_base + 1,
- id_base + 2,
- id_base + 3,
- "customHandleBindingA",
- &custom_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 4,
- id_base + 5,
- id_base + 6,
- id_base + 7,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- }
-
- for (session_id, id_base) in [
- (first.session_id.as_str(), 36030_u64),
- (second.session_id.as_str(), 36040_u64),
- ] {
- for (source, world_name, offset) in [
- (custom_handle_wrapper_source.as_str(), None, 0_u64),
- (retained_wrapper_source.as_str(), None, 1_u64),
- (
- custom_handle_wrapper_source.as_str(),
- Some("utility"),
- 2_u64,
- ),
- (retained_wrapper_source.as_str(), Some("utility"), 3_u64),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id_base + offset,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id_base + offset)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
- }
-
- ctx.process_async(json!({
- "id": 36050,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": "customHandleBindingA" }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, 36050)["result"], json!({}));
-
- for (id, target_id) in [
- (36051_u64, first.target_id.as_str()),
- (36052_u64, second.target_id.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.closeTarget",
- "params": { "targetId": target_id }
- }))
- .await;
- ctx.expect_result(id, json!({ "success": true }), None);
- ctx.take_all();
- }
-
- let first_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 36053,
- 36054,
- )
- .await;
- let second_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &second.browser_context_id,
- 36055,
- 36056,
- )
- .await;
-
- for (id, session_id, html) in [
- (
- 36057_u64,
- first_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-first-replacement-handle-a</div></body>",
- ),
- (
- 36058_u64,
- second_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-second-replacement-handle-a</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 36059_u64,
- first_replacement.target_id.as_str(),
- first_replacement.session_id.as_str(),
- ),
- (
- 36060_u64,
- second_replacement.target_id.as_str(),
- second_replacement.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36061,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(36061, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(attached_events.len(), 2);
- let first_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(first_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin handle first replacement re-auto-attached session")
- .to_owned();
- let second_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(second_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin handle second replacement re-auto-attached session")
- .to_owned();
-
- for (id, session_id, source, expected_type) in [
- (
- 36062_u64,
- first_reauto_session.as_str(),
- custom_handle_wrapper_source.as_str(),
- "undefined",
- ),
- (
- 36063_u64,
- first_reauto_session.as_str(),
- retained_wrapper_source.as_str(),
- "function",
- ),
- (
- 36064_u64,
- second_reauto_session.as_str(),
- custom_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 36065_u64,
- second_reauto_session.as_str(),
- retained_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, id);
- assert_eq!(installed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36066_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 36067_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin handle replay utility context id");
- ctx.take_all();
- }
-
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36068,
- 36069,
- 36070,
- 36071,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36072,
- 36073,
- 36074,
- 36075,
- "customHandleBindingA",
- &custom_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36076,
- 36077,
- 36078,
- 36079,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36080_u64,
- first_reauto_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 36081_u64,
- first_reauto_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 36082_u64,
- second_reauto_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\"]"),
- ),
- (
- 36083_u64,
- second_reauto_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36084,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_second_custom_handle_a = customHandleBindingA(document.getElementById('utility-handle-a')); 'scheduled-thin-second-custom-handle-a'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_custom_handle = take_response_by_id(&mut ctx, 36084);
- assert!(
- scheduled_custom_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin second custom handle")
- .starts_with("scheduled-")
- );
- let custom_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customHandleBindingA")
- && message["params"]["executionContextId"] == json!(second_replay_utility_context)
- })
- .cloned()
- .expect("thin second custom handle bindingCalled");
- let custom_handle_payload: serde_json::Value = serde_json::from_str(
- custom_handle_called["params"]["payload"]
- .as_str()
- .expect("thin second custom handle payload string"),
- )
- .expect("thin second custom handle payload json");
- let custom_handle_seq = custom_handle_payload["seq"]
- .as_i64()
- .expect("thin second custom handle seq");
- assert_eq!(custom_handle_seq, 1);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36085,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {custom_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {custom_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36085)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-second-replacement-handle-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36086,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_a_deliver({{ name: 'customHandleBindingA', seq: {custom_handle_seq}, result: 'thin-second-custom-handle-a-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36086)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36087,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_second_custom_handle_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36087)["result"]["result"]["value"],
- json!("thin-second-custom-handle-a-ok")
- );
-
- ctx.process_async(json!({
- "id": 36088,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_first_pw_binding = __pw_keptBinding({ source: 'thin-first-pw-binding', nested: { count: 16, values: ['thin', 17, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-first-pw-binding'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_pw_binding = take_response_by_id(&mut ctx, 36088);
- assert!(
- scheduled_pw_binding["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin first pw binding")
- .starts_with("scheduled-")
- );
- let pw_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptBinding")
- })
- .cloned()
- .expect("thin first pw binding bindingCalled");
- let pw_binding_payload: serde_json::Value = serde_json::from_str(
- pw_binding_called["params"]["payload"]
- .as_str()
- .expect("thin first pw binding payload string"),
- )
- .expect("thin first pw binding payload json");
- let pw_binding_seq = pw_binding_payload["seq"]
- .as_i64()
- .expect("thin first pw binding seq");
- assert_eq!(
- pw_binding_payload["serializedArgs"],
- json!([{ "source": "thin-first-pw-binding", "nested": { "count": 16, "values": ["thin", 17, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36089,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_pw_kept_binding_deliver({{ name: '__pw_keptBinding', seq: {pw_binding_seq}, error: 'thin-first-pw-binding-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36089)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36090,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_first_pw_binding",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36090)["result"]["result"]["value"],
- json!("rejected:thin-first-pw-binding-error")
- );
-
- for (id, session_id, target_id) in [
- (
- 36091_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- ),
- (
- 36092_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id,
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36093,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": first_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let first_reattached_session = take_response_by_id(&mut ctx, 36093)["result"]["sessionId"]
- .as_str()
- .expect("thin handle first reattached session id")
- .to_owned();
- assert_ne!(first_reattached_session, first_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": first_reattached_session,
- "targetInfo": {
- "targetId": first_replacement.target_id,
- "browserContextId": first.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 36094,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let second_reattached_session = take_response_by_id(&mut ctx, 36094)["result"]["sessionId"]
- .as_str()
- .expect("thin handle second reattached session id")
- .to_owned();
- assert_ne!(second_reattached_session, second_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": second_reattached_session,
- "targetInfo": {
- "targetId": second_replacement.target_id,
- "browserContextId": second.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36095_u64,
- first_reattached_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 36096_u64,
- first_reattached_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\"]"),
- ),
- (
- 36097_u64,
- second_reattached_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\"]"),
- ),
- (
- 36098_u64,
- second_reattached_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36099,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_reattached_second_custom_handle_a = customHandleBindingA(document.getElementById('utility-handle-a')); 'scheduled-thin-reattached-second-custom-handle-a'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_custom_handle = take_response_by_id(&mut ctx, 36099);
- assert!(
- scheduled_reattached_custom_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin reattached second custom handle")
- .starts_with("scheduled-")
- );
- let reattached_custom_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reattached_session)
- && message["params"]["name"] == json!("customHandleBindingA")
- && message["params"]["executionContextId"] == json!(second_replay_utility_context)
- })
- .cloned()
- .expect("thin reattached second custom handle bindingCalled");
- let reattached_custom_handle_payload: serde_json::Value = serde_json::from_str(
- reattached_custom_handle_called["params"]["payload"]
- .as_str()
- .expect("thin reattached second custom handle payload string"),
- )
- .expect("thin reattached second custom handle payload json");
- let reattached_custom_handle_seq = reattached_custom_handle_payload["seq"]
- .as_i64()
- .expect("thin reattached second custom handle seq");
- assert_eq!(reattached_custom_handle_seq, 2);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36100,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {reattached_custom_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {reattached_custom_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36100)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-second-replacement-handle-a\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36101,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_a_deliver({{ name: 'customHandleBindingA', seq: {reattached_custom_handle_seq}, result: 'thin-reattached-second-custom-handle-a-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36101)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36102,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_reattached_second_custom_handle_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36102)["result"]["result"]["value"],
- json!("thin-reattached-second-custom-handle-a-ok")
- );
-
- ctx.process_async(json!({
- "id": 36103,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_reattached_first_pw_binding = __pw_keptBinding({ source: 'thin-reattached-first-pw-binding', nested: { count: 18, values: ['reattach', 19, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-reattached-first-pw-binding'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_pw_binding = take_response_by_id(&mut ctx, 36103);
- assert!(
- scheduled_reattached_pw_binding["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin reattached first pw binding")
- .starts_with("scheduled-")
- );
- let reattached_pw_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reattached_session)
- && message["params"]["name"] == json!("__pw_keptBinding")
- })
- .cloned()
- .expect("thin reattached first pw binding bindingCalled");
- let reattached_pw_binding_payload: serde_json::Value = serde_json::from_str(
- reattached_pw_binding_called["params"]["payload"]
- .as_str()
- .expect("thin reattached first pw binding payload string"),
- )
- .expect("thin reattached first pw binding payload json");
- let reattached_pw_binding_seq = reattached_pw_binding_payload["seq"]
- .as_i64()
- .expect("thin reattached first pw binding seq");
- assert_eq!(reattached_pw_binding_seq, 2);
- assert_eq!(
- reattached_pw_binding_payload["serializedArgs"],
- json!([{ "source": "thin-reattached-first-pw-binding", "nested": { "count": 18, "values": ["reattach", 19, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36104,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "expression": format!("globalThis.__lm_pw_kept_binding_deliver({{ name: '__pw_keptBinding', seq: {reattached_pw_binding_seq}, error: 'thin-reattached-first-pw-binding-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36104)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36105,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_reattached_first_pw_binding",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36105)["result"]["result"]["value"],
- json!("rejected:thin-reattached-first-pw-binding-error")
- );
- })
- .await;
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_replacement_targets_keep_thin_name_cleanup_isolated_per_browser_context_without_runtime_enable()
- {
- patchright_replacement_targets_large_stack(|| async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36110, 36111, 36112)
- .await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36113, 36114, 36115)
- .await;
-
- for (id, session_id, html) in [
- (
- 36116_u64,
- first.session_id.as_str(),
- "<body><div id='page'>thin-first-name</div></body>",
- ),
- (
- 36117_u64,
- second.session_id.as_str(),
- "<body><div id='page'>thin-second-name</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36118_u64,
- first.session_id.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 36119_u64,
- second.session_id.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin name initial utility context id");
- ctx.take_all();
- }
-
- let custom_a_wrapper_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_b_wrapper_source = patchright_page_binding_wrapper_source(
- "customBindingB",
- "__lm_custom_binding_b_deliver",
- None,
- false,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
-
- for (session_id, utility_context_id, id_base) in [
- (first.session_id.as_str(), first_utility_context, 36120_u64),
- (
- second.session_id.as_str(),
- second_utility_context,
- 36132_u64,
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base,
- id_base + 1,
- id_base + 2,
- id_base + 3,
- "customBindingA",
- &custom_a_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 4,
- id_base + 5,
- id_base + 6,
- id_base + 7,
- "customBindingB",
- &custom_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 8,
- id_base + 9,
- id_base + 10,
- id_base + 11,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- }
-
- for (session_id, id_base) in [
- (first.session_id.as_str(), 36144_u64),
- (second.session_id.as_str(), 36150_u64),
- ] {
- for (source, world_name, offset) in [
- (custom_a_wrapper_source.as_str(), None, 0_u64),
- (custom_b_wrapper_source.as_str(), None, 1_u64),
- (retained_wrapper_source.as_str(), None, 2_u64),
- (custom_a_wrapper_source.as_str(), Some("utility"), 3_u64),
- (custom_b_wrapper_source.as_str(), Some("utility"), 4_u64),
- (retained_wrapper_source.as_str(), Some("utility"), 5_u64),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id_base + offset,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id_base + offset)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
- }
-
- ctx.process_async(json!({
- "id": 36156,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": "customBindingA" }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, 36156)["result"], json!({}));
-
- for (id, target_id) in [
- (36157_u64, first.target_id.as_str()),
- (36158_u64, second.target_id.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.closeTarget",
- "params": { "targetId": target_id }
- }))
- .await;
- ctx.expect_result(id, json!({ "success": true }), None);
- ctx.take_all();
- }
-
- let first_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 36159,
- 36160,
- )
- .await;
- let second_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &second.browser_context_id,
- 36161,
- 36162,
- )
- .await;
-
- for (id, session_id, html) in [
- (
- 36163_u64,
- first_replacement.session_id.as_str(),
- "<body><div id='page'>thin-first-name-replacement</div></body>",
- ),
- (
- 36164_u64,
- second_replacement.session_id.as_str(),
- "<body><div id='page'>thin-second-name-replacement</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 36165_u64,
- first_replacement.target_id.as_str(),
- first_replacement.session_id.as_str(),
- ),
- (
- 36166_u64,
- second_replacement.target_id.as_str(),
- second_replacement.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36167,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(36167, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(attached_events.len(), 2);
- let first_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(first_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin name first replacement re-auto-attached session")
- .to_owned();
- let second_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(second_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin name second replacement re-auto-attached session")
- .to_owned();
-
- for (id, session_id, source, expected_type) in [
- (
- 36168_u64,
- first_reauto_session.as_str(),
- custom_a_wrapper_source.as_str(),
- "undefined",
- ),
- (
- 36169_u64,
- first_reauto_session.as_str(),
- custom_b_wrapper_source.as_str(),
- "function",
- ),
- (
- 36170_u64,
- first_reauto_session.as_str(),
- retained_wrapper_source.as_str(),
- "function",
- ),
- (
- 36171_u64,
- second_reauto_session.as_str(),
- custom_a_wrapper_source.as_str(),
- "function",
- ),
- (
- 36172_u64,
- second_reauto_session.as_str(),
- custom_b_wrapper_source.as_str(),
- "function",
- ),
- (
- 36173_u64,
- second_reauto_session.as_str(),
- retained_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, id);
- assert_eq!(installed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36174_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 36175_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin name replay utility context id");
- ctx.take_all();
- }
-
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36176,
- 36177,
- 36178,
- 36179,
- "customBindingB",
- &custom_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36180,
- 36181,
- 36182,
- 36183,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36184,
- 36185,
- 36186,
- 36187,
- "customBindingA",
- &custom_a_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36188,
- 36189,
- 36190,
- 36191,
- "customBindingB",
- &custom_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36192,
- 36193,
- 36194,
- 36195,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36196_u64,
- first_reauto_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36197_u64,
- first_reauto_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36198_u64,
- second_reauto_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\",\"function\"]"),
- ),
- (
- 36199_u64,
- second_reauto_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.__pw_keptBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36200,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_first_custom_b = customBindingB({ source: 'thin-first-custom-b', nested: { count: 20, values: ['first', 21, true] } }); 'scheduled-thin-first-custom-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_custom_b = take_response_by_id(&mut ctx, 36200);
- assert!(
- scheduled_first_custom_b["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin first custom b")
- .starts_with("scheduled-")
- );
- let first_custom_b_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("customBindingB")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin first custom b bindingCalled");
- let first_custom_b_payload: serde_json::Value = serde_json::from_str(
- first_custom_b_called["params"]["payload"]
- .as_str()
- .expect("thin first custom b payload string"),
- )
- .expect("thin first custom b payload json");
- let first_custom_b_seq = first_custom_b_payload["seq"]
- .as_i64()
- .expect("thin first custom b seq");
- assert_eq!(
- first_custom_b_payload["serializedArgs"],
- json!([{ "source": "thin-first-custom-b", "nested": { "count": 20, "values": ["first", 21, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36201,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_binding_b_deliver({{ name: 'customBindingB', seq: {first_custom_b_seq}, result: 'thin-first-custom-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36201)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36202,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_first_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36202)["result"]["result"]["value"],
- json!("thin-first-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 36203,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_second_custom_a_reject = customBindingA({ source: 'thin-second-custom-a-reject', nested: { count: 22, values: ['second', 23, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-second-custom-a-reject'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_second_custom_a = take_response_by_id(&mut ctx, 36203);
- assert!(
- scheduled_second_custom_a["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin second custom a reject")
- .starts_with("scheduled-")
- );
- let second_custom_a_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin second custom a bindingCalled");
- let second_custom_a_payload: serde_json::Value = serde_json::from_str(
- second_custom_a_called["params"]["payload"]
- .as_str()
- .expect("thin second custom a payload string"),
- )
- .expect("thin second custom a payload json");
- let second_custom_a_seq = second_custom_a_payload["seq"]
- .as_i64()
- .expect("thin second custom a seq");
- assert_eq!(
- second_custom_a_payload["serializedArgs"],
- json!([{ "source": "thin-second-custom-a-reject", "nested": { "count": 22, "values": ["second", 23, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36204,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {second_custom_a_seq}, error: 'thin-second-custom-a-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36204)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36205,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_second_custom_a_reject",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36205)["result"]["result"]["value"],
- json!("rejected:thin-second-custom-a-error")
- );
-
- for (id, session_id, target_id) in [
- (
- 36206_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- ),
- (
- 36207_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id,
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36208,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": first_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let first_reattached_session = take_response_by_id(&mut ctx, 36208)["result"]["sessionId"]
- .as_str()
- .expect("thin name first reattached session id")
- .to_owned();
- assert_ne!(first_reattached_session, first_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": first_reattached_session,
- "targetInfo": {
- "targetId": first_replacement.target_id,
- "browserContextId": first.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 36209,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let second_reattached_session = take_response_by_id(&mut ctx, 36209)["result"]["sessionId"]
- .as_str()
- .expect("thin name second reattached session id")
- .to_owned();
- assert_ne!(second_reattached_session, second_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": second_reattached_session,
- "targetInfo": {
- "targetId": second_replacement.target_id,
- "browserContextId": second.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36210_u64,
- first_reattached_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36211_u64,
- first_reattached_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36212_u64,
- second_reattached_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\",\"function\"]"),
- ),
- (
- 36213_u64,
- second_reattached_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.__pw_keptBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36214,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_reattached_first_custom_b = customBindingB({ source: 'thin-reattached-first-custom-b', nested: { count: 24, values: ['reattach', 25, true] } }); 'scheduled-thin-reattached-first-custom-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_first_custom_b = take_response_by_id(&mut ctx, 36214);
- assert!(
- scheduled_reattached_first_custom_b["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin reattached first custom b")
- .starts_with("scheduled-")
- );
- let reattached_first_custom_b_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reattached_session)
- && message["params"]["name"] == json!("customBindingB")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin reattached first custom b bindingCalled");
- let reattached_first_custom_b_payload: serde_json::Value = serde_json::from_str(
- reattached_first_custom_b_called["params"]["payload"]
- .as_str()
- .expect("thin reattached first custom b payload string"),
- )
- .expect("thin reattached first custom b payload json");
- let reattached_first_custom_b_seq = reattached_first_custom_b_payload["seq"]
- .as_i64()
- .expect("thin reattached first custom b seq");
- assert_eq!(reattached_first_custom_b_seq, 2);
- assert_eq!(
- reattached_first_custom_b_payload["serializedArgs"],
- json!([{ "source": "thin-reattached-first-custom-b", "nested": { "count": 24, "values": ["reattach", 25, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36215,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_binding_b_deliver({{ name: 'customBindingB', seq: {reattached_first_custom_b_seq}, result: 'thin-reattached-first-custom-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36215)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36216,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_reattached_first_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36216)["result"]["result"]["value"],
- json!("thin-reattached-first-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 36217,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_reattached_second_custom_a = customBindingA({ source: 'thin-reattached-second-custom-a', nested: { count: 26, values: ['reattach', 27, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-reattached-second-custom-a'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_second_custom_a = take_response_by_id(&mut ctx, 36217);
- assert!(
- scheduled_reattached_second_custom_a["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin reattached second custom a")
- .starts_with("scheduled-")
- );
- let reattached_second_custom_a_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reattached_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin reattached second custom a bindingCalled");
- let reattached_second_custom_a_payload: serde_json::Value = serde_json::from_str(
- reattached_second_custom_a_called["params"]["payload"]
- .as_str()
- .expect("thin reattached second custom a payload string"),
- )
- .expect("thin reattached second custom a payload json");
- let reattached_second_custom_a_seq = reattached_second_custom_a_payload["seq"]
- .as_i64()
- .expect("thin reattached second custom a seq");
- assert_eq!(reattached_second_custom_a_seq, 2);
- assert_eq!(
- reattached_second_custom_a_payload["serializedArgs"],
- json!([{ "source": "thin-reattached-second-custom-a", "nested": { "count": 26, "values": ["reattach", 27, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36218,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {reattached_second_custom_a_seq}, error: 'thin-reattached-second-custom-a-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36218)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36219,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_reattached_second_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36219)["result"]["result"]["value"],
- json!("rejected:thin-reattached-second-custom-a-error")
- );
- })
- .await;
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_replacement_targets_keep_thin_mixed_cleanup_isolated_per_browser_context_without_runtime_enable()
- {
- patchright_replacement_targets_large_stack(|| async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36220, 36221, 36222)
- .await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36223, 36224, 36225)
- .await;
-
- for (id, session_id, html) in [
- (
- 36226_u64,
- first.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-first-mixed</div></body>",
- ),
- (
- 36227_u64,
- second.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-second-mixed</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36228_u64,
- first.session_id.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 36229_u64,
- second.session_id.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin mixed initial utility context id");
- ctx.take_all();
- }
-
- let custom_wrapper_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
- let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptHandleBinding",
- "__lm_pw_kept_handle_binding_deliver",
- Some("__lm_pw_kept_handle_binding_take"),
- true,
- );
-
- for (session_id, utility_context_id, id_base) in [
- (first.session_id.as_str(), first_utility_context, 36230_u64),
- (
- second.session_id.as_str(),
- second_utility_context,
- 36246_u64,
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base,
- id_base + 1,
- id_base + 2,
- id_base + 3,
- "customBindingA",
- &custom_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 4,
- id_base + 5,
- id_base + 6,
- id_base + 7,
- "customHandleBindingA",
- &custom_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 8,
- id_base + 9,
- id_base + 10,
- id_base + 11,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 12,
- id_base + 13,
- id_base + 14,
- id_base + 15,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
- }
-
- for (session_id, id_base) in [
- (first.session_id.as_str(), 36262_u64),
- (second.session_id.as_str(), 36270_u64),
- ] {
- for (source, world_name, offset) in [
- (custom_wrapper_source.as_str(), None, 0_u64),
- (custom_handle_wrapper_source.as_str(), None, 1_u64),
- (retained_wrapper_source.as_str(), None, 2_u64),
- (retained_handle_wrapper_source.as_str(), None, 3_u64),
- (custom_wrapper_source.as_str(), Some("utility"), 4_u64),
- (
- custom_handle_wrapper_source.as_str(),
- Some("utility"),
- 5_u64,
- ),
- (retained_wrapper_source.as_str(), Some("utility"), 6_u64),
- (
- retained_handle_wrapper_source.as_str(),
- Some("utility"),
- 7_u64,
- ),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id_base + offset,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id_base + offset)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
- }
-
- for (id, name) in [
- (36278_u64, "customBindingA"),
- (36279_u64, "customHandleBindingA"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": name }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- for (id, target_id) in [
- (36280_u64, first.target_id.as_str()),
- (36281_u64, second.target_id.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.closeTarget",
- "params": { "targetId": target_id }
- }))
- .await;
- ctx.expect_result(id, json!({ "success": true }), None);
- ctx.take_all();
- }
-
- let first_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 36282,
- 36283,
- )
- .await;
- let second_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &second.browser_context_id,
- 36284,
- 36285,
- )
- .await;
-
- for (id, session_id, html) in [
- (
- 36286_u64,
- first_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-first-mixed-replacement</div></body>",
- ),
- (
- 36287_u64,
- second_replacement.session_id.as_str(),
- "<body><div id='utility-handle-a'>thin-second-mixed-replacement</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 36288_u64,
- first_replacement.target_id.as_str(),
- first_replacement.session_id.as_str(),
- ),
- (
- 36289_u64,
- second_replacement.target_id.as_str(),
- second_replacement.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36290,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(36290, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(attached_events.len(), 2);
- let first_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(first_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin mixed first replacement re-auto-attached session")
- .to_owned();
- let second_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(second_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin mixed second replacement re-auto-attached session")
- .to_owned();
-
- for (id, session_id, source, expected_type) in [
- (
- 36291_u64,
- first_reauto_session.as_str(),
- custom_wrapper_source.as_str(),
- "undefined",
- ),
- (
- 36292_u64,
- first_reauto_session.as_str(),
- custom_handle_wrapper_source.as_str(),
- "undefined",
- ),
- (
- 36293_u64,
- first_reauto_session.as_str(),
- retained_wrapper_source.as_str(),
- "function",
- ),
- (
- 36294_u64,
- first_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 36295_u64,
- second_reauto_session.as_str(),
- custom_wrapper_source.as_str(),
- "function",
- ),
- (
- 36296_u64,
- second_reauto_session.as_str(),
- custom_handle_wrapper_source.as_str(),
- "function",
- ),
- (
- 36297_u64,
- second_reauto_session.as_str(),
- retained_wrapper_source.as_str(),
- "function",
- ),
- (
- 36298_u64,
- second_reauto_session.as_str(),
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let installed = take_response_by_id(&mut ctx, id);
- assert_eq!(installed["result"]["result"]["value"], json!(expected_type));
- }
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36299_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 36300_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin mixed replay utility context id");
- ctx.take_all();
- }
-
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36301,
- 36302,
- 36303,
- 36304,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36305,
- 36306,
- 36307,
- 36308,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36309,
- 36310,
- 36311,
- 36312,
- "customBindingA",
- &custom_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36313,
- 36314,
- 36315,
- 36316,
- "customHandleBindingA",
- &custom_handle_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36317,
- 36318,
- 36319,
- 36320,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36321,
- 36322,
- 36323,
- 36324,
- "__pw_keptHandleBinding",
- &retained_handle_wrapper_source,
- )
- .await;
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36325_u64,
- first_reauto_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36326_u64,
- first_reauto_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36327_u64,
- second_reauto_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- (
- 36328_u64,
- second_reauto_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36329,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_second_custom = customBindingA({ source: 'thin-mixed-second-custom', nested: { count: 28, values: ['mixed', 29, true] } }); 'scheduled-thin-mixed-second-custom'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_second_custom = take_response_by_id(&mut ctx, 36329);
- assert!(
- scheduled_second_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed second custom")
- .starts_with("scheduled-")
- );
- let second_custom_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin mixed second custom bindingCalled");
- let second_custom_payload: serde_json::Value = serde_json::from_str(
- second_custom_called["params"]["payload"]
- .as_str()
- .expect("thin mixed second custom payload string"),
- )
- .expect("thin mixed second custom payload json");
- let second_custom_seq = second_custom_payload["seq"]
- .as_i64()
- .expect("thin mixed second custom seq");
- assert_eq!(
- second_custom_payload["serializedArgs"],
- json!([{ "source": "thin-mixed-second-custom", "nested": { "count": 28, "values": ["mixed", 29, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36330,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {second_custom_seq}, result: 'thin-mixed-second-custom-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36330)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36331,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_second_custom",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36331)["result"]["result"]["value"],
- json!("thin-mixed-second-custom-ok")
- );
-
- ctx.process_async(json!({
- "id": 36332,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_second_custom_handle = customHandleBindingA(document.getElementById('utility-handle-a')); 'scheduled-thin-mixed-second-custom-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_second_handle = take_response_by_id(&mut ctx, 36332);
- assert!(
- scheduled_second_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed second handle")
- .starts_with("scheduled-")
- );
- let second_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customHandleBindingA")
- && message["params"]["executionContextId"] == json!(second_replay_utility_context)
- })
- .cloned()
- .expect("thin mixed second handle bindingCalled");
- let second_handle_payload: serde_json::Value = serde_json::from_str(
- second_handle_called["params"]["payload"]
- .as_str()
- .expect("thin mixed second handle payload string"),
- )
- .expect("thin mixed second handle payload json");
- let second_handle_seq = second_handle_payload["seq"]
- .as_i64()
- .expect("thin mixed second handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36333,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {second_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {second_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36333)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-second-mixed-replacement\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36334,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_a_deliver({{ name: 'customHandleBindingA', seq: {second_handle_seq}, result: 'thin-mixed-second-custom-handle-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36334)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36335,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_second_custom_handle",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36335)["result"]["result"]["value"],
- json!("thin-mixed-second-custom-handle-ok")
- );
-
- ctx.process_async(json!({
- "id": 36336,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_first_pw = __pw_keptBinding({ source: 'thin-mixed-first-pw', nested: { count: 30, values: ['mixed', 31, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-mixed-first-pw'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_pw = take_response_by_id(&mut ctx, 36336);
- assert!(
- scheduled_first_pw["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed first pw")
- .starts_with("scheduled-")
- );
- let first_pw_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptBinding")
- })
- .cloned()
- .expect("thin mixed first pw bindingCalled");
- let first_pw_payload: serde_json::Value = serde_json::from_str(
- first_pw_called["params"]["payload"]
- .as_str()
- .expect("thin mixed first pw payload string"),
- )
- .expect("thin mixed first pw payload json");
- let first_pw_seq = first_pw_payload["seq"]
- .as_i64()
- .expect("thin mixed first pw seq");
- assert_eq!(
- first_pw_payload["serializedArgs"],
- json!([{ "source": "thin-mixed-first-pw", "nested": { "count": 30, "values": ["mixed", 31, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36337,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_pw_kept_binding_deliver({{ name: '__pw_keptBinding', seq: {first_pw_seq}, error: 'thin-mixed-first-pw-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36337)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36338,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_first_pw",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36338)["result"]["result"]["value"],
- json!("rejected:thin-mixed-first-pw-error")
- );
-
- ctx.process_async(json!({
- "id": 36339,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_first_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-a')); 'scheduled-thin-mixed-first-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_pw_handle = take_response_by_id(&mut ctx, 36339);
- assert!(
- scheduled_first_pw_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed first pw handle")
- .starts_with("scheduled-")
- );
- let first_pw_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin mixed first pw handle bindingCalled");
- let first_pw_handle_payload: serde_json::Value = serde_json::from_str(
- first_pw_handle_called["params"]["payload"]
- .as_str()
- .expect("thin mixed first pw handle payload string"),
- )
- .expect("thin mixed first pw handle payload json");
- let first_pw_handle_seq = first_pw_handle_payload["seq"]
- .as_i64()
- .expect("thin mixed first pw handle seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36340,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_pw_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {first_pw_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36340)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-first-mixed-replacement\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36341,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {first_pw_handle_seq}, result: 'thin-mixed-first-pw-handle-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36341)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36342,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_first_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36342)["result"]["result"]["value"],
- json!("thin-mixed-first-pw-handle-ok")
- );
-
- for (id, session_id, target_id) in [
- (
- 36343_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- ),
- (
- 36344_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id,
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36345,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": first_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let first_reattached_session = take_response_by_id(&mut ctx, 36345)["result"]["sessionId"]
- .as_str()
- .expect("thin mixed first reattached session id")
- .to_owned();
- assert_ne!(first_reattached_session, first_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": first_reattached_session,
- "targetInfo": {
- "targetId": first_replacement.target_id,
- "browserContextId": first.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 36346,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let second_reattached_session = take_response_by_id(&mut ctx, 36346)["result"]["sessionId"]
- .as_str()
- .expect("thin mixed second reattached session id")
- .to_owned();
- assert_ne!(second_reattached_session, second_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": second_reattached_session,
- "targetInfo": {
- "targetId": second_replacement.target_id,
- "browserContextId": second.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36347_u64,
- first_reattached_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36348_u64,
- first_reattached_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36349_u64,
- second_reattached_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- (
- 36350_u64,
- second_reattached_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customHandleBindingA, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36351,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_reattached_second_custom_handle = customHandleBindingA(document.getElementById('utility-handle-a')); 'scheduled-thin-mixed-reattached-second-custom-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_second_handle = take_response_by_id(&mut ctx, 36351);
- assert!(
- scheduled_reattached_second_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed reattached second handle")
- .starts_with("scheduled-")
- );
- let reattached_second_handle_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reattached_session)
- && message["params"]["name"] == json!("customHandleBindingA")
- && message["params"]["executionContextId"] == json!(second_replay_utility_context)
- })
- .cloned()
- .expect("thin mixed reattached second handle bindingCalled");
- let reattached_second_handle_payload: serde_json::Value = serde_json::from_str(
- reattached_second_handle_called["params"]["payload"]
- .as_str()
- .expect("thin mixed reattached second handle payload string"),
- )
- .expect("thin mixed reattached second handle payload json");
- let reattached_second_handle_seq = reattached_second_handle_payload["seq"]
- .as_i64()
- .expect("thin mixed reattached second handle seq");
- assert_eq!(reattached_second_handle_seq, 2);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36352,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {reattached_second_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_a_take({{ name: 'customHandleBindingA', seq: {reattached_second_handle_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36352)["result"]["result"]["value"],
- json!("[\"utility-handle-a\",\"thin-second-mixed-replacement\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36353,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_a_deliver({{ name: 'customHandleBindingA', seq: {reattached_second_handle_seq}, result: 'thin-mixed-reattached-second-custom-handle-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36353)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36354,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "contextId": second_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_reattached_second_custom_handle",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36354)["result"]["result"]["value"],
- json!("thin-mixed-reattached-second-custom-handle-ok")
- );
-
- ctx.process_async(json!({
- "id": 36355,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_reattached_first_pw = __pw_keptBinding({ source: 'thin-mixed-reattached-first-pw', nested: { count: 32, values: ['reattach', 33, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-mixed-reattached-first-pw'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_first_pw = take_response_by_id(&mut ctx, 36355);
- assert!(
- scheduled_reattached_first_pw["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed reattached first pw")
- .starts_with("scheduled-")
- );
- let reattached_first_pw_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reattached_session)
- && message["params"]["name"] == json!("__pw_keptBinding")
- })
- .cloned()
- .expect("thin mixed reattached first pw bindingCalled");
- let reattached_first_pw_payload: serde_json::Value = serde_json::from_str(
- reattached_first_pw_called["params"]["payload"]
- .as_str()
- .expect("thin mixed reattached first pw payload string"),
- )
- .expect("thin mixed reattached first pw payload json");
- let reattached_first_pw_seq = reattached_first_pw_payload["seq"]
- .as_i64()
- .expect("thin mixed reattached first pw seq");
- assert_eq!(reattached_first_pw_seq, 2);
- assert_eq!(
- reattached_first_pw_payload["serializedArgs"],
- json!([{ "source": "thin-mixed-reattached-first-pw", "nested": { "count": 32, "values": ["reattach", 33, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36356,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "expression": format!("globalThis.__lm_pw_kept_binding_deliver({{ name: '__pw_keptBinding', seq: {reattached_first_pw_seq}, error: 'thin-mixed-reattached-first-pw-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36356)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36357,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_reattached_first_pw",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36357)["result"]["result"]["value"],
- json!("rejected:thin-mixed-reattached-first-pw-error")
- );
- })
- .await;
-}
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_auto_attach_sweep_replacement_targets_keep_thin_mixed_name_cleanup_isolated_per_browser_context_without_runtime_enable()
- {
- patchright_replacement_targets_large_stack(|| async {
- let mut ctx = TestContext::new();
- let first =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36358, 36359, 36360)
- .await;
- let second =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 36361, 36362, 36363)
- .await;
-
- for (id, session_id, html) in [
- (
- 36364_u64,
- first.session_id.as_str(),
- "<body><div id='utility-handle-b'>thin-first-mixed-name</div></body>",
- ),
- (
- 36365_u64,
- second.session_id.as_str(),
- "<body><div id='utility-handle-b'>thin-second-mixed-name</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- let mut first_utility_context = 0_i64;
- let mut second_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36366_u64,
- first.session_id.as_str(),
- first.target_id.as_str(),
- &mut first_utility_context,
- ),
- (
- 36367_u64,
- second.session_id.as_str(),
- second.target_id.as_str(),
- &mut second_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin mixed-name initial utility context id");
- ctx.take_all();
- }
-
- let custom_a_wrapper_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_b_wrapper_source = patchright_page_binding_wrapper_source(
- "customBindingB",
- "__lm_custom_binding_b_deliver",
- None,
- false,
- );
- let custom_handle_a_wrapper_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let custom_handle_b_wrapper_source = patchright_page_binding_wrapper_source(
- "customHandleBindingB",
- "__lm_custom_handle_binding_b_deliver",
- Some("__lm_custom_handle_binding_b_take"),
- true,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
-
- for (session_id, utility_context_id, id_base) in [
- (first.session_id.as_str(), first_utility_context, 36368_u64),
- (
- second.session_id.as_str(),
- second_utility_context,
- 36388_u64,
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base,
- id_base + 1,
- id_base + 2,
- id_base + 3,
- "customBindingA",
- &custom_a_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 4,
- id_base + 5,
- id_base + 6,
- id_base + 7,
- "customBindingB",
- &custom_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 8,
- id_base + 9,
- id_base + 10,
- id_base + 11,
- "customHandleBindingA",
- &custom_handle_a_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 12,
- id_base + 13,
- id_base + 14,
- id_base + 15,
- "customHandleBindingB",
- &custom_handle_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- session_id,
- utility_context_id,
- id_base + 16,
- id_base + 17,
- id_base + 18,
- id_base + 19,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- }
-
- for (session_id, id_base) in [
- (first.session_id.as_str(), 36408_u64),
- (second.session_id.as_str(), 36418_u64),
- ] {
- for (source, world_name, offset) in [
- (custom_a_wrapper_source.as_str(), None, 0_u64),
- (custom_b_wrapper_source.as_str(), None, 1_u64),
- (custom_handle_a_wrapper_source.as_str(), None, 2_u64),
- (custom_handle_b_wrapper_source.as_str(), None, 3_u64),
- (retained_wrapper_source.as_str(), None, 4_u64),
- (custom_a_wrapper_source.as_str(), Some("utility"), 5_u64),
- (custom_b_wrapper_source.as_str(), Some("utility"), 6_u64),
- (
- custom_handle_a_wrapper_source.as_str(),
- Some("utility"),
- 7_u64,
- ),
- (
- custom_handle_b_wrapper_source.as_str(),
- Some("utility"),
- 8_u64,
- ),
- (retained_wrapper_source.as_str(), Some("utility"), 9_u64),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id_base + offset,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id_base + offset)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
- }
-
- for (id, name) in [
- (36428_u64, "customBindingA"),
- (36429_u64, "customHandleBindingA"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": name }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- for (id, target_id) in [
- (36430_u64, first.target_id.as_str()),
- (36431_u64, second.target_id.as_str()),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.closeTarget",
- "params": { "targetId": target_id }
- }))
- .await;
- ctx.expect_result(id, json!({ "success": true }), None);
- ctx.take_all();
- }
-
- let first_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 36432,
- 36433,
- )
- .await;
- let second_replacement = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &second.browser_context_id,
- 36434,
- 36435,
- )
- .await;
-
- for (id, session_id, html) in [
- (
- 36436_u64,
- first_replacement.session_id.as_str(),
- "<body><div id='utility-handle-b'>thin-first-mixed-name-replacement</div></body>",
- ),
- (
- 36437_u64,
- second_replacement.session_id.as_str(),
- "<body><div id='utility-handle-b'>thin-second-mixed-name-replacement</div></body>",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.navigate",
- "sessionId": session_id,
- "params": { "url": format!("data:text/html,{html}") }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, id);
- assert_eq!(navigation["sessionId"], json!(session_id));
- ctx.take_all();
- }
-
- for (id, target_id, session_id) in [
- (
- 36438_u64,
- first_replacement.target_id.as_str(),
- first_replacement.session_id.as_str(),
- ),
- (
- 36439_u64,
- second_replacement.target_id.as_str(),
- second_replacement.session_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36440,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(36440, json!({}), None);
- let events = ctx.take_all();
- let attached_events = events
- .iter()
- .filter(|event| event["method"] == json!("Target.attachedToTarget"))
- .cloned()
- .collect::<Vec<_>>();
- assert_eq!(attached_events.len(), 2);
- let first_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(first_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin mixed-name first replacement re-auto-attached session")
- .to_owned();
- let second_reauto_session = attached_events
- .iter()
- .find(|event| {
- event["params"]["targetInfo"]["targetId"] == json!(second_replacement.target_id)
- })
- .and_then(|event| event["params"]["sessionId"].as_str())
- .expect("thin mixed-name second replacement re-auto-attached session")
- .to_owned();
-
- let mut first_replay_utility_context = 0_i64;
- let mut second_replay_utility_context = 0_i64;
- for (id, session_id, target_id, out_context) in [
- (
- 36441_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- &mut first_replay_utility_context,
- ),
- (
- 36442_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- &mut second_replay_utility_context,
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Page.createIsolatedWorld",
- "sessionId": session_id,
- "params": {
- "frameId": target_id,
- "worldName": "utility"
- }
- }))
- .await;
- *out_context = take_response_by_id(&mut ctx, id)["result"]["executionContextId"]
- .as_i64()
- .expect("thin mixed-name replay utility context id");
- ctx.take_all();
- }
-
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36443,
- 36444,
- 36445,
- 36446,
- "customBindingB",
- &custom_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36447,
- 36448,
- 36449,
- 36450,
- "customHandleBindingB",
- &custom_handle_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- first_reauto_session.as_str(),
- first_replay_utility_context,
- 36451,
- 36452,
- 36453,
- 36454,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36455,
- 36456,
- 36457,
- 36458,
- "customBindingA",
- &custom_a_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36459,
- 36460,
- 36461,
- 36462,
- "customBindingB",
- &custom_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36463,
- 36464,
- 36465,
- 36466,
- "customHandleBindingA",
- &custom_handle_a_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36467,
- 36468,
- 36469,
- 36470,
- "customHandleBindingB",
- &custom_handle_b_wrapper_source,
- )
- .await;
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- second_reauto_session.as_str(),
- second_replay_utility_context,
- 36471,
- 36472,
- 36473,
- 36474,
- "__pw_keptBinding",
- &retained_wrapper_source,
- )
- .await;
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36475_u64,
- first_reauto_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36476_u64,
- first_reauto_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36477_u64,
- second_reauto_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\",\"function\",\"function\",\"function\"]"),
- ),
- (
- 36478_u64,
- second_reauto_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36479,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_name_first_custom_handle_b = customHandleBindingB(document.getElementById('utility-handle-b')); 'scheduled-thin-mixed-name-first-custom-handle-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_first_handle_b = take_response_by_id(&mut ctx, 36479);
- assert!(
- scheduled_first_handle_b["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed-name first custom handle b")
- .starts_with("scheduled-")
- );
- let first_handle_b_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reauto_session)
- && message["params"]["name"] == json!("customHandleBindingB")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin mixed-name first custom handle b bindingCalled");
- let first_handle_b_payload: serde_json::Value = serde_json::from_str(
- first_handle_b_called["params"]["payload"]
- .as_str()
- .expect("thin mixed-name first custom handle b payload string"),
- )
- .expect("thin mixed-name first custom handle b payload json");
- let first_handle_b_seq = first_handle_b_payload["seq"]
- .as_i64()
- .expect("thin mixed-name first custom handle b seq");
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36480,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_b_take({{ name: 'customHandleBindingB', seq: {first_handle_b_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_b_take({{ name: 'customHandleBindingB', seq: {first_handle_b_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36480)["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"thin-first-mixed-name-replacement\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36481,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_b_deliver({{ name: 'customHandleBindingB', seq: {first_handle_b_seq}, result: 'thin-mixed-name-first-custom-handle-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36481)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36482,
- "method": "Runtime.evaluate",
- "sessionId": first_reauto_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_name_first_custom_handle_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36482)["result"]["result"]["value"],
- json!("thin-mixed-name-first-custom-handle-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 36483,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_name_second_custom_a = customBindingA({ source: 'thin-mixed-name-second-custom-a', nested: { count: 34, values: ['mixed-name', 35, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-mixed-name-second-custom-a'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_second_custom_a = take_response_by_id(&mut ctx, 36483);
- assert!(
- scheduled_second_custom_a["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed-name second custom a")
- .starts_with("scheduled-")
- );
- let second_custom_a_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reauto_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin mixed-name second custom a bindingCalled");
- let second_custom_a_payload: serde_json::Value = serde_json::from_str(
- second_custom_a_called["params"]["payload"]
- .as_str()
- .expect("thin mixed-name second custom a payload string"),
- )
- .expect("thin mixed-name second custom a payload json");
- let second_custom_a_seq = second_custom_a_payload["seq"]
- .as_i64()
- .expect("thin mixed-name second custom a seq");
- assert_eq!(
- second_custom_a_payload["serializedArgs"],
- json!([{ "source": "thin-mixed-name-second-custom-a", "nested": { "count": 34, "values": ["mixed-name", 35, false] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36484,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {second_custom_a_seq}, error: 'thin-mixed-name-second-custom-a-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36484)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36485,
- "method": "Runtime.evaluate",
- "sessionId": second_reauto_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_name_second_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36485)["result"]["result"]["value"],
- json!("rejected:thin-mixed-name-second-custom-a-error")
- );
-
- for (id, session_id, target_id) in [
- (
- 36486_u64,
- first_reauto_session.as_str(),
- first_replacement.target_id.as_str(),
- ),
- (
- 36487_u64,
- second_reauto_session.as_str(),
- second_replacement.target_id.as_str(),
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": target_id,
- "sessionId": session_id,
- }
- }))
- .await;
- ctx.expect_result(id, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": target_id,
- "sessionId": session_id,
- })),
- );
- }
-
- ctx.process_async(json!({
- "id": 36488,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": first_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let first_reattached_session = take_response_by_id(&mut ctx, 36488)["result"]["sessionId"]
- .as_str()
- .expect("thin mixed-name first reattached session id")
- .to_owned();
- assert_ne!(first_reattached_session, first_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": first_reattached_session,
- "targetInfo": {
- "targetId": first_replacement.target_id,
- "browserContextId": first.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 36489,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second_replacement.target_id,
- "flatten": true
- }
- }))
- .await;
- let second_reattached_session = take_response_by_id(&mut ctx, 36489)["result"]["sessionId"]
- .as_str()
- .expect("thin mixed-name second reattached session id")
- .to_owned();
- assert_ne!(second_reattached_session, second_reauto_session);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": second_reattached_session,
- "targetInfo": {
- "targetId": second_replacement.target_id,
- "browserContextId": second.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, session_id, context_id, expected_state) in [
- (
- 36490_u64,
- first_reattached_session.as_str(),
- None::<i64>,
- json!("[\"undefined\",\"function\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36491_u64,
- first_reattached_session.as_str(),
- Some(first_replay_utility_context),
- json!("[\"undefined\",\"function\",\"undefined\",\"function\",\"function\"]"),
- ),
- (
- 36492_u64,
- second_reattached_session.as_str(),
- None::<i64>,
- json!("[\"function\",\"function\",\"function\",\"function\",\"function\"]"),
- ),
- (
- 36493_u64,
- second_reattached_session.as_str(),
- Some(second_replay_utility_context),
- json!("[\"function\",\"function\",\"function\",\"function\",\"function\"]"),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": session_id,
- "params": params
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
- expected_state
- );
- }
-
- ctx.process_async(json!({
- "id": 36494,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_name_reattached_first_custom_handle_b = customHandleBindingB(document.getElementById('utility-handle-b')); 'scheduled-thin-mixed-name-reattached-first-custom-handle-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_first_handle_b = take_response_by_id(&mut ctx, 36494);
- assert!(
- scheduled_reattached_first_handle_b["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed-name reattached first custom handle b")
- .starts_with("scheduled-")
- );
- let reattached_first_handle_b_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(first_reattached_session)
- && message["params"]["name"] == json!("customHandleBindingB")
- && message["params"]["executionContextId"] == json!(first_replay_utility_context)
- })
- .cloned()
- .expect("thin mixed-name reattached first custom handle b bindingCalled");
- let reattached_first_handle_b_payload: serde_json::Value = serde_json::from_str(
- reattached_first_handle_b_called["params"]["payload"]
- .as_str()
- .expect("thin mixed-name reattached first custom handle b payload string"),
- )
- .expect("thin mixed-name reattached first custom handle b payload json");
- let reattached_first_handle_b_seq = reattached_first_handle_b_payload["seq"]
- .as_i64()
- .expect("thin mixed-name reattached first custom handle b seq");
- assert_eq!(reattached_first_handle_b_seq, 2);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36495,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("(() => {{ const handle = globalThis.__lm_custom_handle_binding_b_take({{ name: 'customHandleBindingB', seq: {reattached_first_handle_b_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_custom_handle_binding_b_take({{ name: 'customHandleBindingB', seq: {reattached_first_handle_b_seq} }})]); }})()")
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36495)["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"thin-first-mixed-name-replacement\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 36496,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": format!("globalThis.__lm_custom_handle_binding_b_deliver({{ name: 'customHandleBindingB', seq: {reattached_first_handle_b_seq}, result: 'thin-mixed-name-reattached-first-custom-handle-b-ok' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36496)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36497,
- "method": "Runtime.evaluate",
- "sessionId": first_reattached_session,
- "params": {
- "contextId": first_replay_utility_context,
- "expression": "globalThis.__lm_thin_mixed_name_reattached_first_custom_handle_b",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36497)["result"]["result"]["value"],
- json!("thin-mixed-name-reattached-first-custom-handle-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 36498,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_name_reattached_second_custom_a = customBindingA({ source: 'thin-mixed-name-reattached-second-custom-a', nested: { count: 36, values: ['reattach', 37, true] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-thin-mixed-name-reattached-second-custom-a'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_reattached_second_custom_a = take_response_by_id(&mut ctx, 36498);
- assert!(
- scheduled_reattached_second_custom_a["result"]["result"]["value"]
- .as_str()
- .expect("scheduled thin mixed-name reattached second custom a")
- .starts_with("scheduled-")
- );
- let reattached_second_custom_a_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second_reattached_session)
- && message["params"]["name"] == json!("customBindingA")
- })
- .cloned()
- .expect("thin mixed-name reattached second custom a bindingCalled");
- let reattached_second_custom_a_payload: serde_json::Value = serde_json::from_str(
- reattached_second_custom_a_called["params"]["payload"]
- .as_str()
- .expect("thin mixed-name reattached second custom a payload string"),
- )
- .expect("thin mixed-name reattached second custom a payload json");
- let reattached_second_custom_a_seq = reattached_second_custom_a_payload["seq"]
- .as_i64()
- .expect("thin mixed-name reattached second custom a seq");
- assert_eq!(reattached_second_custom_a_seq, 2);
- assert_eq!(
- reattached_second_custom_a_payload["serializedArgs"],
- json!([{ "source": "thin-mixed-name-reattached-second-custom-a", "nested": { "count": 36, "values": ["reattach", 37, true] } }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 36499,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": format!("globalThis.__lm_custom_binding_a_deliver({{ name: 'customBindingA', seq: {reattached_second_custom_a_seq}, error: 'thin-mixed-name-reattached-second-custom-a-error' }}); 'delivered'"),
- "awaitPromise": true
- }
- })).await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36499)["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 36500,
- "method": "Runtime.evaluate",
- "sessionId": second_reattached_session,
- "params": {
- "expression": "globalThis.__lm_thin_mixed_name_reattached_second_custom_a",
- "awaitPromise": true
- }
- }))
- .await;
- assert_eq!(
- take_response_by_id(&mut ctx, 36500)["result"]["result"]["value"],
- json!("rejected:thin-mixed-name-reattached-second-custom-a-error")
- );
- })
- .await;
-}
#[tokio::test(flavor = "multi_thread")]
async fn patchright_over_cdp_auto_attach_sweep_replacement_targets_keep_thin_mixed_name_handle_cleanup_isolated_per_browser_context_without_runtime_enable()
{
diff --git a/moli-protocol/src/domains/target/tests/tests_patchright_runtimeless.rs b/moli-protocol/src/domains/target/tests/tests_patchright_runtimeless.rs
index b0f9f34fd..1f6f39e98 100644
--- a/moli-protocol/src/domains/target/tests/tests_patchright_runtimeless.rs
+++ b/moli-protocol/src/domains/target/tests/tests_patchright_runtimeless.rs
@@ -220,8 +220,7 @@ async fn patchright_over_cdp_switching_back_to_first_context_keeps_older_page_ru
1
);
assert!(
- first_context
- .devtools_session_state
+ first_context.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| {
@@ -442,3035 +441,614 @@ async fn patchright_over_cdp_reactivated_first_context_cleanup_updates_current_a
}
#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_utility_world_init_persists_across_detach_and_reattach_without_runtime_enable()
+async fn patchright_over_cdp_crpage_cleanup_state_persists_when_auto_attach_reattaches_existing_target_with_mixed_binding_kinds_without_runtime_enable()
{
- let mut ctx = TestContext::new();
- let attached =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2240, 2241, 2242).await;
+ run_patchright_runtimeless_large_stack(
+ "patchright-runtimeless-auto-reattach-existing-target",
+ || async {
+ let mut ctx = TestContext::new();
+ let attached = create_attached_page_session_without_runtime_enable_async(
+ &mut ctx, 35194, 35195, 35196,
+ )
+ .await;
- ctx.process_async(json!({
- "id": 2243,
- "method": "Page.addScriptToEvaluateOnNewDocument",
+ ctx.process_async(json!({
+ "id": 35197,
+ "method": "Page.navigate",
"sessionId": attached.session_id,
"params": {
- "source": "globalThis.__lm_detach_reattach_preload = 'ready';",
- "worldName": "utility"
+ "url": "data:text/html,<body><div id='main-handle-b'>main-handle-b</div><div id='utility-handle-b'>utility-handle-b</div></body>"
}
- }))
- .await;
- let preload = take_response_by_id(&mut ctx, 2243);
- assert_eq!(preload["sessionId"], json!(attached.session_id));
- assert!(preload["result"]["identifier"].is_string());
+ })).await;
+ let navigation = take_response_by_id(&mut ctx, 35197);
+ assert_eq!(navigation["sessionId"], json!(attached.session_id));
+ ctx.take_all();
- ctx.process_async(json!({
- "id": 2244,
- "method": "Runtime.addBinding",
- "sessionId": attached.session_id,
- "params": {
- "name": "detachReattachBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, 2244);
- assert_eq!(add_binding["result"], json!({}));
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.executionContextCreated")
- || message["method"] == json!("Runtime.executionContextsCleared")
- }),
- "Patchright-style setup should stay off Runtime.enable surfaces: {:?}",
- ctx.sent
- );
- ctx.sent.clear();
+ ctx.process_async(json!({
+ "id": 35198,
+ "method": "Page.createIsolatedWorld",
+ "sessionId": attached.session_id,
+ "params": {
+ "frameId": attached.target_id,
+ "worldName": "utility"
+ }
+ }))
+ .await;
+ let initial_utility_context =
+ take_response_by_id(&mut ctx, 35198)["result"]["executionContextId"]
+ .as_i64()
+ .expect("initial utility context id");
+ ctx.take_all();
- ctx.process_async(json!({
- "id": 2245,
- "method": "Page.navigate",
- "sessionId": attached.session_id,
- "params": {
- "url": "data:text/html,<body><div id=page>reattach-me</div></body>"
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, 2245);
- assert_eq!(navigation["sessionId"], json!(attached.session_id));
- assert!(
- ctx.sent.iter().all(|message| {
- message.get("error").is_none()
- && message["method"] != json!("Runtime.executionContextCreated")
- && message["method"] != json!("Runtime.executionContextsCleared")
- }),
- "unexpected protocol/runtime event during initial navigation: {:?}",
- ctx.sent
- );
- ctx.take_all();
+ let custom_wrapper_a_source = patchright_page_binding_wrapper_source(
+ "customBindingA",
+ "__lm_custom_binding_a_deliver",
+ None,
+ false,
+ );
+ let custom_wrapper_b_source = patchright_page_binding_wrapper_source(
+ "customBindingB",
+ "__lm_custom_binding_b_deliver",
+ None,
+ false,
+ );
+ let custom_handle_wrapper_a_source = patchright_page_binding_wrapper_source(
+ "customHandleBindingA",
+ "__lm_custom_handle_binding_a_deliver",
+ Some("__lm_custom_handle_binding_a_take"),
+ true,
+ );
+ let custom_handle_wrapper_b_source = patchright_page_binding_wrapper_source(
+ "customHandleBindingB",
+ "__lm_custom_handle_binding_b_deliver",
+ Some("__lm_custom_handle_binding_b_take"),
+ true,
+ );
+ let retained_wrapper_source = patchright_page_binding_wrapper_source(
+ "__pw_keptBinding",
+ "__lm_pw_kept_binding_deliver",
+ None,
+ false,
+ );
+ let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
+ "__pw_keptHandleBinding",
+ "__lm_pw_kept_handle_binding_deliver",
+ Some("__lm_pw_kept_handle_binding_take"),
+ true,
+ );
- ctx.process_async(json!({
- "id": 2246,
- "method": "Page.createIsolatedWorld",
- "sessionId": attached.session_id,
- "params": {
- "frameId": attached.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let initial_utility_context =
- take_response_by_id(&mut ctx, 2246)["result"]["executionContextId"]
- .as_i64()
- .expect("initial utility context id");
- ctx.take_all();
+ for (id, binding_name, source) in [
+ (
+ 35199_u64,
+ "customBindingA",
+ custom_wrapper_a_source.as_str(),
+ ),
+ (
+ 35203_u64,
+ "customBindingB",
+ custom_wrapper_b_source.as_str(),
+ ),
+ (
+ 35207_u64,
+ "customHandleBindingA",
+ custom_handle_wrapper_a_source.as_str(),
+ ),
+ (
+ 35211_u64,
+ "customHandleBindingB",
+ custom_handle_wrapper_b_source.as_str(),
+ ),
+ (
+ 35215_u64,
+ "__pw_keptBinding",
+ retained_wrapper_source.as_str(),
+ ),
+ (
+ 35219_u64,
+ "__pw_keptHandleBinding",
+ retained_handle_wrapper_source.as_str(),
+ ),
+ ] {
+ install_patchright_crpage_binding_in_existing_worlds_async(
+ &mut ctx,
+ &attached.session_id,
+ initial_utility_context,
+ id,
+ id + 1,
+ id + 2,
+ id + 3,
+ binding_name,
+ source,
+ )
+ .await;
+ }
- ctx.process_async(json!({
- "id": 2247,
+ for (id, binding_name) in [
+ (35223_u64, "customBindingA"),
+ (35224_u64, "customHandleBindingA"),
+ ] {
+ ctx.process_async(json!({
+ "id": id,
+ "method": "Runtime.removeBinding",
+ "sessionId": attached.session_id,
+ "params": { "name": binding_name }
+ }))
+ .await;
+ assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
+ }
+
+ ctx.process_async(json!({
+ "id": 35225,
+ "method": "Target.detachFromTarget",
+ "params": {
+ "targetId": attached.target_id,
+ "sessionId": attached.session_id
+ }
+ }))
+ .await;
+ ctx.expect_result(35225, json!({}), None);
+ ctx.expect_event(
+ "Target.detachedFromTarget",
+ Some(&json!({
+ "targetId": attached.target_id,
+ "sessionId": attached.session_id,
+ })),
+ );
+ assert_eq!(
+ ctx.conn
+ .browser_contexts()
+ .find(|bc| bc.id == attached.browser_context_id)
+ .and_then(|bc| bc.active_session_id()),
+ None
+ );
+
+ ctx.process_async(json!({
+ "id": 35226,
+ "method": "Target.setAutoAttach",
+ "params": {
+ "autoAttach": true,
+ "waitForDebuggerOnStart": false
+ }
+ }))
+ .await;
+ ctx.expect_result(35226, json!({}), None);
+ let auto_attach_event = ctx
+ .take_first_matching("reattached target attachedToTarget", |message| {
+ message["method"] == json!("Target.attachedToTarget")
+ });
+ assert_eq!(
+ auto_attach_event["params"]["targetInfo"]["targetId"],
+ json!(attached.target_id)
+ );
+ let auto_attached_session_id = auto_attach_event["params"]["sessionId"]
+ .as_str()
+ .expect("auto-attached session id")
+ .to_owned();
+ assert_ne!(auto_attached_session_id, attached.session_id);
+ ctx.take_all();
+
+ ctx.process_async(json!({
+ "id": 35227,
"method": "Runtime.evaluate",
- "sessionId": attached.session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": initial_utility_context,
- "expression": "detachReattachBinding('before-detach'); JSON.stringify([typeof globalThis.detachReattachBinding, globalThis.__lm_detach_reattach_preload])"
+ "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
}
})).await;
- let before_detach_eval = take_response_by_id(&mut ctx, 2247);
- assert_eq!(
- before_detach_eval["result"]["result"]["value"],
- json!("[\"function\",\"ready\"]")
- );
- let before_detach_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("detachReattachBinding")
- })
- .cloned()
- .expect("utility world should emit bindingCalled before detach");
- assert_eq!(
- before_detach_binding_called["params"]["payload"],
- json!("before-detach")
- );
- assert_eq!(
- before_detach_binding_called["params"]["executionContextId"],
- json!(initial_utility_context)
- );
- ctx.sent.clear();
+ let main_state = take_response_by_id(&mut ctx, 35227);
+ assert_eq!(
+ main_state["result"]["result"]["value"],
+ json!(
+ "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
+ )
+ );
- ctx.process_async(json!({
- "id": 2248,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": attached.target_id,
- "sessionId": attached.session_id
- }
- }))
- .await;
- ctx.expect_result(2248, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": attached.target_id,
- "sessionId": attached.session_id,
- })),
- );
- assert_eq!(
- ctx.conn
- .browser_contexts()
- .find(|bc| bc.id == attached.browser_context_id)
- .and_then(|bc| bc.active_session_id()),
- None,
- "detach should clear the current target session id"
- );
-
- ctx.process_async(json!({
- "id": 2249,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": attached.target_id,
- "flatten": true
- }
- }))
- .await;
- let reattached_session_id = take_response_by_id(&mut ctx, 2249)["result"]["sessionId"]
- .as_str()
- .expect("reattached session id")
- .to_owned();
- assert_ne!(
- reattached_session_id, attached.session_id,
- "reattach after detach should allocate a fresh target session"
- );
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": reattached_session_id,
- "targetInfo": {
- "targetId": attached.target_id,
- "browserContextId": attached.browser_context_id,
- }
- })),
- );
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.executionContextCreated")
- || message["method"] == json!("Runtime.executionContextsCleared")
- }),
- "reattach without Runtime.enable should stay off Runtime surfaces: {:?}",
- ctx.sent
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 2250,
- "method": "Page.createIsolatedWorld",
- "sessionId": reattached_session_id,
- "params": {
- "frameId": attached.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let reattached_utility_context =
- take_response_by_id(&mut ctx, 2250)["result"]["executionContextId"]
- .as_i64()
- .expect("reattached utility context id");
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 2251,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": "detachReattachBinding('after-reattach'); JSON.stringify([typeof globalThis.detachReattachBinding, globalThis.__lm_detach_reattach_preload, document.querySelector('#page').textContent])"
- }
- })).await;
- let after_reattach_eval = take_response_by_id(&mut ctx, 2251);
- assert_eq!(
- after_reattach_eval["result"]["result"]["value"],
- json!("[\"function\",\"ready\",\"reattach-me\"]")
- );
- let after_reattach_binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("detachReattachBinding")
- })
- .cloned()
- .expect("utility world should emit bindingCalled after reattach");
- assert_eq!(
- after_reattach_binding_called["params"]["payload"],
- json!("after-reattach")
- );
- assert_eq!(
- after_reattach_binding_called["params"]["executionContextId"],
- json!(reattached_utility_context)
- );
-
- let active = ctx
- .conn
- .browser_context
- .as_ref()
- .expect("active browser context");
- assert_eq!(active.id, attached.browser_context_id);
- assert_eq!(active.active_target_id(), Some(attached.target_id.as_str()));
- assert_eq!(
- active.active_session_id(),
- Some(reattached_session_id.as_str())
- );
- assert_eq!(
- active
- .active_target
- .owner_state
- .document_start_scripts
- .len(),
- 1
- );
- assert!(
- active
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "detachReattachBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "utility binding definition should survive detach/reattach on the browser context"
- );
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_utility_world_init_persists_when_auto_attach_reattaches_existing_target_without_runtime_enable()
- {
- let mut ctx = TestContext::new();
- let attached =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 2252, 2253, 2254).await;
-
- ctx.process_async(json!({
- "id": 2255,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": attached.session_id,
- "params": {
- "source": "globalThis.__lm_auto_attach_rehydrate_preload = 'ready';",
- "worldName": "utility"
- }
- }))
- .await;
- let preload = take_response_by_id(&mut ctx, 2255);
- assert_eq!(preload["sessionId"], json!(attached.session_id));
- assert!(preload["result"]["identifier"].is_string());
-
- ctx.process_async(json!({
- "id": 2256,
- "method": "Runtime.addBinding",
- "sessionId": attached.session_id,
- "params": {
- "name": "autoAttachRehydrateBinding",
- "executionContextName": "utility"
- }
- }))
- .await;
- let add_binding = take_response_by_id(&mut ctx, 2256);
- assert_eq!(add_binding["result"], json!({}));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 2257,
- "method": "Page.navigate",
- "sessionId": attached.session_id,
- "params": {
- "url": "data:text/html,<body><div id=page>auto-attach-target</div></body>"
- }
- }))
- .await;
- let navigation = take_response_by_id(&mut ctx, 2257);
- assert_eq!(navigation["sessionId"], json!(attached.session_id));
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 2258,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": attached.target_id,
- "sessionId": attached.session_id
- }
- }))
- .await;
- ctx.expect_result(2258, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": attached.target_id,
- "sessionId": attached.session_id,
- })),
- );
- assert_eq!(
- ctx.conn
- .browser_contexts()
- .find(|bc| bc.id == attached.browser_context_id)
- .and_then(|bc| bc.active_session_id()),
- None,
- "detach should leave the target sessionless before auto-attach takes over"
- );
-
- ctx.process_async(json!({
- "id": 2259,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(2259, json!({}), None);
- let auto_attach_event = ctx
- .take_first_matching("reattached target attachedToTarget", |message| {
- message["method"] == json!("Target.attachedToTarget")
- });
- assert_eq!(
- auto_attach_event["params"]["targetInfo"]["targetId"],
- json!(attached.target_id)
- );
- assert_eq!(
- auto_attach_event["params"]["targetInfo"]["browserContextId"],
- json!(attached.browser_context_id)
- );
- let auto_attached_session_id = auto_attach_event["params"]["sessionId"]
- .as_str()
- .expect("auto-attached session id")
- .to_owned();
- assert_ne!(
- auto_attached_session_id, attached.session_id,
- "auto-attach should allocate a fresh session for an existing unattached target"
- );
- assert!(
- !ctx.sent.iter().any(|message| {
- message["method"] == json!("Runtime.executionContextCreated")
- || message["method"] == json!("Runtime.executionContextsCleared")
- }),
- "auto-attach rehydration should stay off Runtime.enable surfaces: {:?}",
- ctx.sent
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 2260,
- "method": "Page.createIsolatedWorld",
- "sessionId": auto_attached_session_id,
- "params": {
- "frameId": attached.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let utility_context = take_response_by_id(&mut ctx, 2260)["result"]["executionContextId"]
- .as_i64()
- .expect("utility context after auto-attach");
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 2261,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": utility_context,
- "expression": "autoAttachRehydrateBinding('after-auto-attach'); JSON.stringify([typeof globalThis.autoAttachRehydrateBinding, globalThis.__lm_auto_attach_rehydrate_preload, document.querySelector('#page').textContent])"
- }
- })).await;
- let evaluation = take_response_by_id(&mut ctx, 2261);
- assert_eq!(
- evaluation["result"]["result"]["value"],
- json!("[\"function\",\"ready\",\"auto-attach-target\"]")
- );
- let binding_called = ctx
- .sent
- .iter()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["params"]["name"] == json!("autoAttachRehydrateBinding")
- })
- .cloned()
- .expect("auto-attached utility world should emit bindingCalled");
- assert_eq!(
- binding_called["params"]["payload"],
- json!("after-auto-attach")
- );
- assert_eq!(
- binding_called["params"]["executionContextId"],
- json!(utility_context)
- );
-
- let active = ctx
- .conn
- .browser_context
- .as_ref()
- .expect("active browser context");
- assert_eq!(active.id, attached.browser_context_id);
- assert_eq!(active.active_target_id(), Some(attached.target_id.as_str()));
- assert_eq!(
- active.active_session_id(),
- Some(auto_attached_session_id.as_str())
- );
- assert_eq!(
- active
- .active_target
- .owner_state
- .document_start_scripts
- .len(),
- 1
- );
- assert!(
- active
- .devtools_session_state
- .runtime_bindings
- .iter()
- .any(|binding| {
- binding.name == "autoAttachRehydrateBinding"
- && binding.execution_context_name.as_deref() == Some("utility")
- }),
- "utility binding definition should survive auto-attach rehydration on the browser context"
- );
- assert!(ctx.conn.auto_attach);
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_crpage_cleanup_state_persists_across_detach_and_reattach_with_mixed_binding_kinds_without_runtime_enable()
- {
- let mut ctx = TestContext::new();
- let attached =
- create_attached_page_session_without_runtime_enable_async(&mut ctx, 35150, 35151, 35152)
- .await;
-
- ctx.process_async(json!({
- "id": 35153,
- "method": "Page.navigate",
- "sessionId": attached.session_id,
- "params": {
- "url": "data:text/html,<body><div id='main-handle-b'>main-handle-b</div><div id='utility-handle-b'>utility-handle-b</div></body>"
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, 35153);
- assert_eq!(navigation["sessionId"], json!(attached.session_id));
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 35154,
- "method": "Page.createIsolatedWorld",
- "sessionId": attached.session_id,
- "params": {
- "frameId": attached.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let initial_utility_context =
- take_response_by_id(&mut ctx, 35154)["result"]["executionContextId"]
- .as_i64()
- .expect("initial utility context id");
- ctx.take_all();
-
- let custom_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customBindingB",
- "__lm_custom_binding_b_deliver",
- None,
- false,
- );
- let custom_handle_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let custom_handle_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customHandleBindingB",
- "__lm_custom_handle_binding_b_deliver",
- Some("__lm_custom_handle_binding_b_take"),
- true,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
- let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptHandleBinding",
- "__lm_pw_kept_handle_binding_deliver",
- Some("__lm_pw_kept_handle_binding_take"),
- true,
- );
-
- for (id, binding_name, source) in [
- (
- 35155_u64,
- "customBindingA",
- custom_wrapper_a_source.as_str(),
- ),
- (
- 35159_u64,
- "customBindingB",
- custom_wrapper_b_source.as_str(),
- ),
- (
- 35163_u64,
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- ),
- (
- 35167_u64,
- "customHandleBindingB",
- custom_handle_wrapper_b_source.as_str(),
- ),
- (
- 35171_u64,
- "__pw_keptBinding",
- retained_wrapper_source.as_str(),
- ),
- (
- 35175_u64,
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- &attached.session_id,
- initial_utility_context,
- id,
- id + 1,
- id + 2,
- id + 3,
- binding_name,
- source,
- )
- .await;
- }
-
- for (id, binding_name) in [
- (35179_u64, "customBindingA"),
- (35180_u64, "customHandleBindingA"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.removeBinding",
- "sessionId": attached.session_id,
- "params": { "name": binding_name }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- for (id, context_id, expected_state) in [
- (
- 35181_u64,
- None::<i64>,
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- ),
- ),
- (
- 35182_u64,
- Some(initial_utility_context),
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- ),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": attached.session_id,
- "params": params
- }))
- .await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- ctx.process_async(json!({
- "id": 35183,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": attached.target_id,
- "sessionId": attached.session_id
- }
- }))
- .await;
- ctx.expect_result(35183, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": attached.target_id,
- "sessionId": attached.session_id,
- })),
- );
-
- ctx.process_async(json!({
- "id": 35184,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": attached.target_id,
- "flatten": true
- }
- }))
- .await;
- let reattached_session_id = take_response_by_id(&mut ctx, 35184)["result"]["sessionId"]
- .as_str()
- .expect("reattached session id")
- .to_owned();
- assert_ne!(reattached_session_id, attached.session_id);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": reattached_session_id,
- "targetInfo": {
- "targetId": attached.target_id,
- "browserContextId": attached.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, context_id, expected_state) in [
- (
- 35185_u64,
- None::<i64>,
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- ),
- ),
- (
- 35186_u64,
- Some(initial_utility_context),
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- ),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": params
- }))
- .await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
-
- ctx.process_async(json!({
- "id": 35187,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "expression": "globalThis.__lm_reattach_custom_b = customBindingB({ source: 'after-reattach-custom-b', nested: { count: 1, values: ['a', 2, true] } }); 'scheduled-custom-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_custom = take_response_by_id(&mut ctx, 35187);
- assert!(
- scheduled_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled custom value")
- .starts_with("scheduled-")
- );
- let custom_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(reattached_session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("custom binding should emit Runtime.bindingCalled after reattach");
- let custom_payload = custom_binding_called["params"]["payload"]
- .as_str()
- .expect("custom binding payload should be string");
- let custom_payload: serde_json::Value =
- serde_json::from_str(custom_payload).expect("custom binding payload should be valid json");
- assert_eq!(custom_payload["name"], json!("customBindingB"));
- assert_eq!(
- custom_payload["serializedArgs"],
- json!([{
- "source": "after-reattach-custom-b",
- "nested": { "count": 1, "values": ["a", 2, true] }
- }])
- );
- assert_eq!(custom_payload["seq"], json!(1));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35188,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 1, result: 'after-reattach-custom-b-ok' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- let delivered_custom = take_response_by_id(&mut ctx, 35188);
- assert_eq!(
- delivered_custom["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35189,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "expression": "globalThis.__lm_reattach_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_custom = take_response_by_id(&mut ctx, 35189);
- assert_eq!(
- resolved_custom["result"]["result"]["value"],
- json!("after-reattach-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35190,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "contextId": initial_utility_context,
- "expression": "globalThis.__lm_reattach_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-b')); 'scheduled-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_handle = take_response_by_id(&mut ctx, 35190);
- assert!(
- scheduled_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled handle value")
- .starts_with("scheduled-")
- );
- let handle_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(reattached_session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(initial_utility_context)
- })
- .cloned()
- .expect("retained handle binding should emit Runtime.bindingCalled after reattach");
- let handle_payload = handle_binding_called["params"]["payload"]
- .as_str()
- .expect("handle binding payload should be string");
- let handle_payload: serde_json::Value =
- serde_json::from_str(handle_payload).expect("handle binding payload should be valid json");
- let handle_seq = handle_payload["seq"]
- .as_i64()
- .expect("handle payload seq should be integer");
- assert_eq!(handle_seq, 1);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35191,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "contextId": initial_utility_context,
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }})]); }})()"
- )
- }
- })).await;
- let taken_handle = take_response_by_id(&mut ctx, 35191);
- assert_eq!(
- taken_handle["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"utility-handle-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35192,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "contextId": initial_utility_context,
- "expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_seq}, result: 'after-reattach-pw-handle-ok' }}); 'delivered'"
- ),
- "awaitPromise": true
- }
- })).await;
- let delivered_handle = take_response_by_id(&mut ctx, 35192);
- assert_eq!(
- delivered_handle["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35193,
- "method": "Runtime.evaluate",
- "sessionId": reattached_session_id,
- "params": {
- "contextId": initial_utility_context,
- "expression": "globalThis.__lm_reattach_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_handle = take_response_by_id(&mut ctx, 35193);
- assert_eq!(
- resolved_handle["result"]["result"]["value"],
- json!("after-reattach-pw-handle-ok")
- );
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_crpage_cleanup_state_persists_when_auto_attach_reattaches_existing_target_with_mixed_binding_kinds_without_runtime_enable()
- {
- run_patchright_runtimeless_large_stack(
- "patchright-runtimeless-auto-reattach-existing-target",
- || async {
- let mut ctx = TestContext::new();
- let attached = create_attached_page_session_without_runtime_enable_async(
- &mut ctx, 35194, 35195, 35196,
- )
- .await;
-
- ctx.process_async(json!({
- "id": 35197,
- "method": "Page.navigate",
- "sessionId": attached.session_id,
- "params": {
- "url": "data:text/html,<body><div id='main-handle-b'>main-handle-b</div><div id='utility-handle-b'>utility-handle-b</div></body>"
- }
- })).await;
- let navigation = take_response_by_id(&mut ctx, 35197);
- assert_eq!(navigation["sessionId"], json!(attached.session_id));
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 35198,
- "method": "Page.createIsolatedWorld",
- "sessionId": attached.session_id,
- "params": {
- "frameId": attached.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let initial_utility_context =
- take_response_by_id(&mut ctx, 35198)["result"]["executionContextId"]
- .as_i64()
- .expect("initial utility context id");
- ctx.take_all();
-
- let custom_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customBindingB",
- "__lm_custom_binding_b_deliver",
- None,
- false,
- );
- let custom_handle_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let custom_handle_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customHandleBindingB",
- "__lm_custom_handle_binding_b_deliver",
- Some("__lm_custom_handle_binding_b_take"),
- true,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
- let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptHandleBinding",
- "__lm_pw_kept_handle_binding_deliver",
- Some("__lm_pw_kept_handle_binding_take"),
- true,
- );
-
- for (id, binding_name, source) in [
- (
- 35199_u64,
- "customBindingA",
- custom_wrapper_a_source.as_str(),
- ),
- (
- 35203_u64,
- "customBindingB",
- custom_wrapper_b_source.as_str(),
- ),
- (
- 35207_u64,
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- ),
- (
- 35211_u64,
- "customHandleBindingB",
- custom_handle_wrapper_b_source.as_str(),
- ),
- (
- 35215_u64,
- "__pw_keptBinding",
- retained_wrapper_source.as_str(),
- ),
- (
- 35219_u64,
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- &attached.session_id,
- initial_utility_context,
- id,
- id + 1,
- id + 2,
- id + 3,
- binding_name,
- source,
- )
- .await;
- }
-
- for (id, binding_name) in [
- (35223_u64, "customBindingA"),
- (35224_u64, "customHandleBindingA"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.removeBinding",
- "sessionId": attached.session_id,
- "params": { "name": binding_name }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- ctx.process_async(json!({
- "id": 35225,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": attached.target_id,
- "sessionId": attached.session_id
- }
- }))
- .await;
- ctx.expect_result(35225, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": attached.target_id,
- "sessionId": attached.session_id,
- })),
- );
- assert_eq!(
- ctx.conn
- .browser_contexts()
- .find(|bc| bc.id == attached.browser_context_id)
- .and_then(|bc| bc.active_session_id()),
- None
- );
-
- ctx.process_async(json!({
- "id": 35226,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(35226, json!({}), None);
- let auto_attach_event = ctx
- .take_first_matching("reattached target attachedToTarget", |message| {
- message["method"] == json!("Target.attachedToTarget")
- });
- assert_eq!(
- auto_attach_event["params"]["targetInfo"]["targetId"],
- json!(attached.target_id)
- );
- let auto_attached_session_id = auto_attach_event["params"]["sessionId"]
- .as_str()
- .expect("auto-attached session id")
- .to_owned();
- assert_ne!(auto_attached_session_id, attached.session_id);
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 35227,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let main_state = take_response_by_id(&mut ctx, 35227);
- assert_eq!(
- main_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
-
- ctx.process_async(json!({
- "id": 35228,
- "method": "Page.createIsolatedWorld",
- "sessionId": auto_attached_session_id,
- "params": {
- "frameId": attached.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let reattached_utility_context =
- take_response_by_id(&mut ctx, 35228)["result"]["executionContextId"]
- .as_i64()
- .expect("reattached utility context id");
- ctx.take_all();
-
- for (id, binding_name) in [
- (35229_u64, "customBindingB"),
- (35230_u64, "customHandleBindingB"),
- (35231_u64, "__pw_keptBinding"),
- (35232_u64, "__pw_keptHandleBinding"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": auto_attached_session_id,
- "params": { "name": binding_name, "executionContextId": reattached_utility_context }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- for (id, source, expected_type) in [
- (35233_u64, custom_wrapper_a_source.as_str(), "undefined"),
- (35234_u64, custom_wrapper_b_source.as_str(), "function"),
- (
- 35235_u64,
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35236_u64,
- custom_handle_wrapper_b_source.as_str(),
- "function",
- ),
- (35237_u64, retained_wrapper_source.as_str(), "function"),
- (
- 35238_u64,
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35239,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let utility_state = take_response_by_id(&mut ctx, 35239);
- assert_eq!(
- utility_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
-
- ctx.process_async(json!({
- "id": 35240,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "globalThis.__lm_auto_reattach_custom_b = customBindingB({ source: 'after-auto-attach-custom-b', nested: { count: 1, values: ['a', 2, true] } }); 'scheduled-custom-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_custom = take_response_by_id(&mut ctx, 35240);
- assert!(
- scheduled_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled custom value")
- .starts_with("scheduled-")
- );
- let custom_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(auto_attached_session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("custom binding should emit Runtime.bindingCalled after auto-attach");
- let custom_payload = custom_binding_called["params"]["payload"]
- .as_str()
- .expect("custom binding payload should be string");
- let custom_payload: serde_json::Value = serde_json::from_str(custom_payload)
- .expect("custom binding payload should be valid json");
- assert_eq!(custom_payload["name"], json!("customBindingB"));
- assert_eq!(custom_payload["seq"], json!(1));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35241,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 1, result: 'after-auto-attach-custom-b-ok' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- let delivered_custom = take_response_by_id(&mut ctx, 35241);
- assert_eq!(
- delivered_custom["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35242,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "globalThis.__lm_auto_reattach_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_custom = take_response_by_id(&mut ctx, 35242);
- assert_eq!(
- resolved_custom["result"]["result"]["value"],
- json!("after-auto-attach-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35243,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": "globalThis.__lm_auto_reattach_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-b')); 'scheduled-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_handle = take_response_by_id(&mut ctx, 35243);
- assert!(
- scheduled_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled handle value")
- .starts_with("scheduled-")
- );
- let handle_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(auto_attached_session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"]
- == json!(reattached_utility_context)
- })
- .cloned()
- .expect(
- "retained handle binding should emit Runtime.bindingCalled after auto-attach",
- );
- let handle_payload = handle_binding_called["params"]["payload"]
- .as_str()
- .expect("handle binding payload should be string");
- let handle_payload: serde_json::Value = serde_json::from_str(handle_payload)
- .expect("handle binding payload should be valid json");
- let handle_seq = handle_payload["seq"]
- .as_i64()
- .expect("handle payload seq should be integer");
- assert_eq!(handle_seq, 1);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35244,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }})]); }})()"
- )
- }
- })).await;
- let taken_handle = take_response_by_id(&mut ctx, 35244);
- assert_eq!(
- taken_handle["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"utility-handle-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35245,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_seq}, result: 'after-auto-attach-pw-handle-ok' }}); 'delivered'"
- ),
- "awaitPromise": true
- }
- })).await;
- let delivered_handle = take_response_by_id(&mut ctx, 35245);
- assert_eq!(
- delivered_handle["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35246,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": "globalThis.__lm_auto_reattach_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_handle = take_response_by_id(&mut ctx, 35246);
- assert_eq!(
- resolved_handle["result"]["result"]["value"],
- json!("after-auto-attach-pw-handle-ok")
- );
-
- ctx.process_async(json!({
- "id": 35247,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "globalThis.__lm_auto_reattach_custom_b_reject = customBindingB({ source: 'after-auto-attach-custom-b-reject', nested: { count: 2, values: ['b', 3, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-custom-b-reject'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_custom_reject = take_response_by_id(&mut ctx, 35247);
- assert!(
- scheduled_custom_reject["result"]["result"]["value"]
- .as_str()
- .expect("scheduled custom reject value")
- .starts_with("scheduled-")
- );
- let custom_reject_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(auto_attached_session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("custom binding should emit Runtime.bindingCalled for rejection after auto-attach");
- let custom_reject_payload = custom_reject_binding_called["params"]["payload"]
- .as_str()
- .expect("custom reject binding payload should be string");
- let custom_reject_payload: serde_json::Value =
- serde_json::from_str(custom_reject_payload)
- .expect("custom reject binding payload should be valid json");
- assert_eq!(custom_reject_payload["name"], json!("customBindingB"));
- assert_eq!(custom_reject_payload["seq"], json!(2));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35248,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 2, error: 'after-auto-attach-custom-b-error' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- let delivered_custom_reject = take_response_by_id(&mut ctx, 35248);
- assert_eq!(
- delivered_custom_reject["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35249,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "expression": "globalThis.__lm_auto_reattach_custom_b_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_custom = take_response_by_id(&mut ctx, 35249);
- assert_eq!(
- rejected_custom["result"]["result"]["value"],
- json!("rejected:after-auto-attach-custom-b-error")
- );
-
- ctx.process_async(json!({
- "id": 35250,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": "globalThis.__lm_auto_reattach_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-pw-handle-reject'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_handle_reject = take_response_by_id(&mut ctx, 35250);
- assert!(
- scheduled_handle_reject["result"]["result"]["value"]
- .as_str()
- .expect("scheduled handle reject value")
- .starts_with("scheduled-")
- );
- let handle_reject_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(auto_attached_session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(reattached_utility_context)
- })
- .cloned()
- .expect("retained handle binding should emit Runtime.bindingCalled for rejection after auto-attach");
- let handle_reject_payload = handle_reject_binding_called["params"]["payload"]
- .as_str()
- .expect("handle reject binding payload should be string");
- let handle_reject_payload: serde_json::Value =
- serde_json::from_str(handle_reject_payload)
- .expect("handle reject binding payload should be valid json");
- let handle_reject_seq = handle_reject_payload["seq"]
- .as_i64()
- .expect("handle reject payload seq should be integer");
- assert_eq!(handle_reject_seq, 2);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35251,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq} }})]); }})()"
- )
- }
- })).await;
- let taken_handle_reject = take_response_by_id(&mut ctx, 35251);
- assert_eq!(
- taken_handle_reject["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"utility-handle-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35252,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq}, error: 'after-auto-attach-pw-handle-error' }}); 'delivered'"
- ),
- "awaitPromise": true
- }
- })).await;
- let delivered_handle_reject = take_response_by_id(&mut ctx, 35252);
- assert_eq!(
- delivered_handle_reject["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35253,
- "method": "Runtime.evaluate",
- "sessionId": auto_attached_session_id,
- "params": {
- "contextId": reattached_utility_context,
- "expression": "globalThis.__lm_auto_reattach_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_handle = take_response_by_id(&mut ctx, 35253);
- assert_eq!(
- rejected_handle["result"]["result"]["value"],
- json!("rejected:after-auto-attach-pw-handle-error")
- );
- },
- );
-}
-
-#[tokio::test(flavor = "multi_thread")]
-async fn patchright_over_cdp_crpage_cleanup_state_rehydrates_correctly_on_new_target_in_same_context_without_runtime_enable()
- {
- run_patchright_runtimeless_large_stack("patchright-runtimeless-rehydrate", || async {
- let mut ctx = TestContext::new();
- let first = create_attached_page_session_without_runtime_enable_async(
- &mut ctx, 35254, 35255, 35256,
- )
- .await;
-
- ctx.process_async(json!({
- "id": 35257,
- "method": "Page.navigate",
- "sessionId": first.session_id,
- "params": {
- "url": "data:text/html,<body><div id='main-handle-b'>main-handle-b</div><div id='utility-handle-b'>utility-handle-b</div></body>"
- }
- })).await;
- let first_navigation = take_response_by_id(&mut ctx, 35257);
- assert_eq!(first_navigation["sessionId"], json!(first.session_id));
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 35258,
- "method": "Page.createIsolatedWorld",
- "sessionId": first.session_id,
- "params": {
- "frameId": first.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let first_utility_context =
- take_response_by_id(&mut ctx, 35258)["result"]["executionContextId"]
- .as_i64()
- .expect("first utility context id");
- ctx.take_all();
-
- let custom_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customBindingA",
- "__lm_custom_binding_a_deliver",
- None,
- false,
- );
- let custom_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customBindingB",
- "__lm_custom_binding_b_deliver",
- None,
- false,
- );
- let custom_handle_wrapper_a_source = patchright_page_binding_wrapper_source(
- "customHandleBindingA",
- "__lm_custom_handle_binding_a_deliver",
- Some("__lm_custom_handle_binding_a_take"),
- true,
- );
- let custom_handle_wrapper_b_source = patchright_page_binding_wrapper_source(
- "customHandleBindingB",
- "__lm_custom_handle_binding_b_deliver",
- Some("__lm_custom_handle_binding_b_take"),
- true,
- );
- let retained_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptBinding",
- "__lm_pw_kept_binding_deliver",
- None,
- false,
- );
- let retained_handle_wrapper_source = patchright_page_binding_wrapper_source(
- "__pw_keptHandleBinding",
- "__lm_pw_kept_handle_binding_deliver",
- Some("__lm_pw_kept_handle_binding_take"),
- true,
- );
-
- for (id, binding_name, source) in [
- (
- 35259_u64,
- "customBindingA",
- custom_wrapper_a_source.as_str(),
- ),
- (
- 35263_u64,
- "customBindingB",
- custom_wrapper_b_source.as_str(),
- ),
- (
- 35267_u64,
- "customHandleBindingA",
- custom_handle_wrapper_a_source.as_str(),
- ),
- (
- 35271_u64,
- "customHandleBindingB",
- custom_handle_wrapper_b_source.as_str(),
- ),
- (
- 35275_u64,
- "__pw_keptBinding",
- retained_wrapper_source.as_str(),
- ),
- (
- 35279_u64,
- "__pw_keptHandleBinding",
- retained_handle_wrapper_source.as_str(),
- ),
- ] {
- install_patchright_crpage_binding_in_existing_worlds_async(
- &mut ctx,
- &first.session_id,
- first_utility_context,
- id,
- id + 1,
- id + 2,
- id + 3,
- binding_name,
- source,
- )
- .await;
- }
-
- for (id, source, world_name) in [
- (35283_u64, custom_wrapper_a_source.as_str(), None),
- (35284_u64, custom_wrapper_b_source.as_str(), None),
- (35285_u64, custom_handle_wrapper_a_source.as_str(), None),
- (35286_u64, custom_handle_wrapper_b_source.as_str(), None),
- (35287_u64, retained_wrapper_source.as_str(), None),
- (35288_u64, retained_handle_wrapper_source.as_str(), None),
- (35289_u64, custom_wrapper_a_source.as_str(), Some("utility")),
- (35290_u64, custom_wrapper_b_source.as_str(), Some("utility")),
- (
- 35291_u64,
- custom_handle_wrapper_a_source.as_str(),
- Some("utility"),
- ),
- (
- 35292_u64,
- custom_handle_wrapper_b_source.as_str(),
- Some("utility"),
- ),
- (35293_u64, retained_wrapper_source.as_str(), Some("utility")),
- (
- 35294_u64,
- retained_handle_wrapper_source.as_str(),
- Some("utility"),
- ),
- ] {
- let mut params = json!({
- "source": source,
- "runImmediately": true
- });
- if let Some(world_name) = world_name {
- params["worldName"] = json!(world_name);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Page.addScriptToEvaluateOnNewDocument",
- "sessionId": first.session_id,
- "params": params
- }))
- .await;
- assert!(
- take_response_by_id(&mut ctx, id)["result"]["identifier"]
- .as_str()
- .is_some()
- );
- }
-
- for (id, binding_name) in [
- (35295_u64, "customBindingA"),
- (35296_u64, "customHandleBindingA"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.removeBinding",
- "sessionId": first.session_id,
- "params": { "name": binding_name }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- ctx.process_async(json!({
- "id": 35297,
- "method": "Target.closeTarget",
- "params": {
- "targetId": first.target_id
- }
- }))
- .await;
- ctx.expect_result(35297, json!({ "success": true }), None);
- ctx.take_all();
-
- let second = attach_page_session_without_runtime_enable_in_existing_context_async(
- &mut ctx,
- &first.browser_context_id,
- 35298,
- 35299,
- )
- .await;
- assert_ne!(second.target_id, first.target_id);
-
- ctx.process_async(json!({
- "id": 35300,
- "method": "Page.navigate",
- "sessionId": second.session_id,
- "params": {
- "url": "data:text/html,<body><div id='main-handle-b'>new-main-handle-b</div><div id='utility-handle-b'>new-utility-handle-b</div></body>"
- }
- })).await;
- let second_navigation = take_response_by_id(&mut ctx, 35300);
- assert_eq!(second_navigation["sessionId"], json!(second.session_id));
- ctx.take_all();
-
- for (id, source, expected_type) in [
- (35321_u64, custom_wrapper_a_source.as_str(), "undefined"),
- (35322_u64, custom_wrapper_b_source.as_str(), "function"),
- (
- 35323_u64,
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35324_u64,
- custom_handle_wrapper_b_source.as_str(),
- "function",
- ),
- (35325_u64, retained_wrapper_source.as_str(), "function"),
- (
- 35326_u64,
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35301,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let second_main_state = take_response_by_id(&mut ctx, 35301);
- assert_eq!(
- second_main_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
-
- ctx.process_async(json!({
- "id": 35302,
- "method": "Page.createIsolatedWorld",
- "sessionId": second.session_id,
- "params": {
- "frameId": second.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let second_utility_context =
- take_response_by_id(&mut ctx, 35302)["result"]["executionContextId"]
- .as_i64()
- .expect("second utility context id");
- ctx.take_all();
-
- for (id, binding_name) in [
- (35303_u64, "customBindingB"),
- (35304_u64, "customHandleBindingB"),
- (35305_u64, "__pw_keptBinding"),
- (35306_u64, "__pw_keptHandleBinding"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": second.session_id,
- "params": {
- "name": binding_name,
- "executionContextId": second_utility_context
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
-
- for (id, source, expected_type) in [
- (35307_u64, custom_wrapper_a_source.as_str(), "undefined"),
- (35308_u64, custom_wrapper_b_source.as_str(), "function"),
- (
- 35309_u64,
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35310_u64,
- custom_handle_wrapper_b_source.as_str(),
- "function",
- ),
- (35311_u64, retained_wrapper_source.as_str(), "function"),
- (
- 35312_u64,
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35313,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let second_utility_state = take_response_by_id(&mut ctx, 35313);
- assert_eq!(
- second_utility_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
-
- ctx.process_async(json!({
- "id": 35314,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_second_target_custom_b = customBindingB({ source: 'new-target-custom-b', nested: { count: 1, values: ['a', 2, true] } }); 'scheduled-custom-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_custom = take_response_by_id(&mut ctx, 35314);
- assert!(
- scheduled_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled custom value")
- .starts_with("scheduled-")
- );
- let custom_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second.session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("custom binding should emit Runtime.bindingCalled on the new target");
- let custom_payload = custom_binding_called["params"]["payload"]
- .as_str()
- .expect("custom binding payload should be string");
- let custom_payload: serde_json::Value = serde_json::from_str(custom_payload)
- .expect("custom binding payload should be valid json");
- assert_eq!(
- custom_payload["serializedArgs"],
- json!([{
- "source": "new-target-custom-b",
- "nested": { "count": 1, "values": ["a", 2, true] }
- }])
- );
- assert_eq!(custom_payload["seq"], json!(1));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35315,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 1, result: 'new-target-custom-b-ok' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- let delivered_custom = take_response_by_id(&mut ctx, 35315);
- assert_eq!(
- delivered_custom["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35316,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_second_target_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_custom = take_response_by_id(&mut ctx, 35316);
- assert_eq!(
- resolved_custom["result"]["result"]["value"],
- json!("new-target-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35327,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_second_target_custom_b_reject = customBindingB({ source: 'new-target-custom-b-reject', nested: { count: 2, values: ['b', 3, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-custom-b-reject'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_custom_reject = take_response_by_id(&mut ctx, 35327);
- assert!(
- scheduled_custom_reject["result"]["result"]["value"]
- .as_str()
- .expect("scheduled custom reject value")
- .starts_with("scheduled-")
- );
- let custom_reject_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second.session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("custom binding should emit Runtime.bindingCalled rejection on the new target");
- let custom_reject_payload = custom_reject_binding_called["params"]["payload"]
- .as_str()
- .expect("custom reject payload should be string");
- let custom_reject_payload: serde_json::Value = serde_json::from_str(custom_reject_payload)
- .expect("custom reject payload should be valid json");
- assert_eq!(custom_reject_payload["seq"], json!(2));
- assert_eq!(
- custom_reject_payload["serializedArgs"],
- json!([{
- "source": "new-target-custom-b-reject",
- "nested": { "count": 2, "values": ["b", 3, false] }
- }])
- );
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35328,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 2, error: 'new-target-custom-b-error' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- let delivered_custom_reject = take_response_by_id(&mut ctx, 35328);
- assert_eq!(
- delivered_custom_reject["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35329,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_second_target_custom_b_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_custom = take_response_by_id(&mut ctx, 35329);
- assert_eq!(
- rejected_custom["result"]["result"]["value"],
- json!("rejected:new-target-custom-b-error")
- );
-
- ctx.process_async(json!({
- "id": 35317,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_second_target_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-b')); 'scheduled-pw-handle'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_handle = take_response_by_id(&mut ctx, 35317);
- assert!(
- scheduled_handle["result"]["result"]["value"]
- .as_str()
- .expect("scheduled handle value")
- .starts_with("scheduled-")
- );
- let handle_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second.session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(second_utility_context)
- })
- .cloned()
- .expect("retained handle binding should emit Runtime.bindingCalled on the new target");
- let handle_payload = handle_binding_called["params"]["payload"]
- .as_str()
- .expect("handle binding payload should be string");
- let handle_payload: serde_json::Value = serde_json::from_str(handle_payload)
- .expect("handle binding payload should be valid json");
- let handle_seq = handle_payload["seq"]
- .as_i64()
- .expect("handle payload seq should be integer");
- assert_eq!(handle_seq, 1);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35318,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }})]); }})()"
- )
- }
- })).await;
- let taken_handle = take_response_by_id(&mut ctx, 35318);
- assert_eq!(
- taken_handle["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"new-utility-handle-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35319,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_seq}, result: 'new-target-pw-handle-ok' }}); 'delivered'"
- ),
- "awaitPromise": true
- }
- })).await;
- let delivered_handle = take_response_by_id(&mut ctx, 35319);
- assert_eq!(
- delivered_handle["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35320,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_second_target_pw_handle",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_handle = take_response_by_id(&mut ctx, 35320);
- assert_eq!(
- resolved_handle["result"]["result"]["value"],
- json!("new-target-pw-handle-ok")
- );
-
- ctx.process_async(json!({
- "id": 35330,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_second_target_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-pw-handle-reject'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_handle_reject = take_response_by_id(&mut ctx, 35330);
- assert!(
- scheduled_handle_reject["result"]["result"]["value"]
- .as_str()
- .expect("scheduled handle reject value")
- .starts_with("scheduled-")
- );
- let handle_reject_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second.session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(second_utility_context)
- })
- .cloned()
- .expect(
- "retained handle binding should emit rejection Runtime.bindingCalled on the new target",
- );
- let handle_reject_payload = handle_reject_binding_called["params"]["payload"]
- .as_str()
- .expect("handle reject payload should be string");
- let handle_reject_payload: serde_json::Value = serde_json::from_str(handle_reject_payload)
- .expect("handle reject payload should be valid json");
- let handle_reject_seq = handle_reject_payload["seq"]
- .as_i64()
- .expect("handle reject payload seq should be integer");
- assert_eq!(handle_reject_seq, 2);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35331,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq} }})]); }})()"
- )
- }
- })).await;
- let taken_handle_reject = take_response_by_id(&mut ctx, 35331);
- assert_eq!(
- taken_handle_reject["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"new-utility-handle-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35332,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq}, error: 'new-target-pw-handle-error' }}); 'delivered'"
- ),
- "awaitPromise": true
- }
- })).await;
- let delivered_handle_reject = take_response_by_id(&mut ctx, 35332);
- assert_eq!(
- delivered_handle_reject["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35333,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": second_utility_context,
- "expression": "globalThis.__lm_second_target_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_handle = take_response_by_id(&mut ctx, 35333);
- assert_eq!(
- rejected_handle["result"]["result"]["value"],
- json!("rejected:new-target-pw-handle-error")
- );
-
- ctx.process_async(json!({
- "id": 35334,
- "method": "Page.navigate",
- "sessionId": second.session_id,
- "params": {
- "url": "data:text/html,<body><div id='main-handle-b'>replay-main-handle-b</div><div id='utility-handle-b'>replay-utility-handle-b</div></body>"
- }
- })).await;
- let replay_navigation = take_response_by_id(&mut ctx, 35334);
- assert_eq!(replay_navigation["sessionId"], json!(second.session_id));
- ctx.take_all();
-
- for (id, source, expected_type) in [
- (35335_u64, custom_wrapper_a_source.as_str(), "undefined"),
- (35336_u64, custom_wrapper_b_source.as_str(), "function"),
- (
- 35337_u64,
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35338_u64,
- custom_handle_wrapper_b_source.as_str(),
- "function",
- ),
- (35339_u64, retained_wrapper_source.as_str(), "function"),
- (
- 35340_u64,
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
+ "id": 35228,
+ "method": "Page.createIsolatedWorld",
+ "sessionId": auto_attached_session_id,
"params": {
- "expression": source,
- "awaitPromise": true
+ "frameId": attached.target_id,
+ "worldName": "utility"
}
}))
.await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35341,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let replay_main_state = take_response_by_id(&mut ctx, 35341);
- assert_eq!(
- replay_main_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
+ let reattached_utility_context =
+ take_response_by_id(&mut ctx, 35228)["result"]["executionContextId"]
+ .as_i64()
+ .expect("reattached utility context id");
+ ctx.take_all();
- ctx.process_async(json!({
- "id": 35342,
- "method": "Page.createIsolatedWorld",
- "sessionId": second.session_id,
- "params": {
- "frameId": second.target_id,
- "worldName": "utility"
- }
+ for (id, binding_name) in [
+ (35229_u64, "customBindingB"),
+ (35230_u64, "customHandleBindingB"),
+ (35231_u64, "__pw_keptBinding"),
+ (35232_u64, "__pw_keptHandleBinding"),
+ ] {
+ ctx.process_async(json!({
+ "id": id,
+ "method": "Runtime.addBinding",
+ "sessionId": auto_attached_session_id,
+ "params": { "name": binding_name, "executionContextId": reattached_utility_context }
}))
.await;
- let replay_utility_context =
- take_response_by_id(&mut ctx, 35342)["result"]["executionContextId"]
- .as_i64()
- .expect("replay utility context id");
- ctx.take_all();
+ assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
+ }
- for (id, binding_name) in [
- (35343_u64, "customBindingB"),
- (35344_u64, "customHandleBindingB"),
- (35345_u64, "__pw_keptBinding"),
- (35346_u64, "__pw_keptHandleBinding"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": second.session_id,
- "params": {
- "name": binding_name,
- "executionContextId": replay_utility_context
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
+ for (id, source, expected_type) in [
+ (35233_u64, custom_wrapper_a_source.as_str(), "undefined"),
+ (35234_u64, custom_wrapper_b_source.as_str(), "function"),
+ (
+ 35235_u64,
+ custom_handle_wrapper_a_source.as_str(),
+ "undefined",
+ ),
+ (
+ 35236_u64,
+ custom_handle_wrapper_b_source.as_str(),
+ "function",
+ ),
+ (35237_u64, retained_wrapper_source.as_str(), "function"),
+ (
+ 35238_u64,
+ retained_handle_wrapper_source.as_str(),
+ "function",
+ ),
+ ] {
+ ctx.process_async(json!({
+ "id": id,
+ "method": "Runtime.evaluate",
+ "sessionId": auto_attached_session_id,
+ "params": {
+ "contextId": reattached_utility_context,
+ "expression": source,
+ "awaitPromise": true
+ }
+ }))
+ .await;
+ let replayed = take_response_by_id(&mut ctx, id);
+ assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
+ }
- for (id, source, expected_type) in [
- (35347_u64, custom_wrapper_a_source.as_str(), "undefined"),
- (35348_u64, custom_wrapper_b_source.as_str(), "function"),
- (
- 35349_u64,
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35350_u64,
- custom_handle_wrapper_b_source.as_str(),
- "function",
- ),
- (35351_u64, retained_wrapper_source.as_str(), "function"),
- (
- 35352_u64,
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": replay_utility_context,
- "expression": source,
- "awaitPromise": true
- }
- }))
- .await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35353,
+ "id": 35239,
"method": "Runtime.evaluate",
- "sessionId": second.session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": replay_utility_context,
+ "contextId": reattached_utility_context,
"expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
}
})).await;
- let replay_utility_state = take_response_by_id(&mut ctx, 35353);
- assert_eq!(
- replay_utility_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
-
- ctx.process_async(json!({
- "id": 35354,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_replay_target_custom_b = customBindingB({ source: 'replay-target-custom-b', nested: { count: 3, values: ['c', 4, true] } }); 'scheduled-replay-custom-b'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_replay_custom = take_response_by_id(&mut ctx, 35354);
- assert!(
- scheduled_replay_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled replay custom value")
- .starts_with("scheduled-")
- );
- let replay_custom_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second.session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect("replay custom binding should emit Runtime.bindingCalled");
- let replay_custom_payload = replay_custom_binding_called["params"]["payload"]
- .as_str()
- .expect("replay custom payload should be string");
- let replay_custom_payload: serde_json::Value = serde_json::from_str(replay_custom_payload)
- .expect("replay custom payload should be valid json");
- assert_eq!(replay_custom_payload["seq"], json!(1));
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35355,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 1, result: 'replay-target-custom-b-ok' }); 'delivered'",
- "awaitPromise": true
- }
- })).await;
- let delivered_replay_custom = take_response_by_id(&mut ctx, 35355);
- assert_eq!(
- delivered_replay_custom["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35356,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "expression": "globalThis.__lm_replay_target_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_replay_custom = take_response_by_id(&mut ctx, 35356);
- assert_eq!(
- resolved_replay_custom["result"]["result"]["value"],
- json!("replay-target-custom-b-ok")
- );
-
- ctx.process_async(json!({
- "id": 35357,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": replay_utility_context,
- "expression": "globalThis.__lm_replay_target_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-replay-pw-handle-reject'",
- "awaitPromise": true
- }
- })).await;
- let scheduled_replay_handle_reject = take_response_by_id(&mut ctx, 35357);
- assert!(
- scheduled_replay_handle_reject["result"]["result"]["value"]
- .as_str()
- .expect("scheduled replay handle reject value")
- .starts_with("scheduled-")
- );
- let replay_handle_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(second.session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(replay_utility_context)
- })
- .cloned()
- .expect("replay retained handle binding should emit Runtime.bindingCalled");
- let replay_handle_payload = replay_handle_binding_called["params"]["payload"]
- .as_str()
- .expect("replay handle payload should be string");
- let replay_handle_payload: serde_json::Value = serde_json::from_str(replay_handle_payload)
- .expect("replay handle payload should be valid json");
- let replay_handle_seq = replay_handle_payload["seq"]
- .as_i64()
- .expect("replay handle seq should be integer");
- assert_eq!(replay_handle_seq, 1);
- ctx.sent.clear();
-
- ctx.process_async(json!({
- "id": 35358,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": replay_utility_context,
- "expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {replay_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {replay_handle_seq} }})]); }})()"
- )
- }
- })).await;
- let taken_replay_handle = take_response_by_id(&mut ctx, 35358);
- assert_eq!(
- taken_replay_handle["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"replay-utility-handle-b\",\"undefined\"]")
- );
-
- ctx.process_async(json!({
- "id": 35359,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": replay_utility_context,
- "expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {replay_handle_seq}, error: 'replay-target-pw-handle-error' }}); 'delivered'"
- ),
- "awaitPromise": true
- }
- })).await;
- let delivered_replay_handle = take_response_by_id(&mut ctx, 35359);
- assert_eq!(
- delivered_replay_handle["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35360,
- "method": "Runtime.evaluate",
- "sessionId": second.session_id,
- "params": {
- "contextId": replay_utility_context,
- "expression": "globalThis.__lm_replay_target_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_replay_handle = take_response_by_id(&mut ctx, 35360);
- assert_eq!(
- rejected_replay_handle["result"]["result"]["value"],
- json!("rejected:replay-target-pw-handle-error")
- );
-
- ctx.process_async(json!({
- "id": 35361,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": second.target_id,
- "sessionId": second.session_id
- }
- }))
- .await;
- ctx.expect_result(35361, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": second.target_id,
- "sessionId": second.session_id,
- })),
- );
-
- ctx.process_async(json!({
- "id": 35362,
- "method": "Target.attachToTarget",
- "params": {
- "targetId": second.target_id,
- "flatten": true
- }
- }))
- .await;
- let reattached_second_session_id =
- take_response_by_id(&mut ctx, 35362)["result"]["sessionId"]
- .as_str()
- .expect("reattached second target session id")
- .to_owned();
- assert_ne!(reattached_second_session_id, second.session_id);
- ctx.expect_event(
- "Target.attachedToTarget",
- Some(&json!({
- "sessionId": reattached_second_session_id,
- "targetInfo": {
- "targetId": second.target_id,
- "browserContextId": second.browser_context_id,
- }
- })),
- );
- ctx.take_all();
-
- for (id, context_id, expected_state) in [
- (
- 35363_u64,
- None::<i64>,
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- ),
- ),
- (
- 35364_u64,
- Some(replay_utility_context),
+ let utility_state = take_response_by_id(&mut ctx, 35239);
+ assert_eq!(
+ utility_state["result"]["result"]["value"],
json!(
"[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- ),
- ),
- ] {
- let mut params = json!({
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- });
- if let Some(context_id) = context_id {
- params["contextId"] = json!(context_id);
- }
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
- "params": params
- }))
- .await;
- let state = take_response_by_id(&mut ctx, id);
- assert_eq!(state["result"]["result"]["value"], expected_state);
- }
+ )
+ );
- ctx.process_async(json!({
- "id": 35365,
+ ctx.process_async(json!({
+ "id": 35240,
"method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "expression": "globalThis.__lm_reattached_new_target_custom_b = customBindingB({ source: 'reattached-new-target-custom-b', nested: { count: 4, values: ['d', 5, true] } }); 'scheduled-custom-b'",
+ "expression": "globalThis.__lm_auto_reattach_custom_b = customBindingB({ source: 'after-auto-attach-custom-b', nested: { count: 1, values: ['a', 2, true] } }); 'scheduled-custom-b'",
"awaitPromise": true
}
})).await;
- let scheduled_reattached_custom = take_response_by_id(&mut ctx, 35365);
- assert!(
- scheduled_reattached_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled reattached custom value")
- .starts_with("scheduled-")
- );
- let reattached_custom_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(reattached_second_session_id)
- && message["params"]["name"] == json!("customBindingB")
- })
- .cloned()
- .expect(
- "custom binding should emit Runtime.bindingCalled after reattaching the new target",
+ let scheduled_custom = take_response_by_id(&mut ctx, 35240);
+ assert!(
+ scheduled_custom["result"]["result"]["value"]
+ .as_str()
+ .expect("scheduled custom value")
+ .starts_with("scheduled-")
);
- let reattached_custom_payload = reattached_custom_binding_called["params"]["payload"]
- .as_str()
- .expect("reattached custom payload should be string");
- let reattached_custom_payload: serde_json::Value =
- serde_json::from_str(reattached_custom_payload)
- .expect("reattached custom payload should be valid json");
- assert_eq!(reattached_custom_payload["seq"], json!(2));
- assert_eq!(
- reattached_custom_payload["serializedArgs"],
- json!([{
- "source": "reattached-new-target-custom-b",
- "nested": { "count": 4, "values": ["d", 5, true] }
- }])
- );
- ctx.sent.clear();
+ let custom_binding_called = ctx
+ .sent
+ .iter()
+ .rev()
+ .find(|message| {
+ message["method"] == json!("Runtime.bindingCalled")
+ && message["sessionId"] == json!(auto_attached_session_id)
+ && message["params"]["name"] == json!("customBindingB")
+ })
+ .cloned()
+ .expect("custom binding should emit Runtime.bindingCalled after auto-attach");
+ let custom_payload = custom_binding_called["params"]["payload"]
+ .as_str()
+ .expect("custom binding payload should be string");
+ let custom_payload: serde_json::Value = serde_json::from_str(custom_payload)
+ .expect("custom binding payload should be valid json");
+ assert_eq!(custom_payload["name"], json!("customBindingB"));
+ assert_eq!(custom_payload["seq"], json!(1));
+ ctx.sent.clear();
- ctx.process_async(json!({
- "id": 35366,
+ ctx.process_async(json!({
+ "id": 35241,
"method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 2, result: 'reattached-new-target-custom-b-ok' }); 'delivered'",
+ "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 1, result: 'after-auto-attach-custom-b-ok' }); 'delivered'",
"awaitPromise": true
}
})).await;
- let delivered_reattached_custom = take_response_by_id(&mut ctx, 35366);
- assert_eq!(
- delivered_reattached_custom["result"]["result"]["value"],
- json!("delivered")
- );
+ let delivered_custom = take_response_by_id(&mut ctx, 35241);
+ assert_eq!(
+ delivered_custom["result"]["result"]["value"],
+ json!("delivered")
+ );
- ctx.process_async(json!({
- "id": 35367,
- "method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
- "params": {
- "expression": "globalThis.__lm_reattached_new_target_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_reattached_custom = take_response_by_id(&mut ctx, 35367);
- assert_eq!(
- resolved_reattached_custom["result"]["result"]["value"],
- json!("reattached-new-target-custom-b-ok")
- );
+ ctx.process_async(json!({
+ "id": 35242,
+ "method": "Runtime.evaluate",
+ "sessionId": auto_attached_session_id,
+ "params": {
+ "expression": "globalThis.__lm_auto_reattach_custom_b",
+ "awaitPromise": true
+ }
+ }))
+ .await;
+ let resolved_custom = take_response_by_id(&mut ctx, 35242);
+ assert_eq!(
+ resolved_custom["result"]["result"]["value"],
+ json!("after-auto-attach-custom-b-ok")
+ );
- ctx.process_async(json!({
- "id": 35368,
+ ctx.process_async(json!({
+ "id": 35243,
"method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": replay_utility_context,
- "expression": "globalThis.__lm_reattached_new_target_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-pw-handle-reject'",
+ "contextId": reattached_utility_context,
+ "expression": "globalThis.__lm_auto_reattach_pw_handle = __pw_keptHandleBinding(document.getElementById('utility-handle-b')); 'scheduled-pw-handle'",
"awaitPromise": true
}
})).await;
- let scheduled_reattached_handle_reject = take_response_by_id(&mut ctx, 35368);
- assert!(
- scheduled_reattached_handle_reject["result"]["result"]["value"]
+ let scheduled_handle = take_response_by_id(&mut ctx, 35243);
+ assert!(
+ scheduled_handle["result"]["result"]["value"]
+ .as_str()
+ .expect("scheduled handle value")
+ .starts_with("scheduled-")
+ );
+ let handle_binding_called = ctx
+ .sent
+ .iter()
+ .rev()
+ .find(|message| {
+ message["method"] == json!("Runtime.bindingCalled")
+ && message["sessionId"] == json!(auto_attached_session_id)
+ && message["params"]["name"] == json!("__pw_keptHandleBinding")
+ && message["params"]["executionContextId"]
+ == json!(reattached_utility_context)
+ })
+ .cloned()
+ .expect(
+ "retained handle binding should emit Runtime.bindingCalled after auto-attach",
+ );
+ let handle_payload = handle_binding_called["params"]["payload"]
.as_str()
- .expect("scheduled reattached handle reject value")
- .starts_with("scheduled-")
- );
- let reattached_handle_binding_called = ctx
- .sent
- .iter()
- .rev()
- .find(|message| {
- message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(reattached_second_session_id)
- && message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(replay_utility_context)
- })
- .cloned()
- .expect("retained handle binding should emit Runtime.bindingCalled after reattaching the new target");
- let reattached_handle_payload = reattached_handle_binding_called["params"]["payload"]
- .as_str()
- .expect("reattached handle payload should be string");
- let reattached_handle_payload: serde_json::Value =
- serde_json::from_str(reattached_handle_payload)
- .expect("reattached handle payload should be valid json");
- let reattached_handle_seq = reattached_handle_payload["seq"]
- .as_i64()
- .expect("reattached handle seq should be integer");
- assert_eq!(reattached_handle_seq, 2);
- ctx.sent.clear();
+ .expect("handle binding payload should be string");
+ let handle_payload: serde_json::Value = serde_json::from_str(handle_payload)
+ .expect("handle binding payload should be valid json");
+ let handle_seq = handle_payload["seq"]
+ .as_i64()
+ .expect("handle payload seq should be integer");
+ assert_eq!(handle_seq, 1);
+ ctx.sent.clear();
- ctx.process_async(json!({
- "id": 35369,
+ ctx.process_async(json!({
+ "id": 35244,
"method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": replay_utility_context,
+ "contextId": reattached_utility_context,
"expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {reattached_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {reattached_handle_seq} }})]); }})()"
+ "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_seq} }})]); }})()"
)
}
})).await;
- let taken_reattached_handle = take_response_by_id(&mut ctx, 35369);
- assert_eq!(
- taken_reattached_handle["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"replay-utility-handle-b\",\"undefined\"]")
- );
+ let taken_handle = take_response_by_id(&mut ctx, 35244);
+ assert_eq!(
+ taken_handle["result"]["result"]["value"],
+ json!("[\"utility-handle-b\",\"utility-handle-b\",\"undefined\"]")
+ );
- ctx.process_async(json!({
- "id": 35370,
+ ctx.process_async(json!({
+ "id": 35245,
"method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": replay_utility_context,
+ "contextId": reattached_utility_context,
"expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {reattached_handle_seq}, error: 'reattached-new-target-pw-handle-error' }}); 'delivered'"
+ "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_seq}, result: 'after-auto-attach-pw-handle-ok' }}); 'delivered'"
),
"awaitPromise": true
}
})).await;
- let delivered_reattached_handle = take_response_by_id(&mut ctx, 35370);
- assert_eq!(
- delivered_reattached_handle["result"]["result"]["value"],
- json!("delivered")
- );
-
- ctx.process_async(json!({
- "id": 35371,
- "method": "Runtime.evaluate",
- "sessionId": reattached_second_session_id,
- "params": {
- "contextId": replay_utility_context,
- "expression": "globalThis.__lm_reattached_new_target_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_reattached_handle = take_response_by_id(&mut ctx, 35371);
- assert_eq!(
- rejected_reattached_handle["result"]["result"]["value"],
- json!("rejected:reattached-new-target-pw-handle-error")
- );
-
- ctx.process_async(json!({
- "id": 35372,
- "method": "Target.detachFromTarget",
- "params": {
- "targetId": second.target_id,
- "sessionId": reattached_second_session_id
- }
- }))
- .await;
- ctx.expect_result(35372, json!({}), None);
- ctx.expect_event(
- "Target.detachedFromTarget",
- Some(&json!({
- "targetId": second.target_id,
- "sessionId": reattached_second_session_id,
- })),
- );
- assert_eq!(
- ctx.conn
- .browser_contexts()
- .find(|bc| bc.id == second.browser_context_id)
- .and_then(|bc| bc.active_session_id()),
- None
- );
-
- ctx.process_async(json!({
- "id": 35373,
- "method": "Target.setAutoAttach",
- "params": {
- "autoAttach": true,
- "waitForDebuggerOnStart": false
- }
- }))
- .await;
- ctx.expect_result(35373, json!({}), None);
- let reauto_attach_event = ctx
- .take_first_matching("re-auto-attached target attachedToTarget", |message| {
- message["method"] == json!("Target.attachedToTarget")
- });
- assert_eq!(
- reauto_attach_event["params"]["targetInfo"]["targetId"],
- json!(second.target_id)
- );
- let reauto_attached_second_session_id = reauto_attach_event["params"]["sessionId"]
- .as_str()
- .expect("re-auto-attached second target session id")
- .to_owned();
- assert_ne!(
- reauto_attached_second_session_id,
- reattached_second_session_id
- );
- ctx.take_all();
-
- ctx.process_async(json!({
- "id": 35374,
- "method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
- "params": {
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let reauto_main_state = take_response_by_id(&mut ctx, 35374);
- assert_eq!(
- reauto_main_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
-
- ctx.process_async(json!({
- "id": 35375,
- "method": "Page.createIsolatedWorld",
- "sessionId": reauto_attached_second_session_id,
- "params": {
- "frameId": second.target_id,
- "worldName": "utility"
- }
- }))
- .await;
- let reauto_utility_context =
- take_response_by_id(&mut ctx, 35375)["result"]["executionContextId"]
- .as_i64()
- .expect("re-auto-attached utility context id");
- ctx.take_all();
-
- for (id, binding_name) in [
- (35376_u64, "customBindingB"),
- (35377_u64, "customHandleBindingB"),
- (35378_u64, "__pw_keptBinding"),
- (35379_u64, "__pw_keptHandleBinding"),
- ] {
- ctx.process_async(json!({
- "id": id,
- "method": "Runtime.addBinding",
- "sessionId": reauto_attached_second_session_id,
- "params": {
- "name": binding_name,
- "executionContextId": reauto_utility_context
- }
- }))
- .await;
- assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
- }
+ let delivered_handle = take_response_by_id(&mut ctx, 35245);
+ assert_eq!(
+ delivered_handle["result"]["result"]["value"],
+ json!("delivered")
+ );
- for (id, source, expected_type) in [
- (35380_u64, custom_wrapper_a_source.as_str(), "undefined"),
- (35381_u64, custom_wrapper_b_source.as_str(), "function"),
- (
- 35382_u64,
- custom_handle_wrapper_a_source.as_str(),
- "undefined",
- ),
- (
- 35383_u64,
- custom_handle_wrapper_b_source.as_str(),
- "function",
- ),
- (35384_u64, retained_wrapper_source.as_str(), "function"),
- (
- 35385_u64,
- retained_handle_wrapper_source.as_str(),
- "function",
- ),
- ] {
ctx.process_async(json!({
- "id": id,
+ "id": 35246,
"method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": reauto_utility_context,
- "expression": source,
+ "contextId": reattached_utility_context,
+ "expression": "globalThis.__lm_auto_reattach_pw_handle",
"awaitPromise": true
}
}))
.await;
- let replayed = take_response_by_id(&mut ctx, id);
- assert_eq!(replayed["result"]["result"]["value"], json!(expected_type));
- }
-
- ctx.process_async(json!({
- "id": 35386,
- "method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
- "params": {
- "contextId": reauto_utility_context,
- "expression": "JSON.stringify([typeof globalThis.customBindingA, typeof globalThis.customBindingB, typeof globalThis.customHandleBindingA, typeof globalThis.customHandleBindingB, typeof globalThis.__pw_keptBinding, typeof globalThis.__pw_keptHandleBinding])"
- }
- })).await;
- let reauto_utility_state = take_response_by_id(&mut ctx, 35386);
- assert_eq!(
- reauto_utility_state["result"]["result"]["value"],
- json!(
- "[\"undefined\",\"function\",\"undefined\",\"function\",\"function\",\"function\"]"
- )
- );
+ let resolved_handle = take_response_by_id(&mut ctx, 35246);
+ assert_eq!(
+ resolved_handle["result"]["result"]["value"],
+ json!("after-auto-attach-pw-handle-ok")
+ );
- ctx.process_async(json!({
- "id": 35387,
+ ctx.process_async(json!({
+ "id": 35247,
"method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "expression": "globalThis.__lm_reauto_new_target_custom_b = customBindingB({ source: 'reauto-new-target-custom-b', nested: { count: 5, values: ['e', 6, true] } }); 'scheduled-custom-b'",
+ "expression": "globalThis.__lm_auto_reattach_custom_b_reject = customBindingB({ source: 'after-auto-attach-custom-b-reject', nested: { count: 2, values: ['b', 3, false] } }).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-custom-b-reject'",
"awaitPromise": true
}
})).await;
- let scheduled_reauto_custom = take_response_by_id(&mut ctx, 35387);
- assert!(
- scheduled_reauto_custom["result"]["result"]["value"]
- .as_str()
- .expect("scheduled re-auto custom value")
- .starts_with("scheduled-")
- );
- let reauto_custom_binding_called = ctx
+ let scheduled_custom_reject = take_response_by_id(&mut ctx, 35247);
+ assert!(
+ scheduled_custom_reject["result"]["result"]["value"]
+ .as_str()
+ .expect("scheduled custom reject value")
+ .starts_with("scheduled-")
+ );
+ let custom_reject_binding_called = ctx
.sent
.iter()
.rev()
.find(|message| {
message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(reauto_attached_second_session_id)
+ && message["sessionId"] == json!(auto_attached_session_id)
&& message["params"]["name"] == json!("customBindingB")
})
.cloned()
- .expect("custom binding should emit Runtime.bindingCalled after re-auto-attaching the new target");
- let reauto_custom_payload = reauto_custom_binding_called["params"]["payload"]
- .as_str()
- .expect("re-auto custom payload should be string");
- let reauto_custom_payload: serde_json::Value = serde_json::from_str(reauto_custom_payload)
- .expect("re-auto custom payload should be valid json");
- assert_eq!(reauto_custom_payload["seq"], json!(3));
- assert_eq!(
- reauto_custom_payload["serializedArgs"],
- json!([{
- "source": "reauto-new-target-custom-b",
- "nested": { "count": 5, "values": ["e", 6, true] }
- }])
- );
- ctx.sent.clear();
+ .expect("custom binding should emit Runtime.bindingCalled for rejection after auto-attach");
+ let custom_reject_payload = custom_reject_binding_called["params"]["payload"]
+ .as_str()
+ .expect("custom reject binding payload should be string");
+ let custom_reject_payload: serde_json::Value =
+ serde_json::from_str(custom_reject_payload)
+ .expect("custom reject binding payload should be valid json");
+ assert_eq!(custom_reject_payload["name"], json!("customBindingB"));
+ assert_eq!(custom_reject_payload["seq"], json!(2));
+ ctx.sent.clear();
- ctx.process_async(json!({
- "id": 35388,
+ ctx.process_async(json!({
+ "id": 35248,
"method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 3, result: 'reauto-new-target-custom-b-ok' }); 'delivered'",
+ "expression": "globalThis.__lm_custom_binding_b_deliver({ name: 'customBindingB', seq: 2, error: 'after-auto-attach-custom-b-error' }); 'delivered'",
"awaitPromise": true
}
})).await;
- let delivered_reauto_custom = take_response_by_id(&mut ctx, 35388);
- assert_eq!(
- delivered_reauto_custom["result"]["result"]["value"],
- json!("delivered")
- );
+ let delivered_custom_reject = take_response_by_id(&mut ctx, 35248);
+ assert_eq!(
+ delivered_custom_reject["result"]["result"]["value"],
+ json!("delivered")
+ );
- ctx.process_async(json!({
- "id": 35389,
- "method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
- "params": {
- "expression": "globalThis.__lm_reauto_new_target_custom_b",
- "awaitPromise": true
- }
- }))
- .await;
- let resolved_reauto_custom = take_response_by_id(&mut ctx, 35389);
- assert_eq!(
- resolved_reauto_custom["result"]["result"]["value"],
- json!("reauto-new-target-custom-b-ok")
- );
+ ctx.process_async(json!({
+ "id": 35249,
+ "method": "Runtime.evaluate",
+ "sessionId": auto_attached_session_id,
+ "params": {
+ "expression": "globalThis.__lm_auto_reattach_custom_b_reject",
+ "awaitPromise": true
+ }
+ }))
+ .await;
+ let rejected_custom = take_response_by_id(&mut ctx, 35249);
+ assert_eq!(
+ rejected_custom["result"]["result"]["value"],
+ json!("rejected:after-auto-attach-custom-b-error")
+ );
- ctx.process_async(json!({
- "id": 35390,
+ ctx.process_async(json!({
+ "id": 35250,
"method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": reauto_utility_context,
- "expression": "globalThis.__lm_reauto_new_target_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-pw-handle-reject'",
+ "contextId": reattached_utility_context,
+ "expression": "globalThis.__lm_auto_reattach_pw_handle_reject = __pw_keptHandleBinding(document.getElementById('utility-handle-b')).then(() => 'unexpected-success', error => `rejected:${error}`); 'scheduled-pw-handle-reject'",
"awaitPromise": true
}
})).await;
- let scheduled_reauto_handle_reject = take_response_by_id(&mut ctx, 35390);
- assert!(
- scheduled_reauto_handle_reject["result"]["result"]["value"]
- .as_str()
- .expect("scheduled re-auto handle reject value")
- .starts_with("scheduled-")
- );
- let reauto_handle_binding_called = ctx
+ let scheduled_handle_reject = take_response_by_id(&mut ctx, 35250);
+ assert!(
+ scheduled_handle_reject["result"]["result"]["value"]
+ .as_str()
+ .expect("scheduled handle reject value")
+ .starts_with("scheduled-")
+ );
+ let handle_reject_binding_called = ctx
.sent
.iter()
.rev()
.find(|message| {
message["method"] == json!("Runtime.bindingCalled")
- && message["sessionId"] == json!(reauto_attached_second_session_id)
+ && message["sessionId"] == json!(auto_attached_session_id)
&& message["params"]["name"] == json!("__pw_keptHandleBinding")
- && message["params"]["executionContextId"] == json!(reauto_utility_context)
+ && message["params"]["executionContextId"] == json!(reattached_utility_context)
})
.cloned()
- .expect("retained handle binding should emit Runtime.bindingCalled after re-auto-attaching the new target");
- let reauto_handle_payload = reauto_handle_binding_called["params"]["payload"]
- .as_str()
- .expect("re-auto handle payload should be string");
- let reauto_handle_payload: serde_json::Value = serde_json::from_str(reauto_handle_payload)
- .expect("re-auto handle payload should be valid json");
- let reauto_handle_seq = reauto_handle_payload["seq"]
- .as_i64()
- .expect("re-auto handle seq should be integer");
- assert_eq!(reauto_handle_seq, 1);
- ctx.sent.clear();
+ .expect("retained handle binding should emit Runtime.bindingCalled for rejection after auto-attach");
+ let handle_reject_payload = handle_reject_binding_called["params"]["payload"]
+ .as_str()
+ .expect("handle reject binding payload should be string");
+ let handle_reject_payload: serde_json::Value =
+ serde_json::from_str(handle_reject_payload)
+ .expect("handle reject binding payload should be valid json");
+ let handle_reject_seq = handle_reject_payload["seq"]
+ .as_i64()
+ .expect("handle reject payload seq should be integer");
+ assert_eq!(handle_reject_seq, 2);
+ ctx.sent.clear();
- ctx.process_async(json!({
- "id": 35391,
+ ctx.process_async(json!({
+ "id": 35251,
"method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": reauto_utility_context,
+ "contextId": reattached_utility_context,
"expression": format!(
- "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {reauto_handle_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {reauto_handle_seq} }})]); }})()"
+ "(() => {{ const handle = globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq} }}); return JSON.stringify([handle.id, handle.textContent, typeof globalThis.__lm_pw_kept_handle_binding_take({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq} }})]); }})()"
)
}
})).await;
- let taken_reauto_handle = take_response_by_id(&mut ctx, 35391);
- assert_eq!(
- taken_reauto_handle["result"]["result"]["value"],
- json!("[\"utility-handle-b\",\"replay-utility-handle-b\",\"undefined\"]")
- );
+ let taken_handle_reject = take_response_by_id(&mut ctx, 35251);
+ assert_eq!(
+ taken_handle_reject["result"]["result"]["value"],
+ json!("[\"utility-handle-b\",\"utility-handle-b\",\"undefined\"]")
+ );
- ctx.process_async(json!({
- "id": 35392,
+ ctx.process_async(json!({
+ "id": 35252,
"method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
+ "sessionId": auto_attached_session_id,
"params": {
- "contextId": reauto_utility_context,
+ "contextId": reattached_utility_context,
"expression": format!(
- "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {reauto_handle_seq}, error: 'reauto-new-target-pw-handle-error' }}); 'delivered'"
+ "globalThis.__lm_pw_kept_handle_binding_deliver({{ name: '__pw_keptHandleBinding', seq: {handle_reject_seq}, error: 'after-auto-attach-pw-handle-error' }}); 'delivered'"
),
"awaitPromise": true
}
})).await;
- let delivered_reauto_handle = take_response_by_id(&mut ctx, 35392);
- assert_eq!(
- delivered_reauto_handle["result"]["result"]["value"],
- json!("delivered")
- );
+ let delivered_handle_reject = take_response_by_id(&mut ctx, 35252);
+ assert_eq!(
+ delivered_handle_reject["result"]["result"]["value"],
+ json!("delivered")
+ );
- ctx.process_async(json!({
- "id": 35393,
- "method": "Runtime.evaluate",
- "sessionId": reauto_attached_second_session_id,
- "params": {
- "contextId": reauto_utility_context,
- "expression": "globalThis.__lm_reauto_new_target_pw_handle_reject",
- "awaitPromise": true
- }
- }))
- .await;
- let rejected_reauto_handle = take_response_by_id(&mut ctx, 35393);
- assert_eq!(
- rejected_reauto_handle["result"]["result"]["value"],
- json!("rejected:reauto-new-target-pw-handle-error")
- );
- });
+ ctx.process_async(json!({
+ "id": 35253,
+ "method": "Runtime.evaluate",
+ "sessionId": auto_attached_session_id,
+ "params": {
+ "contextId": reattached_utility_context,
+ "expression": "globalThis.__lm_auto_reattach_pw_handle_reject",
+ "awaitPromise": true
+ }
+ }))
+ .await;
+ let rejected_handle = take_response_by_id(&mut ctx, 35253);
+ assert_eq!(
+ rejected_handle["result"]["result"]["value"],
+ json!("rejected:after-auto-attach-pw-handle-error")
+ );
+ },
+ );
}
diff --git a/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs b/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
index 9756c249d..7a6782689 100644
--- a/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
+++ b/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
@@ -5672,7 +5672,7 @@ async fn playwright_over_cdp_context_persists_response_cookies_across_navigation
}
#[tokio::test(flavor = "multi_thread")]
-async fn playwright_over_cdp_context_reapplies_document_start_scripts_to_new_targets() {
+async fn playwright_over_cdp_target_document_start_script_does_not_leak_to_new_target() {
async fn handler() -> impl IntoResponse {
(
[(CONTENT_TYPE.as_str(), "text/html")],
@@ -5788,7 +5788,10 @@ async fn playwright_over_cdp_context_reapplies_document_start_scripts_to_new_tar
}))
.await;
let second_evaluation = take_response_by_id(&mut ctx, 2322);
- assert_eq!(second_evaluation["result"]["result"]["value"], json!(1));
+ assert_eq!(
+ second_evaluation["result"]["result"]["type"],
+ json!("undefined")
+ );
let active = ctx
.conn
@@ -5804,7 +5807,7 @@ async fn playwright_over_cdp_context_reapplies_document_start_scripts_to_new_tar
.owner_state
.document_start_scripts
.len(),
- 1
+ 0
);
server.abort();
diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_bindings.rs b/moli-protocol/src/domains/target/tests/tests_same_context_bindings.rs
index 400162010..7bfdae712 100644
--- a/moli-protocol/src/domains/target/tests/tests_same_context_bindings.rs
+++ b/moli-protocol/src/domains/target/tests/tests_same_context_bindings.rs
@@ -821,8 +821,7 @@ async fn same_context_targets_remove_only_their_own_utility_binding_definition_a
.as_ref()
.expect("active browser context");
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| {
@@ -835,7 +834,11 @@ async fn same_context_targets_remove_only_their_own_utility_binding_definition_a
.expect("first target should remain staged");
let staged_bindings = active
.parked_page_session_state(staged.target_id())
- .map(|state| state.devtools_session_state.runtime_bindings.as_slice())
+ .map(|state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .as_slice()
+ })
.unwrap_or(&[]);
assert!(!staged_bindings.iter().any(|binding| {
binding.name == "sharedUtilityBinding"
@@ -1011,8 +1014,7 @@ async fn same_context_targets_remove_only_their_own_main_world_binding_definitio
.as_ref()
.expect("active browser context");
assert!(
- active
- .devtools_session_state
+ active.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
.any(|binding| {
@@ -1024,7 +1026,11 @@ async fn same_context_targets_remove_only_their_own_main_world_binding_definitio
.expect("first target should remain staged");
let staged_bindings = active
.parked_page_session_state(staged.target_id())
- .map(|state| state.devtools_session_state.runtime_bindings.as_slice())
+ .map(|state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .as_slice()
+ })
.unwrap_or(&[]);
assert!(!staged_bindings.iter().any(|binding| {
binding.name == "sharedMainBinding" && binding.execution_context_name.is_none()
@@ -1233,7 +1239,7 @@ async fn same_context_targets_remove_only_their_own_dual_world_binding_definitio
.expect("active browser context");
assert!(
active
- .devtools_session_state
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_bindings
.iter()
@@ -1244,7 +1250,7 @@ async fn same_context_targets_remove_only_their_own_dual_world_binding_definitio
.expect("first target should remain staged");
let staged_bindings = active
.parked_page_session_state(staged.target_id())
- .map(|state| state.devtools_session_state.runtime_bindings.as_slice())
+ .map(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings.as_slice())
.unwrap_or(&[]);
assert_eq!(
staged_bindings
@@ -2660,28 +2666,26 @@ async fn same_context_targets_restore_only_their_own_utility_pre_document_bindin
let mut ctx = TestContext::new();
load_bc_with_target(&mut ctx, "BID-9", "TID-000000000E");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000F".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#second".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-0000000010".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#third".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000F".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#second".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-0000000010".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#third".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
ctx.process_async(json!({
"id": 10456,
diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs b/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs
index 8f554ee10..759f54350 100644
--- a/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs
+++ b/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs
@@ -147,7 +147,7 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swi
"method": "Runtime.evaluate",
"sessionId": "SID-active",
"params": {
- "expression": "JSON.stringify({ title: document.title, lang: navigator.language })"
+ "expression": "JSON.stringify({ title: document.title, lang: navigator.language, locale: Intl.DateTimeFormat().resolvedOptions().locale })"
}
}))
.await;
@@ -158,7 +158,8 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swi
let first_payload: serde_json::Value =
serde_json::from_str(first_payload).expect("first payload should be valid json");
assert_eq!(first_payload["title"], json!("first-restored"));
- assert_eq!(first_payload["lang"], json!("en-GB"));
+ assert_eq!(first_payload["lang"], json!("en-US"));
+ assert_eq!(first_payload["locale"], json!("en-GB"));
ctx.process_async(json!({
"id": 104168,
@@ -204,7 +205,7 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swi
"method": "Runtime.evaluate",
"sessionId": second_session_id,
"params": {
- "expression": "JSON.stringify({ title: document.title, lang: navigator.language })"
+ "expression": "JSON.stringify({ title: document.title, lang: navigator.language, locale: Intl.DateTimeFormat().resolvedOptions().locale })"
}
}))
.await;
@@ -215,7 +216,8 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swi
let second_payload: serde_json::Value =
serde_json::from_str(second_payload).expect("second payload should be valid json");
assert_eq!(second_payload["title"], json!("second-restored"));
- assert_eq!(second_payload["lang"], json!("fr-FR"));
+ assert_eq!(second_payload["lang"], json!("en-US"));
+ assert_eq!(second_payload["locale"], json!("fr-FR"));
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_state.rs b/moli-protocol/src/domains/target/tests/tests_same_context_state.rs
index 9cdbca6c1..8a83b4e7f 100644
--- a/moli-protocol/src/domains/target/tests/tests_same_context_state.rs
+++ b/moli-protocol/src/domains/target/tests/tests_same_context_state.rs
@@ -407,11 +407,8 @@ async fn same_context_targets_restore_their_own_crash_state_after_switching() {
.owner_state
.target_crash_state
.mark_crashed();
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.record_inspector_target_crashed();
@@ -623,17 +620,17 @@ async fn same_context_targets_restore_their_own_domain_enablement_after_switchin
.expect("active browser context");
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
assert!(
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
assert!(
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
assert!(
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -671,17 +668,17 @@ async fn same_context_targets_restore_their_own_domain_enablement_after_switchin
.expect("active browser context");
assert_eq!(bc.active_target_id(), Some(second_target_id.as_str()));
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -1275,11 +1272,8 @@ async fn same_context_targets_restore_their_own_crash_state_after_session_scoped
.owner_state
.target_crash_state
.mark_crashed();
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.record_inspector_target_crashed();
@@ -1531,9 +1525,9 @@ async fn same_context_targets_restore_their_own_domain_enablement_after_session_
.as_ref()
.expect("active browser context");
assert_eq!(bc.active_target_id(), Some("TID-000000000DS"));
- assert!(bc.devtools_session_state.page_session_state.page_lifecycle_events);
- assert!(bc.devtools_session_state.runtime_session_state.runtime_frontend_enabled);
- assert!(bc.devtools_session_state.runtime_session_state.inspector_enabled);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.page_lifecycle_events);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.inspector_enabled);
assert!(
bc.active_target
.runtime_slot
@@ -1569,9 +1563,9 @@ async fn same_context_targets_restore_their_own_domain_enablement_after_session_
.as_ref()
.expect("active browser context after session-scoped promotion");
assert_eq!(bc.active_target_id(), Some(second_target_id.as_str()));
- assert!(!bc.devtools_session_state.page_session_state.page_lifecycle_events);
- assert!(bc.devtools_session_state.runtime_session_state.runtime_frontend_enabled);
- assert!(!bc.devtools_session_state.runtime_session_state.inspector_enabled);
+ assert!(!bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.page_lifecycle_events);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled);
+ assert!(!bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.inspector_enabled);
assert!(
bc.active_target
.runtime_slot
@@ -1607,9 +1601,9 @@ async fn same_context_targets_restore_their_own_domain_enablement_after_session_
.as_ref()
.expect("active browser context after restoring first target");
assert_eq!(bc.active_target_id(), Some("TID-000000000DS"));
- assert!(bc.devtools_session_state.page_session_state.page_lifecycle_events);
- assert!(bc.devtools_session_state.runtime_session_state.runtime_frontend_enabled);
- assert!(bc.devtools_session_state.runtime_session_state.inspector_enabled);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.page_lifecycle_events);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled);
+ assert!(bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.inspector_enabled);
assert!(
bc.active_target
.runtime_slot
diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs b/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs
index f142dc88d..2ea14e51d 100644
--- a/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs
+++ b/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs
@@ -167,7 +167,7 @@ async fn get_target_info_reports_background_target_in_same_browser_context() {
.as_ref()
.expect("active browser context");
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
- assert_eq!(bc.background_targets.len(), 1);
+ assert_eq!(bc.background_target_count(), 1);
}
#[tokio::test(flavor = "multi_thread")]
@@ -508,7 +508,7 @@ async fn close_target_removes_background_target_without_disturbing_active_target
.as_ref()
.expect("active browser context");
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
- assert!(bc.background_targets.is_empty());
+ assert!(bc.has_no_background_targets());
}
#[tokio::test(flavor = "multi_thread")]
@@ -571,7 +571,7 @@ async fn close_active_target_promotes_background_target_to_active_slot() {
.expect("active browser context");
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
assert_eq!(bc.active_session_id(), Some("SID-active"));
- assert!(bc.background_targets.is_empty());
+ assert!(bc.has_no_background_targets());
}
#[tokio::test(flavor = "multi_thread")]
@@ -1345,28 +1345,26 @@ async fn activate_target_chain_restores_multiple_set_auto_attach_background_load
.attach_active_session("SID-active");
{
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000F".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#second".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-0000000010".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#third".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000F".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#second".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-0000000010".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#third".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
}
ctx.process_async(json!({
@@ -1546,28 +1544,26 @@ async fn close_target_restores_loaded_runtime_to_previous_set_auto_attach_target
.attach_active_session("SID-active");
{
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000F".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#second".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
- bc.background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-0000000010".into(),
- None,
- crate::conn::TargetIdentityState::new(
- "about:blank#third".into(),
- crate::conn::URL_BASE.into(),
- "Secure".into(),
- ),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000F".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#second".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
+ bc.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-0000000010".into(),
+ None,
+ crate::conn::TargetIdentityState::new(
+ "about:blank#third".into(),
+ crate::conn::URL_BASE.into(),
+ "Secure".into(),
+ ),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
}
ctx.process_async(json!({
@@ -1804,8 +1800,7 @@ async fn page_command_on_background_target_session_routes_without_promoting_load
.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(crate::conn::BackgroundTarget::new(
+ .insert_page_target_host(crate::conn::PageTargetHost::new(
"TID-000000000F".into(),
Some("SID-bg".into()),
crate::conn::TargetIdentityState::new(
@@ -1891,7 +1886,7 @@ async fn close_target_aborts_paused_request_stage_navigation() {
let mut bc = BrowserContext::new("BID-9".into());
bc.set_active_target_id("TID-000000000A");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -1949,11 +1944,7 @@ async fn close_target_aborts_paused_request_stage_navigation() {
assert!(!bc.has_active_target());
assert!(!bc.has_active_session());
assert!(!bc.has_loaded_page());
- assert!(
- !bc.active_target
- .fetch_owner
- .has_pending_fetch_state_for_test()
- );
+ assert!(bc.page_target("TID-000000000A").is_none());
server.abort();
}
@@ -2076,11 +2067,7 @@ async fn close_target_aborts_paused_runtime_fetch_subresource() {
assert!(!bc.has_active_target());
assert!(!bc.has_active_session());
assert!(!bc.has_loaded_page());
- assert!(
- !bc.active_target
- .fetch_owner
- .has_pending_fetch_state_for_test()
- );
+ assert!(bc.page_target("TID-000000000A").is_none());
server.abort();
}
@@ -2581,7 +2568,7 @@ async fn playwright_over_cdp_context_target_attach_and_navigate_smoke() {
"method": "Runtime.evaluate",
"sessionId": session_id,
"params": {
- "expression": "JSON.stringify({ marker: document.body.dataset.marker, lang: navigator.language, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, dark: matchMedia('(prefers-color-scheme: dark)').matches })"
+ "expression": "JSON.stringify({ marker: document.body.dataset.marker, lang: navigator.language, locale: Intl.DateTimeFormat().resolvedOptions().locale, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, dark: matchMedia('(prefers-color-scheme: dark)').matches })"
}
}))
.await;
@@ -2592,7 +2579,8 @@ async fn playwright_over_cdp_context_target_attach_and_navigate_smoke() {
let payload: serde_json::Value =
serde_json::from_str(payload).expect("evaluation payload should be valid json");
assert_eq!(payload["marker"], "seeded");
- assert_eq!(payload["lang"], "fr-FR");
+ assert_eq!(payload["lang"], "en-US");
+ assert_eq!(payload["locale"], "fr-FR");
assert_eq!(payload["tz"], "UTC");
assert_eq!(payload["dark"], true);
diff --git a/moli-protocol/src/domains/target/tests/tests_target_attachment.rs b/moli-protocol/src/domains/target/tests/tests_target_attachment.rs
index 4b2c52f0a..4a8da9ab3 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_attachment.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_attachment.rs
@@ -765,9 +765,15 @@ async fn attach_to_target_keeps_background_target_parked() {
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
- assert_eq!(bc.background_targets.len(), 1);
- assert_eq!(bc.background_targets[0].target_id(), "TID-000000000B");
- assert_eq!(bc.background_targets[0].session_id(), Some("SID-1"));
+ assert_eq!(bc.background_target_count(), 1);
+ assert_eq!(
+ bc.background_target_at(0).unwrap().target_id(),
+ "TID-000000000B"
+ );
+ assert_eq!(
+ bc.background_target_at(0).unwrap().session_id(),
+ Some("SID-1")
+ );
}
#[tokio::test(flavor = "multi_thread")]
@@ -1264,14 +1270,12 @@ async fn session_route_finds_browser_active_auxiliary_background_and_inactive_se
let mut inactive = BrowserContext::new("BID-B".to_owned());
inactive.set_active_target_id("TID-000000000C".to_owned());
inactive.attach_active_session("SID-inactive");
- inactive
- .background_targets
- .push(crate::conn::BackgroundTarget::new(
- "TID-000000000D".to_owned(),
- Some("SID-inactive-background".to_owned()),
- crate::conn::TargetIdentityState::about_blank(),
- crate::conn::TargetPageSlot::empty_for_test_fixture(),
- ));
+ inactive.insert_page_target_host(crate::conn::PageTargetHost::new(
+ "TID-000000000D".to_owned(),
+ Some("SID-inactive-background".to_owned()),
+ crate::conn::TargetIdentityState::about_blank(),
+ crate::conn::TargetPageSlot::empty_for_test_fixture(),
+ ));
assert!(inactive.assign_auxiliary_session_to_target(
"TID-000000000D",
"SID-inactive-aux-background".to_owned()
@@ -1308,7 +1312,7 @@ async fn session_route_finds_browser_active_auxiliary_background_and_inactive_se
);
assert_eq!(
ctx.conn.session_route(Some("SID-background")),
- Some(CdpSessionRoute::BackgroundTarget {
+ Some(CdpSessionRoute::PageTargetHost {
browser_context_id: "BID-A".to_owned(),
target_id: "TID-000000000B".to_owned(),
})
@@ -1362,8 +1366,7 @@ async fn session_route_finds_browser_active_auxiliary_background_and_inactive_se
|bc, target_id| {
assert_eq!(bc.id, "BID-B");
bc.mutate_parked_page_session_state(target_id, |state| {
- state
- .devtools_session_state
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled = true;
});
@@ -1384,8 +1387,8 @@ async fn session_route_finds_browser_active_auxiliary_background_and_inactive_se
assert_eq!(bc.id, "BID-B");
let mut console_enabled = false;
bc.mutate_parked_page_session_state(target_id, |state| {
- console_enabled = state
- .devtools_session_state
+ console_enabled = state.devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.console_output_session_state
.console_enabled;
});
@@ -1533,13 +1536,13 @@ async fn detach_from_target() {
ctx.expect_result(11, json!({ "sessionId": sid }), None);
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -1567,17 +1570,17 @@ async fn detach_from_target() {
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert!(!bc.has_active_session());
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
@@ -1796,6 +1799,181 @@ async fn detach_from_target_drops_only_selected_page_renderer_inspector_session(
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn detach_from_target_removes_only_selected_session_document_start_scripts() {
+ let mut ctx = TestContext::new();
+ load_bc_with_titled_page_async(
+ &mut ctx,
+ "BID-detach-preload",
+ "TID-detach-preload",
+ "<!doctype html><body>detach preload</body>",
+ )
+ .await;
+ {
+ let browser_context = ctx.conn.browser_context.as_mut().unwrap();
+ browser_context.attach_active_session("SID-preload-primary");
+ assert!(browser_context.assign_auxiliary_session_to_target(
+ "TID-detach-preload",
+ "SID-preload-aux".to_owned(),
+ ));
+ }
+ ctx.sent.clear();
+
+ for (id, session_id, source) in [
+ (
+ 120_101,
+ "SID-preload-primary",
+ "globalThis.__primaryPreload = 'primary';",
+ ),
+ (
+ 120_102,
+ "SID-preload-aux",
+ "globalThis.__auxPreload = 'auxiliary';",
+ ),
+ ] {
+ ctx.process_async(json!({
+ "id": id,
+ "sessionId": session_id,
+ "method": "Page.addScriptToEvaluateOnNewDocument",
+ "params": { "source": source }
+ }))
+ .await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, id)["result"]["identifier"],
+ json!("1"),
+ "each DevTools session must own an independent script identifier namespace"
+ );
+ }
+
+ ctx.process_async(json!({
+ "id": 120_107,
+ "sessionId": "SID-preload-aux",
+ "method": "Page.addScriptToEvaluateOnNewDocument",
+ "params": { "source": "globalThis.__auxSecondPreload = 'auxiliary-2';" }
+ }))
+ .await;
+ ctx.expect_result(
+ 120_107,
+ json!({ "identifier": "2" }),
+ Some("SID-preload-aux"),
+ );
+
+ ctx.process_async(json!({
+ "id": 120_108,
+ "sessionId": "SID-preload-aux",
+ "method": "Page.removeScriptToEvaluateOnNewDocument",
+ "params": { "identifier": "1" }
+ }))
+ .await;
+ ctx.expect_result(120_108, json!({}), Some("SID-preload-aux"));
+ ctx.process_async(json!({
+ "id": 120_109,
+ "sessionId": "SID-preload-aux",
+ "method": "Page.removeScriptToEvaluateOnNewDocument",
+ "params": { "identifier": "1" }
+ }))
+ .await;
+ ctx.expect_error(120_109, -32000, "Script not found");
+ {
+ let owner_state = &ctx
+ .conn
+ .browser_context
+ .as_ref()
+ .unwrap()
+ .active_target
+ .owner_state;
+ assert_eq!(owner_state.document_start_scripts.len(), 2);
+ assert!(
+ owner_state
+ .document_start_scripts
+ .iter()
+ .any(|(identifier, script)| {
+ identifier == "1"
+ && script.devtools_session
+ == Some(moli_page_types::DevToolsSessionKey::Primary)
+ })
+ );
+ assert!(
+ owner_state
+ .document_start_scripts
+ .iter()
+ .any(|(identifier, script)| {
+ identifier == "2"
+ && script.devtools_session
+ == Some(moli_page_types::DevToolsSessionKey::Attached(
+ "SID-preload-aux".to_owned(),
+ ))
+ })
+ );
+ }
+
+ ctx.process_async(json!({
+ "id": 120_103,
+ "method": "Target.detachFromTarget",
+ "params": {
+ "targetId": "TID-detach-preload",
+ "sessionId": "SID-preload-aux"
+ }
+ }))
+ .await;
+ ctx.expect_result(120_103, json!({}), None);
+ ctx.expect_event(
+ "Target.detachedFromTarget",
+ Some(&json!({
+ "targetId": "TID-detach-preload",
+ "sessionId": "SID-preload-aux"
+ })),
+ );
+
+ {
+ let owner_state = &ctx
+ .conn
+ .browser_context
+ .as_ref()
+ .unwrap()
+ .active_target
+ .owner_state;
+ assert_eq!(owner_state.document_start_scripts.len(), 1);
+ assert_eq!(
+ owner_state
+ .document_start_scripts
+ .iter()
+ .filter_map(|(_, script)| script.devtools_session.clone())
+ .collect::<Vec<_>>(),
+ vec![moli_page_types::DevToolsSessionKey::Primary]
+ );
+ }
+
+ ctx.process_async(json!({
+ "id": 120_105,
+ "sessionId": "SID-preload-primary",
+ "method": "Page.navigate",
+ "params": { "url": "data:text/html,<body>replacement</body>" }
+ }))
+ .await;
+ consume_main_document_navigation_start(&mut ctx);
+ let navigation = take_response_by_id(&mut ctx, 120_105);
+ assert_eq!(navigation["result"]["frameId"], json!("TID-detach-preload"));
+ ctx.take_all();
+
+ ctx.process_async(json!({
+ "id": 120_106,
+ "sessionId": "SID-preload-primary",
+ "method": "Runtime.evaluate",
+ "params": {
+ "expression": "JSON.stringify({ primary: globalThis.__primaryPreload ?? null, auxiliary: globalThis.__auxPreload ?? null })",
+ "returnByValue": true
+ }
+ }))
+ .await;
+ let replacement = take_response_by_id(&mut ctx, 120_106);
+ assert_eq!(
+ replacement["result"]["result"]["value"],
+ json!(r#"{"primary":"primary","auxiliary":null}"#),
+ "only the surviving session script must replay into the replacement Document"
+ );
+}
+
async fn page_renderer_inspector_session_count(ctx: &mut TestContext) -> u64 {
let response = ctx
.conn
@@ -2007,13 +2185,13 @@ async fn set_auto_attach_false_detaches_existing_target() {
load_bc_with_target(&mut ctx, "BID-9", "TID-000000000D");
let bc = ctx.conn.browser_context.as_mut().unwrap();
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -2073,17 +2251,17 @@ async fn set_auto_attach_false_detaches_existing_target() {
assert!(!bc.has_active_session());
assert_eq!(bc.active_target_id(), Some("TID-000000000D"));
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events
);
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled
);
assert!(
- !bc.devtools_session_state
+ !bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled
);
diff --git a/moli-protocol/src/domains/target/tests/tests_target_basics.rs b/moli-protocol/src/domains/target/tests/tests_target_basics.rs
index 67f60de3e..e4e77fe10 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_basics.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_basics.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::conn::BackgroundTarget;
+use crate::conn::PageTargetHost;
#[tokio::test(flavor = "multi_thread")]
async fn get_browser_contexts_returns_active_and_inactive_ids() {
@@ -42,7 +42,7 @@ async fn close_active_target_fails_only_active_owner_pending_awaits() {
let mut bc = BrowserContext::new("BID-await-owner".into());
bc.set_active_target_id("TID-active-await".to_owned());
bc.attach_active_session("SID-active-await".to_owned());
- bc.background_targets.push(BackgroundTarget::with_url(
+ bc.insert_page_target_host(PageTargetHost::with_url(
"TID-bg-await".to_owned(),
Some("SID-bg-await".to_owned()),
"about:blank#bg-await".to_owned(),
@@ -98,8 +98,8 @@ async fn create_browser_context_records_proxy_server_override() {
.expect("active browser context");
(
active.id.clone(),
- active.http_proxy_override.clone(),
- active.http_no_proxy_override.clone(),
+ active.default_http_proxy_override.clone(),
+ active.default_http_no_proxy_override.clone(),
)
};
ctx.expect_result(41, json!({ "browserContextId": active_id }), None);
@@ -129,7 +129,10 @@ async fn create_browser_context_preserves_non_loopback_proxy_bypass_entries() {
.browser_context
.as_ref()
.expect("active browser context");
- (active.id.clone(), active.http_no_proxy_override.clone())
+ (
+ active.id.clone(),
+ active.default_http_no_proxy_override.clone(),
+ )
};
ctx.expect_result(42, json!({ "browserContextId": active_id }), None);
assert_eq!(active_no_proxy.as_deref(), Some("example.com,.internal"));
@@ -248,7 +251,7 @@ async fn dispose_browser_context_aborts_paused_request_stage_navigation() {
let mut bc = BrowserContext::new("BID-9".into());
bc.set_active_target_id("TID-000000000A");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -1625,7 +1628,7 @@ async fn same_context_targets_do_not_replay_bare_isolated_worlds_after_switching
.active_target
.runtime_slot
.replace_loaded_page(Some(first_page));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
}
@@ -1715,11 +1718,8 @@ async fn same_context_targets_do_not_replay_bare_isolated_worlds_after_switching
second_promote["result"]["result"]["value"],
json!("second-target")
);
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
@@ -1752,11 +1752,8 @@ async fn same_context_targets_do_not_replay_bare_isolated_worlds_after_switching
.is_empty(),
"target activation must not turn a document-scoped world into persistent state"
);
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
let target_a_replay_url =
@@ -1816,11 +1813,8 @@ async fn same_context_targets_do_not_replay_bare_isolated_worlds_after_switching
}))
.await;
ctx.expect_result(104157, json!({}), None);
- ctx.conn
- .browser_context
- .as_mut()
- .unwrap()
- .devtools_session_state
+ ctx.conn.browser_context.as_mut().unwrap().devtools_sessions
+ [moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
diff --git a/moli-protocol/src/domains/target/tests/tests_target_creation.rs b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
index e770a6316..e7fd7e71f 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_creation.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
@@ -1461,7 +1461,7 @@ async fn resetting_opener_target_clears_live_opener_but_keeps_frame_attribution(
.browser_context
.as_mut()
.unwrap()
- .reset_active_target_slot_to_empty_async()
+ .remove_active_page_target_async()
.await;
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
@@ -1904,9 +1904,12 @@ async fn window_open_named_target_reused_in_same_command_emits_one_page_event()
"same-command named reuse must create one target: {sent:?}"
);
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
- assert_eq!(browser_context.background_targets.len(), 1);
+ assert_eq!(browser_context.background_target_count(), 1);
assert_eq!(
- browser_context.background_targets[0].target_url(),
+ browser_context
+ .background_target_at(0)
+ .unwrap()
+ .target_url(),
"https://example.com/second-popup"
);
}
@@ -3523,8 +3526,8 @@ async fn create_target_with_background_true_stages_second_target_in_background_s
let created = take_created_target_id(&mut ctx, 10);
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
- assert_eq!(bc.background_targets.len(), 1);
- assert_eq!(bc.background_targets[0].target_id(), created);
+ assert_eq!(bc.background_target_count(), 1);
+ assert_eq!(bc.background_target_at(0).unwrap().target_id(), created);
}
#[tokio::test(flavor = "multi_thread")]
@@ -3546,8 +3549,8 @@ async fn create_target_with_focus_false_stages_second_target_in_background_slot(
let created = take_created_target_id(&mut ctx, 11);
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
- assert_eq!(bc.background_targets.len(), 1);
- assert_eq!(bc.background_targets[0].target_id(), created);
+ assert_eq!(bc.background_target_count(), 1);
+ assert_eq!(bc.background_target_at(0).unwrap().target_id(), created);
}
#[tokio::test(flavor = "multi_thread")]
@@ -3573,5 +3576,5 @@ async fn create_target_rejects_focus_in_background() {
);
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert_eq!(bc.active_target_id(), Some("TID-000000000A"));
- assert!(bc.background_targets.is_empty());
+ assert!(bc.has_no_background_targets());
}
diff --git a/moli-protocol/src/domains/target/tests/tests_target_management.rs b/moli-protocol/src/domains/target/tests/tests_target_management.rs
index a21120dd1..5626715c5 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_management.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_management.rs
@@ -1,5 +1,4 @@
use super::*;
-use crate::conn::ParkedPageSessionState;
/// cdp.target: closeTarget – no browser context
#[tokio::test(flavor = "multi_thread")]
@@ -39,13 +38,13 @@ async fn close_target_success() {
let mut ctx = TestContext::new();
load_bc_with_target(&mut ctx, "BID-9", "TID-000000000A");
let bc = ctx.conn.browser_context.as_mut().unwrap();
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_lifecycle_events = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.runtime_frontend_enabled = true;
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -87,53 +86,8 @@ async fn close_target_success() {
assert!(!bc.has_active_target());
assert!(!bc.has_active_session());
assert!(!bc.has_loaded_page());
- assert!(!bc.active_target.owner_state.target_crash_state.is_crashed());
- assert_eq!(bc.target_security_origin(), crate::conn::URL_BASE);
- assert_eq!(bc.target_secure_context_type(), "Secure");
- assert_eq!(bc.next_network_request_sequence_for_test(), 0);
- assert_eq!(bc.subresource_network_emitted_record_count_for_test(), 0);
- assert_eq!(bc.next_io_stream_sequence_for_test(), 0);
- assert_eq!(
- bc.active_target
- .runtime_slot
- .next_subresource_fetch_request_id_for_test(),
- 0
- );
- assert!(
- !bc.devtools_session_state
- .page_session_state
- .page_lifecycle_events
- );
- assert!(
- !bc.devtools_session_state
- .runtime_session_state
- .runtime_frontend_enabled
- );
- assert!(
- !bc.devtools_session_state
- .runtime_session_state
- .inspector_enabled
- );
- assert!(
- !bc.active_target
- .runtime_slot
- .primary_network_events_enabled()
- );
- assert!(!bc.network_policy.cache_disabled());
- assert!(!bc.network_policy.bypass_service_worker());
- assert!(!bc.css_enabled);
- assert!(!bc.active_target.fetch_owner.is_enabled());
- assert!(!bc.active_target.fetch_owner.handle_auth_requests());
- assert!(
- bc.active_target
- .fetch_owner
- .config_snapshot()
- .patterns()
- .is_empty()
- );
- assert!(bc.network_policy.extra_headers().is_empty());
- assert!(bc.captured_response_bodies_empty_for_test());
- assert!(bc.io_streams_empty_for_test());
+ assert!(bc.page_target("TID-000000000A").is_none());
+ assert_eq!(bc.background_target_count(), 0);
}
#[tokio::test(flavor = "multi_thread")]
@@ -342,7 +296,7 @@ async fn close_target_emits_detached_events() {
let bc = ctx.conn.browser_context.as_mut().unwrap();
bc.attach_active_session(session_id.clone());
assert!(bc.assign_auxiliary_session_to_target("TID-000000000A", "SID-aux".into()));
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
@@ -417,12 +371,12 @@ async fn close_target_invalidates_runtime_context_and_object_without_active_page
let mut bc = BrowserContext::new("BID-runtime-close".into());
bc.set_active_target_id("TID-active");
bc.attach_active_session("SID-active");
- let background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::PageTargetHost::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
"about:blank".to_owned(),
);
- bc.background_targets.push(background_target);
+ bc.insert_page_target_host(background_target);
ctx.conn.browser_context = Some(bc);
ctx.install_navigation_fixture_for_session_owner(
"data:text/html,<html><body><script>globalThis.__lm_closed_target_marker = 'active-clean';</script>active</body></html>",
@@ -562,19 +516,16 @@ async fn close_background_target_emits_detached_events_and_clears_attached_sessi
);
let bc = ctx.conn.browser_context.as_mut().unwrap();
assert!(bc.assign_auxiliary_session_to_target("TID-000000000B", "SID-aux".into()));
- bc.replace_parked_page_session_state(
- "TID-000000000B".into(),
- ParkedPageSessionState {
- devtools_session_state: crate::conn::DevToolsSessionState {
+ bc.mutate_parked_page_session_state("TID-000000000B", |state| {
+ state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =
+ crate::conn::DevToolsSessionState {
runtime_session_state: crate::conn::TargetRuntimeSessionState {
inspector_enabled: true,
..Default::default()
},
..Default::default()
- },
- ..Default::default()
- },
- );
+ };
+ });
ctx.process_async(json!({
"id": 121,
@@ -633,7 +584,7 @@ async fn close_target_aborts_paused_request_stage_navigation() {
let mut bc = BrowserContext::new("BID-9".into());
bc.set_active_target_id("TID-000000000A");
bc.attach_active_session("SID-1");
- bc.devtools_session_state
+ bc.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.runtime_session_state
.inspector_enabled = true;
bc.active_target
@@ -691,11 +642,7 @@ async fn close_target_aborts_paused_request_stage_navigation() {
assert!(!bc.has_active_target());
assert!(!bc.has_active_session());
assert!(!bc.has_loaded_page());
- assert!(
- !bc.active_target
- .fetch_owner
- .has_pending_fetch_state_for_test()
- );
+ assert!(bc.page_target("TID-000000000A").is_none());
server.abort();
}
@@ -818,11 +765,7 @@ async fn close_target_aborts_paused_runtime_fetch_subresource() {
assert!(!bc.has_active_target());
assert!(!bc.has_active_session());
assert!(!bc.has_loaded_page());
- assert!(
- !bc.active_target
- .fetch_owner
- .has_pending_fetch_state_for_test()
- );
+ assert!(bc.page_target("TID-000000000A").is_none());
server.abort();
}
@@ -1226,8 +1169,11 @@ async fn activate_target_promotes_background_target_into_active_slot() {
let bc = ctx.conn.browser_context.as_ref().unwrap();
assert_eq!(bc.active_target_id(), Some("TID-000000000B"));
- assert_eq!(bc.background_targets.len(), 1);
- assert_eq!(bc.background_targets[0].target_id(), "TID-000000000A");
+ assert_eq!(bc.background_target_count(), 1);
+ assert_eq!(
+ bc.background_target_at(0).unwrap().target_id(),
+ "TID-000000000A"
+ );
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-protocol/src/domains/target/worker_target.rs b/moli-protocol/src/domains/target/worker_target.rs
index 3da1456ac..cd06fac0d 100644
--- a/moli-protocol/src/domains/target/worker_target.rs
+++ b/moli-protocol/src/domains/target/worker_target.rs
@@ -3986,8 +3986,7 @@ mod tests {
conn.browser_context
.as_mut()
.unwrap()
- .background_targets
- .push(crate::conn::BackgroundTarget::with_url(
+ .insert_page_target_host(crate::conn::PageTargetHost::with_url(
"TID-other-page".to_owned(),
Some("SID-other-page".to_owned()),
"about:blank".to_owned(),
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
index 0cf5f6868..918120990 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
@@ -704,16 +704,6 @@ fn navigator_runtime_data_getter_callback<'s>(
}
return;
}
- if key == "language" {
- let locale_override = context_host_ptr_from_global_bridge(scope)
- .and_then(|host_ptr| unsafe { (&*host_ptr).locale_override().map(str::to_owned) })
- .filter(|locale| !locale.is_empty());
- if let Some(locale) = locale_override.as_deref() {
- let value = v8_string(scope, locale).unwrap_or_else(|| v8::String::empty(scope));
- rv.set(value.into());
- return;
- }
- }
match backing.get(scope, v8str(scope, key).into()) {
Some(value) => rv.set(value),
None => rv.set(v8::undefined(scope).into()),
@@ -1129,12 +1119,6 @@ fn effective_navigator_languages<'s>(
scope: &mut v8::PinScope<'s, '_>,
backing: v8::Local<'s, v8::Object>,
) -> Vec<String> {
- if let Some(locale) = context_host_ptr_from_global_bridge(scope)
- .and_then(|host_ptr| unsafe { (&*host_ptr).locale_override().map(str::to_owned) })
- .filter(|locale| !locale.is_empty())
- {
- return vec![locale];
- }
navigator_identity_from_backing(scope, backing)
.languages()
.to_vec()
diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rs
index fd07faf6e..147223654 100644
--- a/moli-renderer-v8/src/runtime/page_dom.rs
+++ b/moli-renderer-v8/src/runtime/page_dom.rs
@@ -1366,7 +1366,7 @@ impl PageVm {
)?;
}
for binding in stored_runtime_bindings {
- if session_runtime_bindings.contains(binding) {
+ if binding.devtools_session.is_some() || session_runtime_bindings.contains(binding) {
continue;
}
self.install_runtime_binding(
@@ -1428,36 +1428,37 @@ impl PageVm {
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
- let had_world = match frame_id {
- Some(frame_id) => self.has_isolated_world_named_for_frame(frame_id, name),
- None => self.has_isolated_world_named(name),
- };
+ let devtools_session = DevToolsSessionKey::from_wire_session_id(
+ inspector_session_id.filter(|session_id| !session_id.is_empty()),
+ );
+ let had_world =
+ self.vm()
+ .has_isolated_world_for_owner(Some(&devtools_session), frame_id, name);
let execution_context_id = match frame_id {
- Some(frame_id) => {
- self.create_isolated_world_for_frame(frame_id, name, grant_universal_access)?
- }
- None => self.create_isolated_world(name, grant_universal_access)?,
+ Some(frame_id) => self.vm_mut().ensure_isolated_world_for_frame_owner(
+ Some(&devtools_session),
+ frame_id,
+ name,
+ grant_universal_access,
+ )?,
+ None => self.vm_mut().ensure_isolated_world_for_owner(
+ Some(&devtools_session),
+ name,
+ grant_universal_access,
+ )?,
};
- let runtime_bindings =
- self.inspector_session_runtime_bindings_for_world(inspector_session_id, name);
- for binding in runtime_bindings {
- if let Err(error) =
- self.install_runtime_binding(&binding.name, Some(name), Some(execution_context_id))
- {
- tracing::debug!(
- %error,
- execution_context_id,
- world_name = name,
- binding_name = binding.name.as_str(),
- "isolated world binding install failed after context creation"
- );
- }
+ for binding in self.inspector_session_runtime_bindings_for_world(inspector_session_id, name)
+ {
+ self.install_runtime_binding(&binding.name, Some(name), Some(execution_context_id))?;
}
if !had_world {
let scripts = self
.document_start_scripts
.iter()
- .filter(|script| script.world_name.as_deref() == Some(name))
+ .filter(|script| {
+ script.world_name.as_deref() == Some(name)
+ && script.devtools_session.as_ref() == Some(&devtools_session)
+ })
.cloned()
.collect::<Vec<_>>();
for script in scripts {
@@ -3771,11 +3772,33 @@ impl PageVm {
let mut created_world_before_script = false;
if let Some(world_name) = script.world_name.as_deref() {
- let runtime_bindings =
- self.inspector_session_runtime_bindings_for_world(inspector_session_id, world_name);
- if !runtime_bindings.is_empty() && !self.has_isolated_world_named(world_name) {
- let execution_context_id = self.create_isolated_world(world_name, false)?;
- created_world_before_script = true;
+ let session_key = DevToolsSessionKey::from_wire_session_id(
+ inspector_session_id.filter(|session_id| !session_id.is_empty()),
+ );
+ let runtime_bindings = if script.devtools_session.as_ref() == Some(&session_key) {
+ self.inspector_session_runtime_bindings_for_world(inspector_session_id, world_name)
+ } else {
+ self.runtime_bindings
+ .iter()
+ .filter(|binding| {
+ binding.devtools_session.as_ref() == script.devtools_session.as_ref()
+ && binding.execution_context_name.as_deref() == Some(world_name)
+ })
+ .cloned()
+ .collect()
+ };
+ if !runtime_bindings.is_empty() {
+ let had_world = self.vm().has_isolated_world_for_owner(
+ script.devtools_session.as_ref(),
+ None,
+ world_name,
+ );
+ let execution_context_id = self.vm_mut().ensure_isolated_world_for_owner(
+ script.devtools_session.as_ref(),
+ world_name,
+ false,
+ )?;
+ created_world_before_script = !had_world;
for binding in runtime_bindings {
self.install_runtime_binding(
&binding.name,
@@ -3898,12 +3921,16 @@ impl PageVm {
&mut self,
inspector_session_id: Option<&str>,
) -> bool {
- let detached = self
- .vm_mut()
- .detach_runtime_inspector_session(inspector_session_id);
let session_key = DevToolsSessionKey::from_wire_session_id(
inspector_session_id.filter(|session_id| !session_id.is_empty()),
);
+ self.runtime_bindings
+ .retain(|binding| binding.devtools_session.as_ref() != Some(&session_key));
+ let runtime_bindings = self.runtime_bindings.clone();
+ self.vm_mut().set_stored_runtime_bindings(&runtime_bindings);
+ let detached = self
+ .vm_mut()
+ .detach_runtime_inspector_session(inspector_session_id);
self.runtime_inspector_protocol_configurations
.remove(&session_key);
detached
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index 0338f9fda..c6eda3047 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -2237,20 +2237,31 @@ impl PageVm {
fn ensure_named_world_ready_for_document_start_script(
&mut self,
- world_name: &str,
+ script: &DocumentStartScript,
) -> Result<i64> {
- let execution_context_id = self.vm_mut().ensure_isolated_world(world_name, false)?;
+ let world_name = script
+ .world_name
+ .as_deref()
+ .expect("named-world document-start script must carry its world name");
+ let execution_context_id = self.vm_mut().ensure_isolated_world_for_owner(
+ script.devtools_session.as_ref(),
+ world_name,
+ false,
+ )?;
let matching_bindings = self
.runtime_bindings
.iter()
- .filter(|binding| binding.execution_context_name.as_deref() == Some(world_name))
+ .filter(|binding| {
+ binding.devtools_session.as_ref() == script.devtools_session.as_ref()
+ && binding.execution_context_name.as_deref() == Some(world_name)
+ })
.cloned()
.collect::<Vec<_>>();
for binding in &matching_bindings {
self.vm_mut().install_runtime_binding(
&binding.name,
binding.execution_context_name.as_deref(),
- None,
+ Some(execution_context_id),
)?;
}
Ok(execution_context_id)
@@ -2262,7 +2273,10 @@ impl PageVm {
"runtime binding replay must execute on the matching named owner lane"
);
let runtime_bindings = self.runtime_bindings.clone();
- for binding in runtime_bindings {
+ for binding in runtime_bindings
+ .into_iter()
+ .filter(|binding| binding.devtools_session.is_none())
+ {
self.vm_mut().install_runtime_binding(
&binding.name,
binding.execution_context_name.as_deref(),
@@ -2354,9 +2368,9 @@ impl PageVm {
for script in document_start_scripts {
let script_started = Instant::now();
match script.world_name.as_deref() {
- Some(world_name) => {
+ Some(_) => {
let execution_context_id =
- self.ensure_named_world_ready_for_document_start_script(world_name)?;
+ self.ensure_named_world_ready_for_document_start_script(script)?;
self.vm_mut()
.exec_in_execution_context(execution_context_id, &script.source)?;
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization_completion.rs b/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization_completion.rs
index 4663d313a..afcd69140 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization_completion.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization_completion.rs
@@ -10,6 +10,7 @@ fn install_two_child_document_start_scripts(page_vm: &mut PageVm) {
page_vm.vm_mut().set_stored_document_start_scripts(&[
crate::DocumentStartScript {
registry_key: Some("realm-completion-first".to_owned()),
+ devtools_session: None,
source: r#"
parent.__childRealmCompletionOrder.push("first-body");
Promise.resolve().then(() => {
@@ -23,6 +24,7 @@ Promise.resolve().then(() => {
},
crate::DocumentStartScript {
registry_key: Some("realm-completion-second".to_owned()),
+ devtools_session: None,
source: r#"
parent.__childRealmCompletionOrder.push("second-body");
"#
@@ -134,6 +136,7 @@ async fn child_realm_materialization_creates_named_preload_world_in_the_selected
page_vm.set_stored_document_start_scripts(&[crate::DocumentStartScript {
registry_key: Some("child-named-world-script".to_owned()),
+ devtools_session: None,
source: "globalThis.__childNamedWorldReady = 'ready';".to_owned(),
world_name: Some("child-utility".to_owned()),
has_bidi_channel_argument: false,
@@ -141,6 +144,7 @@ async fn child_realm_materialization_creates_named_preload_world_in_the_selected
}]);
page_vm.set_stored_runtime_bindings(&[
crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "childNamedBinding".to_owned(),
execution_context_name: Some("child-utility".to_owned()),
},
@@ -185,6 +189,56 @@ async fn child_realm_materialization_creates_named_preload_world_in_the_selected
.expect("child named-world materialization witness should run");
}
+#[tokio::test(flavor = "current_thread")]
+async fn detached_session_binding_is_not_installed_in_a_later_child_realm() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let document_url =
+ Url::parse("https://example.com/detached-session-child-binding").unwrap();
+ let (mut page_vm, _resource_source, _owner_wake_rx) =
+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);
+ let session_a =
+ moli_page_types::DevToolsSessionKey::from_wire_session_id(Some("session-a"));
+ let session_b =
+ moli_page_types::DevToolsSessionKey::from_wire_session_id(Some("session-b"));
+ let binding =
+ |devtools_session, name: &str| crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: Some(devtools_session),
+ name: name.to_owned(),
+ execution_context_name: None,
+ };
+ let bindings = [
+ binding(session_a, "detachedChildBinding"),
+ binding(session_b, "liveChildBinding"),
+ ];
+ page_vm.set_stored_runtime_bindings(&bindings);
+ page_vm
+ .vm_mut()
+ .ensure_runtime_inspector_session(Some("session-a"));
+
+ assert!(page_vm.detach_runtime_inspector_session(Some("session-a")));
+ queue_child_realm_materialization(&mut page_vm, "post-detach-binding-child")?;
+ page_vm
+ .run_child_realm_materialization_body_for_test()?
+ .expect("the post-detach child realm should materialize");
+
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ r#"JSON.stringify([
+typeof document.getElementById("post-detach-binding-child").contentWindow.detachedChildBinding,
+typeof document.getElementById("post-detach-binding-child").contentWindow.liveChildBinding,
+])"#,
+ )?,
+ r#"["undefined","function"]"#,
+ "a child realm created after detach must receive only live-session bindings",
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("detached-session child binding witness should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn selected_child_realm_materialization_checkpoints_after_all_document_start_scripts() {
run_page_vm_async_test(async move {
@@ -245,6 +299,7 @@ async fn child_realm_document_start_reaction_publishes_nested_navigation_before_
.vm_mut()
.set_stored_document_start_scripts(&[crate::DocumentStartScript {
registry_key: Some("realm-completion-nested-child".to_owned()),
+ devtools_session: None,
source: r#"
Promise.resolve().then(() => {
const nested = document.createElement("iframe");
diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rs
index ee307d4d0..d525fc441 100644
--- a/moli-renderer-v8/src/runtime/tests.rs
+++ b/moli-renderer-v8/src/runtime/tests.rs
@@ -1480,6 +1480,7 @@ async fn streaming_unstyled_xml_converts_live_document_before_domcontentloaded()
.update_commit_configuration(RendererPreparedDocumentCommitConfiguration {
document_start_scripts: vec![crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: concat!(
"globalThis.__xmlViewerDcl = null;",
"document.addEventListener('DOMContentLoaded', () => {",
@@ -1599,6 +1600,7 @@ async fn prepared_streaming_xml_document_waits_for_permit_and_uses_latest_config
document_start_scripts: vec![
crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: r#"globalThis.__nativePreload = "ready";"#.to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -1606,6 +1608,7 @@ async fn prepared_streaming_xml_document_waits_for_permit_and_uses_latest_config
},
crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: r#"globalThis.__nativeWorldPreload = "ready";"#.to_owned(),
world_name: Some("native-world".to_owned()),
has_bidi_channel_argument: false,
@@ -1613,6 +1616,7 @@ async fn prepared_streaming_xml_document_waits_for_permit_and_uses_latest_config
},
],
runtime_bindings: vec![crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "nativeBinding".to_owned(),
execution_context_name: None,
}],
@@ -2564,6 +2568,7 @@ globalThis.__preparedCommitObserved = JSON.stringify([
document_start_scripts: vec![
crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: r#"globalThis.__latestPreload = "ready";"#.to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -2571,6 +2576,7 @@ globalThis.__preparedCommitObserved = JSON.stringify([
},
crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: r#"globalThis.__latestWorld = "ready";"#.to_owned(),
world_name: Some("latest-world".to_owned()),
has_bidi_channel_argument: false,
@@ -2578,6 +2584,7 @@ globalThis.__preparedCommitObserved = JSON.stringify([
},
],
runtime_bindings: vec![crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "latestBinding".to_owned(),
execution_context_name: None,
}],
@@ -4222,6 +4229,7 @@ async fn runtime_binding_replay_cannot_consume_same_id_frontend_deferred_respons
));
let binding = crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "internalCollisionBinding".to_owned(),
execution_context_name: None,
};
@@ -9862,6 +9870,7 @@ async fn set_runtime_binding_state_updates_renderer_inspector_session_store() {
)
.await;
let binding = crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "rendererSessionStoredBinding".to_owned(),
execution_context_name: None,
};
@@ -9900,6 +9909,7 @@ async fn set_runtime_binding_state_updates_renderer_inspector_session_store() {
)
.await;
let scoped_binding = crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "rendererSessionClearedBinding".to_owned(),
execution_context_name: Some("cleared-binding-world".to_owned()),
};
@@ -9957,6 +9967,7 @@ async fn apply_runtime_protocol_state_keeps_session_binding_replay_scoped() {
)
.await;
let stored_only_binding = crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "storedOnlySessionBinding".to_owned(),
execution_context_name: Some("stored-only-world".to_owned()),
};
@@ -10831,6 +10842,7 @@ async fn per_page_isolate_policy_scopes_document_start_scripts_to_page_worlds()
let script = crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: r#"globalThis.__sharedPreloadOwner = "first-page";"#.to_owned(),
world_name: Some("shared-preload-world".to_owned()),
has_bidi_channel_argument: false,
@@ -10978,6 +10990,7 @@ async fn per_page_isolate_policy_keeps_stored_document_start_scripts_page_local(
let stored_script = crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: r#"globalThis.__sharedStoredPreloadOwner = "first-page";"#.to_owned(),
world_name: Some("shared-stored-preload-world".to_owned()),
has_bidi_channel_argument: false,
@@ -11116,6 +11129,7 @@ async fn stored_document_start_script_remove_uses_registry_key_namespace() {
vec![
crate::DocumentStartScript {
registry_key: Some("default:1".to_owned()),
+ devtools_session: None,
source: r#"globalThis.__defaultPreload = "default";"#.to_owned(),
world_name: Some("registry-key-world".to_owned()),
has_bidi_channel_argument: false,
@@ -11123,6 +11137,7 @@ async fn stored_document_start_script_remove_uses_registry_key_namespace() {
},
crate::DocumentStartScript {
registry_key: Some("target:TID-1:1".to_owned()),
+ devtools_session: None,
source: r#"globalThis.__targetPreload = "target";"#.to_owned(),
world_name: Some("registry-key-world".to_owned()),
has_bidi_channel_argument: false,
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 2fd61fe1c..6e65aa8c8 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -40,9 +40,9 @@ use crate::{
};
use anyhow::{Context, Result, anyhow};
use moli_page_types::{
- RendererDomDebuggerDomBreakpointType, RendererDomDebuggerEventListenerBreakpoint,
- RendererDomDebuggerXhrBreakpoint, RendererInspectorProtocolConfiguration,
- V8InspectorSessionAttach,
+ DevToolsSessionKey, RendererDomDebuggerDomBreakpointType,
+ RendererDomDebuggerEventListenerBreakpoint, RendererDomDebuggerXhrBreakpoint,
+ RendererInspectorProtocolConfiguration, V8InspectorSessionAttach,
};
#[cfg(any(test, feature = "test-support"))]
@@ -3401,13 +3401,22 @@ impl ScriptVm {
pub(super) fn has_isolated_world_named(&self, name: &str) -> bool {
self.page_isolated_world_contexts
- .execution_context_id_for_scope(None, name)
- .is_some()
+ .has_world_for_scope(None, name)
}
pub(super) fn has_isolated_world_named_for_frame(&self, frame_id: &str, name: &str) -> bool {
self.page_isolated_world_contexts
- .execution_context_id_for_scope(Some(frame_id), name)
+ .has_world_for_scope(Some(frame_id), name)
+ }
+
+ pub(super) fn has_isolated_world_for_owner(
+ &self,
+ devtools_session: Option<&DevToolsSessionKey>,
+ frame_id: Option<&str>,
+ name: &str,
+ ) -> bool {
+ self.page_isolated_world_contexts
+ .execution_context_id_for_scope(devtools_session, frame_id, name)
.is_some()
}
@@ -3956,6 +3965,20 @@ impl ScriptVm {
retired_count
}
+ fn retire_isolated_worlds_for_devtools_session(
+ &mut self,
+ devtools_session: &DevToolsSessionKey,
+ ) -> usize {
+ let context_ids = self
+ .page_isolated_world_contexts
+ .execution_context_ids_for_devtools_session(devtools_session);
+ let retired_count = context_ids.len();
+ for context_id in context_ids {
+ self.destroy_isolated_world_context(context_id);
+ }
+ retired_count
+ }
+
pub(super) fn rebind_isolated_worlds_for_document_owner_transition(
&mut self,
retired_owner: FrameDocumentTaskOwner,
@@ -4035,6 +4058,7 @@ impl ScriptVm {
fn create_new_isolated_world(
&mut self,
+ devtools_session: Option<DevToolsSessionKey>,
name: &str,
grant_universal_access: bool,
frame_id: Option<String>,
@@ -4113,6 +4137,7 @@ impl ScriptVm {
execution_context_id,
PageIsolatedWorldContext {
name: name.to_owned(),
+ devtools_session,
grant_universal_access,
frame_id,
child_handle,
@@ -4257,7 +4282,7 @@ impl ScriptVm {
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
- self.ensure_isolated_world(name, grant_universal_access)
+ self.ensure_isolated_world_for_owner(None, name, grant_universal_access)
}
pub(super) fn create_isolated_world_for_frame(
@@ -4266,17 +4291,18 @@ impl ScriptVm {
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
- self.ensure_isolated_world_for_frame(frame_id, name, grant_universal_access)
+ self.ensure_isolated_world_for_frame_owner(None, frame_id, name, grant_universal_access)
}
- pub(super) fn ensure_isolated_world(
+ pub(super) fn ensure_isolated_world_for_owner(
&mut self,
+ devtools_session: Option<&DevToolsSessionKey>,
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
if let Some(execution_context_id) = self
.page_isolated_world_contexts
- .execution_context_id_for_scope(None, name)
+ .execution_context_id_for_scope(devtools_session, None, name)
{
let owner_is_current = self
.page_isolated_world_contexts
@@ -4293,18 +4319,25 @@ impl ScriptVm {
}
return Ok(execution_context_id);
}
- self.create_new_isolated_world(name, grant_universal_access, None, None)
+ self.create_new_isolated_world(
+ devtools_session.cloned(),
+ name,
+ grant_universal_access,
+ None,
+ None,
+ )
}
- pub(super) fn ensure_isolated_world_for_frame(
+ pub(super) fn ensure_isolated_world_for_frame_owner(
&mut self,
+ devtools_session: Option<&DevToolsSessionKey>,
frame_id: &str,
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
if let Some(execution_context_id) = self
.page_isolated_world_contexts
- .execution_context_id_for_scope(Some(frame_id), name)
+ .execution_context_id_for_scope(devtools_session, Some(frame_id), name)
{
let owner_is_current = self
.page_isolated_world_contexts
@@ -4325,6 +4358,7 @@ impl ScriptVm {
.child_browsing_context_handle_by_frame_id(frame_id)
.ok_or_else(|| anyhow!("no live child browsing context for frame `{frame_id}`"))?;
self.create_new_isolated_world(
+ devtools_session.cloned(),
name,
grant_universal_access,
Some(frame_id.to_owned()),
@@ -4382,9 +4416,17 @@ impl ScriptVm {
Some(world_name) => {
let created = self
.page_isolated_world_contexts
- .execution_context_id_for_scope(None, world_name)
+ .execution_context_id_for_scope(
+ script.devtools_session.as_ref(),
+ None,
+ world_name,
+ )
.is_none();
- let execution_context_id = self.ensure_isolated_world(world_name, false)?;
+ let execution_context_id = self.ensure_isolated_world_for_owner(
+ script.devtools_session.as_ref(),
+ world_name,
+ false,
+ )?;
self.exec_in_execution_context(execution_context_id, &script.source)?;
Ok(Some((execution_context_id, created)))
}
@@ -4917,7 +4959,12 @@ impl ScriptVm {
self._context_host
.borrow_mut()
.remove_dom_debugger_session(inspector_session_id);
- self.page_inspector.detach_session(inspector_session_id)
+ let devtools_session = DevToolsSessionKey::from_wire_session_id(
+ inspector_session_id.filter(|session_id| !session_id.is_empty()),
+ );
+ let detached = self.page_inspector.detach_session(inspector_session_id);
+ let retired_worlds = self.retire_isolated_worlds_for_devtools_session(&devtools_session);
+ detached || retired_worlds != 0
}
pub(super) fn set_permission_overrides(
diff --git a/moli-renderer-v8/src/script_vm/child_frame_realm_materialization.rs b/moli-renderer-v8/src/script_vm/child_frame_realm_materialization.rs
index 527773444..70c5e0c9f 100644
--- a/moli-renderer-v8/src/script_vm/child_frame_realm_materialization.rs
+++ b/moli-renderer-v8/src/script_vm/child_frame_realm_materialization.rs
@@ -417,12 +417,15 @@ impl ScriptVm {
frame_id: &str,
handle: DomHandle,
owner: FrameDocumentTaskOwner,
+ devtools_session: Option<&moli_page_types::DevToolsSessionKey>,
world: &crate::protocol_types::RuntimeIsolatedWorldDefinition,
bindings: &[crate::protocol_types::RuntimeBindingRegistration],
- prepared_worlds: &mut Vec<(String, i64)>,
+ prepared_worlds: &mut Vec<(Option<moli_page_types::DevToolsSessionKey>, String, i64)>,
) -> Result<i64> {
- if let Some((_, execution_context_id)) =
- prepared_worlds.iter().find(|(name, _)| name == &world.name)
+ if let Some((_, _, execution_context_id)) =
+ prepared_worlds.iter().find(|(prepared_session, name, _)| {
+ prepared_session.as_ref() == devtools_session && name == &world.name
+ })
{
return Ok(*execution_context_id);
}
@@ -430,7 +433,8 @@ impl ScriptVm {
anyhow::bail!("child Document owner changed during named-world materialization");
}
- let execution_context_id = self.ensure_isolated_world_for_frame(
+ let execution_context_id = self.ensure_isolated_world_for_frame_owner(
+ devtools_session,
frame_id,
&world.name,
world.grant_universal_access,
@@ -444,13 +448,17 @@ impl ScriptVm {
// Chromium's V8RuntimeAgentImpl::addBindings() boundary. Moli
// additionally installs its native callback-backed binding so calls
// enter the exact Document-owned runtime queue.
- for binding in bindings
- .iter()
- .filter(|binding| binding.execution_context_name.as_deref() == Some(&world.name))
- {
+ for binding in bindings.iter().filter(|binding| {
+ binding.devtools_session.as_ref() == devtools_session
+ && binding.execution_context_name.as_deref() == Some(&world.name)
+ }) {
self.install_runtime_binding_in_execution_context(execution_context_id, &binding.name)?;
}
- prepared_worlds.push((world.name.clone(), execution_context_id));
+ prepared_worlds.push((
+ devtools_session.cloned(),
+ world.name.clone(),
+ execution_context_id,
+ ));
Ok(execution_context_id)
}
@@ -478,7 +486,8 @@ impl ScriptVm {
)
};
let worlds = self.child_named_runtime_world_definitions(runtime_isolated_worlds);
- let mut prepared_worlds = Vec::<(String, i64)>::new();
+ let mut prepared_worlds =
+ Vec::<(Option<moli_page_types::DevToolsSessionKey>, String, i64)>::new();
let mut activity = ChildRealmMaterializationBodyActivity::StateOnly;
// Explicit Page.createIsolatedWorld state corresponds to Chromium's
@@ -489,6 +498,7 @@ impl ScriptVm {
frame_id,
handle,
owner,
+ None,
world,
&bindings,
&mut prepared_worlds,
@@ -527,6 +537,7 @@ impl ScriptVm {
frame_id,
handle,
owner,
+ script.devtools_session.as_ref(),
world,
&bindings,
&mut prepared_worlds,
@@ -549,24 +560,33 @@ impl ScriptVm {
}
// A world retained only by a named Runtime binding has no script to
- // trigger lazy creation. Materialize it before this child-realm turn
- // settles so its contextCreated fact remains ordered before frame
- // navigation output.
- for world in &worlds {
+ // trigger lazy creation. Materialize it for that binding's owning
+ // session before this child-realm turn settles, so equal world names
+ // from peer sessions never share a context or native callback.
+ for binding in &bindings {
if !self.child_materialization_owner_is_current(handle, owner) {
break;
}
+ let Some(world_name) = binding.execution_context_name.as_deref() else {
+ continue;
+ };
+ let Some(world) = worlds.iter().find(|world| world.name == world_name) else {
+ self.record_runtime_warning(format_args!(
+ "child Runtime binding world `{world_name}` has no retained definition"
+ ));
+ continue;
+ };
if let Err(error) = self.prepare_child_named_runtime_world(
frame_id,
handle,
owner,
+ binding.devtools_session.as_ref(),
world,
&bindings,
&mut prepared_worlds,
) {
self.record_runtime_warning(format_args!(
- "child named world `{}` initialization failed: {error}",
- world.name
+ "child named world `{world_name}` initialization failed: {error}"
));
}
}
diff --git a/moli-renderer-v8/src/script_vm/inspector/agent_sessions.rs b/moli-renderer-v8/src/script_vm/inspector/agent_sessions.rs
index d88b2c33c..0422381ea 100644
--- a/moli-renderer-v8/src/script_vm/inspector/agent_sessions.rs
+++ b/moli-renderer-v8/src/script_vm/inspector/agent_sessions.rs
@@ -451,6 +451,7 @@ mod tests {
RendererDevToolsSessionConnection::new(context_group_id, agent_token, None);
let session_key = DevToolsSessionKey::Attached("SID-agent-sessions".to_owned());
let binding = RuntimeBindingRegistration {
+ devtools_session: None,
name: "bridge".to_owned(),
execution_context_name: Some("utility".to_owned()),
};
@@ -499,6 +500,7 @@ mod tests {
fn runtime_binding_configuration_is_agent_local() {
let session_key = DevToolsSessionKey::Attached("SID-agent-local-config".to_owned());
let binding = RuntimeBindingRegistration {
+ devtools_session: None,
name: "bridge".to_owned(),
execution_context_name: Some("utility".to_owned()),
};
diff --git a/moli-renderer-v8/src/script_vm/isolated_worlds.rs b/moli-renderer-v8/src/script_vm/isolated_worlds.rs
index 8025d5646..dd41428da 100644
--- a/moli-renderer-v8/src/script_vm/isolated_worlds.rs
+++ b/moli-renderer-v8/src/script_vm/isolated_worlds.rs
@@ -3,11 +3,13 @@ use crate::{
native_bridge::{JsContextHostBridgeRef, RuntimeObservableContextToken},
script_vm::inspector::DocumentInspectorContextRegistrationId,
};
+use moli_page_types::DevToolsSessionKey;
use serde_json::Value;
use std::collections::BTreeMap;
pub(super) struct PageIsolatedWorldContext {
pub(super) name: String,
+ pub(super) devtools_session: Option<DevToolsSessionKey>,
pub(super) grant_universal_access: bool,
pub(super) frame_id: Option<String>,
pub(super) child_handle: Option<DomHandle>,
@@ -90,17 +92,39 @@ impl PageIsolatedWorldRegistry {
pub(super) fn execution_context_id_for_scope(
&self,
+ devtools_session: Option<&DevToolsSessionKey>,
frame_id: Option<&str>,
name: &str,
) -> Option<i64> {
self.contexts
.iter()
.find_map(|(execution_context_id, world)| {
- (world.frame_id.as_deref() == frame_id && world.name == name)
+ (world.devtools_session.as_ref() == devtools_session
+ && world.frame_id.as_deref() == frame_id
+ && world.name == name)
.then_some(*execution_context_id)
})
}
+ pub(super) fn has_world_for_scope(&self, frame_id: Option<&str>, name: &str) -> bool {
+ self.contexts
+ .values()
+ .any(|world| world.frame_id.as_deref() == frame_id && world.name == name)
+ }
+
+ pub(super) fn execution_context_ids_for_devtools_session(
+ &self,
+ devtools_session: &DevToolsSessionKey,
+ ) -> Vec<i64> {
+ self.contexts
+ .iter()
+ .filter_map(|(execution_context_id, world)| {
+ (world.devtools_session.as_ref() == Some(devtools_session))
+ .then_some(*execution_context_id)
+ })
+ .collect()
+ }
+
pub(super) fn execution_context_ids_for_name(&self, name: &str) -> Vec<i64> {
self.contexts
.iter()
@@ -204,6 +228,13 @@ impl PageIsolatedWorldRegistry {
created: &InspectorIsolatedContextCreated<'_>,
root_frame_id: Option<&str>,
) -> Option<i64> {
+ if self
+ .contexts
+ .get(&created.inspector_context_id)
+ .is_some_and(|world| self.matches_inspector_context(world, created, root_frame_id))
+ {
+ return Some(created.inspector_context_id);
+ }
self.contexts
.iter()
.find_map(|(execution_context_id, world)| {
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
index c8d62e920..f9c564573 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
@@ -1441,6 +1441,7 @@ fn document_start_run_immediately_drains_pending_style_invalidations_without_com
let result = vm
.run_document_start_script_now(&crate::DocumentStartScript {
registry_key: None,
+ devtools_session: None,
source: "globalThis.__runImmediatelyDrainTarget.className = 'active';".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index ab14b3808..77b3ccc9d 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -937,6 +937,7 @@ fn main_document_open_rebinds_preserved_isolated_runtime_binding_context() {
async fn child_navigation_retires_runtime_binding_context_and_stale_function() {
let mut vm = new_storage_test_vm("https://child-runtime-binding-owner.test/");
vm.set_stored_runtime_bindings(&[crate::protocol_types::RuntimeBindingRegistration {
+ devtools_session: None,
name: "childOwnerBoundRuntimeBinding".to_owned(),
execution_context_name: None,
}]);
@@ -5115,7 +5116,7 @@ fn isolated_world_bridge_ref_is_released_with_script_vm() {
let mut vm = new_storage_test_vm("https://example.test/");
let context_host = vm.context_host_weak_for_test();
- vm.ensure_isolated_world("bridge-ref-regression", false)
+ vm.ensure_isolated_world_for_owner(None, "bridge-ref-regression", false)
.expect("isolated world should be created");
assert!(
context_host.upgrade().is_some(),
@@ -6354,6 +6355,7 @@ async fn pending_child_navigation_does_not_materialize_initial_empty_preload_rea
let mut vm = new_storage_test_vm("https://child-preload-lazy.test/");
vm.set_stored_document_start_scripts(&[crate::DocumentStartScript {
registry_key: Some("initial-empty-lazy-preload".to_owned()),
+ devtools_session: None,
source: "globalThis.__documentStartUrl = document.URL;".to_owned(),
world_name: None,
has_bidi_channel_argument: false,
@@ -14661,6 +14663,7 @@ fn inspector_context_created_matches_same_name_child_isolated_world_by_frame_id(
.expect("root isolated world should be created");
let child_context_id = vm
.create_new_isolated_world(
+ None,
"shared-utility",
false,
Some("child-frame".to_owned()),
@@ -14707,6 +14710,57 @@ fn inspector_context_created_matches_same_name_child_isolated_world_by_frame_id(
assert_eq!(vm.page_isolated_world_contexts.len(), 2);
}
+#[test]
+fn same_name_isolated_worlds_are_scoped_to_devtools_session_and_detach() {
+ let mut vm = new_storage_test_vm("https://isolated-world-session.test/");
+ let session_a = moli_page_types::DevToolsSessionKey::from_wire_session_id(Some("session-a"));
+ let session_b = moli_page_types::DevToolsSessionKey::from_wire_session_id(Some("session-b"));
+
+ let context_a = vm
+ .ensure_isolated_world_for_owner(Some(&session_a), "utility", false)
+ .expect("session A isolated world should be created");
+ let context_b = vm
+ .ensure_isolated_world_for_owner(Some(&session_b), "utility", false)
+ .expect("session B same-name isolated world should be distinct");
+ assert_ne!(context_a, context_b);
+ vm.eval_in_isolated_context(context_a, "globalThis.owner = 'session-a'")
+ .expect("session A isolated world should evaluate");
+ vm.eval_in_isolated_context(context_b, "globalThis.owner = 'session-b'")
+ .expect("session B isolated world should evaluate");
+ assert_eq!(
+ vm.eval_in_isolated_context(context_a, "owner")
+ .expect("session A isolated world should retain its state"),
+ "session-a"
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(context_b, "owner")
+ .expect("session B isolated world should retain its state"),
+ "session-b"
+ );
+
+ assert!(vm.detach_runtime_inspector_session(Some("session-a")));
+ assert!(
+ vm.page_isolated_world_contexts.context(context_a).is_none(),
+ "detaching session A must retire only its isolated world"
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(context_b, "owner")
+ .expect("session B isolated world should survive peer detach"),
+ "session-b"
+ );
+
+ let replacement_session =
+ moli_page_types::DevToolsSessionKey::from_wire_session_id(Some("session-c"));
+ let replacement_context = vm
+ .ensure_isolated_world_for_owner(Some(&replacement_session), "utility", false)
+ .expect("replacement session isolated world should be created");
+ assert_eq!(
+ vm.eval_in_isolated_context(replacement_context, "typeof owner")
+ .expect("replacement session isolated world should evaluate"),
+ "undefined"
+ );
+}
+
fn test_trusted_key_dispatch_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments<'_>,