Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(cdp): name stable page target selection
ldm0963de5c520a4
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex bd8dfbf04..5e028858b 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -134,6 +134,12 @@ assumptions: wire and live UA overrides both follow session attachment order,and an activation-churn preload probe must enable the Page agent beforeregistering its new-Document script.+Every `multi-page` case runs even when an earlier case fails, so one race does+not hide later failures. For focused reproduction, set+`MOLI_MULTI_PAGE_CASES` to a comma-separated list of case names. Parallel+workers can partition that selected list with the one-based+`MOLI_MULTI_PAGE_SHARD=INDEX/COUNT` setting.+## Current CoverageThe current suite is a strong core smoke gate, not a complete Playwright compatibility suite.diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.pyindex 0ebe8ff25..d8bd42c40 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page.py@@ -11,9 +11,15 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom ..assertions import SmokeError, assert_equal, record, wait_untilfrom ..helpers import attach_cdp_event_collector, run_worker_command-from .multi_page_contracts import run_multi_page_contracts-from .multi_page_chromium_contracts import run_multi_page_chromium_contracts-from .multi_page_isolation_contracts import run_multi_page_isolation_contracts+from .multi_page_chromium_contracts import multi_page_chromium_contract_cases+from .multi_page_contracts import multi_page_contract_cases+from .multi_page_isolation_contracts import multi_page_isolation_contract_cases+from .multi_page_support import (+ MultiPageCase,+ close_context,+ run_multi_page_cases,+ runtime_value,+)async def run_multi_page_group(@@ -22,20 +28,26 @@ async def run_multi_page_group(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)- await run_multi_page_isolation_contracts(browser, fixture, results)- await run_multi_page_chromium_contracts(browser, fixture, results)+ await run_multi_page_cases(browser, fixture, results, _multi_page_cases())+++def _multi_page_cases() -> tuple[MultiPageCase, ...]:+ return (+ _page_churn_and_session_reattach,+ _same_context_storage_and_history,+ _mixed_navigation_outcomes_and_recovery,+ _concurrent_route_outcomes,+ _inflight_navigation_close_and_peer_recovery,+ _target_local_session_events,+ _target_local_dialogs,+ _concurrent_downloads_and_peer,+ _popup_tree_survives_middle_close,+ _background_tasks_workers_and_screenshots,+ _context_teardown_with_pending_commands,+ *multi_page_contract_cases(),+ *multi_page_isolation_contract_cases(),+ *multi_page_chromium_contract_cases(),+ )async def _page_churn_and_session_reattach(@@ -76,7 +88,7 @@ async def _page_churn_and_session_reattach())assert_equal(- [_runtime_value(write) for write in writes],+ [runtime_value(write) for write in writes],[f"page-{index}" for index in range(6)],"six target-local Runtime writes",)@@ -98,7 +110,7 @@ async def _page_churn_and_session_reattach())assert_equal(- [_runtime_value(read) for read in reads],+ [runtime_value(read) for read in reads],[f"page-{index}" for index in range(6)],"Runtime state after alternating session reattach",)@@ -154,7 +166,7 @@ async def _page_churn_and_session_reattach()with suppress(Exception):await browser_cdp.detach()- await _close_context(context)+ await close_context(context)async def _same_context_storage_and_history(@@ -241,8 +253,8 @@ async def _same_context_storage_and_history(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)+ await close_context(context_a)+ await close_context(context_b)async def _mixed_navigation_outcomes_and_recovery(@@ -356,7 +368,7 @@ async def _mixed_navigation_outcomes_and_recovery(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _concurrent_route_outcomes(@@ -442,8 +454,8 @@ async def _concurrent_route_outcomes(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)+ await close_context(context_a)+ await close_context(context_b)async def _inflight_navigation_close_and_peer_recovery(@@ -525,7 +537,7 @@ async def _inflight_navigation_close_and_peer_recovery(for task in (victim_navigation, victim_close):if task is not None and not task.done():task.cancel()- await _close_context(context)+ await close_context(context)async def _target_local_session_events(@@ -639,7 +651,7 @@ async def _target_local_session_events("Runtime.evaluate",{"expression": "21 * 2", "returnByValue": True},)- assert_equal(_runtime_value(surviving), 42, "auxiliary after primary detach")+ 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(@@ -648,7 +660,7 @@ async def _target_local_session_events({"expression": "location.search", "returnByValue": True},)assert_equal(- _runtime_value(replacement_read),+ runtime_value(replacement_read),"?session-network=1","reattached target session route",)@@ -662,7 +674,7 @@ async def _target_local_session_events(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _popup_tree_survives_middle_close(@@ -740,7 +752,7 @@ async def _popup_tree_survives_middle_close({"survivingPages": len(context.pages)},)finally:- await _close_context(context)+ await close_context(context)async def _target_local_dialogs(@@ -809,7 +821,7 @@ async def _target_local_dialogs()record(results, "multi_page_target_local_concurrent_dialogs")finally:- await _close_context(context)+ await close_context(context)async def _concurrent_downloads_and_peer(@@ -873,7 +885,7 @@ async def _concurrent_downloads_and_peer()record(results, "multi_page_concurrent_downloads_and_peer_cancel")finally:- await _close_context(context)+ await close_context(context)async def _background_tasks_workers_and_screenshots(@@ -966,7 +978,7 @@ async def _background_tasks_workers_and_screenshots({"screenshots": 4, "workers": 3},)finally:- await _close_context(context)+ await close_context(context)async def _context_teardown_with_pending_commands(@@ -1028,8 +1040,8 @@ async def _context_teardown_with_pending_commands()finally:if not context_a_closed:- await _close_context(context_a)- await _close_context(context_b)+ await close_context(context_a)+ await close_context(context_b)async def _open_popup(page: Any, url: str, name: str) -> Any:@@ -1117,17 +1129,6 @@ async def _send_cdp(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")diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_chromium_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_chromium_contracts.pyindex ebef799f9..906304dc8 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_chromium_contracts.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_chromium_contracts.py@@ -2,33 +2,26 @@ from __future__ import annotationsimport asynciofrom contextlib import suppress-from typing import Any, Awaitable+from typing import Anyfrom ..assertions import SmokeError, assert_equal, record_contract, wait_untilfrom ..helpers import attach_cdp_event_collector-from ..progress import await_with_progress+from .multi_page_support import (+ MultiPageCase,+ close_context,+ expect_protocol_error,+ runtime_value,+)-async def run_multi_page_chromium_contracts(- browser: Any,- fixture: str,- results: list[dict[str, Any]],-) -> None:- """Run executable Chromium contracts that stress cross-Page ownership."""-- contracts = (+def multi_page_chromium_contract_cases() -> tuple[MultiPageCase, ...]:+ return (_debugger_pause_is_target_local,_dom_storage_namespaces_route_across_targets,_navigation_history_entries_are_target_local,_blocked_urls_aggregate_across_target_sessions,_cache_disabled_aggregates_without_crossing_targets,)- for contract in contracts:- await await_with_progress(- f"multi-page/{contract.__name__.removeprefix('_')}",- contract(browser, fixture, results),- timeout_seconds=20,- )async def _debugger_pause_is_target_local(@@ -86,7 +79,7 @@ async def _debugger_pause_is_target_local(timeout=5,)assert_equal(- _runtime_value(peer_result),+ runtime_value(peer_result),42,"peer Runtime remains live while another Page is paused",)@@ -100,7 +93,7 @@ async def _debugger_pause_is_target_local(owner_result = await asyncio.wait_for(paused_evaluation, timeout=5)paused_evaluation = Noneassert_equal(- _runtime_value(owner_result),+ runtime_value(owner_result),42,"owning Runtime evaluation resumes",)@@ -146,7 +139,7 @@ async def _debugger_pause_is_target_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _dom_storage_namespaces_route_across_targets(@@ -282,7 +275,7 @@ async def _dom_storage_namespaces_route_across_targets(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _navigation_history_entries_are_target_local(@@ -329,7 +322,7 @@ async def _navigation_history_entries_are_target_local()peer_url_before = peer.url- foreign_error = await _expect_protocol_error(+ foreign_error = await expect_protocol_error(peer_session.send("Page.navigateToHistoryEntry",{"entryId": foreign_id},@@ -383,7 +376,7 @@ async def _navigation_history_entries_are_target_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _blocked_urls_aggregate_across_target_sessions(@@ -525,7 +518,7 @@ async def _blocked_urls_aggregate_across_target_sessions(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _cache_disabled_aggregates_without_crossing_targets(@@ -645,7 +638,7 @@ async def _cache_disabled_aggregates_without_crossing_targets(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _fetch_result(page: Any, url: str) -> dict[str, Any]:@@ -692,24 +685,3 @@ def _storage_event_count(is is_localfor event in events)---def _runtime_value(response: dict[str, Any]) -> Any:- return response.get("result", {}).get("value")---async def _expect_protocol_error(awaitable: Awaitable[Any], label: str) -> str:- try:- await awaitable- except Exception as error:- return str(error)- raise SmokeError(f"{label} unexpectedly succeeded")---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 errordiff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.pyindex 9777868e9..ffdf8c90f 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py@@ -1,24 +1,21 @@from __future__ import annotationsimport asyncio-import json-import urllib.requestfrom contextlib import suppress-from typing import Any, Awaitable+from typing import Anyfrom ..assertions import SmokeError, assert_equal, record_contract, wait_untilfrom ..helpers import attach_cdp_event_collector-from ..progress import await_with_progress+from .multi_page_support import (+ MultiPageCase,+ close_context,+ expect_protocol_error,+ read_fixture_json,+)-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 = (+def multi_page_contract_cases() -> tuple[MultiPageCase, ...]:+ return (_remote_object_and_execution_context_ownership,_target_local_device_metrics,_new_document_script_session_lifecycle,@@ -43,12 +40,6 @@ async def run_multi_page_contracts(_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(@@ -98,11 +89,11 @@ async def _remote_object_and_execution_context_ownership(f"page A isolated world returned no executionContextId: {isolated!r}")- foreign_object_error = await _expect_protocol_error(+ 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(+ foreign_context_error = await expect_protocol_error(session_b.send("Runtime.evaluate",{@@ -142,7 +133,7 @@ async def _remote_object_and_execution_context_ownership(f"{fixture}/plain?multi-page-object=a-replaced",wait_until="load",)- stale_object_error = await _expect_protocol_error(+ stale_object_error = await expect_protocol_error(session_a.send("Runtime.getProperties", {"objectId": object_id}),"old objectId after its owning Document was replaced",)@@ -175,7 +166,7 @@ async def _remote_object_and_execution_context_ownership(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _target_local_device_metrics(@@ -277,7 +268,7 @@ async def _target_local_device_metrics(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _new_document_script_session_lifecycle(@@ -417,7 +408,7 @@ async def _new_document_script_session_lifecycle(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_target_new_document_script_session_ownership(@@ -543,7 +534,7 @@ async def _same_target_new_document_script_session_ownership(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _isolated_world_script_detach_lifecycle(@@ -658,7 +649,7 @@ async def _isolated_world_script_detach_lifecycle(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_name_isolated_worlds_are_session_local(@@ -838,7 +829,7 @@ async def _same_name_isolated_worlds_are_session_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _runtime_binding_session_lifecycle(@@ -978,7 +969,7 @@ async def _runtime_binding_session_lifecycle(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_target_remote_objects_are_session_local(@@ -1049,7 +1040,7 @@ async def _same_target_remote_objects_are_session_local(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(+ foreign_error = await expect_protocol_error(session_b.send("Runtime.getProperties", {"objectId": object_a}),"same-target session B resolving session A objectId",)@@ -1067,7 +1058,7 @@ async def _same_target_remote_objects_are_session_local("same-target object owner resolves its handle",)await session_a.send("Runtime.releaseObject", {"objectId": object_a})- released_error = await _expect_protocol_error(+ released_error = await expect_protocol_error(session_a.send("Runtime.getProperties", {"objectId": object_a}),"released same-target objectId",)@@ -1099,7 +1090,7 @@ async def _same_target_remote_objects_are_session_local("Runtime.releaseObjectGroup",{"objectGroup": "shared-name-group"},)- released_group_error = await _expect_protocol_error(+ released_group_error = await expect_protocol_error(session_a.send("Runtime.getProperties", {"objectId": grouped_object_a}),"released owner object group",)@@ -1158,7 +1149,7 @@ async def _same_target_remote_objects_are_session_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_target_dom_node_and_backend_node_ownership(@@ -1218,7 +1209,7 @@ async def _same_target_dom_node_and_backend_node_ownership(f"DOM.describeNode returned no backendNodeId: {owner_description!r}")- foreign_node_error = await _expect_protocol_error(+ foreign_node_error = await expect_protocol_error(session_b.send("DOM.describeNode", {"nodeId": owner_node_id}),"unpublished DOM nodeId in peer session",)@@ -1242,7 +1233,7 @@ async def _same_target_dom_node_and_backend_node_ownership("owner","peer resolves target-scoped backendNodeId",)- foreign_object_error = await _expect_protocol_error(+ foreign_object_error = await expect_protocol_error(session_a.send("Runtime.getProperties", {"objectId": peer_object_id}),"DOM-resolved peer Runtime objectId",)@@ -1290,7 +1281,7 @@ async def _same_target_dom_node_and_backend_node_ownership(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_source_scripts_keep_session_authority(@@ -1357,7 +1348,7 @@ async def _same_source_scripts_keep_session_authority(1,"colliding identifier removes only session B's registration",)- repeated_remove_error = await _expect_protocol_error(+ repeated_remove_error = await expect_protocol_error(session_b.send("Page.removeScriptToEvaluateOnNewDocument",{"identifier": identifier_a},@@ -1465,7 +1456,7 @@ async def _same_source_scripts_keep_session_authority(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _network_enablement_is_session_local(@@ -1502,7 +1493,7 @@ async def _network_enablement_is_session_local(events_a.clear()events_b.clear()await session_a.send("Network.disable")- disabled_cache_error = await _expect_protocol_error(+ disabled_cache_error = await expect_protocol_error(session_a.send("Network.getResponseBody", {"requestId": request_a}),"disabled Network session response-body cache",)@@ -1572,7 +1563,7 @@ async def _network_enablement_is_session_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _page_lifecycle_enablement_is_session_local(@@ -1681,7 +1672,7 @@ async def _page_lifecycle_enablement_is_session_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_name_runtime_bindings_keep_session_authority(@@ -1796,7 +1787,7 @@ async def _same_name_runtime_bindings_keep_session_authority(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _runtime_enablement_and_context_replay_are_session_local(@@ -1898,7 +1889,7 @@ async def _runtime_enablement_and_context_replay_are_session_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _session_detach_cancels_only_its_pending_await(@@ -1981,7 +1972,7 @@ async def _session_detach_cancels_only_its_pending_await(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _fetch_interception_is_session_local(@@ -2097,7 +2088,7 @@ async def _fetch_interception_is_session_local(),timeout=2,)- await _close_context(context)+ await close_context(context)async def _network_and_emulation_profiles_are_target_local(@@ -2182,7 +2173,7 @@ async def _network_and_emulation_profiles_are_target_local(async def read_profile() -> bool:try:profile = await asyncio.to_thread(- _read_fixture_json,+ read_fixture_json,f"{fixture}/profile-result?token={token}",)except Exception:@@ -2293,7 +2284,7 @@ async def _network_and_emulation_profiles_are_target_local(wait_until="load",)detached_wire_profile = await asyncio.to_thread(- _read_fixture_json,+ read_fixture_json,f"{fixture}/profile-result?token={detached_token}",)detached_runtime_profile, surviving_runtime_profile = await asyncio.gather(@@ -2355,7 +2346,7 @@ async def _network_and_emulation_profiles_are_target_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _closed_target_new_document_script_does_not_leak(@@ -2460,7 +2451,7 @@ async def _closed_target_new_document_script_does_not_leak(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _broadcast_channel_context_partition(@@ -2561,8 +2552,8 @@ async def _broadcast_channel_context_partition(},)finally:- await _close_context(context_a)- await _close_context(context_b)+ await close_context(context_a)+ await close_context(context_b)async def _same_target_navigation_supersession(@@ -2658,7 +2649,7 @@ async def _same_target_navigation_supersession(first_navigation.cancel()with suppress(Exception):await context.unroute("**/multi-page-supersession-held")- await _close_context(context)+ await close_context(context)async def _target_destroy_event_cardinality(@@ -2769,7 +2760,7 @@ async def _target_destroy_event_cardinality(with suppress(Exception):await browser_cdp.detach()if not context_closed:- await _close_context(context)+ await close_context(context)async def _network_response_body_target_ownership(@@ -2824,11 +2815,11 @@ async def _network_response_body_target_ownership([True, True],"target sessions resolve their own response bodies",)- foreign_a = await _expect_protocol_error(+ 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(+ foreign_b = await expect_protocol_error(session_b.send("Network.getResponseBody", {"requestId": request_a}),"page B resolving page A requestId",)@@ -2865,7 +2856,7 @@ async def _network_response_body_target_ownership(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _websocket_survives_peer_target_close(@@ -2987,15 +2978,7 @@ async def _websocket_survives_peer_target_close(*(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}")+ await close_context(context)def _default_execution_context_id(events: list[dict[str, Any]]) -> int | None:@@ -3209,18 +3192,3 @@ def _has_received_websocket_payload_length(if observed_length == payload_length:return Truereturn 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/groups/multi_page_isolation_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.pyindex 3895ad37c..47bd36416 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.py@@ -1,35 +1,27 @@from __future__ import annotationsimport asyncio-import json-import urllib.requestfrom contextlib import suppress-from typing import Any, Awaitable+from typing import Anyfrom ..assertions import SmokeError, assert_equal, record_contract, wait_untilfrom ..helpers import attach_cdp_event_collector-from ..progress import await_with_progress+from .multi_page_support import (+ MultiPageCase,+ close_context,+ expect_protocol_error,+ read_fixture_json,+ runtime_value,+)-async def run_multi_page_isolation_contracts(- browser: Any,- fixture: str,- results: list[dict[str, Any]],-) -> None:- """Exercise shared-renderer boundaries that can silently cross Page owners."""-- contracts = (+def multi_page_isolation_contract_cases() -> tuple[MultiPageCase, ...]:+ return (_busy_runtime_termination_is_target_local,_stop_loading_is_target_local,_same_target_session_policies_follow_chromium,_activation_churn_preserves_target_ownership,)- for contract in contracts:- await await_with_progress(- f"multi-page/{contract.__name__.removeprefix('_')}",- contract(browser, fixture, results),- timeout_seconds=20,- )async def _busy_runtime_termination_is_target_local(@@ -51,7 +43,7 @@ async def _busy_runtime_termination_is_target_local(session_b = await context.new_cdp_session(page_b)sessions = [session_a, session_b]await asyncio.to_thread(- _read_fixture_json,+ read_fixture_json,f"{fixture}/inspector-routing-witness/reset",)@@ -73,7 +65,7 @@ for (;;) {}""",async def busy_loop_entered() -> bool:try:status = await asyncio.to_thread(- _read_fixture_json,+ read_fixture_json,f"{fixture}/inspector-routing-witness/status",)except Exception:@@ -124,7 +116,7 @@ for (;;) {}""",f"{peer_result!r}")assert_equal(- _runtime_value(peer_result),+ runtime_value(peer_result),1,"target B queued Runtime command after target A termination",)@@ -146,7 +138,7 @@ for (;;) {}""",),)assert_equal(- [_runtime_value(recovery_a), _runtime_value(recovery_b)],+ [runtime_value(recovery_a), runtime_value(recovery_b)],[1, 1],"target-local Runtime recovery after termination",)@@ -162,10 +154,10 @@ for (;;) {}""",commands=["Runtime.evaluate x4", "Runtime.terminateExecution"],observed={"busyTargetTerminated": True,- "peerValue": _runtime_value(peer_result),+ "peerValue": runtime_value(peer_result),"recoveryValues": [- _runtime_value(recovery_a),- _runtime_value(recovery_b),+ runtime_value(recovery_a),+ runtime_value(recovery_b),],},)@@ -187,7 +179,7 @@ for (;;) {}""",*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _stop_loading_is_target_local(@@ -324,7 +316,7 @@ async def _stop_loading_is_target_local({"dcl": "1", "load": "0", "readyState": "complete"},"target A lifecycle after Page.stopLoading",)- stale_interception_error = await _expect_protocol_error(+ stale_interception_error = await expect_protocol_error(session_a.send("Fetch.continueRequest",{"requestId": paused_request_id},@@ -387,7 +379,7 @@ async def _stop_loading_is_target_local(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _same_target_session_policies_follow_chromium(@@ -446,11 +438,11 @@ async def _same_target_session_policies_follow_chromium("Emulation.setTimezoneOverride",{"timezoneId": "Europe/Paris"},)- locale_error = await _expect_protocol_error(+ locale_error = await expect_protocol_error(second.send("Emulation.setLocaleOverride", {"locale": "ja-JP"}),"second same-target locale claim",)- timezone_error = await _expect_protocol_error(+ timezone_error = await expect_protocol_error(second.send("Emulation.setTimezoneOverride",{"timezoneId": "Asia/Tokyo"},@@ -628,7 +620,7 @@ async def _same_target_session_policies_follow_chromium(*(session.detach() for session in sessions),return_exceptions=True,)- await _close_context(context)+ await close_context(context)async def _activation_churn_preserves_target_ownership(@@ -715,7 +707,7 @@ async def _activation_churn_preserves_target_ownership())assert_equal(- [_runtime_value(value) for value in owner_values],+ [runtime_value(value) for value in owner_values],[f"activation-{index}" for index in range(4)],f"session ownership after activating target {active_index}",)@@ -839,18 +831,7 @@ async def _activation_churn_preserves_target_ownership()with suppress(Exception):await browser_session.detach()- await _close_context(context)---async def _expect_protocol_error(- awaitable: Awaitable[Any],- label: str,-) -> str:- try:- result = await asyncio.wait_for(awaitable, timeout=5)- except Exception as error:- return str(error)- raise SmokeError(f"{label} unexpectedly succeeded: {result!r}")+ await close_context(context)async def _runtime_identity(page: Any) -> dict[str, Any]:@@ -868,27 +849,9 @@ async def _runtime_identity(page: Any) -> dict[str, Any]:async def _read_fixture_profile(fixture: str, token: str) -> dict[str, Any]:value = await asyncio.to_thread(- _read_fixture_json,+ read_fixture_json,f"{fixture}/profile-result?token={token}",)if not isinstance(value, dict):raise SmokeError(f"fixture recorded no profile for {token}: {value!r}")return value---def _runtime_value(response: dict[str, Any]) -> Any:- return response.get("result", {}).get("value")---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:- with urllib.request.urlopen(url, timeout=2) as response:- return json.loads(response.read().decode("utf-8"))diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_support.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_support.pynew file mode 100644index 000000000..202ace336--- /dev/null+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_support.py@@ -0,0 +1,129 @@+from __future__ import annotations++import asyncio+import json+import os+import urllib.request+from collections.abc import Awaitable, Callable, Sequence+from typing import Any++from ..assertions import SmokeError+from ..progress import await_with_progress++MultiPageCase = Callable[[Any, str, list[dict[str, Any]]], Awaitable[None]]+_CASE_ENV = "MOLI_MULTI_PAGE_CASES"+_SHARD_ENV = "MOLI_MULTI_PAGE_SHARD"+++def multi_page_case_name(case: MultiPageCase) -> str:+ return case.__name__.removeprefix("_")+++def select_multi_page_cases(+ cases: Sequence[MultiPageCase],+ *,+ requested: str | None = None,+ shard: str | None = None,+) -> tuple[MultiPageCase, ...]:+ by_name = {multi_page_case_name(case): case for case in cases}+ if len(by_name) != len(cases):+ raise ValueError("multi-page case names must be unique")++ requested = os.environ.get(_CASE_ENV, "") if requested is None else requested+ requested_names = tuple(+ dict.fromkeys(name.strip() for name in requested.split(",") if name.strip())+ )+ if requested_names:+ unknown = sorted(set(requested_names) - by_name.keys())+ if unknown:+ available = ", ".join(by_name)+ raise ValueError(+ f"unknown {_CASE_ENV} value(s): {', '.join(unknown)}; "+ f"available cases: {available}"+ )+ selected = tuple(by_name[name] for name in requested_names)+ else:+ selected = tuple(cases)++ shard = os.environ.get(_SHARD_ENV, "") if shard is None else shard+ shard = shard.strip()+ if shard:+ shard_index, shard_count = _parse_shard(shard)+ selected = tuple(+ case+ for index, case in enumerate(selected)+ if index % shard_count == shard_index+ )+ if not selected:+ raise ValueError(f"{_SHARD_ENV}={shard!r} selected no multi-page cases")++ return selected+++async def run_multi_page_cases(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+ cases: Sequence[MultiPageCase],+ *,+ timeout_seconds: float = 20,+) -> None:+ selected = select_multi_page_cases(cases)+ failures: list[Exception] = []+ for case in selected:+ name = multi_page_case_name(case)+ try:+ await await_with_progress(+ f"multi-page/{name}",+ case(browser, fixture, results),+ timeout_seconds=timeout_seconds,+ )+ except Exception as error: # noqa: BLE001 - keep running independent cases.+ error.add_note(f"multi-page case: {name}")+ failures.append(error)++ if failures:+ raise ExceptionGroup("multi-page cases failed", failures)+++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+++async def expect_protocol_error(awaitable: Awaitable[Any], label: str) -> str:+ try:+ result = await asyncio.wait_for(awaitable, timeout=5)+ except Exception as error: # noqa: BLE001 - any CDP error is the expected result.+ return str(error)+ raise SmokeError(f"{label} unexpectedly succeeded: {result!r}")+++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)+++def runtime_value(response: dict[str, Any]) -> Any:+ return response.get("result", {}).get("value")+++def _parse_shard(value: str) -> tuple[int, int]:+ try:+ raw_index, raw_count = value.split("/", maxsplit=1)+ index = int(raw_index)+ count = int(raw_count)+ except ValueError as error:+ raise ValueError(+ f"{_SHARD_ENV} must use one-based INDEX/COUNT syntax, got {value!r}"+ ) from error+ if count <= 0 or index <= 0 or index > count:+ raise ValueError(+ f"{_SHARD_ENV} must satisfy 1 <= INDEX <= COUNT, got {value!r}"+ )+ return index - 1, countdiff --git a/moli-cdp-smoke/tests/test_multi_page_support.py b/moli-cdp-smoke/tests/test_multi_page_support.pynew file mode 100644index 000000000..47a2d1733--- /dev/null+++ b/moli-cdp-smoke/tests/test_multi_page_support.py@@ -0,0 +1,120 @@+from __future__ import annotations++import os+import unittest+from typing import Any+from unittest.mock import patch++from moli_cdp_smoke.groups.multi_page_support import (+ multi_page_case_name,+ run_multi_page_cases,+ select_multi_page_cases,+)+++async def _alpha(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+) -> None:+ results.append({"case": "alpha"})+++async def _beta(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+) -> None:+ results.append({"case": "beta"})+++async def _gamma(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+) -> None:+ results.append({"case": "gamma"})+++class MultiPageCaseSelectionTests(unittest.TestCase):+ def test_case_name_hides_private_function_prefix(self) -> None:+ self.assertEqual(multi_page_case_name(_alpha), "alpha")++ def test_explicit_selection_preserves_requested_order_and_deduplicates(+ self,+ ) -> None:+ selected = select_multi_page_cases(+ (_alpha, _beta, _gamma),+ requested="gamma, alpha,gamma",+ shard="",+ )++ self.assertEqual(selected, (_gamma, _alpha))++ def test_one_based_shards_partition_the_selected_cases(self) -> None:+ first = select_multi_page_cases(+ (_alpha, _beta, _gamma),+ requested="",+ shard="1/2",+ )+ second = select_multi_page_cases(+ (_alpha, _beta, _gamma),+ requested="",+ shard="2/2",+ )++ self.assertEqual(first, (_alpha, _gamma))+ self.assertEqual(second, (_beta,))++ def test_unknown_case_and_invalid_shard_are_rejected(self) -> None:+ with self.assertRaisesRegex(ValueError, "unknown MOLI_MULTI_PAGE_CASES"):+ select_multi_page_cases((_alpha,), requested="missing", shard="")+ with self.assertRaisesRegex(ValueError, "one-based INDEX/COUNT"):+ select_multi_page_cases((_alpha,), requested="", shard="zero")+ with self.assertRaisesRegex(ValueError, "1 <= INDEX <= COUNT"):+ select_multi_page_cases((_alpha,), requested="", shard="2/1")+++class MultiPageCaseRunnerTests(unittest.IsolatedAsyncioTestCase):+ async def test_runner_finishes_remaining_cases_before_reporting_failures(+ self,+ ) -> None:+ observed: list[str] = []++ async def _fails(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+ ) -> None:+ observed.append("fails")+ raise RuntimeError("expected failure")++ async def _survives(+ browser: Any,+ fixture: str,+ results: list[dict[str, Any]],+ ) -> None:+ observed.append("survives")++ with (+ patch.dict(+ os.environ,+ {"MOLI_MULTI_PAGE_CASES": "", "MOLI_MULTI_PAGE_SHARD": ""},+ ),+ self.assertRaises(ExceptionGroup) as raised,+ ):+ await run_multi_page_cases(+ object(),+ "http://fixture.test",+ [],+ (_fails, _survives),+ timeout_seconds=1,+ )++ self.assertEqual(observed, ["fails", "survives"])+ self.assertEqual(len(raised.exception.exceptions), 1)+ self.assertIn("expected failure", str(raised.exception.exceptions[0]))+++if __name__ == "__main__":+ unittest.main()diff --git a/moli-protocol/src/conn/browser_context/lookup.rs b/moli-protocol/src/conn/browser_context/lookup.rsindex bbc09cb2c..e4dc34377 100644--- a/moli-protocol/src/conn/browser_context/lookup.rs+++ b/moli-protocol/src/conn/browser_context/lookup.rs@@ -81,17 +81,17 @@ impl CdpConnection {.map(|bc| bc.id.as_str())}- pub(crate) async fn apply_parked_target_surface_overrides_async(+ pub(crate) async fn apply_background_target_surface_overrides_async(&mut self,target_id: &str,- ) -> Result<bool, String> {+ ) -> anyhow::Result<bool> {let browser_context_id = self.browser_context_id_for_target(target_id).map(str::to_owned)- .ok_or_else(|| "UnknownTargetId".to_owned())?;+ .ok_or_else(|| anyhow::anyhow!("UnknownTargetId"))?;self.browser_context_by_id_mut(&browser_context_id)- .ok_or_else(|| "UnknownBrowserContextId".to_owned())?- .apply_parked_target_surface_overrides_async(target_id)+ .ok_or_else(|| anyhow::anyhow!("UnknownBrowserContextId"))?+ .apply_background_target_surface_overrides_async(target_id).await}}diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rsindex ac2b9fd80..cb28a58c0 100644--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs@@ -248,7 +248,7 @@ impl TargetNavigationLoadInputs {let generated_surface_script = if browser_context.is_active_target(target_id) {browser_context.generated_surface_override_script_for_active_target()} else {- browser_context.generated_surface_override_script_for_parked_state(page_state)+ browser_context.generated_surface_override_script_for_background_state(page_state)};if let Some(script) = generated_surface_script {document_start_scripts.push(script);@@ -1413,18 +1413,16 @@ impl CdpConnection {let closed = self.close_page_target_for_target_close_async(&target_id, out, reason).await?;- let promoted_target_id = if let Some(browser_context) = self.browser_context.as_mut() {- browser_context- .promote_last_background_target_to_active_async()- .await+ let selected_target_id = if let Some(browser_context) = self.browser_context.as_mut() {+ browser_context.select_last_background_target_async().await} else {None};self.refresh_active_browser_context_loader_async().await;- if let Some(promoted_target_id) = promoted_target_id {- self.notify_target_host_activated(&promoted_target_id);+ if let Some(selected_target_id) = selected_target_id {+ self.notify_target_host_activated(&selected_target_id);out.extend(- self.page_screencast_session_ids_for_target(&promoted_target_id)+ self.page_screencast_session_ids_for_target(&selected_target_id).into_iter().map(|session_id| {BackgroundProtocolEvent::page_screencast_visibility_changed(@@ -2628,7 +2626,9 @@ mod tests {}assert!(parked- .background_target_owner_state_or_default_for_test("TID-parked")+ .background_target("TID-parked")+ .expect("background target must exist")+ .owner_state.target_crash_state.is_crashed());@@ -2761,8 +2761,10 @@ mod tests {}assert!(parked- .nonempty_background_fetch_state_for_test("TID-parked")- .expect("parked fetch state")+ .background_target("TID-parked")+ .expect("background target must exist")+ .fetch_owner+ .pending_state().has_pending_subresource_fetch_for_test("FETCH-parked"));}@@ -2835,13 +2837,17 @@ mod tests {}assert!(parked- .non_default_background_page_target_for_test("TID-parked")+ .background_target("TID-parked")+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| !state.fetch_owner.is_enabled()));assert!(parked- .nonempty_background_fetch_state_for_test("TID-parked")- .is_none()+ .background_target("TID-parked")+ .expect("background target must exist")+ .fetch_owner+ .pending_state()+ .is_empty());}@@ -2871,12 +2877,14 @@ mod tests {}let mut parked = parked_target_context();- parked.mutate_background_target_owner_state_for_test("TID-parked", |owner_state| {- owner_state.record_loaded_page_navigation_history((+ parked+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .owner_state+ .record_loaded_page_navigation_history(("https://parked.example/".to_owned(),"parked".to_owned(),));- });{let mut owner = TargetSessionOwnerMut {browser_context: &mut parked,@@ -3011,7 +3019,10 @@ mod tests {Some("SID-parked".to_owned()),"about:blank".to_owned(),));- parked.mutate_background_page_target_for_test("TID-parked", |state| {+ {+ let state = parked+ .background_target_mut("TID-parked")+ .expect("background target must exist");state.runtime_slot.enable_primary_network_events();state.network_policy@@ -3025,7 +3036,7 @@ mod tests {request_stage: FetchRequestStage::Response,}],);- });+ }parked.background_target_mut("TID-parked").expect("background target should exist")@@ -3118,9 +3129,11 @@ mod tests {Some("SID-parked".to_owned()),"about:blank".to_owned(),));- parked.mutate_background_page_target_for_test("TID-parked", |state| {- state.runtime_slot.enable_primary_network_events();- });+ parked+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .runtime_slot+ .enable_primary_network_events();let mut owner = TargetSessionOwnerMut {browser_context: &mut parked,@@ -3166,7 +3179,10 @@ mod tests {Some("SID-parked".to_owned()),"https://parked.example/start".to_owned(),));- parked.mutate_background_page_target_for_test("TID-parked", |state| {+ {+ let state = parked+ .background_target_mut("TID-parked")+ .expect("background target must exist");state.set_base_locale_override(Some("fr-FR".to_owned()));state.set_base_timezone_override(Some("Europe/Paris".to_owned()));state.http_proxy_override = Some("http://proxy.example:8080".to_owned());@@ -3193,9 +3209,13 @@ mod tests {request_stage: FetchRequestStage::Request,}],);- });- parked.mutate_background_target_owner_state_for_test("TID-parked", |owner_state| {- owner_state.document_start_scripts.push((+ }+ parked+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .owner_state+ .document_start_scripts+ .push(("1".to_owned(),DocumentStartScript {registry_key: None,@@ -3206,14 +3226,14 @@ mod tests {bidi_channel_handoffs: Vec::new(),},));- });- parked.mutate_background_page_target_for_test("TID-parked", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .upsert_runtime_binding_definition(- "fromParkedBinding".to_owned(),- Some("utility".to_owned()),- );- });+ parked+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .upsert_runtime_binding_definition(+ "fromParkedBinding".to_owned(),+ Some("utility".to_owned()),+ );let owner = TargetSessionOwnerRef {browser_context: &parked,@@ -3292,7 +3312,10 @@ mod tests {Some("SID-parked".to_owned()),"about:blank".to_owned(),));- parked.mutate_background_page_target_for_test("TID-parked", |state| {+ {+ let state = parked+ .background_target_mut("TID-parked")+ .expect("background target must exist");state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.page_lifecycle_events = true;@@ -3308,7 +3331,7 @@ mod tests {request_stage: FetchRequestStage::Request,}],);- });+ }let commit_state = {let mut owner = TargetSessionOwnerMut {@@ -3383,13 +3406,17 @@ mod tests {Some("SID-parked".to_owned()),"about:blank".to_owned(),));- parked.mutate_background_target_owner_state_for_test("TID-parked", |owner_state| {+ {+ let owner_state = &mut parked+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .owner_state;owner_state.record_loaded_page_navigation_history(("https://old.example/".to_owned(),"old".to_owned(),));owner_state.mark_next_navigation_history_replace_current();- });+ }{let mut owner = TargetSessionOwnerMut {browser_context: &mut parked,@@ -3401,16 +3428,19 @@ mod tests {.clear_pending_navigation_history_update().expect("background history update should clear");}- parked.mutate_background_target_owner_state_for_test("TID-parked", |owner_state| {- owner_state.record_loaded_page_navigation_history((+ parked+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .owner_state+ .record_loaded_page_navigation_history(("https://new.example/".to_owned(),"new".to_owned(),));- });let (_, entries) = parked- .mutate_background_target_owner_state_for_test("TID-parked", |owner_state| {- owner_state.navigation_history_snapshot(None)- });+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .owner_state+ .navigation_history_snapshot(None);assert_eq!(entries.iter()@@ -3467,9 +3497,10 @@ mod tests {&& target.page_attachment_id() != initial_attachment_id);let (_, entries) = parked- .mutate_background_target_owner_state_for_test("TID-parked", |owner_state| {- owner_state.navigation_history_snapshot(None)- });+ .background_target_mut("TID-parked")+ .expect("background target must exist")+ .owner_state+ .navigation_history_snapshot(None);assert_eq!(entries.len(), 1);assert_eq!(entries[0].title, "background commit");}@@ -3601,11 +3632,12 @@ mod tests {[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled = true;- browser_context.mutate_background_page_target_for_test("TID-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .inspector_enabled = true;- });+ browser_context+ .background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .runtime_session_state+ .inspector_enabled = true;conn.browser_context = Some(browser_context);conn.with_target_owner_state_for_session_mut(Some("SID-active"), |owner_state| {@@ -3807,11 +3839,12 @@ mod tests {Some("SID-background".to_owned()),"https://background.example/".to_owned(),));- active.mutate_background_page_target_for_test("TID-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .page_session_state- .log_enabled = true;- });+ active+ .background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .page_session_state+ .log_enabled = true;assert!(active.assign_auxiliary_session_to_target("TID-background",@@ -3936,7 +3969,8 @@ mod tests {));assert!(browser_context- .non_default_background_page_target_for_test("TID-background-dialog")+ .background_target("TID-background-dialog")+ .filter(|target| target.has_non_default_session_state()).is_none(),"a background target with default protocol settings should not allocate parked overrides");@@ -3955,7 +3989,8 @@ mod tests {let browser_context = conn.browser_context.as_ref().expect("browser context");assert!(browser_context- .non_default_background_page_target_for_test("TID-background-dialog")+ .background_target("TID-background-dialog")+ .filter(|target| target.has_non_default_session_state()).is_none(),"clearing an empty dialog list should fold the temporary session state");diff --git a/moli-protocol/src/conn/dispatch_tests.rs b/moli-protocol/src/conn/dispatch_tests.rsindex e5d151d28..9cc520271 100644--- a/moli-protocol/src/conn/dispatch_tests.rs+++ b/moli-protocol/src/conn/dispatch_tests.rs@@ -8218,12 +8218,10 @@ async fn pending_emulation_viewport_keeps_original_page_when_active_target_chang};assert!(- conn.promote_background_target_to_active_for_connection_async(- "TID-emulation-viewport-replacement",- )- .await- .expect("target activation should succeed")- .is_some()+ conn.select_page_target_for_connection_async("TID-emulation-viewport-replacement",)+ .await+ .expect("target activation should succeed")+ .is_some());let messages = complete_command_task_for_test(&mut conn, *pending).await;@@ -8685,7 +8683,8 @@ async fn devtools_network_intercept_commands_route_to_fetch_owner() {conn.browser_context.as_ref().expect("browser context")- .non_default_background_page_target_for_test("TID-bidi-intercept-background")+ .background_target("TID-bidi-intercept-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.fetch_owner.is_enabled()),"background target should own the intercept");@@ -8707,7 +8706,8 @@ async fn devtools_network_intercept_commands_route_to_fetch_owner() {conn.browser_context.as_ref().expect("browser context")- .non_default_background_page_target_for_test("TID-bidi-intercept-background")+ .background_target("TID-bidi-intercept-background")+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| !state.fetch_owner.is_enabled()),"target-less remove should clear the background intercept");diff --git a/moli-protocol/src/conn/page_state.rs b/moli-protocol/src/conn/page_state.rsindex 8f9b9fa90..adf4160ff 100644--- a/moli-protocol/src/conn/page_state.rs+++ b/moli-protocol/src/conn/page_state.rs@@ -1,6 +1,6 @@mod fetch_state;mod loaded;-mod parked;+mod page_targets;mod surfaces;pub(crate) use loaded::{LoadedNavigationPageCommit, LoadedNavigationRendererAttachmentCommit};diff --git a/moli-protocol/src/conn/page_state/parked.rs b/moli-protocol/src/conn/page_state/page_targets.rssimilarity index 82%rename from moli-protocol/src/conn/page_state/parked.rsrename to moli-protocol/src/conn/page_state/page_targets.rsindex e2d30cf3f..1a21bc2f4 100644--- a/moli-protocol/src/conn/page_state/parked.rs+++ b/moli-protocol/src/conn/page_state/page_targets.rs@@ -1,3 +1,5 @@+//! Stable page-target registry behavior and foreground target selection.+use super::super::state::{TargetPageAbsenceReason, TargetSessionStorageNamespace};use super::super::{BrowserContext, DedicatedWorkerTargetState, PageTargetHost, ServiceWorkerTargetState,@@ -99,7 +101,7 @@ impl BrowserContext {debug_assert!(inserted, "staged page target id must be unique");}- pub(crate) fn stage_active_target_demoting_current(+ pub(crate) fn stage_foreground_target(&mut self,target_id: String,session_id: Option<String>,@@ -432,7 +434,7 @@ impl BrowserContext {let surface_script = if is_active {self.generated_surface_override_script_for_active_target()} else {- self.generated_surface_override_script_for_parked_target(target_id)+ self.generated_surface_override_script_for_background_target(target_id)};let cleared_emulated_media = moli_core::page::EmulatedMediaOverrides::default();@@ -551,10 +553,8 @@ impl BrowserContext {}#[cfg(test)]- pub(crate) async fn promote_first_background_target_to_active_async(- &mut self,- ) -> Option<String> {- let promoted = self+ pub(crate) async fn select_first_background_target_async(&mut self) -> Option<String> {+ let selected_target_id = self.background_targets().find(|target| target.has_loaded_page()).map(|target| target.target_id().to_owned())@@ -563,19 +563,17 @@ impl BrowserContext {.next().map(|target| target.target_id().to_owned())})?;- self.promote_selected_background_target_to_active_async(promoted)+ self.select_background_target_async(selected_target_id).await}- pub(crate) async fn promote_last_background_target_to_active_async(- &mut self,- ) -> Option<String> {- let promoted = self.last_promotable_background_target_id()?;- self.promote_selected_background_target_to_active_async(promoted)+ pub(crate) async fn select_last_background_target_async(&mut self) -> Option<String> {+ let selected_target_id = self.last_selectable_background_target_id()?;+ self.select_background_target_async(selected_target_id).await}- pub(crate) fn last_promotable_background_target_id(&self) -> Option<String> {+ pub(crate) fn last_selectable_background_target_id(&self) -> Option<String> {self.background_targets().rev().find(|target| target.has_loaded_page())@@ -587,20 +585,17 @@ impl BrowserContext {})}- async fn promote_selected_background_target_to_active_async(- &mut self,- promoted: String,- ) -> Option<String> {- self.promote_background_target_to_active_slot_async(&promoted)+ async fn select_background_target_async(&mut self, target_id: String) -> Option<String> {+ self.select_page_target_async(&target_id).await- .expect("applying promoted target visibility should succeed")- .then_some(promoted)+ .expect("applying selected target visibility should succeed")+ .then_some(target_id)}- pub(crate) async fn promote_background_target_to_active_slot_async(+ pub(crate) async fn select_page_target_async(&mut self,target_id: &str,- ) -> Result<bool, String> {+ ) -> anyhow::Result<bool> {if self.is_active_target(target_id) {return Ok(true);}@@ -615,10 +610,10 @@ impl BrowserContext {.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 {+ let previous_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)+ self.generated_surface_override_script_for_background_state(host)})} else {None@@ -629,7 +624,7 @@ impl BrowserContext {self.apply_surface_overrides_to_loaded_page_async().await?;}if let (Some(previous_active_target_id), Some(script)) =- (previous_active_target_id, demoted_surface_script)+ (previous_active_target_id, previous_surface_script)&& let Some(page) = self.page_target_mut(&previous_active_target_id).and_then(|host| host.runtime_slot.loaded_page_mut())@@ -637,81 +632,11 @@ impl BrowserContext {.run_page_surface_override_script_async(&script.source).await{- tracing::warn!(target_id = previous_active_target_id, %error, "failed to update demoted page visibility");- }- Ok(true)- }-- #[cfg(test)]- pub(crate) async fn demote_active_target_to_background_slot_async(- &mut self,- ) -> Result<bool, String> {- let Some(active_target_id) = self.active_target_id_owned() else {- return Ok(false);- };- let surface_script = self- .page_target(&active_target_id)- .and_then(|host| self.generated_surface_override_script_for_parked_state(host));- 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())?;+ tracing::warn!(target_id = previous_active_target_id, %error, "failed to update background page visibility");}- self.clear_active_target_id();Ok(true)}- #[cfg(test)]- pub fn take_background_document_start_script_counter_for_test(- &mut self,- target_id: &str,- ) -> u32 {- let owner_state = &mut self- .background_target_mut(target_id)- .expect("background target must exist")- .owner_state;- let counter = owner_state.next_document_start_script_id;- owner_state.next_document_start_script_id = 0;- counter- }-- #[cfg(test)]- pub fn replace_background_document_start_script_counter_for_test(- &mut self,- target_id: String,- counter: u32,- ) {- self.background_target_mut(&target_id)- .expect("background target must exist")- .owner_state- .next_document_start_script_id = counter;- }-- #[cfg(test)]- pub(crate) fn non_default_background_page_target_for_test(- &self,- target_id: &str,- ) -> Option<&crate::conn::state::PageTargetHost> {- let state = self.background_target(target_id)?;- state.has_non_default_session_state().then_some(state)- }-- #[cfg(test)]- pub fn mutate_background_page_target_for_test<T>(- &mut self,- target_id: &str,- mutate: impl FnOnce(&mut crate::conn::state::PageTargetHost) -> T,- ) -> T {- mutate(- self.background_target_mut(target_id)- .expect("background target must exist"),- )- }-pub(crate) fn begin_active_target_initial_empty_document(&mut self, initial_url: String) {self.begin_active_target_initial_empty_document_with_storage_key(initial_url, None);}@@ -777,51 +702,6 @@ impl BrowserContext {Some(mutate(&mut self.page_target_mut(target_id)?.owner_state))}- #[cfg(test)]- pub(crate) fn mutate_background_target_owner_state_for_test<T>(- &mut self,- target_id: &str,- mutate: impl FnOnce(&mut TargetOwnerState) -> T,- ) -> T {- mutate(- &mut self- .background_target_mut(target_id)- .expect("background target must exist")- .owner_state,- )- }-- #[cfg(test)]- pub(crate) fn non_default_background_target_owner_state_for_test(- &self,- target_id: &str,- ) -> Option<&TargetOwnerState> {- let state = &self.background_target(target_id)?.owner_state;- (!state.is_default()).then_some(state)- }-- #[cfg(test)]- pub(crate) fn background_target_owner_state_or_default_for_test(- &self,- target_id: &str,- ) -> TargetOwnerState {- self.background_target(target_id)- .map(|target| target.owner_state.clone())- .unwrap_or_default()- }-- #[cfg(test)]- pub(crate) fn nonempty_background_fetch_state_for_test(- &self,- target_id: &str,- ) -> Option<&crate::conn::state::TargetFetchState> {- let state = self- .background_target(target_id)?- .fetch_owner- .pending_state();- (!state.is_empty()).then_some(state)- }-#[cfg(test)]pub(crate) fn target_info(&self, target_id: &str) -> Option<serde_json::Value> {self.devtools_target_info(target_id)@@ -1336,8 +1216,6 @@ fn background_target_identity_for_initial_url(#[cfg(test)]mod tests {- use std::sync::Arc;-use super::*;use crate::conn::state::{PerformanceTimeDomain, TargetPerformanceSessionState};use crate::conn::{@@ -1346,6 +1224,7 @@ mod tests {};use crate::testing::TestContext;use serde_json::json;+ use std::sync::Arc;#[test]fn independent_top_level_targets_isolate_session_storage_but_share_local_storage() {@@ -1447,7 +1326,7 @@ mod tests {}#[test]- fn demoted_target_retains_its_session_storage_namespace() {+ fn changing_foreground_selection_retains_each_session_storage_namespace() {let mut context = BrowserContext::new("BC-demoted-storage".to_owned());context.set_active_target_id("TID-first");let first_session_storage = context.page_storage_handles().session_storage_store.clone();@@ -1457,27 +1336,27 @@ mod tests {.set_item("https://same.test", "session", "first"));- context.stage_active_target_demoting_current(+ context.stage_foreground_target("TID-second".to_owned(),None,"about:blank".to_owned(),None,);- let parked_first_storage = context+ let first_target_storage = context.page_storage_handles_for_target("TID-first")- .expect("demoted target should retain storage");+ .expect("previous target should retain storage");let second_storage = context.page_storage_handles();assert!(Arc::ptr_eq(&first_session_storage,- &parked_first_storage.session_storage_store+ &first_target_storage.session_storage_store));assert!(!Arc::ptr_eq(&first_session_storage,&second_storage.session_storage_store));assert_eq!(- parked_first_storage+ first_target_storage.session_storage_store.lock().get_item("https://same.test", "session"),@@ -1485,33 +1364,6 @@ mod tests {);}- #[test]- fn replacing_active_target_releases_its_session_storage_namespace() {- let mut context = BrowserContext::new("BC-replaced-storage".to_owned());- context.set_active_target_id("TID-first");- let first_session_storage = context.page_storage_handles().session_storage_store.clone();- assert!(- first_session_storage- .lock()- .set_item("https://same.test", "session", "first")- );-- context.clear_active_target_id();- context.set_active_target_id("TID-second");- let second_session_storage = context.page_storage_handles().session_storage_store.clone();-- assert!(!Arc::ptr_eq(- &first_session_storage,- &second_session_storage- ));- assert_eq!(- second_session_storage- .lock()- .get_item("https://same.test", "session"),- None- );- }-#[test]fn window_open_target_registry_preserves_named_target_bytes() {assert_eq!(@@ -1551,8 +1403,11 @@ mod tests {None,None,);- context.replace_background_document_start_script_counter_for_test("TID-bg".to_owned(), 7);- context.mutate_background_page_target_for_test("TID-bg", |state| {+ {+ let state = context+ .background_target_mut("TID-bg")+ .expect("background target must exist");+ state.owner_state.next_document_start_script_id = 7;state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =DevToolsSessionState {runtime_session_state: TargetRuntimeSessionState {@@ -1561,7 +1416,7 @@ mod tests {},..Default::default()};- });+ }let host = context.background_target("TID-bg")@@ -1581,16 +1436,14 @@ mod tests {);assert!(context- .non_default_background_page_target_for_test("TID-bg")+ .background_target("TID-bg")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled));- assert_eq!(- context.take_background_document_start_script_counter_for_test("TID-bg"),- 7- );+ assert_eq!(host.owner_state.next_document_start_script_id, 7);}#[test]@@ -1634,80 +1487,8 @@ mod tests {);}- #[test]- 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());- context.set_target_url("https://active.test/".to_owned());- context.set_target_security_origin("https://active.test".to_owned());- context.set_target_secure_context_type("Secure".to_owned());- context- .active_page_target_mut()- .runtime_slot- .set_page_attachment_id_for_test(42);- context.active_page_target_mut().devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled = true;- context.active_page_target_mut().devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .inspector_enabled = true;- context- .active_page_target_mut()- .owner_state- .next_document_start_script_id = 3;- context- .active_page_target_mut()- .owner_state- .document_start_scripts- .push((- "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,- bidi_channel_handoffs: Vec::new(),- },- ));-- context.clear_active_target_id();- let host = context- .page_target("TID-active")- .expect("clearing foreground selection must not remove the host");-- 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!(- host.target_identity().security_origin(),- "https://active.test"- );- assert_eq!(host.target_identity().secure_context_type(), "Secure");- assert_eq!(- host.page_attachment_id()- .map(|attachment_id| attachment_id.get()),- Some(42)- );- assert_eq!(host.owner_state.document_start_scripts.len(), 1);- assert!(- host.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled- );- assert!(- host.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .inspector_enabled- );- assert_eq!(host.owner_state.next_document_start_script_id, 3);- }-#[tokio::test(flavor = "multi_thread")]- async fn active_target_demote_to_background_slot_preserves_page_session_and_owner_state() {+ async fn selecting_another_foreground_target_preserves_page_session_and_owner_state() {let mut ctx = TestContext::new();let active_page = ctx.conn@@ -1791,162 +1572,170 @@ mod tests {.runtime_slot.current_renderer_attachment().expect("loaded active page should have a renderer attachment");+ context.stage_background_target(+ "TID-selected".to_owned(),+ Some("SID-selected".to_owned()),+ "about:blank#selected".to_owned(),+ None,+ None,+ );- assert!(+ assert_eq!(context- .demote_active_target_to_background_slot_async()+ .select_background_target_async("TID-selected".to_owned()).await- .expect("demote should not fail")+ .as_deref(),+ Some("TID-selected"));- assert_eq!(context.active_target_id(), None);+ assert_eq!(context.active_target_id(), Some("TID-selected"));assert!(context.page_target("TID-demote").is_some_and(|host| host.has_loaded_page()),- "demoting should retain the loaded page in its stable host"+ "changing foreground selection must retain the loaded page in its stable host");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"));+ let background_target = &context.background_target_at(0).unwrap();+ assert_eq!(background_target.target_id(), "TID-demote");+ assert_eq!(background_target.session_id(), Some("SID-demote"));assert_eq!(- parked.target_url(),+ background_target.target_url(),"data:text/html,<title>demote-active</title>");assert!(- parked.has_loaded_page(),- "demoting should move the loaded page back into the parked target"+ background_target.has_loaded_page(),+ "the loaded page must remain in the same stable target host");assert_eq!(- parked+ background_target.runtime_slot().current_renderer_attachment().map(|attachment| attachment.id()),Some(active_attachment.id()),- "demoting a target must move its renderer channel without allocating a new route lease"+ "changing foreground selection must not reallocate the renderer channel");assert_eq!(- parked+ background_target.loaded_page().and_then(|page| page.renderer_agent_attachment_id()),Some(active_attachment.id()),- "the parked Page and its renderer channel must retain the same attachment"+ "the background Page and its renderer channel must retain the same attachment");assert!(- parked.runtime_slot.primary_network_events_enabled(),- "demoted target runtime slot should mirror parked Network.enable state for direct owner backlog delivery"+ background_target+ .runtime_slot+ .primary_network_events_enabled(),+ "the stable target runtime slot must retain Network.enable state");assert!(context- .non_default_background_page_target_for_test("TID-demote")+ .background_target("TID-demote")+ .filter(|target| target.has_non_default_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"+ "session-scoped Runtime.enable state must remain owned by the target");- let non_default_background_page_target_for_test = context- .non_default_background_page_target_for_test("TID-demote")- .expect("demoted target should retain parked page session state");+ let background_state = context+ .background_target("TID-demote")+ .filter(|target| target.has_non_default_session_state())+ .expect("background target should retain page session state");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled,- "Runtime.enable state should move with the demoted target"+ "Runtime.enable state must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.inspector_enabled,- "Inspector.enable state should move with the demoted target"+ "Inspector.enable state must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].console_output_session_state.console_enabled,- "Console.enable state should move with the demoted target"+ "Console.enable state must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.log_enabled,- "Log.enable state should move with the demoted target"+ "Log.enable state must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.performance.enabled(),- "Performance.enable state should move with the demoted target"+ "Performance.enable state must remain target-owned");assert_eq!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.performance.time_domain(),PerformanceTimeDomain::ThreadTicks,- "Performance time domain should move with the demoted target"+ "Performance time domain must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.page_lifecycle_events,- "Page lifecycle listener state should move with the demoted target"+ "Page lifecycle listener state must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_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"+ "file chooser opened listener state must remain target-owned");assert!(- non_default_background_page_target_for_test.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]+ background_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"+ "file chooser interception state must remain target-owned");assert_eq!(- context.take_background_document_start_script_counter_for_test("TID-demote"),+ context+ .background_target("TID-demote")+ .expect("previous target must remain registered")+ .owner_state+ .next_document_start_script_id,9,- "target owner state should be parked with the target"+ "owner state must remain target-owned");assert_eq!(context- .non_default_background_target_owner_state_for_test("TID-demote")- .expect("demoted target should retain owner state")+ .background_target("TID-demote")+ .expect("background target should retain owner state")+ .owner_state.document_start_scripts.len(),1,- "document-start scripts should be parked with the target owner state"+ "document-start scripts must remain target-owned");- let parked_runtime = &context+ let background_runtime = &context.background_target("TID-demote")- .expect("demoted target should retain network state")+ .expect("background target should retain network state").runtime_slot;- assert_eq!(parked_runtime.next_fetch_request_id_for_test(), 77);+ assert_eq!(background_runtime.next_fetch_request_id_for_test(), 77);assert_eq!(- parked_runtime.next_subresource_fetch_request_id_for_test(),+ background_runtime.next_subresource_fetch_request_id_for_test(),88);assert_eq!(- parked_runtime.emitted_subresource_record_count_for_session_for_test(None),+ background_runtime.emitted_subresource_record_count_for_session_for_test(None),3,- "target network artifacts should move into the parked target runtime slot"+ "network artifacts must remain in the stable target runtime slot");}- #[tokio::test]- async fn active_target_demote_without_active_target_is_noop() {+ #[test]+ fn staging_background_target_in_empty_context_leaves_foreground_empty() {let mut context = BrowserContext::new("BC-demote-empty".to_owned());context.stage_background_target("TID-existing-bg".to_owned(),@@ -1956,13 +1745,6 @@ mod tests {None,);- assert!(- !context- .demote_active_target_to_background_slot_async()- .await- .expect("no-op demote should not fail")- );-assert_eq!(context.active_target_id(), None);assert_eq!(context.background_target_count(), 1);assert_eq!(@@ -1976,13 +1758,13 @@ mod tests {}#[test]- fn active_target_demote_without_page_preserves_pending_initial_document_reason() {+ fn selecting_new_target_preserves_previous_pending_initial_document_reason() {let mut context = BrowserContext::new("BC-demote-pending".to_owned());context.set_active_target_id("TID-old-active");context.set_target_url("about:blank#old".to_owned());context.begin_active_target_initial_empty_document("about:blank#old".to_owned());- context.stage_active_target_demoting_current(+ context.stage_foreground_target("TID-new-active".to_owned(),Some("SID-new-active".to_owned()),"about:blank#new".to_owned(),@@ -1992,11 +1774,11 @@ mod tests {assert_eq!(context.background_target("TID-old-active")- .expect("previous active target should be parked")+ .expect("previous active target should remain registered").runtime_slot().moli_memory_diagnostics()["loadedPageAbsenceReason"],json!("initial-document-page-build-pending"),- "production demotion must preserve a pending initial document absence reason"+ "foreground selection must preserve a pending initial document absence reason");assert_eq!(context@@ -2021,9 +1803,9 @@ mod tests {assert!(context- .promote_background_target_to_active_slot_async("TID-pending-bg")+ .select_page_target_async("TID-pending-bg").await- .expect("pending background target should still promote")+ .expect("pending background target should remain selectable"));assert_eq!(@@ -2032,12 +1814,12 @@ mod tests {.runtime_slot.moli_memory_diagnostics()["loadedPageAbsenceReason"],json!("initial-document-page-build-pending"),- "production promotion must preserve a pending initial document absence reason"+ "foreground selection must preserve a pending initial document absence reason");}#[tokio::test(flavor = "multi_thread")]- async fn promote_first_background_target_prefers_first_loaded_target() {+ async fn select_first_background_target_prefers_first_loaded_target() {let mut ctx = TestContext::new();let first_loaded_page = ctx.conn@@ -2093,12 +1875,12 @@ mod tests {.current_renderer_attachment().expect("second loaded background target should have an attachment");- let promoted = context- .promote_first_background_target_to_active_async()+ let selected = context+ .select_first_background_target_async().await- .expect("loaded background target should promote");+ .expect("loaded background target should be selectable");- assert_eq!(promoted, "TID-first-loaded");+ assert_eq!(selected, "TID-first-loaded");assert_eq!(context.active_target_id(), Some("TID-first-loaded"));assert_eq!(context.active_session_id(), Some("SID-first-loaded"));assert!(@@ -2112,13 +1894,13 @@ mod tests {.current_renderer_attachment().map(|attachment| attachment.id()),Some(first_attachment.id()),- "promotion must move the selected target's renderer channel with its Page"+ "selection must preserve the target's renderer channel and Page");assert!(context.background_target("TID-second-loaded").is_some_and(PageTargetHost::has_loaded_page),- "later loaded background target should remain parked"+ "later loaded background target should remain in the background");assert_eq!(context@@ -2170,9 +1952,9 @@ mod tests {assert!(context- .promote_background_target_to_active_slot_async("TID-background-route")+ .select_page_target_async("TID-background-route").await- .expect("target swap should succeed")+ .expect("target selection should succeed"));assert_eq!(@@ -2193,7 +1975,7 @@ mod tests {}#[tokio::test]- async fn background_target_promotion_restores_nested_page_session_state() {+ async fn background_target_selection_preserves_nested_page_session_state() {let mut context = BrowserContext::new("BC-promote".to_owned());context.stage_background_target("TID-bg".to_owned(),@@ -2226,10 +2008,11 @@ mod tests {devtools_session_state.console_output_session_state.console_enabled = true;- context.mutate_background_page_target_for_test("TID-bg", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =- devtools_session_state;- });+ context+ .background_target_mut("TID-bg")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =+ devtools_session_state;context.background_target_mut("TID-bg").expect("background target")@@ -2238,9 +2021,9 @@ mod tests {assert!(context- .promote_background_target_to_active_slot_async("TID-bg")+ .select_page_target_async("TID-bg").await- .expect("promotion should not fail")+ .expect("target selection should not fail"));assert_eq!(context.active_target_id(), Some("TID-bg"));diff --git a/moli-protocol/src/conn/page_state/surfaces.rs b/moli-protocol/src/conn/page_state/surfaces.rsindex a90fc1192..a5444b065 100644--- a/moli-protocol/src/conn/page_state/surfaces.rs+++ b/moli-protocol/src/conn/page_state/surfaces.rs@@ -39,7 +39,7 @@ impl SurfaceOverrideInputs {}}- fn from_parked(+ fn from_background(state: &PageTargetHost,default_network_conditions: Option<EmulatedNetworkConditions>,default_geolocation_override: Option<EmulatedGeolocationOverrideState>,@@ -99,7 +99,7 @@ impl SurfaceOverrideInputs {fn document_is_focused(&self) -> bool {// Focus and Page Visibility are target-state surfaces, not raw mirrors// of the CDP focus-emulation flag. Chrome's created active targets- // report focused and visible by default; parked/background targets+ // report focused and visible by default; background targets// stay unfocused/hidden unless CDP explicitly asks to simulate a// focused and active page.(self.active_target_surface && !self.window_document_hidden) || self.focus_emulation_enabled@@ -352,34 +352,36 @@ impl BrowserContext {))}- pub(crate) fn generated_surface_override_script_for_parked_target(+ pub(crate) fn generated_surface_override_script_for_background_target(&self,target_id: &str,) -> Option<DocumentStartScript> {let target = self.background_target(target_id)?;- self.generated_surface_override_script_for_parked_state(target)+ self.generated_surface_override_script_for_background_state(target)}- pub(crate) fn generated_surface_override_script_for_parked_state(+ pub(crate) fn generated_surface_override_script_for_background_state(&self,state: &PageTargetHost,) -> Option<DocumentStartScript> {- Self::generated_surface_override_script_from_inputs(&SurfaceOverrideInputs::from_parked(- state,- self.default_network_conditions- .or(self.global_network_conditions),- self.default_geolocation_override- .clone()- .or_else(|| self.global_geolocation_override.clone()),- self.default_emulated_device_metrics.clone(),- ))+ Self::generated_surface_override_script_from_inputs(+ &SurfaceOverrideInputs::from_background(+ state,+ self.default_network_conditions+ .or(self.global_network_conditions),+ self.default_geolocation_override+ .clone()+ .or_else(|| self.global_geolocation_override.clone()),+ self.default_emulated_device_metrics.clone(),+ ),+ )}- pub(crate) async fn apply_parked_target_surface_overrides_async(+ pub(crate) async fn apply_background_target_surface_overrides_async(&mut self,target_id: &str,- ) -> Result<bool, String> {- let Some(script) = self.generated_surface_override_script_for_parked_target(target_id)+ ) -> anyhow::Result<bool> {+ let Some(script) = self.generated_surface_override_script_for_background_target(target_id)else {return Ok(false);};@@ -391,7 +393,7 @@ impl BrowserContext {};page.run_page_surface_override_script_async(&script.source).await- .map_err(|error| format!("failed to hide demoted page surface: {error}"))?;+ .map_err(|error| anyhow::anyhow!("failed to hide background page surface: {error}"))?;Ok(true)}@@ -602,7 +604,7 @@ impl BrowserContext {pub(crate) async fn apply_surface_overrides_to_loaded_page_async(&mut self,- ) -> Result<(), String> {+ ) -> anyhow::Result<()> {let Some(script) = self.generated_surface_override_script() else {return Ok(());};@@ -611,7 +613,7 @@ impl BrowserContext {};page.run_page_surface_override_script_async(&script.source).await- .map_err(|error| format!("failed to apply page surface overrides: {error}"))+ .map_err(|error| anyhow::anyhow!("failed to apply page surface overrides: {error}"))}#[cfg(test)]diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rsindex 063fe3aaf..172348f63 100644--- a/moli-protocol/src/conn/runtime_eval.rs+++ b/moli-protocol/src/conn/runtime_eval.rs@@ -8107,7 +8107,8 @@ mod tests {);assert!(browser_context- .non_default_background_page_target_for_test("TID-bg")+ .background_target("TID-bg")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].has_pending_inspector_awaits()),diff --git a/moli-protocol/src/conn/state/browser_context.rs b/moli-protocol/src/conn/state/browser_context.rsindex e1681eb12..6e2226c5e 100644--- a/moli-protocol/src/conn/state/browser_context.rs+++ b/moli-protocol/src/conn/state/browser_context.rs@@ -32,9 +32,9 @@ use super::{javascript_dialog::TargetPreparedJavaScriptDialog,page_slot::{DocumentNavigationToken, DocumentStartScript},page_target_host::{PageTargetHost, PageTargetRegistry},- parking::TargetOwnerState,service_worker_target::ServiceWorkerTargetState,shared_worker_target::SharedWorkerTargetState,+ target_state::TargetOwnerState,};pub struct BrowserContext {@@ -1677,11 +1677,6 @@ impl BrowserContext {self.page_targets.rekey_active(target_id.into())}- #[cfg(test)]- pub(crate) fn clear_active_target_id(&mut self) {- self.page_targets.clear_selection();- }-pub(crate) fn active_session_id(&self) -> Option<&str> {self.page_targets.active()?.session_id()}diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rsindex fcfdd651a..66539c765 100644--- a/moli-protocol/src/conn/state/devtools_session.rs+++ b/moli-protocol/src/conn/state/devtools_session.rs@@ -5,13 +5,13 @@ use std::{use super::{page_slot::RuntimeBindingDefinition,- parking::{PendingInspectorAwait, TargetPendingInspectorAwaitRegistry},pending_renderer_command::{DuplicatePendingRendererCommand, PreparedRendererCallDispatch, PreparedRendererCallReplay,PreparedRendererCallTermination, RegisterRendererCallError, RendererCallIdExhausted,RendererCommandCorrelation, RendererCommandDescriptor,},session::{InspectorSessionState, TargetPageSessionState, TargetRuntimeSessionState},+ target_state::{PendingInspectorAwait, TargetPendingInspectorAwaitRegistry},};use moli_core::{network::WebStorageMutationSubscription,diff --git a/moli-protocol/src/conn/state/javascript_dialog.rs b/moli-protocol/src/conn/state/javascript_dialog.rsindex 2a6a019fa..8f14ffb5e 100644--- a/moli-protocol/src/conn/state/javascript_dialog.rs+++ b/moli-protocol/src/conn/state/javascript_dialog.rs@@ -294,7 +294,7 @@ impl TargetJavaScriptDialog {/// Clearing dismisses every installed renderer completion. In-flight prepared/// output is authorized separately by the stable Page scope in/// `TargetRuntimeSlot`; keeping that authority out of this state lets an-/// otherwise-default parked session fold away without losing Page identity.+/// otherwise-default session state disappear without losing Page identity.#[derive(Debug, Clone, Default, PartialEq)]pub(crate) struct TargetJavaScriptDialogState {pending_dialogs: Vec<TargetJavaScriptDialog>,diff --git a/moli-protocol/src/conn/state/mod.rs b/moli-protocol/src/conn/state/mod.rsindex 28cb5a590..e87d57b4d 100644--- a/moli-protocol/src/conn/state/mod.rs+++ b/moli-protocol/src/conn/state/mod.rs@@ -17,7 +17,6 @@ mod page_residence_token;mod page_resource;mod page_slot;mod page_target_host;-mod parking;mod pending_renderer_command;mod profiler;mod runtime_slot;@@ -27,6 +26,7 @@ mod session;mod session_storage;mod shared_worker_attachment;mod shared_worker_target;+mod target_state;#[cfg(test)]mod tests;@@ -73,8 +73,6 @@ pub use page_slot::{DocumentStartScript, IsolatedWorldDefinition, RuntimeBindingpub(crate) use runtime_slot::{FinishedRendererDocumentNavigation, TargetRuntimeSlot};pub use fetch::TargetFetchConfig;-#[cfg(test)]-pub(crate) use fetch::TargetFetchState;pub(crate) use fetch::{TargetFetchOwner, TargetFetchSubresourceInterceptionSnapshot};pub(crate) use inspector::InspectorCommandDispatch;@@ -127,7 +125,7 @@ pub(crate) use emulation::{EmulatedNetworkConditions, EmulatedViewportSurface, viewport_surface_install_script,};pub use page_target_host::PageTargetHost;-pub(crate) use parking::{+pub(crate) use target_state::{PendingBidiChannelListener, PendingInspectorAwait, TargetInitialEmptyDocumentCreator,TargetOwnerState, TargetWindowSurfaceState,};diff --git a/moli-protocol/src/conn/state/page_target_host.rs b/moli-protocol/src/conn/state/page_target_host.rsindex 2b844fa87..76f03b3ba 100644--- a/moli-protocol/src/conn/state/page_target_host.rs+++ b/moli-protocol/src/conn/state/page_target_host.rs@@ -14,10 +14,10 @@ use super::{fetch::TargetFetchOwner,identity::TargetIdentityState,page_slot::TargetPageSlot,- parking::TargetOwnerState,runtime_slot::TargetRuntimeSlot,session::TargetNetworkPolicyState,session_storage::TargetSessionStorageNamespace,+ target_state::TargetOwnerState,};use crate::conn::cookie_manager_surface::BrowserContextCookieManagerSurface;@@ -338,11 +338,6 @@ impl PageTargetRegistry {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.values()}diff --git a/moli-protocol/src/conn/state/pending_renderer_command.rs b/moli-protocol/src/conn/state/pending_renderer_command.rsindex d30e3d7ab..634debbc0 100644--- a/moli-protocol/src/conn/state/pending_renderer_command.rs+++ b/moli-protocol/src/conn/state/pending_renderer_command.rs@@ -957,7 +957,7 @@ mod tests {let worker_descriptor = RendererCommandDescriptor::from_frontend_policy(frontend.json().to_owned(),frontend.renderer_policy(),- RendererInspectorResponseDelivery::CommandReply,+ RendererInspectorResponseDelivery::DevToolsSession,);let adapter_descriptor =RendererCommandDescriptor::from_synthesized_payload(frontend.json().to_owned())@@ -969,8 +969,8 @@ mod tests {);assert_eq!(worker_descriptor.response_delivery(),- RendererInspectorResponseDelivery::CommandReply,- "the method catalog must not choose a Page-only output capability for Workers"+ RendererInspectorResponseDelivery::DevToolsSession,+ "external Worker commands must publish through their DevTools session");assert_eq!(adapter_descriptor.response_delivery(),diff --git a/moli-protocol/src/conn/state/service_worker_target.rs b/moli-protocol/src/conn/state/service_worker_target.rsindex 64babf567..938afeee7 100644--- a/moli-protocol/src/conn/state/service_worker_target.rs+++ b/moli-protocol/src/conn/state/service_worker_target.rs@@ -9,7 +9,6 @@ use serde_json::Value;use crate::devtools_runtime::RuntimeExecutionContextEvent;-use super::parking::PendingInspectorAwait;use super::service_worker_lifetime::{TargetServiceWorkerProtocolAttachmentIdentity, TargetServiceWorkerProtocolAttachmentRetirement,TargetServiceWorkerProtocolAttachmentScope, TargetServiceWorkerRunIdentity,@@ -17,6 +16,7 @@ use super::service_worker_lifetime::{TargetServiceWorkerRuntimeAttachmentIdentity, TargetServiceWorkerVersionIdentity,TargetServiceWorkerVersionRetirement, TargetServiceWorkerVersionScope,};+use super::target_state::PendingInspectorAwait;use super::{DevToolsSessionState, DuplicatePendingRendererCommand, PreparedRendererCallDispatch,RegisterRendererCallError, RendererCommandCorrelation, RendererCommandDescriptor,diff --git a/moli-protocol/src/conn/state/shared_worker_target.rs b/moli-protocol/src/conn/state/shared_worker_target.rsindex c5e7d8d71..c96d2a80d 100644--- a/moli-protocol/src/conn/state/shared_worker_target.rs+++ b/moli-protocol/src/conn/state/shared_worker_target.rs@@ -14,11 +14,11 @@ use super::{DevToolsSessionState, DuplicatePendingRendererCommand, PreparedRendererCallDispatch,RegisterRendererCallError, RendererCommandCorrelation, RendererCommandDescriptor,page_slot::RuntimeBindingDefinition,- parking::PendingInspectorAwait,shared_worker_attachment::{TargetSharedWorkerProtocolAttachmentIdentity,TargetSharedWorkerProtocolAttachmentRetirement, TargetSharedWorkerProtocolAttachmentScope,},+ target_state::PendingInspectorAwait,};// Chromium does not reserve negative Runtime.ExecutionContextId values fordiff --git a/moli-protocol/src/conn/state/parking.rs b/moli-protocol/src/conn/state/target_state.rssimilarity index 99%rename from moli-protocol/src/conn/state/parking.rsrename to moli-protocol/src/conn/state/target_state.rsindex 11b13dc06..2b295caff 100644--- a/moli-protocol/src/conn/state/parking.rs+++ b/moli-protocol/src/conn/state/target_state.rs@@ -1,3 +1,5 @@+//! State owned for the lifetime of one stable protocol target.+use std::collections::HashSet;use moli_page_types::{DevToolsSessionKey, FrontendCommandId};diff --git a/moli-protocol/src/conn/state/tests.rs b/moli-protocol/src/conn/state/tests.rsindex afd69cf52..9e930b4af 100644--- a/moli-protocol/src/conn/state/tests.rs+++ b/moli-protocol/src/conn/state/tests.rs@@ -17,7 +17,7 @@ use super::navigation_outcome::{NavigationDispatchState, NavigationResultProjectuse super::page_slot::DocumentStartScript;use super::runtime_slot::TargetRuntimeSlot;use super::session::TargetPageSessionState;-use super::{PageTargetHost, parking::TargetOwnerState};+use super::{PageTargetHost, target_state::TargetOwnerState};use serde_json::json;use std::collections::HashMap;@@ -1634,8 +1634,10 @@ fn background_target_initial_empty_document_record_tracks_navigation_lifecycle());let initial = context- .non_default_background_target_owner_state_for_test("TID-initial-bg")- .and_then(TargetOwnerState::initial_empty_document_state)+ .background_target("TID-initial-bg")+ .expect("background target must exist")+ .owner_state+ .initial_empty_document_state().expect("background target should record initial empty document");assert_eq!(initial.target_id(), "TID-initial-bg");assert_eq!(initial.initial_url(), "about:blank#background");@@ -1645,8 +1647,10 @@ fn background_target_initial_empty_document_record_tracks_navigation_lifecycle()context.mark_target_initial_empty_document_materialized("TID-initial-bg");assert!(context- .non_default_background_target_owner_state_for_test("TID-initial-bg")- .and_then(TargetOwnerState::initial_empty_document_state)+ .background_target("TID-initial-bg")+ .expect("background target must exist")+ .owner_state+ .initial_empty_document_state().expect("initial empty document state").materialized());@@ -1656,16 +1660,20 @@ fn background_target_initial_empty_document_record_tracks_navigation_lifecycle().expect("background target should start document navigation");assert!(context- .non_default_background_target_owner_state_for_test("TID-initial-bg")- .and_then(TargetOwnerState::initial_empty_document_state)+ .background_target("TID-initial-bg")+ .expect("background target must exist")+ .owner_state+ .initial_empty_document_state().expect("initial empty document state").pending_cross_document_navigation());context.commit_document_navigation_if_matches(&token);let exited = context- .non_default_background_target_owner_state_for_test("TID-initial-bg")- .and_then(TargetOwnerState::initial_empty_document_state)+ .background_target("TID-initial-bg")+ .expect("background target must exist")+ .owner_state+ .initial_empty_document_state().expect("initial empty document state");assert!(exited.exited());assert!(!exited.pending_cross_document_navigation());diff --git a/moli-protocol/src/conn/target/activation.rs b/moli-protocol/src/conn/target/activation.rsindex 84e48ad4b..fa68c3e61 100644--- a/moli-protocol/src/conn/target/activation.rs+++ b/moli-protocol/src/conn/target/activation.rs@@ -3,36 +3,36 @@ use crate::conn::{BackgroundProtocolEvent, BrowserContext, CdpConnection};/// The stable Target identities on both sides of one foreground selection.#[derive(Clone, Debug, PartialEq, Eq)]pub(crate) struct TargetActivationTransition {- promoted_target_id: String,+ selected_target_id: String,previous_active_target_id: Option<String>,}impl TargetActivationTransition {pub(crate) fn new(- promoted_target_id: impl Into<String>,+ selected_target_id: impl Into<String>,previous_active_target_id: Option<String>,) -> Self {Self {- promoted_target_id: promoted_target_id.into(),+ selected_target_id: selected_target_id.into(),previous_active_target_id,}}- fn promoted_target_id(&self) -> &str {- &self.promoted_target_id+ fn selected_target_id(&self) -> &str {+ &self.selected_target_id}fn previous_active_target_id(&self) -> Option<&str> {self.previous_active_target_id.as_deref()}- fn demoted_target_id(&self) -> Option<&str> {+ fn previous_backgrounded_target_id(&self) -> Option<&str> {self.previous_active_target_id()- .filter(|target_id| *target_id != self.promoted_target_id())+ .filter(|target_id| *target_id != self.selected_target_id())}fn changed_active_target(&self) -> bool {- self.previous_active_target_id() != Some(self.promoted_target_id())+ self.previous_active_target_id() != Some(self.selected_target_id())}}@@ -62,11 +62,11 @@ impl CdpConnection {&mut self,transition: &TargetActivationTransition,) -> CompletedTargetActivation {- let Some(demoted_target_id) = transition.demoted_target_id() else {+ let Some(previous_target_id) = transition.previous_backgrounded_target_id() else {return CompletedTargetActivation::new(Vec::new());};let protocol_events = self- .page_screencast_session_ids_for_target(demoted_target_id)+ .page_screencast_session_ids_for_target(previous_target_id).into_iter().map(|session_id| {BackgroundProtocolEvent::page_screencast_visibility_changed(@@ -76,12 +76,12 @@ impl CdpConnection {}).collect();if let Err(error) = self- .apply_parked_target_surface_overrides_async(demoted_target_id)+ .apply_background_target_surface_overrides_async(previous_target_id).await{tracing::warn!(- target_id = demoted_target_id,- promoted_target_id = transition.promoted_target_id(),+ target_id = previous_target_id,+ selected_target_id = transition.selected_target_id(),%error,"failed to update Page visibility after target activation");@@ -89,26 +89,24 @@ impl CdpConnection {CompletedTargetActivation::new(protocol_events)}- pub(crate) async fn promote_background_target_to_active_for_connection_async(+ pub(crate) async fn select_page_target_for_connection_async(&mut self,target_id: &str,- ) -> Result<Option<CompletedTargetActivation>, String> {+ ) -> anyhow::Result<Option<CompletedTargetActivation>> {let previous_active_target_id = self.browser_context.as_ref().and_then(BrowserContext::active_target_id_owned);let transition = TargetActivationTransition::new(target_id, previous_active_target_id);let hidden_screencast_sessions = transition- .demoted_target_id()+ .previous_backgrounded_target_id().map(|active_target_id| self.page_screencast_session_ids_for_target(active_target_id)).unwrap_or_default();let Some(browser_context) = self.browser_context.as_mut() else {- return Err("BrowserContextNotLoaded".to_owned());+ anyhow::bail!("BrowserContextNotLoaded");};- let promoted = browser_context- .promote_background_target_to_active_slot_async(target_id)- .await?;- if !promoted {+ let selected = browser_context.select_page_target_async(target_id).await?;+ if !selected {return Ok(None);}self.refresh_active_browser_context_loader_async().await;@@ -118,7 +116,7 @@ impl CdpConnection {if transition.changed_active_target() {// Chromium's PageHandler reports RenderWidgetHost visibility only// while that attachment has an active screencast. Hide the old- // surface before exposing the promoted one.+ // surface before exposing the selected one.protocol_events.extend(hidden_screencast_sessions.into_iter().map(|session_id| {BackgroundProtocolEvent::page_screencast_visibility_changed(session_id.as_deref(),diff --git a/moli-protocol/src/conn/tests/resource_runtime.rs b/moli-protocol/src/conn/tests/resource_runtime.rsindex 3ec9ef5aa..f861c8c09 100644--- a/moli-protocol/src/conn/tests/resource_runtime.rs+++ b/moli-protocol/src/conn/tests/resource_runtime.rs@@ -1856,11 +1856,12 @@ async fn direct_runtime_evaluate_javascript_dialog_uses_inactive_background_ownelet mut inactive = BrowserContext::new("BID-dialog-background".into());inactive.insert_page_target_host(background);- inactive.mutate_background_page_target_for_test("TID-dialog-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled = true;- });+ inactive+ .background_target_mut("TID-dialog-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .runtime_session_state+ .runtime_frontend_enabled = true;ctx.conn.inactive_browser_contexts.push(inactive);ctx.install_navigation_fixture_for_session_owner(&page_url, Some("SID-dialog-background")).await;@@ -1938,7 +1939,8 @@ async fn direct_runtime_evaluate_javascript_dialog_uses_inactive_background_owne.expect("inactive owner should remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-dialog-background")+ .background_target("TID-dialog-background")+ .filter(|target| target.has_non_default_session_state()).expect("background page session state should remain parked").devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state@@ -1960,11 +1962,12 @@ async fn direct_runtime_evaluate_popup_creates_target_in_inactive_background_ownlet mut inactive = BrowserContext::new("BID-popup-background".into());inactive.insert_page_target_host(background);- inactive.mutate_background_page_target_for_test("TID-popup-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled = true;- });+ inactive+ .background_target_mut("TID-popup-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .runtime_session_state+ .runtime_frontend_enabled = true;ctx.conn.inactive_browser_contexts.push(inactive);ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-popup-background")).await;@@ -2049,11 +2052,12 @@ async fn direct_runtime_evaluate_self_popup_does_not_navigate_active_target_for_let mut inactive = BrowserContext::new("BID-self-popup-background".into());inactive.insert_page_target_host(background);- inactive.mutate_background_page_target_for_test("TID-self-popup-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled = true;- });+ inactive+ .background_target_mut("TID-self-popup-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .runtime_session_state+ .runtime_frontend_enabled = true;ctx.conn.inactive_browser_contexts.push(inactive);ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-self-popup-background")).await;@@ -2103,14 +2107,17 @@ async fn direct_runtime_evaluate_file_chooser_uses_inactive_background_owner() {let mut inactive = BrowserContext::new("BID-file-background".into());inactive.insert_page_target_host(background);- inactive.mutate_background_page_target_for_test("TID-file-background", |state| {+ {+ let state = inactive+ .background_target_mut("TID-file-background")+ .expect("background target must exist");state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled = true;state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state.page_file_chooser_opened_event_enabled = true;- });+ }ctx.conn.inactive_browser_contexts.push(inactive);ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-file-background")).await;@@ -2420,7 +2427,8 @@ async fn direct_network_enable_routes_to_inactive_background_owner_without_promo.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background session state should be staged").runtime_slot.primary_network_events_enabled()@@ -2460,7 +2468,8 @@ async fn direct_auxiliary_network_enable_for_background_target_does_not_enable_p.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| !state.runtime_slot.primary_network_events_enabled()),"auxiliary background Network.enable must not enable the target's primary listener");@@ -2505,7 +2514,8 @@ async fn direct_network_enable_routes_to_active_background_owner_without_promoti);assert!(active- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background session state should be staged").runtime_slot.primary_network_events_enabled()@@ -2815,7 +2825,8 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].console_output_session_state@@ -2843,7 +2854,8 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].console_output_session_state@@ -2871,7 +2883,8 @@ async fn direct_console_routes_to_inactive_background_owner_without_promoting_sl.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| !state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].console_output_session_state@@ -2932,7 +2945,9 @@ async fn direct_console_routes_to_loaded_background_owner_and_advances_parked_cu.expect("inactive owner must remain parked");assert_eq!(inactive- .background_target_owner_state_or_default_for_test("TID-background")+ .background_target("TID-background")+ .expect("background target must exist")+ .owner_state.console_output_state.console_domain_cursor(),(0, 0),@@ -2958,7 +2973,9 @@ async fn direct_console_routes_to_loaded_background_owner_and_advances_parked_cu.expect("inactive owner must remain parked");assert_eq!(inactive- .background_target_owner_state_or_default_for_test("TID-background")+ .background_target("TID-background")+ .expect("background target must exist")+ .owner_state.console_output_state.console_domain_cursor(),(0, 0),@@ -3057,7 +3074,8 @@ async fn direct_log_enable_routes_to_inactive_background_owner_without_promoting.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state@@ -3112,7 +3130,8 @@ async fn direct_log_enable_routes_to_loaded_background_owner_without_replaying_c.expect("inactive owner must remain parked");assert_eq!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("parked session state").devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].console_output_session_state@@ -3197,11 +3216,12 @@ async fn direct_log_disable_routes_to_inactive_background_owner_without_promotinTargetIdentityState::about_blank(),TargetPageSlot::empty_for_test_fixture(),));- inactive.mutate_background_page_target_for_test("TID-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .page_session_state- .log_enabled = true;- });+ inactive+ .background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .page_session_state+ .log_enabled = true;conn.inactive_browser_contexts.push(inactive);let response = conn@@ -3224,7 +3244,8 @@ async fn direct_log_disable_routes_to_inactive_background_owner_without_promotin.expect("inactive owner must remain parked");assert!(inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| !state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state@@ -3440,7 +3461,8 @@ async fn direct_network_policy_routes_to_inactive_background_owner_without_promo.find(|bc| bc.id == "BID-B").expect("inactive owner must remain parked");let staged = inactive- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background session state should be staged");assert!(staged.effective_policy().cache_disabled());assert!(staged.effective_policy().bypass_service_worker());diff --git a/moli-protocol/src/domains/activity/publication_route.rs b/moli-protocol/src/domains/activity/publication_route.rsindex 534233e16..b488cfee7 100644--- a/moli-protocol/src/domains/activity/publication_route.rs+++ b/moli-protocol/src/domains/activity/publication_route.rs@@ -26,8 +26,8 @@ pub(crate) enum RendererPublicationOwner {/// Exact protocol delivery route selected for one renderer publication.////// An attached session is already an exact route. A publication without a-/// session instead carries the owner route needed to enter the correct parked-/// target without promoting it into the active target slot. This type contains+/// session instead carries the owner route needed to address the correct+/// background target without changing foreground selection. This type contains/// no output payload and grants no renderer execution authority.#[derive(Clone, Debug, Eq, PartialEq)]pub(crate) enum RendererPublicationRoute {@@ -84,7 +84,7 @@ pub(crate) fn renderer_publication_owners(// transaction that reserved that exact renderer Page. Inferring its// target from the mutable inventory at `Opened` time is ambiguous:// protocol can transiently retain two handles to the same Page while- // moving a target between active/background residence. Leave Page+ // changing foreground selection. Leave Page// discovery empty and let the explicit binding win in either// open-before-bind or bind-before-open order.RendererOutputResidenceIdentity::Page { .. } => Vec::new(),@@ -176,7 +176,8 @@ 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.+ // which the old and new renderer attachments can both be+ // observable from one stable target host.let frozen_target = target_id.as_deref().and_then(|target_id| browser_context.page_target(target_id))diff --git a/moli-protocol/src/domains/console.rs b/moli-protocol/src/domains/console.rsindex 1215900dc..8b69d368b 100644--- a/moli-protocol/src/domains/console.rs+++ b/moli-protocol/src/domains/console.rs@@ -577,7 +577,8 @@ mod tests {);assert!(active- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].console_output_session_statediff --git a/moli-protocol/src/domains/dom/tests/frames.rs b/moli-protocol/src/domains/dom/tests/frames.rsindex 7436f1598..6caa10fa1 100644--- a/moli-protocol/src/domains/dom/tests/frames.rs+++ b/moli-protocol/src/domains/dom/tests/frames.rs@@ -5013,31 +5013,15 @@ async fn get_frame_owner_invalid_params_error() {#[tokio::test(flavor = "multi_thread")]async fn get_frame_owner_without_selected_target_errors() {let mut ctx = TestContext::new();- load_bc(&mut ctx, "BID-A");+ ctx.conn.browser_context = Some(crate::conn::BrowserContext::new("BID-A".to_owned()));ctx.process_async(json!({"id": 1,- "method": "Page.navigate",- "params": {- "url": "data:text/html,<!doctype html><html><body><div></div></body></html>"- }- }))- .await;- ctx.expect_result(1, json!({"loaderId": "LID-0000000001"}), None);- crate::testing::wait_until_renderer_document_load(&mut ctx, None, "TID-1", "LID-0000000001")- .await;- let _ = ctx.take_all();- if let Some(bc) = ctx.conn.browser_context.as_mut() {- bc.clear_active_target_id();- }-- ctx.process_async(json!({- "id": 2,"method": "DOM.getFrameOwner","params": { "frameId": "TID-1" }})).await;- ctx.expect_error(2, -31998, "BrowserContextNotLoaded");+ ctx.expect_error(1, -31998, "BrowserContextNotLoaded");}#[tokio::test(flavor = "multi_thread")]diff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rsindex 681ed1e4c..8b4744669 100644--- a/moli-protocol/src/domains/emulation.rs+++ b/moli-protocol/src/domains/emulation.rs@@ -2772,7 +2772,7 @@ fn start_session_surface_override_page_command_for_route(if let Some(target_id) = target_id.as_deref()&& browser_context.background_target(target_id).is_some(){- browser_context.generated_surface_override_script_for_parked_target(target_id)+ browser_context.generated_surface_override_script_for_background_target(target_id)} else {browser_context.generated_surface_override_script_for_active_target()}@@ -2812,7 +2812,7 @@ fn start_surface_override_for_route(if browser_context.is_active_target(target_id) {browser_context.generated_surface_override_script_for_active_target()} else {- browser_context.generated_surface_override_script_for_parked_target(target_id)+ browser_context.generated_surface_override_script_for_background_target(target_id)}}PendingEmulationPageTarget::SessionOwner { owner_scope } => {diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rsindex 287ccffe3..a0ed064e6 100644--- a/moli-protocol/src/domains/emulation/tests.rs+++ b/moli-protocol/src/domains/emulation/tests.rs@@ -2859,7 +2859,8 @@ async fn context_locale_override_applies_to_loaded_background_page_without_promo);assert!(browser_context- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).and_then(|state| {state.effective_policy()@@ -2991,7 +2992,8 @@ async fn session_emulation_routes_to_loaded_background_owner_without_promotion()"background Emulation should not mutate the active target locale override");let parked = browser_context- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background parked state");assert_eq!(parked.emulated_media.color_scheme.as_deref(), Some("dark"));assert_eq!(parked.effective_policy().locale_override(), Some("zh-CN"));diff --git a/moli-protocol/src/domains/fetch/subresource.rs b/moli-protocol/src/domains/fetch/subresource.rsindex 2f0fa7347..149c06eee 100644--- a/moli-protocol/src/domains/fetch/subresource.rs+++ b/moli-protocol/src/domains/fetch/subresource.rs@@ -924,8 +924,11 @@ mod tests {let bc = conn.browser_context.as_ref().unwrap();assert!(- bc.nonempty_background_fetch_state_for_test("TID-background")- .is_some_and(|state| state.has_pending_subresource_fetch_for_test("FETCH-1"))+ bc.background_target("TID-background")+ .expect("background target must exist")+ .fetch_owner+ .pending_state()+ .has_pending_subresource_fetch_for_test("FETCH-1"));assert!(!bc.active_page_target()diff --git a/moli-protocol/src/domains/fetch/tests/basics.rs b/moli-protocol/src/domains/fetch/tests/basics.rsindex 8d06ae43f..15d173743 100644--- a/moli-protocol/src/domains/fetch/tests/basics.rs+++ b/moli-protocol/src/domains/fetch/tests/basics.rs@@ -433,7 +433,8 @@ async fn enable_targets_loaded_background_owner_without_promotion() {assert_eq!(bc.active_target_id(), Some("TID-active"));assert!(!bc.active_page_target().fetch_owner.is_enabled());let staged = bc- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background owner fetch config should be staged");assert!(staged.fetch_owner.config_snapshot().is_enabled());assert_eq!(@@ -512,7 +513,8 @@ async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {assert_eq!(bc.active_target_id(), Some("TID-fetch-active"));assert!(!bc.active_page_target().fetch_owner.is_enabled());let staged = bc- .non_default_background_page_target_for_test("TID-fetch-background")+ .background_target("TID-fetch-background")+ .filter(|target| target.has_non_default_session_state()).expect("background fetch config should stay parked");assert!(staged.fetch_owner.config_snapshot().is_enabled());assert_eq!(staged.fetch_owner.config_snapshot().patterns().len(), 1);@@ -598,7 +600,10 @@ async fn disable_targets_loaded_background_owner_without_promotion() {bc.set_active_target_id("TID-active".to_owned());bc.attach_active_session("SID-active".to_owned());bc.insert_page_target_host(background);- bc.mutate_background_page_target_for_test("TID-background", |state| {+ {+ let state = bc+ .background_target_mut("TID-background")+ .expect("background target must exist");state.fetch_owner.configure(Some("SID-background".to_owned()),false,@@ -608,7 +613,7 @@ async fn disable_targets_loaded_background_owner_without_promotion() {request_stage: FetchRequestStage::Request,}],);- });+ }ctx.conn.browser_context = Some(bc);ctx.install_navigation_fixture_for_session_owner("data:text/html,<title>fetch disable background</title>",@@ -629,7 +634,8 @@ async fn disable_targets_loaded_background_owner_without_promotion() {assert_eq!(bc.active_target_id(), Some("TID-active"));assert!(!bc.active_page_target().fetch_owner.is_enabled());assert!(- bc.non_default_background_page_target_for_test("TID-background")+ bc.background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_none(),"disabled background fetch config should collapse to default");diff --git a/moli-protocol/src/domains/inspector.rs b/moli-protocol/src/domains/inspector.rsindex 7a42b148b..6eb0740fd 100644--- a/moli-protocol/src/domains/inspector.rs+++ b/moli-protocol/src/domains/inspector.rs@@ -180,9 +180,11 @@ mod tests {Some("SID-background".into()),"about:blank#background".into(),));- bc.mutate_background_target_owner_state_for_test("TID-background", |owner_state| {- owner_state.target_crash_state.mark_crashed();- });+ bc.background_target_mut("TID-background")+ .expect("background target must exist")+ .owner_state+ .target_crash_state+ .mark_crashed();ctx.conn.browser_context = Some(bc);ctx.process_async(json!({@@ -198,7 +200,8 @@ mod tests {let bc = ctx.conn.browser_context.as_ref().expect("browser context");assert_eq!(bc.active_target_id(), Some("TID-active"));assert!(- bc.non_default_background_page_target_for_test("TID-background")+ bc.background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state@@ -294,7 +297,8 @@ mod tests {.inspector_enabled);assert!(- bc.non_default_background_page_target_for_test("TID-B")+ bc.background_target("TID-B")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| {state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state@@ -314,7 +318,8 @@ mod tests {.inspector_enabled);assert!(- bc.non_default_background_page_target_for_test("TID-B")+ bc.background_target("TID-B")+ .filter(|target| target.has_non_default_session_state()).is_none(),"disable should collapse staged parked state back to default");diff --git a/moli-protocol/src/domains/log.rs b/moli-protocol/src/domains/log.rsindex b20de3826..6fa8f9769 100644--- a/moli-protocol/src/domains/log.rs+++ b/moli-protocol/src/domains/log.rs@@ -672,7 +672,8 @@ mod tests {);assert!(active- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_statediff --git a/moli-protocol/src/domains/network/tests/cache.rs b/moli-protocol/src/domains/network/tests/cache.rsindex e6f217441..2ea7a0666 100644--- a/moli-protocol/src/domains/network/tests/cache.rs+++ b/moli-protocol/src/domains/network/tests/cache.rs@@ -808,7 +808,8 @@ async fn devtools_set_cache_behavior_global_updates_existing_targets_and_defaultlet bc = ctx.conn.browser_context.as_ref().expect("browser context");assert!(bc.active_page_target().effective_policy().cache_disabled());assert!(- bc.non_default_background_page_target_for_test("TID-background")+ bc.background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background state").effective_policy().cache_disabled()@@ -858,7 +859,8 @@ async fn devtools_set_cache_behavior_contexts_only_updates_requested_targets() {let bc = ctx.conn.browser_context.as_ref().expect("browser context");assert!(!bc.active_page_target().effective_policy().cache_disabled());assert!(- bc.non_default_background_page_target_for_test("TID-background")+ bc.background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background state").effective_policy().cache_disabled()diff --git a/moli-protocol/src/domains/observable_output/emission.rs b/moli-protocol/src/domains/observable_output/emission.rsindex f89365129..6d2f948b8 100644--- a/moli-protocol/src/domains/observable_output/emission.rs+++ b/moli-protocol/src/domains/observable_output/emission.rs@@ -756,11 +756,11 @@ mod tests {TargetIdentityState::with_url("data:text/html,background-owner".to_owned()),TargetPageSlot::with_loaded_page_for_test(background_page),));- bc.mutate_background_page_target_for_test("TID-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .console_output_session_state- .console_enabled = true;- });+ bc.background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .console_output_session_state+ .console_enabled = true;ctx.conn.browser_context = Some(bc);assert_eq!(@@ -845,11 +845,11 @@ mod tests {TargetIdentityState::with_url("data:text/html,promoted-owner".to_owned()),TargetPageSlot::with_loaded_page_for_test(promoted_page),));- bc.mutate_background_page_target_for_test("TID-promoted", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .console_output_session_state- .console_enabled = true;- });+ bc.background_target_mut("TID-promoted")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .console_output_session_state+ .console_enabled = true;ctx.conn.browser_context = Some(bc);let (old_active_attachment, promoted_attachment) = {@@ -876,7 +876,7 @@ mod tests {.browser_context.as_mut().expect("browser context")- .promote_background_target_to_active_slot_async("TID-promoted")+ .select_page_target_async("TID-promoted").await.expect("target promotion should succeed"));diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rsindex 161203618..e9c505e0c 100644--- a/moli-protocol/src/domains/page.rs+++ b/moli-protocol/src/domains/page.rs@@ -1461,12 +1461,12 @@ async fn bring_session_route_to_front_async(}match conn- .promote_background_target_to_active_for_connection_async(&target_id)+ .select_page_target_for_connection_async(&target_id).await{Ok(Some(activation)) => Ok(activation.into_protocol_events()),Ok(None) => Err("UnknownTargetId".into()),- Err(message) => Err(message),+ Err(error) => Err(error.to_string()),}}diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rsindex 4e2e13d2e..619e67dbf 100644--- a/moli-protocol/src/domains/page/tests/capture.rs+++ b/moli-protocol/src/domains/page/tests/capture.rs@@ -513,15 +513,15 @@ async fn capture_screenshot_targets_loaded_background_owner_without_promotion().browser_context.as_mut().expect("browser context")- .mutate_background_page_target_for_test("TID-background", |state| {- state.emulated_device_metrics = Some(EmulatedDeviceMetrics {- width: 320,- height: 240,- device_scale_factor: 2.0,- screen_width: 320,- screen_height: 240,- });- });+ .background_target_mut("TID-background")+ .expect("background target must exist")+ .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,diff --git a/moli-protocol/src/domains/page/tests/dialog.rs b/moli-protocol/src/domains/page/tests/dialog.rsindex b49c73e69..e0f8a650f 100644--- a/moli-protocol/src/domains/page/tests/dialog.rs+++ b/moli-protocol/src/domains/page/tests/dialog.rs@@ -153,7 +153,7 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {));assert!(browser_context- .promote_background_target_to_active_slot_async("TID-B")+ .select_page_target_async("TID-B").await.unwrap());@@ -175,7 +175,7 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {let browser_context = ctx.conn.browser_context.as_mut().unwrap();assert!(browser_context- .promote_background_target_to_active_slot_async("TID-A")+ .select_page_target_async("TID-A").await.unwrap());@@ -193,7 +193,7 @@ async fn pending_javascript_dialogs_are_preserved_per_parked_target() {let browser_context = ctx.conn.browser_context.as_mut().unwrap();assert!(browser_context- .promote_background_target_to_active_slot_async("TID-B")+ .select_page_target_async("TID-B").await.unwrap());diff --git a/moli-protocol/src/domains/page/tests/lifecycle.rs b/moli-protocol/src/domains/page/tests/lifecycle.rsindex 068ad3c27..ca8cbea02 100644--- a/moli-protocol/src/domains/page/tests/lifecycle.rs+++ b/moli-protocol/src/domains/page/tests/lifecycle.rs@@ -1139,7 +1139,8 @@ async fn set_lifecycle_events_enabled_is_session_local_for_background_auxiliary_let browser_context = ctx.conn.browser_context.as_ref().unwrap();let parked = browser_context- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background target should retain parked page session state");assert!(!parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]@@ -1218,12 +1219,15 @@ async fn page_disable_clears_page_handler_state_for_background_auxiliary_sessionbrowser_context.assign_auxiliary_session_to_target("TID-background", "SID-background-aux".to_owned()));- browser_context.mutate_background_page_target_for_test("TID-background", |state| {+ {+ let state = browser_context+ .background_target_mut("TID-background")+ .expect("background target must exist");mark_page_domain_enabled(&mut state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state,);- });+ }ctx.conn.browser_context = Some(browser_context);enable_page_domain_for_session(&mut ctx.conn, "SID-background-aux");@@ -1243,7 +1247,8 @@ async fn page_disable_clears_page_handler_state_for_background_auxiliary_sessionlet browser_context = ctx.conn.browser_context.as_ref().unwrap();let parked = browser_context- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background target should retain parked page session state");assert_page_domain_enabled(&parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_state,@@ -2248,11 +2253,11 @@ async fn document_start_script_run_immediately_targets_loaded_background_owner_w.browser_context.as_mut().expect("browser context")- .mutate_background_page_target_for_test("TID-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled = true;- });+ .background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .runtime_session_state+ .runtime_frontend_enabled = true;ctx.sent.clear();ctx.process_async(json!({@@ -2669,16 +2674,16 @@ async fn crash_targets_background_owner_without_promotion() {bc.attach_active_session("SID-active".to_owned());bc.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());bc.insert_page_target_host(background);- bc.mutate_background_page_target_for_test("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()- },+ bc.background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =+ crate::conn::DevToolsSessionState {+ runtime_session_state: crate::conn::TargetRuntimeSessionState {+ inspector_enabled: true,..Default::default()- };- });+ },+ ..Default::default()+ };let background_document_token = bc.start_document_navigation_for_target("TID-background",@@ -2716,7 +2721,9 @@ async fn crash_targets_background_owner_without_promotion() {"background Page.crash must reject late body completions for the crashed document");assert!(- bc.background_target_owner_state_or_default_for_test("TID-background")+ bc.background_target("TID-background")+ .expect("background target must exist")+ .owner_state.target_crash_state.is_crashed());@@ -2847,8 +2854,8 @@ async fn crash_aborts_background_paused_navigation_without_promotion() {"background Page.crash should not promote the target");assert!(- bc.nonempty_background_fetch_state_for_test("TID-background")- .is_none_or(|state| state.is_empty())+ bc.background_target("TID-background")+ .is_none_or(|target| target.fetch_owner.pending_state().is_empty()));}#[tokio::test(flavor = "multi_thread")]@@ -3155,16 +3162,16 @@ async fn close_aborts_background_paused_navigation_without_promotion() {"about:blank#background".to_owned(),));assert!(bc.assign_auxiliary_session_to_target("TID-background", "SID-aux".to_owned()));- bc.mutate_background_page_target_for_test("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()- },+ bc.background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =+ crate::conn::DevToolsSessionState {+ runtime_session_state: crate::conn::TargetRuntimeSessionState {+ inspector_enabled: true,..Default::default()- };- });+ },+ ..Default::default()+ };ctx.process_async(json!({"id": 246,@@ -3245,14 +3252,6 @@ async fn close_aborts_background_paused_navigation_without_promotion() {);assert!(bc.background_target("TID-background").is_none());assert!(bc.auxiliary_target_id_for_session("SID-aux").is_none());- assert!(- bc.non_default_background_page_target_for_test("TID-background")- .is_none()- );- assert!(- bc.nonempty_background_fetch_state_for_test("TID-background")- .is_none_or(|state| state.is_empty())- );}#[tokio::test(flavor = "multi_thread")]async fn close_without_target_loaded_errors() {@@ -4080,7 +4079,8 @@ async fn start_screencast_is_session_local_for_background_auxiliary_session() {let browser_context = ctx.conn.browser_context.as_ref().unwrap();let parked = browser_context- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).expect("background target should retain parked page session state");assert!(!parked.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]diff --git a/moli-protocol/src/domains/page/tests/mod.rs b/moli-protocol/src/domains/page/tests/mod.rsindex 58ec8ed18..02c971620 100644--- a/moli-protocol/src/domains/page/tests/mod.rs+++ b/moli-protocol/src/domains/page/tests/mod.rs@@ -177,7 +177,7 @@ fn load_bc_with_session(// materialized; setting only target/session/url metadata creates a Page// with no exact renderer Document attachment and makes typed child-frame// output correctly fail authorization.- bc.stage_active_target_demoting_current(+ bc.stage_foreground_target(target_id.to_owned(),Some(session_id.to_owned()),url.to_owned(),diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rsindex f66885fa6..fe426a87b 100644--- a/moli-protocol/src/domains/page/tests/navigation.rs+++ b/moli-protocol/src/domains/page/tests/navigation.rs@@ -1232,7 +1232,7 @@ async fn navigation_history_is_preserved_per_parked_target() {}assert!(ctx.conn- .promote_background_target_to_active_for_connection_async("TID-B")+ .select_page_target_for_connection_async("TID-B").await.unwrap().is_some()@@ -1263,7 +1263,7 @@ async fn navigation_history_is_preserved_per_parked_target() {{assert!(ctx.conn- .promote_background_target_to_active_for_connection_async("TID-A")+ .select_page_target_for_connection_async("TID-A").await.unwrap().is_some()diff --git a/moli-protocol/src/domains/performance.rs b/moli-protocol/src/domains/performance.rsindex c00e45866..f93d0a416 100644--- a/moli-protocol/src/domains/performance.rs+++ b/moli-protocol/src/domains/performance.rs@@ -1186,7 +1186,8 @@ mod tests {);assert!(active- .non_default_background_page_target_for_test("TID-background")+ .background_target("TID-background")+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].page_session_statediff --git a/moli-protocol/src/domains/runtime/tests/console.rs b/moli-protocol/src/domains/runtime/tests/console.rsindex 64a6a2efe..cb61d2046 100644--- a/moli-protocol/src/domains/runtime/tests/console.rs+++ b/moli-protocol/src/domains/runtime/tests/console.rs@@ -1464,7 +1464,9 @@ async fn runtime_discard_console_entries_advances_background_owner_without_promo);assert_eq!(browser_context- .background_target_owner_state_or_default_for_test("TID-background")+ .background_target("TID-background")+ .expect("background target must exist")+ .owner_state.runtime_observable_state.emitted_console_entries(),queue_console_entries,diff --git a/moli-protocol/src/domains/runtime/tests/evaluate.rs b/moli-protocol/src/domains/runtime/tests/evaluate.rsindex ec6d43374..75c88e0be 100644--- a/moli-protocol/src/domains/runtime/tests/evaluate.rs+++ b/moli-protocol/src/domains/runtime/tests/evaluate.rs@@ -1950,11 +1950,12 @@ 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_background_page_target_for_test("TID-background", |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .runtime_session_state- .runtime_frontend_enabled = true;- });+ browser_context+ .background_target_mut("TID-background")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .runtime_session_state+ .runtime_frontend_enabled = true;browser_context.start_document_navigation_for_target("TID-background",diff --git a/moli-protocol/src/domains/runtime/tests/mod.rs b/moli-protocol/src/domains/runtime/tests/mod.rsindex ef7ed8b00..c4031f75b 100644--- a/moli-protocol/src/domains/runtime/tests/mod.rs+++ b/moli-protocol/src/domains/runtime/tests/mod.rs@@ -177,11 +177,14 @@ async fn with_loaded_runtime_frontend_enabled_background_target_async(browser_context.set_active_target_id(active_target_id.to_owned());browser_context.attach_active_session(active_session_id.to_owned());browser_context.insert_page_target_host(background_target);- browser_context.mutate_background_page_target_for_test(background_target_id, |state| {+ {+ let state = browser_context+ .background_target_mut(background_target_id)+ .expect("background target must exist");state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state.runtime_frontend_enabled = true;- });+ }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/objects.rs b/moli-protocol/src/domains/runtime/tests/objects.rsindex 400321da2..76716de20 100644--- a/moli-protocol/src/domains/runtime/tests/objects.rs+++ b/moli-protocol/src/domains/runtime/tests/objects.rs@@ -607,7 +607,9 @@ async fn runtime_disable_advances_background_owner_observable_cursor_without_pro);assert_eq!(browser_context- .background_target_owner_state_or_default_for_test("TID-background")+ .background_target("TID-background")+ .expect("background target must exist")+ .owner_state.runtime_observable_state.emitted_console_entries(),queue_console_entries,diff --git a/moli-protocol/src/domains/target/activation.rs b/moli-protocol/src/domains/target/activation.rsindex 32f5a7123..ce44e265a 100644--- a/moli-protocol/src/domains/target/activation.rs+++ b/moli-protocol/src/domains/target/activation.rs@@ -125,7 +125,7 @@ pub(super) async fn execute_devtools_activate_target_command_async() && bc.background_target(&target_id).is_some(){match conn- .promote_background_target_to_active_for_connection_async(&target_id)+ .select_page_target_for_connection_async(&target_id).await{Ok(Some(activation)) => activation.into_protocol_events(),@@ -139,12 +139,15 @@ pub(super) async fn execute_devtools_activate_target_command_async("UnknownTargetId",));}- Err(message) => {+ Err(error) => {restore_previously_active_browser_context(conn,previously_active_browser_context_id.as_deref(),);- return Err(DevToolsError::new(DevToolsErrorKind::NoSuchTarget, message));+ return Err(DevToolsError::new(+ DevToolsErrorKind::NoSuchTarget,+ error.to_string(),+ ));}}} else if !matches!(diff --git a/moli-protocol/src/domains/target/auto_attach.rs b/moli-protocol/src/domains/target/auto_attach.rsindex b0319d341..3ce9a815c 100644--- a/moli-protocol/src/domains/target/auto_attach.rs+++ b/moli-protocol/src/domains/target/auto_attach.rs@@ -587,11 +587,10 @@ async fn set_auto_attach_inner_async(.into_iter().map(|target_id| (target_id, conn.gen_session_id())).collect::<Vec<_>>();- let promote_target_id = {- let bc = conn- .browser_context- .as_ref()- .expect("browser context must exist when considering auto-attach promotion");+ let foreground_target_id = {+ let bc = conn.browser_context.as_ref().expect(+ "browser context must exist when choosing an auto-attached foreground target",+ );if !attach_page_targets || bc.has_loaded_page() {None} else {@@ -651,18 +650,18 @@ async fn set_auto_attach_inner_async();debug_assert!(assigned, "attached tab target must remain addressable");}- if let Some(promote_target_id) = promote_target_id {+ if let Some(foreground_target_id) = foreground_target_id {match conn- .promote_background_target_to_active_for_connection_async(&promote_target_id)+ .select_page_target_for_connection_async(&foreground_target_id).await{Ok(Some(activation)) => {out.extend_background_events(activation.into_protocol_events());}Ok(None) => {}- Err(message) => {+ Err(error) => {panic!(- "same-context target should remain promotable during auto-attach: {message}"+ "same-context target should remain selectable during auto-attach: {error}");}}diff --git a/moli-protocol/src/domains/target/creation.rs b/moli-protocol/src/domains/target/creation.rsindex cedf91989..0675eefcc 100644--- a/moli-protocol/src/domains/target/creation.rs+++ b/moli-protocol/src/domains/target/creation.rs@@ -329,7 +329,7 @@ pub(super) fn execute_devtools_create_target_command(None,);} else if activating_created_target {- bc.stage_active_target_demoting_current(+ bc.stage_foreground_target(target_id.clone(),None,command.url.clone(),diff --git a/moli-protocol/src/domains/target/popup.rs b/moli-protocol/src/domains/target/popup.rsindex a1bbd2748..698d8a2b0 100644--- a/moli-protocol/src/domains/target/popup.rs+++ b/moli-protocol/src/domains/target/popup.rs@@ -639,12 +639,12 @@ async fn activate_popup_target_async(Ok(Vec::new())} else {match conn- .promote_background_target_to_active_for_connection_async(target_id)+ .select_page_target_for_connection_async(target_id).await{Ok(Some(activation)) => Ok(activation.into_protocol_events()),Ok(None) => Err("PopupTargetUnavailable".to_owned()),- Err(message) => Err(message),+ Err(error) => Err(error.to_string()),}};restore_previously_active_browser_context(conn, restore_browser_context_id.as_deref());diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rsindex 4448c9e1a..f1d08a3a2 100644--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs@@ -156,7 +156,8 @@ async fn same_context_background_session_can_stage_its_own_pre_document_state_be.background_target(&second_target_id).expect("staged background target");let staged_devtools_state = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).expect("staged page session state").devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings@@ -165,14 +166,18 @@ async fn same_context_background_session_can_stage_its_own_pre_document_state_beassert_eq!(staged_devtools_state[0].name, "targetBPreDocumentBinding");assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.len(),1);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts[0].0,script_id@@ -357,7 +362,8 @@ async fn same_context_background_session_can_stage_its_own_utility_pre_document_.background_target(&second_target_id).expect("staged background target");let staged_devtools_state = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).expect("staged page session state").devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings@@ -373,14 +379,18 @@ async fn same_context_background_session_can_stage_its_own_utility_pre_document_);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.len(),1);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts[0].0,script_id@@ -614,7 +624,8 @@ async fn same_context_background_session_can_remove_its_own_binding_before_promo.background_target(&second_target_id).expect("staged background target");let staged_bindings_empty = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| {state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings@@ -626,14 +637,18 @@ async fn same_context_background_session_can_remove_its_own_binding_before_promo);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.len(),1);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts[0].0,script_id@@ -776,14 +791,17 @@ async fn same_context_background_session_can_remove_its_own_preload_before_promo.background_target(&second_target_id).expect("staged background target");let staged_bindings = &active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).expect("staged page session state").devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings;assert_eq!(staged_bindings.len(), 1);assert!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.is_empty());@@ -928,7 +946,8 @@ async fn same_context_background_session_can_remove_its_own_utility_binding_befo.background_target(&second_target_id).expect("staged background target");let staged_bindings_empty = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| {state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings@@ -940,14 +959,18 @@ async fn same_context_background_session_can_remove_its_own_utility_binding_befo);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.len(),1);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts[0].0,script_id@@ -1115,7 +1138,8 @@ async fn same_context_background_session_can_remove_its_own_utility_preload_befo.background_target(&second_target_id).expect("staged background target");let staged_bindings = &active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).expect("staged page session state").devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings;@@ -1126,7 +1150,9 @@ async fn same_context_background_session_can_remove_its_own_utility_preload_befo);assert!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.is_empty());@@ -1301,7 +1327,8 @@ async fn same_context_background_session_can_stage_its_own_emulated_media_beforeSome("dark"));let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert_eq!(staged.emulated_media.color_scheme.as_deref(), Some("light"));}@@ -1440,7 +1467,8 @@ async fn same_context_background_session_can_clear_its_own_emulated_media_before);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"clearing staged emulated media back to default should fold away the parked state entry",);@@ -1578,7 +1606,8 @@ async fn same_context_background_session_can_stage_its_own_network_conditions_be10.0);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.network_policy.network_offline());assert_eq!(staged.network_policy.emulated_network_latency(), 25.0);@@ -1745,7 +1774,8 @@ async fn same_context_background_session_can_stage_its_own_blocked_urls_before_p"active target should keep its own block list");let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.effective_policy().blocked_url_patterns().is_empty(),@@ -1912,7 +1942,8 @@ async fn same_context_background_session_can_reset_its_own_network_conditions_be"active target should keep its default online state",);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(!staged.network_policy.network_offline());assert_eq!(staged.network_policy.emulated_network_latency(), 0.0);@@ -2128,7 +2159,8 @@ async fn same_context_background_session_can_stage_its_own_extra_headers_before_vec![("X-Target".into(), "A".into())]);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert_eq!(staged.effective_policy().extra_headers(),@@ -2336,7 +2368,8 @@ async fn same_context_background_session_can_clear_its_own_extra_headers_before_vec![("X-Target".into(), "A".into())]);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("enabled background session should retain its target-owned state");assert!(staged.effective_policy().extra_headers().is_empty());}@@ -2509,7 +2542,8 @@ async fn same_context_background_session_can_stage_its_own_user_agent_before_proSome("Moli/Stage-A"));let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert_eq!(staged@@ -2719,7 +2753,8 @@ async fn same_context_background_session_can_clear_its_own_user_agent_before_pro"active target should keep its default user agent override",);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert_eq!(staged@@ -2907,7 +2942,8 @@ async fn same_context_background_session_stages_locale_without_changing_request_Some("UTC"));let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert_eq!(staged.effective_policy().locale_override(), Some("fr-FR"));assert_eq!(@@ -3112,7 +3148,8 @@ async fn same_context_background_session_can_clear_its_own_locale_before_promoti);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"clearing staged locale back to default should fold away the parked state entry",);@@ -3275,7 +3312,8 @@ async fn same_context_background_session_can_clear_its_own_timezone_before_promo);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"clearing staged timezone back to default should fold away the parked state entry",);@@ -3480,7 +3518,8 @@ async fn same_context_background_session_can_stage_its_own_emulation_overrides_bassert!(active.active_page_target().focus_emulation_enabled);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert_eq!(staged.emulated_device_metrics.as_ref().map(|metrics| (@@ -3674,7 +3713,8 @@ async fn same_context_background_session_can_stage_its_own_page_settings_before_.as_ref().expect("active browser context");let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("staged page settings for background target");assert!(staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]@@ -3826,7 +3866,8 @@ async fn same_context_background_session_can_clear_its_own_device_metrics_before);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"clearing staged device metrics back to default should fold away the parked state entry",);@@ -4002,7 +4043,8 @@ async fn same_context_background_session_can_clear_its_own_touch_and_focus_befor);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"clearing staged touch/focus back to defaults should fold away the parked state entry",);@@ -4145,7 +4187,8 @@ async fn same_context_background_session_can_stage_its_own_script_execution_disa.expect("active browser context");assert!(!active.active_page_target().script_execution_disabled);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.script_execution_disabled);}@@ -4315,10 +4358,13 @@ async fn same_context_background_session_can_reenable_its_own_script_execution_b// collapse back to the default.assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none_or(|state| !state.script_execution_disabled),"script execution re-enable should clear the staged parked setting: {:#?}",- active.non_default_background_page_target_for_test(&second_target_id)+ active+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()));}@@ -4487,7 +4533,8 @@ async fn same_context_background_session_can_stage_its_own_lifecycle_events_befo.page_lifecycle_events);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]@@ -4665,7 +4712,8 @@ async fn same_context_background_session_can_disable_its_own_lifecycle_events_be);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"lifecycle disable should collapse staged parked state back to default");@@ -4802,7 +4850,8 @@ async fn same_context_background_session_can_stage_its_own_runtime_enable_before.runtime_frontend_enabled);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]@@ -5023,7 +5072,8 @@ async fn same_context_loaded_background_session_runtime_enable_replays_context_w"direct Runtime.enable should not promote the loaded background target");assert!(- bc.non_default_background_page_target_for_test(&second_target_id)+ bc.background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_some_and(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_session_state@@ -5877,7 +5927,8 @@ async fn same_context_background_session_can_stage_its_own_inspector_enable_befo.inspector_enabled);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]@@ -6020,7 +6071,8 @@ async fn same_context_background_session_can_disable_its_own_inspector_before_pr);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"inspector disable should collapse staged parked state back to default");@@ -6137,7 +6189,8 @@ async fn same_context_background_session_can_stage_its_own_css_enable_before_pro.expect("active browser context");assert!(!active.active_page_target().css_enabled);let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.css_enabled);}@@ -6256,7 +6309,8 @@ async fn same_context_background_session_can_disable_its_own_css_before_promotioassert!(!active.active_page_target().css_enabled);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"css disable should collapse staged parked state back to default");@@ -6402,7 +6456,8 @@ async fn same_context_background_session_can_stage_its_own_fetch_enable_before_p.is_empty());let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.fetch_owner.config_snapshot().is_enabled());assert_eq!(staged.fetch_owner.config_snapshot().patterns().len(), 1);@@ -6593,8 +6648,11 @@ async fn same_context_background_fetch_continue_request_keeps_target_parked() {assert_eq!(active.active_target_id(), Some("TID-000000000PFC"));assert!(active- .nonempty_background_fetch_state_for_test(&second_target_id)- .is_some_and(|state| state.has_pending_fetch_navigation()),+ .background_target(&second_target_id)+ .expect("background target must exist")+ .fetch_owner+ .pending_state()+ .has_pending_fetch_navigation(),"background fetch pause should stay parked before continueRequest");}@@ -6736,7 +6794,8 @@ async fn same_context_background_session_can_stage_its_own_fetch_auth_handling_b.expect("active browser context");assert!(!active.active_page_target().fetch_owner.is_enabled());let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.fetch_owner.config_snapshot().is_enabled());assert!(staged.fetch_owner.config_snapshot().handle_auth_requests());@@ -6941,7 +7000,8 @@ async fn same_context_background_session_can_disable_its_own_fetch_before_promot);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"fetch disable should collapse staged parked state back to default");@@ -7091,7 +7151,8 @@ async fn same_context_background_session_can_stage_its_own_network_enable_before.primary_network_events_enabled());let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.runtime_slot.primary_network_events_enabled());}@@ -7285,7 +7346,8 @@ async fn same_context_background_session_can_disable_its_own_network_before_prom);assert!(active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).is_none(),"network disable should collapse staged parked state back to default");@@ -7492,7 +7554,8 @@ async fn same_context_background_session_can_stage_its_own_cache_and_service_wor.bypass_service_worker());let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.runtime_slot.primary_network_events_enabled());assert!(staged.effective_policy().cache_disabled());@@ -7747,7 +7810,8 @@ async fn same_context_background_session_can_disable_its_own_cache_and_service_w.bypass_service_worker());let staged = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should have staged parked page session state");assert!(staged.runtime_slot.primary_network_events_enabled());assert!(!staged.effective_policy().cache_disabled());diff --git a/moli-protocol/src/domains/target/tests/tests_control_plane.rs b/moli-protocol/src/domains/target/tests/tests_control_plane.rsindex 6509cdc21..6e03aa3fa 100644--- a/moli-protocol/src/domains/target/tests/tests_control_plane.rs+++ b/moli-protocol/src/domains/target/tests/tests_control_plane.rs@@ -928,8 +928,10 @@ async fn same_context_targets_keep_paused_fetch_state_target_local_after_switchi"promoted target should not see another target's pending fetch ids",);let parked = bc- .nonempty_background_fetch_state_for_test(&first_target_id)- .expect("first target pending fetch state should be parked");+ .background_target(&first_target_id)+ .expect("background target must exist")+ .fetch_owner+ .pending_state();assert!(parked.has_pending_fetch_request_id_for_test(&request_id),"first target pending fetch id should move with parked target state",@@ -1373,7 +1375,7 @@ async fn set_auto_attach_prefers_existing_background_target_with_parked_loaded_r),crate::conn::TargetPageSlot::empty_for_test_fixture(),));- bc.stage_active_target_demoting_current(+ bc.stage_foreground_target("TID-0000000010".into(),None,"about:blank#parked".into(),@@ -1390,7 +1392,7 @@ async fn set_auto_attach_prefers_existing_background_target_with_parked_loaded_r.browser_context.as_mut().unwrap()- .promote_background_target_to_active_slot_async("TID-000000000E")+ .select_page_target_async("TID-000000000E").await.expect("restoring the original active target should succeed"),"the original active target should remain parked during fixture setup"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.rsindex a3e8bb104..87937b659 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@@ -482,14 +482,18 @@ async fn same_context_targets_remove_only_their_own_pre_document_script_identifi.expect("background target should remain staged");assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.len(),1);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts[0].0,"1"@@ -635,14 +639,18 @@ async fn same_context_targets_remove_only_their_own_utility_pre_document_script_.expect("background target should remain staged");assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts.len(),1);assert_eq!(active- .background_target_owner_state_or_default_for_test(staged.target_id())+ .background_target(staged.target_id())+ .expect("background target must exist")+ .owner_state.document_start_scripts[0].0,"1"@@ -834,7 +842,8 @@ async fn same_context_targets_remove_only_their_own_utility_binding_definition_a.background_target("TID-000000000UB").expect("first target should remain staged");let staged_bindings = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).map(|state| {state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings@@ -1027,7 +1036,8 @@ async fn same_context_targets_remove_only_their_own_main_world_binding_definitio.background_target("TID-000000000MB").expect("first target should remain staged");let staged_bindings = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id())+ .filter(|target| target.has_non_default_session_state()).map(|state| {state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings@@ -1251,7 +1261,7 @@ async fn same_context_targets_remove_only_their_own_dual_world_binding_definitio.background_target("TID-000000000DB").expect("first target should remain staged");let staged_bindings = active- .non_default_background_page_target_for_test(staged.target_id())+ .background_target(staged.target_id()).filter(|target| target.has_non_default_session_state()).map(|state| state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary].runtime_bindings.as_slice()).unwrap_or(&[]);assert_eq!(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.rsindex 02bb86891..635821288 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@@ -362,7 +362,8 @@ async fn same_context_targets_restore_their_own_network_conditions_after_session.expect("active browser context after direct background navigation");assert_eq!(active.active_target_id(), Some("TID-000000000NA"));let parked = active- .non_default_background_page_target_for_test(&second_target_id)+ .background_target(&second_target_id)+ .filter(|target| target.has_non_default_session_state()).expect("second target should keep parked network state");assert!(parked.network_policy.network_offline());assert_eq!(parked.network_policy.emulated_network_latency(), 25.0);diff --git a/moli-protocol/src/domains/target/tests/tests_target_attachment.rs b/moli-protocol/src/domains/target/tests/tests_target_attachment.rsindex 4bde11821..cb81cb61e 100644--- a/moli-protocol/src/domains/target/tests/tests_target_attachment.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_attachment.rs@@ -1378,11 +1378,11 @@ async fn session_route_finds_browser_active_auxiliary_background_and_inactive_seSome("SID-inactive-background"),|bc, target_id| {assert_eq!(bc.id, "BID-B");- bc.mutate_background_page_target_for_test(target_id, |state| {- state.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]- .console_output_session_state- .console_enabled = true;- });+ bc.background_target_mut(target_id)+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .console_output_session_state+ .console_enabled = true;target_id.to_owned()}),@@ -1398,14 +1398,11 @@ async fn session_route_finds_browser_active_auxiliary_background_and_inactive_seSome("SID-inactive-background"),|bc, target_id| {assert_eq!(bc.id, "BID-B");- let mut console_enabled = false;- bc.mutate_background_page_target_for_test(target_id, |state| {- console_enabled = state.devtools_sessions- [moli_page_types::DevToolsSessionKey::Primary]- .console_output_session_state- .console_enabled;- });- console_enabled+ bc.background_target(target_id)+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]+ .console_output_session_state+ .console_enabled}),Some(true)diff --git a/moli-protocol/src/domains/target/tests/tests_target_basics.rs b/moli-protocol/src/domains/target/tests/tests_target_basics.rsindex db773359e..23bcde915 100644--- a/moli-protocol/src/domains/target/tests/tests_target_basics.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_basics.rs@@ -852,8 +852,11 @@ async fn page_stop_loading_aborts_background_pending_fetch_without_promotion() {let bc = ctx.conn.browser_context.as_ref().expect("browser context");assert_eq!(bc.active_target_id(), Some("TID-000000000A"));assert!(- bc.nonempty_background_fetch_state_for_test(&second_target_id)- .is_some_and(|state| !state.is_empty())+ !bc.background_target(&second_target_id)+ .expect("background target must exist")+ .fetch_owner+ .pending_state()+ .is_empty());}@@ -881,8 +884,11 @@ async fn page_stop_loading_aborts_background_pending_fetch_without_promotion() {.expect("background target should remain parked");assert_eq!(background.session_id(), Some(session_id.as_str()));assert!(- bc.nonempty_background_fetch_state_for_test(&second_target_id)- .is_none_or(|state| state.is_empty())+ bc.background_target(&second_target_id)+ .expect("background target must exist")+ .fetch_owner+ .pending_state()+ .is_empty());}}diff --git a/moli-protocol/src/domains/target/tests/tests_target_creation.rs b/moli-protocol/src/domains/target/tests/tests_target_creation.rsindex 2b268d264..6765fda0d 100644--- a/moli-protocol/src/domains/target/tests/tests_target_creation.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_creation.rs@@ -1521,8 +1521,10 @@ async fn popup_initial_empty_document_record_captures_creator_identity() {let browser_context = ctx.conn.browser_context.as_ref().unwrap();let initial = browser_context- .non_default_background_target_owner_state_for_test(popup_target_id)- .and_then(|owner_state| owner_state.initial_empty_document_state())+ .background_target(popup_target_id)+ .expect("background target must exist")+ .owner_state+ .initial_empty_document_state().expect("popup target should record initial empty document");let creator = initial.creator()@@ -1605,8 +1607,10 @@ async fn popup_initial_empty_document_frame_tree_inherits_opener_origin() {let browser_context = ctx.conn.browser_context.as_ref().unwrap();let initial = browser_context- .non_default_background_target_owner_state_for_test(&popup_target_id)- .and_then(|owner_state| owner_state.initial_empty_document_state())+ .background_target(&popup_target_id)+ .expect("background target must exist")+ .owner_state+ .initial_empty_document_state().expect("popup target should still record initial empty document");assert!(initial.is_on_initial_empty_document());}diff --git a/moli-protocol/src/domains/target/tests/tests_target_management.rs b/moli-protocol/src/domains/target/tests/tests_target_management.rsindex d27fff80b..3452ff124 100644--- a/moli-protocol/src/domains/target/tests/tests_target_management.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_management.rs@@ -522,16 +522,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.mutate_background_page_target_for_test("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()- },+ bc.background_target_mut("TID-000000000B")+ .expect("background target must exist")+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary] =+ crate::conn::DevToolsSessionState {+ runtime_session_state: crate::conn::TargetRuntimeSessionState {+ inspector_enabled: true,..Default::default()- };- });+ },+ ..Default::default()+ };ctx.process_async(json!({"id": 121,@@ -564,7 +564,8 @@ async fn close_background_target_emits_detached_events_and_clears_attached_sessiassert!(bc.background_target("TID-000000000B").is_none());assert!(bc.auxiliary_target_id_for_session("SID-aux").is_none());assert!(- bc.non_default_background_page_target_for_test("TID-000000000B")+ bc.background_target("TID-000000000B")+ .filter(|target| target.has_non_default_session_state()).is_none());}