Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(cdp): support concurrent clients
ldm0777edb9fa47f
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex 8f4843481..9035bef3e 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -2,7 +2,7 @@This is a standalone CDP smoke project for moli. The default suite uses Playwright and raw CDP because those dependencies are managed by `uv`; the Puppeteer group uses the pinned `puppeteer-core` development dependency in this directory. Optional agent-browser, chrome-remote-interface, cdp-use, and Stagehand groups exercise their real published clients when the corresponding local dependencies are installed. High-value protocol contracts should also be mirrored as focused Rust tests near their owning `moli-protocol` boundary so they run under `cargo nextest`.-The suite covers real CDP-client workflows: `connect_over_cdp`, multiple pages and contexts, navigation, history, `Page.setDocumentContent`, popup target creation, JavaScript dialog events, Network/Fetch routing, workers, WebSocket, file upload, downloads, locator/input flows, DOM/handle flows, Chromium-derived CDP protocol samples, Playwright-upstream-derived route/CDPSession samples, screenshots, `Page.printToPDF`, viewport, and storage/profile behavior. It is not a replacement for unit tests. Its job is to answer whether moli is usable as a Playwright/Puppeteer-style CDP endpoint.+The suite covers real CDP-client workflows: `connect_over_cdp`, concurrent browser and direct-page clients, multiple pages and contexts, navigation, history, `Page.setDocumentContent`, popup target creation, JavaScript dialog events, Network/Fetch routing, workers, WebSocket, file upload, downloads, locator/input flows, DOM/handle flows, Chromium-derived CDP protocol samples, Playwright-upstream-derived route/CDPSession samples, screenshots, `Page.printToPDF`, viewport, and storage/profile behavior. It is not a replacement for unit tests. Its job is to answer whether moli is usable as a Playwright/Puppeteer-style CDP endpoint.## Chromium Behavior Evidence@@ -43,6 +43,23 @@ security contract rather than claiming identical interception placement. Thelocal `~/chromium/src/out/Default/chrome` 147 binary remains unusable for thisprobe because its V8 snapshot does not match the executable.+The default raw `multi-client` group was calibrated on 2026-08-14 against+Debian `/usr/bin/chromium` 145.0.7632.116 and then run unchanged against Moli.+The group covers 2-, 3-, and 7-client browser and direct-page WebSocket fan-out+against one target. Every connection can reuse the same command ids without+response crossover and observe the same target runtime through distinct+sessions. For each connection, `Target.attachedToTarget` precedes its attach+response and four-command bursts preserve both response order and runtime+side-effect order; ordering between different WebSockets is intentionally+unconstrained. Target discovery enabled on alternating browser connections does+not leak to their peers, and subscribers observe `Target.targetCreated` before+their attach event and response. Chromium rejects a foreign flattened session with+`-32001` and a foreign+`Target.detachFromTarget` session reference with `-32602`. Closing either kind+of peer connection leaves the other client's root and target sessions usable.+The final matrix passed five consecutive runs against one Chromium process and+ten runs against freshly started Moli processes.+The default `xhr-sync-semantics` group was calibrated on 2026-08-09 against thesame executable Chromium and then run unchanged against Moli. It ports 14Chromium-vendored XHR WPT contracts into one public-process matrix: nine success@@ -83,6 +100,12 @@ Covered well:- Optional Stagehand 3.7.0 deterministic coverage for explicit CDP binding, navigation/evaluate, locator fill, attached-state waiting, shadow piercing, multiple pages and storage ownership, history, frame registry/deep locators, Network extra headers plus page fetch, and the declared position-click boundary. LLM `act`/`extract`/`observe` and a route API are not part of this group.- Optional agent-browser CLI coverage for explicit CDP binding identity, navigation/read/evaluate, fill and keyboard input, media override, Network route/request observation, tab lifecycle, trace/profiler transport, and the declared position-click boundary. The group uses a unique daemon namespace and an empty config so it cannot silently attach to or launch a different browser.- CDP discovery and `chromium.connect_over_cdp()`.+- Concurrent 2-, 3-, and 7-client raw browser and direct-page WebSocket fan-out+ against the same target, including colliding per-client command ids, distinct+ session ids, alternating discovery subscriptions, attach-event-before-response+ ordering, four-command per-client FIFO bursts, shared target state without+ response/event crossover, foreign flattened and legacy session rejection,+ and staged peer-disconnect isolation.- Raw CDP websocket command flow for `Runtime.evaluate(awaitPromise=true)` resolving page `fetch()`, timer-triggered `fetch()`, and WebSocket echo work without any follow-up client command; emitted `Runtime.executionContextCreated.uniqueId` round-tripping through DevTools-shaped `Runtime.evaluate` and `Runtime.callFunctionOn`; Chromium-calibrated pre-commit navigation suspension where DOM/Runtime/Debugger main-thread commands wait while `Performance.getMetrics`, `Runtime.terminateExecution`, and browser commands remain dispatchable; `Debugger.pause` responding before `Debugger.paused`, interrupting an in-flight `Runtime.evaluate`, and resuming that evaluation; commands queued behind a winning `Debugger.resume` completing through normal owner dispatch rather than synthetic cancellation; deterministic nested-function `Debugger.stepOut` response/resumed/caller-pause ordering; browser-global Tracing ownership across independent browser/page WebSocket frontends, including exactly one response for a synchronously completed start and the stop-before-start-ack `end response -> start error -> data -> complete` sequence; shared worker target discovery through `Target.getTargets`, worker-session `Runtime.executionContextCreated` / console log replay, and `Profiler.enable` / `Profiler.start` / `Profiler.stop` through `Target.setAutoAttach`; plus Chromium-calibrated DedicatedWorker target creation/update/attach ordering, exact worker-isolate Runtime/Console routing, `Inspector.workerScriptLoaded`, terminate, and owner-navigation cleanup.- The focused raw `agent-episode` group copies the recorded RL`Runtime.evaluate(awaitPromise=true)` observe/fill/click path. It requires the@@ -184,6 +207,9 @@ Runner layout:- `assertions.py`, `helpers.py`, `state.py`, `config.py`: shared runner utilities and state.- `groups/core.py`: discovery-adjacent page workflows: navigation, iframe, wait, cookies, redirects, and history.- `groups/protocol.py`: raw CDP protocol workflows that intentionally avoid Playwright helper commands, including shared worker target discovery, Runtime context/log replay, the Chromium/V8 `Debugger.pause` response-event-resume and nested-function `Debugger.stepOut` resume/re-pause sequences, and profiler session state.+- `groups/multi_client.py`: Chromium-calibrated 2/3/7-client browser/direct-page+ WebSocket routing, session ownership, command-id collision, per-client FIFO,+ attach event/response ordering, and staged disconnect isolation contracts.- `groups/agent_episode.py`: short raw-CDP RL-shaped observation/action,response/realm ordering, and failed-navigation error-Document contract.- `groups/fetch_runtime_teardown.py`: holds an exact module-fetch lease while CDP disposes its BrowserContext, then verifies that callback-thread cancellation, browser commands, and a replacement context survive teardown.@@ -247,6 +273,7 @@ Run a focused subset while developing a CDP area:```bashuv run moli-cdp-smoke --group protocol --group network+uv run moli-cdp-smoke --group multi-clientuv run moli-cdp-smoke --group layout-screenshotuv run moli-cdp-smoke --group pdfuv run moli-cdp-smoke --group agent-episodediff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_client.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_client.pynew file mode 100644index 000000000..d0fd647bc--- /dev/null+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_client.py@@ -0,0 +1,1112 @@+from __future__ import annotations++import asyncio+import logging+from dataclasses import dataclass+from typing import Any++from ..assertions import SmokeError, assert_equal, record+from ..raw_cdp import (+ RawCdpClient,+ connect_raw_cdp,+ connect_raw_cdp_websocket,+ discover_target_websocket_url,+)++LOGGER = logging.getLogger(__name__)+ORDERED_BURST_SIZE = 4+++@dataclass(frozen=True)+class AttachedTarget:+ browser_context_id: str+ target_id: str+ first_session_id: str+ second_session_id: str+++async def run_multi_client_group(+ endpoint: str,+ _fixture: str,+ results: list[dict[str, Any]],+) -> None:+ first = await connect_raw_cdp(endpoint)+ second: RawCdpClient | None = None+ browser_context_id: str | None = None+ try:+ second = await connect_raw_cdp(endpoint)+ await _colliding_browser_root_commands(first, second)+ browser_context_id = await _create_browser_context(second)+ attached = await _create_and_attach_shared_target(+ first,+ second,+ browser_context_id,+ )+ await _browser_session_isolation(first, second, attached, results)++ page_websocket_url = await discover_target_websocket_url(+ endpoint,+ attached.target_id,+ )+ await _direct_page_client_isolation(page_websocket_url, results)++ await first.websocket.close()+ await _surviving_browser_client(second, attached, results)+ finally:+ if browser_context_id is not None:+ await _dispose_browser_context(browser_context_id, (second, first))+ await asyncio.gather(+ *(+ client.websocket.close()+ for client in (first, second)+ if client is not None+ ),+ return_exceptions=True,+ )+ for client_count in (3, 7):+ await _run_fanout_case(endpoint, client_count, results)+++async def _colliding_browser_root_commands(+ first: RawCdpClient,+ second: RawCdpClient,+) -> None:+ first_id, second_id = await asyncio.gather(+ first.send("Browser.getVersion"),+ second.send("Browser.getVersion"),+ )+ assert_equal(first_id, second_id, "multi-client browser root command id collision")+ (first_response, _), (second_response, _) = await asyncio.gather(+ first.recv_until_id(first_id, timeout=5),+ second.recv_until_id(second_id, timeout=5),+ )+ for label, response in (+ ("first", first_response),+ ("second", second_response),+ ):+ product = response.get("result", {}).get("product")+ if not isinstance(product, str) or not product:+ raise SmokeError(f"{label} browser client returned no product: {response}")+ if "sessionId" in response:+ raise SmokeError(+ f"{label} browser response leaked its hidden base session: {response}"+ )+++async def _create_and_attach_shared_target(+ first: RawCdpClient,+ second: RawCdpClient,+ browser_context_id: str,+) -> AttachedTarget:+ discover_id = await first.send(+ "Target.setDiscoverTargets",+ {"discover": True, "filter": [{"type": "page"}]},+ )+ await first.recv_until_id(discover_id, timeout=5)++ create_target_id = await second.send(+ "Target.createTarget",+ {"browserContextId": browser_context_id, "url": "about:blank"},+ )+ create_target, second_create_seen = await second.recv_until_id(+ create_target_id,+ timeout=5,+ )+ target_id = create_target.get("result", {}).get("targetId")+ if not isinstance(target_id, str) or not target_id:+ raise SmokeError(f"multi-client setup returned no targetId: {create_target}")+ if (+ _find_target_event(second_create_seen, "Target.targetCreated", target_id)+ is not None+ ):+ raise SmokeError(+ "target discovery state leaked from the first browser client to the second"+ )++ collision_id = _align_next_command_id(first, second)+ first_attach_id, second_attach_id = await asyncio.gather(+ first.send(+ "Target.attachToTarget",+ {"targetId": target_id, "flatten": True},+ ),+ second.send(+ "Target.attachToTarget",+ {"targetId": target_id, "flatten": True},+ ),+ )+ assert_equal(first_attach_id, collision_id, "first colliding attach command id")+ assert_equal(second_attach_id, collision_id, "second colliding attach command id")+ (first_attach, first_seen), (second_attach, second_seen) = await asyncio.gather(+ first.recv_until_id(first_attach_id, timeout=5),+ second.recv_until_id(second_attach_id, timeout=5),+ )+ first_session_id = _required_session_id(first_attach, "first browser attach")+ second_session_id = _required_session_id(second_attach, "second browser attach")+ if first_session_id == second_session_id:+ raise SmokeError(+ "two browser clients attached to the same target with one shared sessionId"+ )+ _assert_attach_event_precedes_response(+ first_seen,+ first_attach_id,+ first_session_id,+ "first browser attach",+ )+ _assert_attach_event_precedes_response(+ second_seen,+ second_attach_id,+ second_session_id,+ "second browser attach",+ )+ target_created = _find_target_event(first_seen, "Target.targetCreated", target_id)+ if target_created is None:+ raise SmokeError(+ "the browser client with discovery enabled did not receive Target.targetCreated"+ )+ if "sessionId" in target_created:+ raise SmokeError(+ f"target discovery leaked the browser client's hidden base session: {target_created}"+ )+ _reject_foreign_session_output(+ first_seen,+ second_session_id,+ "first browser attach",+ )+ _reject_foreign_session_output(+ second_seen,+ first_session_id,+ "second browser attach",+ )+ return AttachedTarget(+ browser_context_id=browser_context_id,+ target_id=target_id,+ first_session_id=first_session_id,+ second_session_id=second_session_id,+ )+++async def _create_browser_context(client: RawCdpClient) -> str:+ create_context_id = await client.send("Target.createBrowserContext")+ create_context, _ = await client.recv_until_id(create_context_id, timeout=5)+ browser_context_id = create_context.get("result", {}).get("browserContextId")+ if not isinstance(browser_context_id, str) or not browser_context_id:+ raise SmokeError(+ f"multi-client setup returned no browserContextId: {create_context}"+ )+ return browser_context_id+++async def _browser_session_isolation(+ first: RawCdpClient,+ second: RawCdpClient,+ attached: AttachedTarget,+ results: list[dict[str, Any]],+) -> None:+ collision_id = _align_next_command_id(first, second)+ first_evaluate_id, second_evaluate_id = await asyncio.gather(+ first.send(+ "Runtime.evaluate",+ {"expression": "'first-browser-client'", "returnByValue": True},+ session_id=attached.first_session_id,+ ),+ second.send(+ "Runtime.evaluate",+ {"expression": "'second-browser-client'", "returnByValue": True},+ session_id=attached.second_session_id,+ ),+ )+ assert_equal(first_evaluate_id, collision_id, "first colliding evaluate command id")+ assert_equal(+ second_evaluate_id, collision_id, "second colliding evaluate command id"+ )+ (first_response, first_seen), (second_response, second_seen) = await asyncio.gather(+ first.recv_until_id(first_evaluate_id, timeout=5),+ second.recv_until_id(second_evaluate_id, timeout=5),+ )+ assert_equal(+ _runtime_value(first_response),+ "first-browser-client",+ "first colliding browser response route",+ )+ assert_equal(+ _runtime_value(second_response),+ "second-browser-client",+ "second colliding browser response route",+ )+ assert_equal(+ first_response.get("sessionId"),+ attached.first_session_id,+ "first browser response session route",+ )+ assert_equal(+ second_response.get("sessionId"),+ attached.second_session_id,+ "second browser response session route",+ )+ _reject_foreign_session_output(+ first_seen,+ attached.second_session_id,+ "first browser evaluate",+ )+ _reject_foreign_session_output(+ second_seen,+ attached.first_session_id,+ "second browser evaluate",+ )++ write_id = await first.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliMultiClientState = 41",+ "returnByValue": True,+ },+ session_id=attached.first_session_id,+ )+ write, _ = await first.recv_until_id(write_id, timeout=5)+ assert_equal(_runtime_value(write), 41, "first browser shared-target write")++ read_id = await second.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliMultiClientState",+ "returnByValue": True,+ },+ session_id=attached.second_session_id,+ )+ read, _ = await second.recv_until_id(read_id, timeout=5)+ assert_equal(_runtime_value(read), 41, "second browser shared-target read")++ foreign_id = await second.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliForeignSessionRan = true",+ "returnByValue": True,+ },+ session_id=attached.first_session_id,+ )+ foreign, _ = await _recv_until_id_allow_error(second, foreign_id, timeout=5)+ assert_equal(+ foreign.get("error", {}).get("code"),+ -32001,+ "foreign flattened session rejection code",+ )++ foreign_detach_id = await second.send(+ "Target.detachFromTarget",+ {"sessionId": attached.first_session_id},+ )+ foreign_detach, _ = await _recv_until_id_allow_error(+ second,+ foreign_detach_id,+ timeout=5,+ )+ assert_equal(+ foreign_detach.get("error", {}).get("code"),+ -32602,+ "foreign legacy session rejection code",+ )++ mutation_probe_id = await second.send(+ "Runtime.evaluate",+ {+ "expression": "typeof globalThis.__moliForeignSessionRan",+ "returnByValue": True,+ },+ session_id=attached.second_session_id,+ )+ mutation_probe, _ = await second.recv_until_id(mutation_probe_id, timeout=5)+ assert_equal(+ _runtime_value(mutation_probe),+ "undefined",+ "foreign session command did not execute",+ )+ record(+ results,+ "raw_cdp_concurrent_browser_clients",+ {+ "clients": 2,+ "sameTarget": True,+ "collidingCommandId": collision_id,+ "discoveryStateIsolated": True,+ "attachEventBeforeResponse": True,+ "foreignSessionRejected": True,+ },+ )+++async def _direct_page_client_isolation(+ websocket_url: str,+ results: list[dict[str, Any]],+) -> None:+ first, second = await asyncio.gather(+ connect_raw_cdp_websocket(websocket_url),+ connect_raw_cdp_websocket(websocket_url),+ )+ try:+ first_id, second_id = await asyncio.gather(+ first.send(+ "Runtime.evaluate",+ {"expression": "'first-page-client'", "returnByValue": True},+ ),+ second.send(+ "Runtime.evaluate",+ {"expression": "'second-page-client'", "returnByValue": True},+ ),+ )+ assert_equal(first_id, second_id, "direct-page command id collision")+ (first_response, _), (second_response, _) = await asyncio.gather(+ first.recv_until_id(first_id, timeout=5),+ second.recv_until_id(second_id, timeout=5),+ )+ assert_equal(+ _runtime_value(first_response),+ "first-page-client",+ "first direct-page response route",+ )+ assert_equal(+ _runtime_value(second_response),+ "second-page-client",+ "second direct-page response route",+ )+ if "sessionId" in first_response or "sessionId" in second_response:+ raise SmokeError(+ "a direct-page response leaked its private flattened session: "+ f"first={first_response}, second={second_response}"+ )++ write_id = await first.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliDirectPageClientState = 41",+ "returnByValue": True,+ },+ )+ write, _ = await first.recv_until_id(write_id, timeout=5)+ assert_equal(_runtime_value(write), 41, "first direct-page shared-target write")++ read_id = await second.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliDirectPageClientState",+ "returnByValue": True,+ },+ )+ read, _ = await second.recv_until_id(read_id, timeout=5)+ assert_equal(_runtime_value(read), 41, "second direct-page shared-target read")++ await first.websocket.close()+ surviving_id = await second.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliDirectPageClientState + 1",+ "returnByValue": True,+ },+ )+ surviving, _ = await second.recv_until_id(surviving_id, timeout=5)+ assert_equal(+ _runtime_value(surviving),+ 42,+ "surviving direct-page client after peer disconnect",+ )+ record(+ results,+ "raw_cdp_concurrent_page_clients",+ {"clients": 2, "sameTarget": True, "peerDisconnectSurvived": True},+ )+ finally:+ await asyncio.gather(+ first.websocket.close(),+ second.websocket.close(),+ return_exceptions=True,+ )+++async def _surviving_browser_client(+ client: RawCdpClient,+ attached: AttachedTarget,+ results: list[dict[str, Any]],+) -> None:+ evaluate_id = await client.send(+ "Runtime.evaluate",+ {+ "expression": "globalThis.__moliMultiClientState + 1",+ "returnByValue": True,+ },+ session_id=attached.second_session_id,+ )+ evaluate, seen = await client.recv_until_id(evaluate_id, timeout=5)+ assert_equal(+ _runtime_value(evaluate),+ 42,+ "surviving browser session after peer disconnect",+ )+ _reject_foreign_session_output(+ seen,+ attached.first_session_id,+ "surviving browser after peer disconnect",+ )++ version_id = await client.send("Browser.getVersion")+ version, _ = await client.recv_until_id(version_id, timeout=5)+ product = version.get("result", {}).get("product")+ if not isinstance(product, str) or not product:+ raise SmokeError(+ f"surviving browser root session returned no product: {version}"+ )+ record(+ results,+ "raw_cdp_browser_client_disconnect_isolation",+ {"peerSessionSurvived": True, "rootSessionSurvived": True},+ )+++async def _run_fanout_case(+ endpoint: str,+ client_count: int,+ results: list[dict[str, Any]],+) -> None:+ clients: list[RawCdpClient] = []+ browser_context_id: str | None = None+ try:+ for _ in range(client_count):+ clients.append(await connect_raw_cdp(endpoint))+ await _fanout_root_command_collision(clients)++ discovery_clients = set(range(0, client_count, 2))+ await _enable_fanout_discovery(clients, discovery_clients)+ coordinator_index = client_count - 1+ coordinator = clients[coordinator_index]+ browser_context_id = await _create_browser_context(coordinator)+ target_id, create_seen = await _create_target(coordinator, browser_context_id)+ session_ids, attach_seen, attach_command_id = await _attach_fanout_clients(+ clients,+ target_id,+ )+ _assert_fanout_discovery_routes(+ target_id,+ discovery_clients,+ coordinator_index,+ create_seen,+ attach_seen,+ )++ burst_command_id = await _ordered_runtime_fanout(+ clients,+ session_ids,+ "browser",+ client_count,+ )+ page_websocket_url = await discover_target_websocket_url(endpoint, target_id)+ await _run_direct_page_fanout(page_websocket_url, client_count, results)++ disconnect_order = await _disconnect_fanout_peers(+ clients,+ session_ids,+ "browser",+ )+ survivor = clients[-1]+ version_id = await survivor.send("Browser.getVersion")+ version, _ = await survivor.recv_until_id(version_id, timeout=5)+ product = version.get("result", {}).get("product")+ if not isinstance(product, str) or not product:+ raise SmokeError(+ f"{client_count}-client browser survivor returned no product: {version}"+ )+ record(+ results,+ f"raw_cdp_browser_client_fanout_{client_count}",+ {+ "clients": client_count,+ "uniqueSessions": len(set(session_ids)),+ "discoverySubscribers": len(discovery_clients),+ "attachEventBeforeResponse": True,+ "attachCommandId": attach_command_id,+ "orderedBurstSize": ORDERED_BURST_SIZE,+ "burstCommandId": burst_command_id,+ "perClientOrder": True,+ "crossClientOrder": "unconstrained",+ "disconnectOrder": disconnect_order,+ },+ )+ finally:+ if browser_context_id is not None and clients:+ await _dispose_browser_context(+ browser_context_id,+ (clients[-1], *clients[:-1]),+ )+ await asyncio.gather(+ *(client.websocket.close() for client in clients),+ return_exceptions=True,+ )+++async def _fanout_root_command_collision(clients: list[RawCdpClient]) -> None:+ command_ids = await asyncio.gather(+ *(client.send("Browser.getVersion") for client in clients)+ )+ if len(set(command_ids)) != 1:+ raise SmokeError(+ f"fan-out browser root command ids did not collide: {command_ids}"+ )+ responses = await asyncio.gather(+ *(+ client.recv_until_id(command_id, timeout=5)+ for client, command_id in zip(clients, command_ids, strict=True)+ )+ )+ for client_index, (response, _) in enumerate(responses):+ product = response.get("result", {}).get("product")+ if not isinstance(product, str) or not product:+ raise SmokeError(+ f"fan-out browser client {client_index} returned no product: {response}"+ )+ if "sessionId" in response:+ raise SmokeError(+ "fan-out browser response leaked its hidden base session: "+ f"client={client_index}, response={response}"+ )+++async def _enable_fanout_discovery(+ clients: list[RawCdpClient],+ discovery_clients: set[int],+) -> None:+ subscribers = [clients[index] for index in sorted(discovery_clients)]+ command_ids = await asyncio.gather(+ *(+ client.send(+ "Target.setDiscoverTargets",+ {"discover": True, "filter": [{"type": "page"}]},+ )+ for client in subscribers+ )+ )+ await asyncio.gather(+ *(+ client.recv_until_id(command_id, timeout=5)+ for client, command_id in zip(subscribers, command_ids, strict=True)+ )+ )+++async def _create_target(+ client: RawCdpClient,+ browser_context_id: str,+) -> tuple[str, list[dict[str, Any]]]:+ create_target_id = await client.send(+ "Target.createTarget",+ {"browserContextId": browser_context_id, "url": "about:blank"},+ )+ create_target, seen = await client.recv_until_id(create_target_id, timeout=5)+ target_id = create_target.get("result", {}).get("targetId")+ if not isinstance(target_id, str) or not target_id:+ raise SmokeError(f"fan-out setup returned no targetId: {create_target}")+ return target_id, seen+++async def _attach_fanout_clients(+ clients: list[RawCdpClient],+ target_id: str,+) -> tuple[list[str], list[list[dict[str, Any]]], int]:+ collision_id = _align_client_command_ids(clients)+ command_ids = await asyncio.gather(+ *(+ client.send(+ "Target.attachToTarget",+ {"targetId": target_id, "flatten": True},+ )+ for client in clients+ )+ )+ if command_ids != [collision_id] * len(clients):+ raise SmokeError(+ f"fan-out attach command ids did not collide at {collision_id}: {command_ids}"+ )+ responses = await asyncio.gather(+ *(+ client.recv_until_id(command_id, timeout=5)+ for client, command_id in zip(clients, command_ids, strict=True)+ )+ )+ session_ids = [+ _required_session_id(response, f"fan-out browser attach {client_index}")+ for client_index, (response, _) in enumerate(responses)+ ]+ if len(set(session_ids)) != len(clients):+ raise SmokeError(f"fan-out browser sessions were not unique: {session_ids}")+ seen_by_client = [seen for _, seen in responses]+ for client_index, (session_id, seen) in enumerate(+ zip(session_ids, seen_by_client, strict=True)+ ):+ _assert_attach_event_precedes_response(+ seen,+ collision_id,+ session_id,+ f"fan-out browser attach {client_index}",+ )+ for foreign_session_id in session_ids:+ if foreign_session_id != session_id:+ _reject_foreign_session_output(+ seen,+ foreign_session_id,+ f"fan-out browser attach {client_index}",+ )+ return session_ids, seen_by_client, collision_id+++def _assert_fanout_discovery_routes(+ target_id: str,+ discovery_clients: set[int],+ coordinator_index: int,+ create_seen: list[dict[str, Any]],+ attach_seen: list[list[dict[str, Any]]],+) -> None:+ for client_index, attach_messages in enumerate(attach_seen):+ messages = list(attach_messages)+ if client_index == coordinator_index:+ messages = [*create_seen, *messages]+ event = _find_target_event(messages, "Target.targetCreated", target_id)+ if client_index in discovery_clients:+ if event is None:+ raise SmokeError(+ f"fan-out discovery client {client_index} missed Target.targetCreated"+ )+ if "sessionId" in event:+ raise SmokeError(+ "fan-out target discovery leaked a hidden base session: "+ f"client={client_index}, event={event}"+ )+ attached_event = _find_target_event(+ messages,+ "Target.attachedToTarget",+ target_id,+ )+ if attached_event is None or messages.index(event) >= messages.index(+ attached_event+ ):+ raise SmokeError(+ "fan-out target discovery did not precede attachment: "+ f"client={client_index}, messages={messages}"+ )+ elif event is not None:+ raise SmokeError(+ f"fan-out discovery state leaked to client {client_index}: {event}"+ )+++async def _ordered_runtime_fanout(+ clients: list[RawCdpClient],+ session_ids: list[str | None],+ client_kind: str,+ client_count: int,+) -> int:+ burst_start_id = _align_client_command_ids(clients)+ state_name = f"__moli{client_kind.title()}FanoutOrder{client_count}"+ sent_ids = await asyncio.gather(+ *(+ _send_ordered_runtime_burst(+ client,+ session_id,+ client_kind,+ client_count,+ client_index,+ state_name,+ )+ for client_index, (client, session_id) in enumerate(+ zip(clients, session_ids, strict=True)+ )+ )+ )+ expected_ids = list(range(burst_start_id, burst_start_id + ORDERED_BURST_SIZE))+ for client_index, client_sent_ids in enumerate(sent_ids):+ assert_equal(+ client_sent_ids,+ expected_ids,+ f"{client_kind} fan-out client {client_index} sent command order",+ )+ received_messages = await asyncio.gather(+ *(+ _receive_ordered_runtime_burst(+ client,+ session_id,+ client_kind,+ client_count,+ client_index,+ expected_ids,+ )+ for client_index, (client, session_id) in enumerate(+ zip(clients, session_ids, strict=True)+ )+ )+ )+ for client_index, messages in enumerate(received_messages):+ own_session_id = session_ids[client_index]+ if own_session_id is None:+ continue+ for foreign_session_id in session_ids:+ if foreign_session_id is not None and foreign_session_id != own_session_id:+ _reject_foreign_session_output(+ messages,+ foreign_session_id,+ f"{client_kind} fan-out burst {client_index}",+ )+ await _assert_shared_runtime_order(+ clients[0],+ session_ids[0],+ client_kind,+ client_count,+ state_name,+ )+ return burst_start_id+++async def _send_ordered_runtime_burst(+ client: RawCdpClient,+ session_id: str | None,+ client_kind: str,+ client_count: int,+ client_index: int,+ state_name: str,+) -> list[int]:+ command_ids: list[int] = []+ for sequence in range(ORDERED_BURST_SIZE):+ token = f"{client_kind}-{client_count}-{client_index}-{sequence}"+ expression = (+ "(() => {"+ f"globalThis.{state_name} ??= [];"+ f"globalThis.{state_name}.push('{token}');"+ f"return {{client: {client_index}, sequence: {sequence}}};"+ "})()"+ )+ command_ids.append(+ await client.send(+ "Runtime.evaluate",+ {"expression": expression, "returnByValue": True},+ session_id=session_id,+ )+ )+ return command_ids+++async def _receive_ordered_runtime_burst(+ client: RawCdpClient,+ session_id: str | None,+ client_kind: str,+ client_count: int,+ client_index: int,+ expected_ids: list[int],+) -> list[dict[str, Any]]:+ expected_id_set = set(expected_ids)+ response_ids: list[int] = []+ messages: list[dict[str, Any]] = []+ deadline = asyncio.get_running_loop().time() + 10+ while len(response_ids) < len(expected_ids):+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ raise SmokeError(+ f"timed out waiting for {client_kind} fan-out client {client_index} "+ f"ordered responses; ids={response_ids}, messages={messages[-20:]}"+ )+ message = await asyncio.wait_for(client.recv(), timeout=remaining)+ messages.append(message)+ message_id = message.get("id")+ if message_id not in expected_id_set:+ continue+ if message_id in response_ids:+ raise SmokeError(+ f"{client_kind} fan-out client {client_index} received duplicate "+ f"response id {message_id}: {message}"+ )+ if "error" in message:+ raise SmokeError(+ f"{client_kind} fan-out client {client_index} command "+ f"{message_id} failed: {message['error']}"+ )+ response_ids.append(message_id)+ _assert_wire_session(+ message,+ session_id,+ f"{client_kind} fan-out client {client_index} response {message_id}",+ )+ sequence = expected_ids.index(message_id)+ assert_equal(+ _runtime_value(message),+ {"client": client_index, "sequence": sequence},+ f"{client_kind} fan-out client {client_index} response payload",+ )+ assert_equal(+ response_ids,+ expected_ids,+ f"{client_kind} fan-out client {client_index} response order",+ )+ return messages+++async def _assert_shared_runtime_order(+ client: RawCdpClient,+ session_id: str | None,+ client_kind: str,+ client_count: int,+ state_name: str,+) -> None:+ read_id = await client.send(+ "Runtime.evaluate",+ {"expression": f"globalThis.{state_name}", "returnByValue": True},+ session_id=session_id,+ )+ response, _ = await client.recv_until_id(read_id, timeout=5)+ observed = _runtime_value(response)+ expected = [+ f"{client_kind}-{client_count}-{client_index}-{sequence}"+ for client_index in range(client_count)+ for sequence in range(ORDERED_BURST_SIZE)+ ]+ if not isinstance(observed, list):+ raise SmokeError(+ f"{client_kind} fan-out shared order was not an array: {observed!r}"+ )+ if len(observed) != len(expected) or set(observed) != set(expected):+ raise SmokeError(+ f"{client_kind} fan-out shared order was incomplete: {observed!r}"+ )+ positions = {token: position for position, token in enumerate(observed)}+ for client_index in range(client_count):+ client_positions = [+ positions[f"{client_kind}-{client_count}-{client_index}-{sequence}"]+ for sequence in range(ORDERED_BURST_SIZE)+ ]+ if client_positions != sorted(client_positions):+ raise SmokeError(+ f"{client_kind} fan-out reordered client {client_index}: "+ f"positions={client_positions}, observed={observed}"+ )+++async def _run_direct_page_fanout(+ websocket_url: str,+ client_count: int,+ results: list[dict[str, Any]],+) -> None:+ clients: list[RawCdpClient] = []+ try:+ for _ in range(client_count):+ clients.append(await connect_raw_cdp_websocket(websocket_url))+ burst_command_id = await _ordered_runtime_fanout(+ clients,+ [None] * client_count,+ "page",+ client_count,+ )+ disconnect_order = await _disconnect_fanout_peers(+ clients,+ [None] * client_count,+ "page",+ )+ record(+ results,+ f"raw_cdp_page_client_fanout_{client_count}",+ {+ "clients": client_count,+ "orderedBurstSize": ORDERED_BURST_SIZE,+ "burstCommandId": burst_command_id,+ "perClientOrder": True,+ "crossClientOrder": "unconstrained",+ "disconnectOrder": disconnect_order,+ },+ )+ finally:+ await asyncio.gather(+ *(client.websocket.close() for client in clients),+ return_exceptions=True,+ )+++async def _disconnect_fanout_peers(+ clients: list[RawCdpClient],+ session_ids: list[str | None],+ client_kind: str,+) -> list[int]:+ disconnect_order = [+ *range(0, len(clients) - 1, 2),+ *range(1, len(clients) - 1, 2),+ ]+ survivor = clients[-1]+ survivor_session_id = session_ids[-1]+ closed_session_ids: list[str] = []+ for sequence, client_index in enumerate(disconnect_order):+ await clients[client_index].websocket.close()+ closed_session_id = session_ids[client_index]+ if closed_session_id is not None:+ closed_session_ids.append(closed_session_id)+ token = f"{client_kind}-survivor-{sequence}"+ probe_id = await survivor.send(+ "Runtime.evaluate",+ {"expression": f"'{token}'", "returnByValue": True},+ session_id=survivor_session_id,+ )+ probe, seen = await survivor.recv_until_id(probe_id, timeout=5)+ assert_equal(+ _runtime_value(probe),+ token,+ f"{client_kind} fan-out survivor after disconnect {client_index}",+ )+ _assert_wire_session(+ probe,+ survivor_session_id,+ f"{client_kind} fan-out survivor response",+ )+ for foreign_session_id in closed_session_ids:+ _reject_foreign_session_output(+ seen,+ foreign_session_id,+ f"{client_kind} fan-out survivor after disconnect {client_index}",+ )+ if client_kind == "browser":+ for message in seen:+ if message.get("method") == "Target.detachedFromTarget":+ raise SmokeError(+ "browser fan-out survivor received another client's detach: "+ f"closed={client_index}, message={message}"+ )+ return disconnect_order+++def _align_next_command_id(first: RawCdpClient, second: RawCdpClient) -> int:+ return _align_client_command_ids([first, second])+++def _align_client_command_ids(clients: list[RawCdpClient]) -> int:+ command_id = max(client.next_id for client in clients)+ for client in clients:+ client.next_id = command_id+ return command_id+++def _required_session_id(response: dict[str, Any], label: str) -> str:+ session_id = response.get("result", {}).get("sessionId")+ if not isinstance(session_id, str) or not session_id:+ raise SmokeError(f"{label} returned no sessionId: {response}")+ if "sessionId" in response:+ raise SmokeError(f"{label} leaked its hidden base session: {response}")+ return session_id+++def _assert_attach_event_precedes_response(+ messages: list[dict[str, Any]],+ command_id: int,+ session_id: str,+ label: str,+) -> None:+ response_index: int | None = None+ event_index: int | None = None+ event: dict[str, Any] | None = None+ for index, message in enumerate(messages):+ if message.get("id") == command_id:+ response_index = index+ if (+ message.get("method") == "Target.attachedToTarget"+ and message.get("params", {}).get("sessionId") == session_id+ ):+ event_index = index+ event = message+ if event_index is None or response_index is None:+ raise SmokeError(+ f"{label} did not include its attach event and response: {messages}"+ )+ if event_index >= response_index:+ raise SmokeError(f"{label} delivered response before attach event: {messages}")+ if event is not None and "sessionId" in event:+ raise SmokeError(f"{label} attach event leaked a hidden base session: {event}")+++def _assert_wire_session(+ message: dict[str, Any],+ expected_session_id: str | None,+ label: str,+) -> None:+ if expected_session_id is None:+ if "sessionId" in message:+ raise SmokeError(f"{label} leaked a private page session: {message}")+ return+ assert_equal(+ message.get("sessionId"),+ expected_session_id,+ f"{label} session route",+ )+++def _runtime_value(response: dict[str, Any]) -> Any:+ return response.get("result", {}).get("result", {}).get("value")+++def _find_target_event(+ messages: list[dict[str, Any]],+ method: str,+ target_id: str,+) -> dict[str, Any] | None:+ for message in messages:+ if message.get("method") != method:+ continue+ event_target_id = (+ message.get("params", {}).get("targetInfo", {}).get("targetId")+ )+ if event_target_id == target_id:+ return message+ return None+++def _reject_foreign_session_output(+ messages: list[dict[str, Any]],+ foreign_session_id: str,+ label: str,+) -> None:+ for message in messages:+ params = message.get("params")+ if message.get("sessionId") == foreign_session_id or (+ isinstance(params, dict) and params.get("sessionId") == foreign_session_id+ ):+ raise SmokeError(+ f"{label} received output for another client's session: {message}"+ )+++async def _recv_until_id_allow_error(+ client: RawCdpClient,+ message_id: int,+ *,+ timeout: float,+) -> tuple[dict[str, Any], list[dict[str, Any]]]:+ deadline = asyncio.get_running_loop().time() + timeout+ seen: list[dict[str, Any]] = []+ while True:+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ raise SmokeError(+ f"timed out waiting for CDP response id={message_id}; seen={seen[-20:]}"+ )+ message = await asyncio.wait_for(client.recv(), timeout=remaining)+ seen.append(message)+ if message.get("id") == message_id:+ return message, seen+++async def _dispose_browser_context(+ browser_context_id: str,+ clients: tuple[RawCdpClient | None, ...],+) -> None:+ for client in clients:+ if client is None:+ continue+ try:+ dispose_id = await client.send(+ "Target.disposeBrowserContext",+ {"browserContextId": browser_context_id},+ )+ await client.recv_until_id(dispose_id, timeout=3)+ return+ except Exception:+ # Best-effort cleanup must not mask the original smoke failure.+ LOGGER.debug(+ "failed to dispose multi-client smoke browser context",+ exc_info=True,+ )diff --git a/moli-cdp-smoke/moli_cdp_smoke/raw_cdp.py b/moli-cdp-smoke/moli_cdp_smoke/raw_cdp.pyindex 8ef088548..3a95c5f83 100644--- a/moli-cdp-smoke/moli_cdp_smoke/raw_cdp.py+++ b/moli-cdp-smoke/moli_cdp_smoke/raw_cdp.py@@ -46,6 +46,25 @@ async def discover_page_websocket_url(endpoint: str) -> str:raise RawCdpError(f"CDP target discovery response included no page websocket: {payload!r}")+async def discover_target_websocket_url(endpoint: str, target_id: str) -> str:+ targets_url = endpoint.rstrip("/") + "/json/list"+ payload = await asyncio.to_thread(_read_json_url, targets_url)+ if not isinstance(payload, list):+ raise RawCdpError(f"CDP target discovery response was not a list: {payload!r}")+ for target in payload:+ if not isinstance(target, dict) or target.get("id") != target_id:+ continue+ websocket_url = target.get("webSocketDebuggerUrl")+ if isinstance(websocket_url, str) and websocket_url:+ return websocket_url+ raise RawCdpError(+ f"CDP target {target_id} did not include webSocketDebuggerUrl: {target!r}"+ )+ raise RawCdpError(+ f"CDP target {target_id} was not present in discovery: {payload!r}"+ )++@dataclassclass RawCdpClient:websocket: ClientConnectiondiff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.pyindex b32902c17..48121321c 100644--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py@@ -35,6 +35,7 @@ from .groups.emulation_storage import run_emulation_storage_groupfrom .groups.error_document import run_error_document_groupfrom .groups.fetch_runtime_teardown import run_fetch_runtime_teardown_groupfrom .groups.layout_screenshot import run_layout_screenshot_group+from .groups.multi_client import run_multi_client_groupfrom .groups.multi_context import run_multi_context_groupfrom .groups.network import (run_download_group,@@ -124,6 +125,13 @@ RAW_GROUPS: tuple[SmokeGroup, ...] = ("raw",run_target_semantics_group,),+ SmokeGroup(+ "multi-client",+ "Concurrent 2/3/7-client browser/page WebSocket routing, isolation, "+ "and per-client ordering.",+ "raw",+ run_multi_client_group,+ ),SmokeGroup("protocol","Raw CDP command/reply flows that avoid Playwright helper follow-up commands.",diff --git a/moli-protocol-cdp/src/wire.rs b/moli-protocol-cdp/src/wire.rsindex c0edb2245..808b512c7 100644--- a/moli-protocol-cdp/src/wire.rs+++ b/moli-protocol-cdp/src/wire.rs@@ -147,6 +147,12 @@ impl CdpRequest {self.id = internal_command_id;self.session_id = dispatch_session_id.map(str::to_owned);}++ fn rewrite_target_session_reference(&mut self, session_id: &str) {+ self.params+ .get_or_insert_default()+ .insert("sessionId".to_owned(), Value::String(session_id.to_owned()));+ }}/// Renderer access required by one parsed CDP command.@@ -305,6 +311,21 @@ impl ParsedCdpCommand {Ok(self)}+ /// Resolve a legacy Target-domain `params.targetId` route to its concrete+ /// session before dispatch.+ ///+ /// Frontend adapters use this to preserve Chromium's per-client+ /// `TargetHandler::FindSession` ownership boundary even though all socket+ /// clients share one downstream protocol connection.+ pub fn rewrite_target_session_reference(+ mut self,+ session_id: &str,+ ) -> serde_json::Result<Self> {+ self.request.rewrite_target_session_reference(session_id);+ self.json = serde_json::to_string(&self.request)?;+ Ok(self)+ }+pub fn method(&self) -> &str {self.request.method()}@@ -851,6 +872,31 @@ mod tests {);}+ #[test]+ fn target_session_reference_rewrite_preserves_other_command_fields() {+ let command = parse(+ r#"{"id":14,"method":"Target.detachFromTarget","params":{"targetId":"TID-1"},"futureExtension":true}"#,+ )+ .rewrite_target_session_reference("SID-owned")+ .expect("target session reference rewrite must serialize")+ .rewrite_frontend_route(91, Some("SID-browser"))+ .expect("frontend route rewrite must serialize");++ assert_eq!(+ serde_json::from_str::<Value>(command.json()).expect("rewritten dispatch JSON"),+ serde_json::json!({+ "id": 91,+ "method": "Target.detachFromTarget",+ "params": {+ "targetId": "TID-1",+ "sessionId": "SID-owned",+ },+ "sessionId": "SID-browser",+ "futureExtension": true,+ })+ );+ }+#[test]fn absent_and_null_params_share_chromium_empty_params_semantics() {for raw in [diff --git a/moli-protocol-server/src/cdp_frontend.rs b/moli-protocol-server/src/cdp_frontend.rsindex 0ab39864f..a5b5769ff 100644--- a/moli-protocol-server/src/cdp_frontend.rs+++ b/moli-protocol-server/src/cdp_frontend.rs@@ -1,3 +1,4 @@+use anyhow::{Context, Result, bail};use tokio::sync::{mpsc, oneshot};use crate::cdp_writer::CdpSocketSink;@@ -19,12 +20,12 @@ pub(crate) struct CdpFrontendEndpoint {pub(crate) enum CdpFrontendControlRequest {AttachBrowser {sink: CdpSocketSink,- completion_tx: oneshot::Sender<Result<u64, String>>,+ completion_tx: oneshot::Sender<Result<u64>>,},AttachPage {target_id: String,sink: CdpSocketSink,- completion_tx: oneshot::Sender<Result<u64, String>>,+ completion_tx: oneshot::Sender<Result<u64>>,},DetachBrowser {frontend_id: u64,@@ -37,15 +38,15 @@ pub(crate) enum CdpFrontendControlRequest {},ActivateTarget {target_id: String,- completion_tx: oneshot::Sender<Result<(), String>>,+ completion_tx: oneshot::Sender<Result<()>>,},CloseTarget {target_id: String,- completion_tx: oneshot::Sender<Result<(), String>>,+ completion_tx: oneshot::Sender<Result<()>>,},CreateManagedTarget {target_url: String,- completion_tx: oneshot::Sender<Result<String, String>>,+ completion_tx: oneshot::Sender<Result<String>>,},Shutdown,}@@ -73,9 +74,9 @@ pub(crate) fn cdp_frontend_channel() -> (CdpFrontendEndpoint, CdpFrontendReceive}impl CdpFrontendEndpoint {- pub(crate) async fn attach_browser(&self, sink: CdpSocketSink) -> Result<u64, String> {+ pub(crate) async fn attach_browser(&self, sink: CdpSocketSink) -> Result<u64> {if self.is_shutting_down() {- return Err("CDP owner is shutting down".to_owned());+ bail!("CDP owner is shutting down");}let (completion_tx, completion_rx) = oneshot::channel();self.control_tx@@ -83,22 +84,18 @@ impl CdpFrontendEndpoint {sink,completion_tx,})- .map_err(|_| "CDP owner is no longer available".to_owned())?;+ .context("CDP owner is no longer available")?;tokio::select! {biased;- _ = self.wait_for_shutdown() => Err("CDP owner stopped before browser frontend attach".to_owned()),+ _ = self.wait_for_shutdown() => bail!("CDP owner stopped before browser frontend attach"),completion = completion_rx => completion- .map_err(|_| "CDP owner stopped before browser frontend attach".to_owned())?,+ .context("CDP owner stopped before browser frontend attach")?,}}- pub(crate) async fn attach_page(- &self,- target_id: String,- sink: CdpSocketSink,- ) -> Result<u64, String> {+ pub(crate) async fn attach_page(&self, target_id: String, sink: CdpSocketSink) -> Result<u64> {if self.is_shutting_down() {- return Err("CDP target owner is shutting down".to_owned());+ bail!("CDP target owner is shutting down");}let (completion_tx, completion_rx) = oneshot::channel();self.control_tx@@ -107,12 +104,12 @@ impl CdpFrontendEndpoint {sink,completion_tx,})- .map_err(|_| "CDP target owner is no longer available".to_owned())?;+ .context("CDP target owner is no longer available")?;tokio::select! {biased;- _ = self.wait_for_shutdown() => Err("CDP target owner stopped before page frontend attach".to_owned()),+ _ = self.wait_for_shutdown() => bail!("CDP target owner stopped before page frontend attach"),completion = completion_rx => completion- .map_err(|_| "CDP target owner stopped before page frontend attach".to_owned())?,+ .context("CDP target owner stopped before page frontend attach")?,}}@@ -142,9 +139,9 @@ impl CdpFrontendEndpoint {.send(CdpFrontendControlRequest::TargetDestroyed { target_id });}- pub(crate) async fn activate_target(&self, target_id: String) -> Result<(), String> {+ pub(crate) async fn activate_target(&self, target_id: String) -> Result<()> {if self.is_shutting_down() {- return Err("CDP target owner is shutting down".to_owned());+ bail!("CDP target owner is shutting down");}let (completion_tx, completion_rx) = oneshot::channel();self.control_tx@@ -152,18 +149,18 @@ impl CdpFrontendEndpoint {target_id,completion_tx,})- .map_err(|_| "CDP target owner is no longer available".to_owned())?;+ .context("CDP target owner is no longer available")?;tokio::select! {biased;- _ = self.wait_for_shutdown() => Err("CDP target owner stopped before target activation".to_owned()),+ _ = self.wait_for_shutdown() => bail!("CDP target owner stopped before target activation"),completion = completion_rx => completion- .map_err(|_| "CDP target owner stopped before target activation".to_owned())?,+ .context("CDP target owner stopped before target activation")?,}}- pub(crate) async fn close_target(&self, target_id: String) -> Result<(), String> {+ pub(crate) async fn close_target(&self, target_id: String) -> Result<()> {if self.is_shutting_down() {- return Err("CDP target owner is shutting down".to_owned());+ bail!("CDP target owner is shutting down");}let (completion_tx, completion_rx) = oneshot::channel();self.control_tx@@ -171,18 +168,18 @@ impl CdpFrontendEndpoint {target_id,completion_tx,})- .map_err(|_| "CDP target owner is no longer available".to_owned())?;+ .context("CDP target owner is no longer available")?;tokio::select! {biased;- _ = self.wait_for_shutdown() => Err("CDP target owner stopped before target close".to_owned()),+ _ = self.wait_for_shutdown() => bail!("CDP target owner stopped before target close"),completion = completion_rx => completion- .map_err(|_| "CDP target owner stopped before target close".to_owned())?,+ .context("CDP target owner stopped before target close")?,}}- pub(crate) async fn create_managed_target(&self, target_url: String) -> Result<String, String> {+ pub(crate) async fn create_managed_target(&self, target_url: String) -> Result<String> {if self.is_shutting_down() {- return Err("CDP target owner is shutting down".to_owned());+ bail!("CDP target owner is shutting down");}let (completion_tx, completion_rx) = oneshot::channel();self.control_tx@@ -190,12 +187,12 @@ impl CdpFrontendEndpoint {target_url,completion_tx,})- .map_err(|_| "CDP target owner is no longer available".to_owned())?;+ .context("CDP target owner is no longer available")?;tokio::select! {biased;- _ = self.wait_for_shutdown() => Err("CDP target owner stopped before target creation".to_owned()),+ _ = self.wait_for_shutdown() => bail!("CDP target owner stopped before target creation"),completion = completion_rx => completion- .map_err(|_| "CDP target owner stopped before target creation".to_owned())?,+ .context("CDP target owner stopped before target creation")?,}}diff --git a/moli-protocol-server/src/cdp_frontend_router.rs b/moli-protocol-server/src/cdp_frontend_router.rsindex 519674db4..fa66ded3b 100644--- a/moli-protocol-server/src/cdp_frontend_router.rs+++ b/moli-protocol-server/src/cdp_frontend_router.rs@@ -1,5 +1,6 @@use std::time::Instant;+use anyhow::Result;use moli_protocol::ParsedCdpCommand;use parking_lot::Mutex;use serde_json::Value;@@ -44,11 +45,12 @@ impl CdpFrontendRouter {pub(crate) fn register_browser_frontend(&self,frontend_id: u64,+ session_id: String,sink: CdpSocketSink,- ) -> Result<(), String> {+ ) -> Result<()> {self.routing.lock()- .register_browser_frontend(frontend_id, sink)+ .register_browser_frontend(frontend_id, session_id, sink)}pub(crate) fn register_page_frontend(@@ -57,13 +59,13 @@ impl CdpFrontendRouter {target_id: String,session_id: String,sink: CdpSocketSink,- ) -> Result<(), String> {+ ) -> Result<()> {self.routing.lock().register_page_frontend(frontend_id, target_id, session_id, sink)}- pub(crate) fn unregister_browser_frontend(&self, frontend_id: u64) -> bool {+ pub(crate) fn unregister_browser_frontend(&self, frontend_id: u64) -> Option<String> {self.routing.lock().unregister_browser_frontend(frontend_id)}diff --git a/moli-protocol-server/src/cdp_frontend_router/routing.rs b/moli-protocol-server/src/cdp_frontend_router/routing.rsindex 548089cbe..d4100949e 100644--- a/moli-protocol-server/src/cdp_frontend_router/routing.rs+++ b/moli-protocol-server/src/cdp_frontend_router/routing.rs@@ -1,5 +1,6 @@use std::collections::{HashMap, HashSet};+use anyhow::{Result, bail};use moli_protocol::ParsedCdpCommand;use serde_json::{Value, json};@@ -17,12 +18,13 @@ struct PendingCommandRoute {frontend: CdpCommandFrontend,client_command_id: u64,method: String,+ attach_target_id: Option<String>,}struct CdpSessionFrontendRoute {kind: CdpSessionFrontendKind,target_id: Option<String>,- base_session_id: Option<String>,+ base_session_id: String,sink: CdpSocketSink,}@@ -40,8 +42,21 @@ struct FrontendSessionRoute {#[derive(Clone)]enum FrontendSessionKind {+ /// One hidden browser-target or page-target session owned by exactly one+ /// WebSocket frontend. Commands without a public sessionId dispatch here.Base,- Child { parent_session_id: Option<String> },+ /// A client-visible session created underneath the base session (or one+ /// of its descendants). Parent and target identity enforce Chromium's+ /// per-TargetHandler session lookup boundary.+ Child {+ parent_session_id: Option<String>,+ target_id: Option<String>,+ },+}++struct CdpTargetSessionReferenceError {+ code: i32,+ message: &'static str,}pub(super) struct CdpRoutedFrontend {@@ -61,6 +76,8 @@ impl CdpRoutedFrontend {#[derive(Default)]pub(super) struct CdpFrontendRoutingState {+ // The downstream protocol connection is shared, so client command ids and+ // session ownership must never be used as global frontend identities.next_internal_command_id: u64,pending_commands: HashMap<u64, PendingCommandRoute>,frontends: HashMap<u64, CdpSessionFrontendRoute>,@@ -104,7 +121,16 @@ impl CdpFrontendRoutingState {let client_command_id = request.id();let method = request.method().to_owned();let client_session_id = request.session_id().map(str::to_owned);- let route = self.frontends.get(&frontend_id)?;+ let attach_target_id = (method == "Target.attachToTarget")+ .then(|| {+ request+ .params()+ .and_then(|params| params.get("targetId"))+ .and_then(Value::as_str)+ .map(str::to_owned)+ })+ .flatten();+ let base_session_id = self.frontends.get(&frontend_id)?.base_session_id.clone();let dispatch_session_id = if let Some(session_id) = client_session_id.as_deref() {let Some(session) = self.sessions.get(session_id) else {return Some(CdpPreparedFrontendCommand::ImmediateResponse {@@ -130,7 +156,42 @@ impl CdpFrontendRoutingState {}Some(session_id.to_owned())} else {- route.base_session_id.clone()+ Some(base_session_id)+ };+ let target_session_reference = match self.resolve_target_session_reference(+ frontend_id,+ dispatch_session_id.as_deref(),+ &method,+ request.params(),+ ) {+ Ok(session_id) => session_id,+ Err(error) => {+ return Some(CdpPreparedFrontendCommand::ImmediateResponse {+ frontend_id,+ message: cdp_error_response(Some(client_command_id), error.code, error.message),+ });+ }+ };+ let command = if let Some(session_id) = target_session_reference.as_deref() {+ match command.rewrite_target_session_reference(session_id) {+ Ok(command) => command,+ Err(error) => {+ tracing::error!(+ ?error,+ "frontend routing could not serialize a Target session reference"+ );+ return Some(CdpPreparedFrontendCommand::ImmediateResponse {+ frontend_id,+ message: cdp_error_response(+ Some(client_command_id),+ -32603,+ "Internal error",+ ),+ });+ }+ }+ } else {+ command};let internal_command_id = self.allocate_internal_command_id();let command = match command@@ -158,11 +219,85 @@ impl CdpFrontendRoutingState {},client_command_id,method,+ attach_target_id,},);Some(CdpPreparedFrontendCommand::Command(command))}+ fn resolve_target_session_reference(+ &self,+ frontend_id: u64,+ dispatch_session_id: Option<&str>,+ method: &str,+ params: Option<&serde_json::Map<String, Value>>,+ ) -> std::result::Result<Option<String>, CdpTargetSessionReferenceError> {+ if !matches!(+ method,+ "Target.detachFromTarget" | "Target.sendMessageToTarget"+ ) {+ return Ok(None);+ }+ let Some(params) = params else {+ return Ok(None);+ };+ if let Some(session_id) = params.get("sessionId") {+ if let Some(session_id) = session_id.as_str() {+ let owned_direct_child = self.sessions.get(session_id).is_some_and(|session| {+ session.frontend_id == frontend_id+ && matches!(+ &session.kind,+ FrontendSessionKind::Child {+ parent_session_id,+ ..+ } if parent_session_id.as_deref() == dispatch_session_id+ )+ });+ return if owned_direct_child {+ Ok(None)+ } else {+ Err(CdpTargetSessionReferenceError {+ code: -32602,+ message: "No session with given id",+ })+ };+ }+ if !session_id.is_null() {+ // Preserve domain validation for a malformed optional value;+ // do not turn it into a valid command via targetId fallback.+ return Ok(None);+ }+ }+ let Some(target_id) = params.get("targetId").and_then(Value::as_str) else {+ return Ok(None);+ };+ let mut matching_sessions = self.sessions.iter().filter_map(|(session_id, session)| {+ (session.frontend_id == frontend_id+ && matches!(+ &session.kind,+ FrontendSessionKind::Child {+ parent_session_id,+ target_id: Some(session_target_id),+ } if parent_session_id.as_deref() == dispatch_session_id+ && session_target_id == target_id+ ))+ .then_some(session_id.as_str())+ });+ let Some(session_id) = matching_sessions.next() else {+ return Err(CdpTargetSessionReferenceError {+ code: -32602,+ message: "No session for given target id",+ });+ };+ if matching_sessions.next().is_some() {+ return Err(CdpTargetSessionReferenceError {+ code: -32000,+ message: "Multiple sessions attached, specify id.",+ });+ }+ Ok(Some(session_id.to_owned()))+ }+fn allocate_internal_command_id(&mut self) -> u64 {loop {self.next_internal_command_id = self.next_internal_command_id.wrapping_add(1);@@ -179,27 +314,17 @@ impl CdpFrontendRoutingState {pub(super) fn register_browser_frontend(&mut self,frontend_id: u64,+ session_id: String,sink: CdpSocketSink,- ) -> Result<(), String> {- if self- .frontends- .values()- .any(|route| route.kind == CdpSessionFrontendKind::Browser)- {- return Err("CDP owner already has a browser frontend".to_owned());- }- if self.frontends.contains_key(&frontend_id) {- return Err("CDP frontend id is already registered".to_owned());- }- self.frontends.insert(+ ) -> Result<()> {+ self.register_session_frontend(frontend_id,- CdpSessionFrontendRoute {- kind: CdpSessionFrontendKind::Browser,- target_id: None,- base_session_id: None,- sink,- },- );+ CdpSessionFrontendKind::Browser,+ None,+ session_id.clone(),+ sink,+ )?;+ self.private_sessions.remove(&session_id);Ok(())}@@ -209,7 +334,7 @@ impl CdpFrontendRoutingState {target_id: String,session_id: String,sink: CdpSocketSink,- ) -> Result<(), String> {+ ) -> Result<()> {self.register_session_frontend(frontend_id,CdpSessionFrontendKind::Page,@@ -226,12 +351,12 @@ impl CdpFrontendRoutingState {target_id: Option<String>,session_id: String,sink: CdpSocketSink,- ) -> Result<(), String> {+ ) -> Result<()> {if self.frontends.contains_key(&frontend_id) {- return Err("CDP frontend id is already registered".to_owned());+ bail!("CDP frontend id is already registered");}if self.sessions.contains_key(&session_id) {- return Err("CDP frontend session is already registered".to_owned());+ bail!("CDP frontend session is already registered");}self.sessions.insert(session_id.clone(),@@ -245,21 +370,21 @@ impl CdpFrontendRoutingState {CdpSessionFrontendRoute {kind,target_id,- base_session_id: Some(session_id),+ base_session_id: session_id,sink,},);Ok(())}- pub(super) fn unregister_browser_frontend(&mut self, frontend_id: u64) -> bool {+ pub(super) fn unregister_browser_frontend(&mut self, frontend_id: u64) -> Option<String> {self.unregister_session_frontend(frontend_id, CdpSessionFrontendKind::Browser)- .is_some()+ .map(|route| route.base_session_id)}pub(super) fn unregister_page_frontend(&mut self, frontend_id: u64) -> Option<String> {self.unregister_session_frontend(frontend_id, CdpSessionFrontendKind::Page)- .and_then(|route| route.base_session_id)+ .map(|route| route.base_session_id)}fn unregister_session_frontend(@@ -337,6 +462,7 @@ impl CdpFrontendRoutingState {frontend_id,dispatch_session_id.as_deref(),&child_session_id,+ pending.attach_target_id.as_deref(),);}set_top_level_session_id(&mut message, client_session_id.as_deref());@@ -364,22 +490,25 @@ impl CdpFrontendRoutingState {.pointer("/params/sessionId").and_then(Value::as_str).map(str::to_owned);+ let target_event_target_id = message+ .pointer("/params/targetInfo/targetId")+ .and_then(Value::as_str)+ .map(str::to_owned);if method.as_deref() == Some("Target.attachedToTarget")&& let Some(child_session_id) = target_event_session_id.as_deref(){if self.private_sessions.contains(child_session_id) {return None;}- if let Some(parent_session_id) = parent_session_id.as_deref() {- if let Some(parent) = self.sessions.get(parent_session_id) {- self.register_child_session(- parent.frontend_id,- Some(parent_session_id),- child_session_id,- );- }- } else if let Some(frontend_id) = self.browser_frontend_id() {- self.register_child_session(frontend_id, None, child_session_id);+ if let Some(parent_session_id) = parent_session_id.as_deref()+ && let Some(parent) = self.sessions.get(parent_session_id)+ {+ self.register_child_session(+ parent.frontend_id,+ Some(parent_session_id),+ child_session_id,+ target_event_target_id.as_deref(),+ );}}@@ -415,28 +544,38 @@ impl CdpFrontendRoutingState {if self.private_sessions.remove(session_id) {return None;}- if self- .sessions- .get(session_id)- .is_some_and(|session| matches!(session.kind, FrontendSessionKind::Base))- {- // Base sessions are private transport adapters and never- // surface on their frontend's wire protocol.- self.remove_session_descendants(session_id);- return None;+ if let Some(session) = self.sessions.get(session_id).cloned() {+ match session.kind {+ FrontendSessionKind::Base => {+ // Base sessions are private transport adapters and+ // never surface on their frontend's wire protocol.+ self.remove_session_descendants(session_id);+ return None;+ }+ FrontendSessionKind::Child {+ parent_session_id, ..+ } => {+ let route = self.frontends.get(&session.frontend_id)?;+ let client_parent_session_id = parent_session_id+ .as_deref()+ .filter(|parent| route.base_session_id.as_str() != *parent);+ let sink = route.sink.clone();+ set_top_level_session_id(&mut message, client_parent_session_id);+ self.remove_child_session_cascade(session_id);+ return Some((+ CdpRoutedFrontend {+ frontend_id: session.frontend_id,+ sink,+ },+ message,+ ));+ }+ }}self.remove_child_session_cascade(session_id);}- let frontend_id = self.browser_frontend_id()?;- let sink = self.frontends.get(&frontend_id)?.sink.clone();- Some((CdpRoutedFrontend { frontend_id, sink }, message))- }-- fn browser_frontend_id(&self) -> Option<u64> {- self.frontends.iter().find_map(|(frontend_id, route)| {- (route.kind == CdpSessionFrontendKind::Browser).then_some(*frontend_id)- })+ None}fn register_child_session(@@ -444,6 +583,7 @@ impl CdpFrontendRoutingState {frontend_id: u64,parent_session_id: Option<&str>,child_session_id: &str,+ target_id: Option<&str>,) {let frontend = self.frontends.get(&frontend_id);if frontend.is_none() {@@ -472,6 +612,7 @@ impl CdpFrontendRoutingState {frontend_id,kind: FrontendSessionKind::Child {parent_session_id: parent_session_id.map(str::to_owned),+ target_id: target_id.map(str::to_owned),},},);@@ -501,6 +642,7 @@ impl CdpFrontendRoutingState {.filter_map(|(child_session_id, route)| match &route.kind {FrontendSessionKind::Child {parent_session_id: parent,+ ..} if parent.as_deref() == Some(parent_session_id.as_str()) => {Some(child_session_id.clone())}@@ -574,7 +716,7 @@ mod tests {fn browser_and_page_client_command_ids_are_isolated_and_restored() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing.register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())@@ -598,6 +740,10 @@ mod tests {.expect("browser command JSON")["id"].as_u64().expect("browser internal id");+ assert_eq!(+ serde_json::from_str::<Value>(browser_command.json()).expect("browser command JSON")["sessionId"],+ json!("SID-browser")+ );let page_internal_id = serde_json::from_str::<Value>(page_command.json()).expect("page command JSON")["id"].as_u64()@@ -609,8 +755,9 @@ mod tests {json!({"id": browser_internal_id,"result": {},+ "sessionId": "SID-browser",}),- None,+ Some("SID-browser"),).expect("route browser response");assert_eq!(browser_frontend.frontend_id, 5);@@ -632,13 +779,264 @@ mod tests {assert!(page_response.get("sessionId").is_none());}+ #[test]+ fn browser_frontends_with_the_same_client_command_id_route_independently() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser-1".to_owned(), test_sink())+ .expect("register first browser frontend");+ routing+ .register_browser_frontend(6, "SID-browser-2".to_owned(), test_sink())+ .expect("register second browser frontend");++ let first = expect_prepared_command(+ routing.prepare_command(+ 5,+ parsed_command(json!({ "id": 7, "method": "Browser.getVersion" }).to_string()),+ ),+ "first browser",+ );+ let second = expect_prepared_command(+ routing.prepare_command(+ 6,+ parsed_command(json!({ "id": 7, "method": "Browser.getVersion" }).to_string()),+ ),+ "second browser",+ );+ let first = serde_json::from_str::<Value>(first.json()).expect("first command JSON");+ let second = serde_json::from_str::<Value>(second.json()).expect("second command JSON");+ assert_ne!(first["id"], second["id"]);+ assert_eq!(first["sessionId"], json!("SID-browser-1"));+ assert_eq!(second["sessionId"], json!("SID-browser-2"));++ let (frontend, response) = routing+ .route_message(+ json!({+ "id": second["id"],+ "result": { "product": "second" },+ "sessionId": "SID-browser-2",+ }),+ Some("SID-browser-2"),+ )+ .expect("route second response");+ assert_eq!(frontend.frontend_id(), 6);+ assert_eq!(response["id"], json!(7));+ assert_eq!(response["result"]["product"], json!("second"));+ assert!(response.get("sessionId").is_none());++ let (frontend, response) = routing+ .route_message(+ json!({+ "id": first["id"],+ "result": { "product": "first" },+ "sessionId": "SID-browser-1",+ }),+ Some("SID-browser-1"),+ )+ .expect("route first response");+ assert_eq!(frontend.frontend_id(), 5);+ assert_eq!(response["id"], json!(7));+ assert_eq!(response["result"]["product"], json!("first"));+ assert!(response.get("sessionId").is_none());+ }++ #[test]+ fn browser_base_session_events_are_private_and_frontend_scoped() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser-1".to_owned(), test_sink())+ .expect("register first browser frontend");+ routing+ .register_browser_frontend(6, "SID-browser-2".to_owned(), test_sink())+ .expect("register second browser frontend");++ let (frontend, event) = routing+ .route_message(+ json!({+ "method": "Target.targetCreated",+ "sessionId": "SID-browser-1",+ "params": { "targetInfo": { "targetId": "TID-1" } },+ }),+ Some("SID-browser-1"),+ )+ .expect("route first browser event");+ assert_eq!(frontend.frontend_id(), 5);+ assert!(event.get("sessionId").is_none());++ assert!(+ routing+ .route_message(+ json!({+ "method": "Target.targetCreated",+ "params": { "targetInfo": { "targetId": "TID-root" } },+ }),+ None,+ )+ .is_none(),+ "unowned root event must not be assigned to an arbitrary browser frontend"+ );+ }++ #[test]+ fn root_detach_with_a_known_child_routes_to_its_exact_frontend() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser-1".to_owned(), test_sink())+ .expect("register first browser frontend");+ routing+ .register_browser_frontend(6, "SID-browser-2".to_owned(), test_sink())+ .expect("register second browser frontend");+ routing.register_child_session(5, Some("SID-browser-1"), "SID-child-1", Some("TID-1"));+ routing.register_child_session(6, Some("SID-browser-2"), "SID-child-2", Some("TID-1"));++ let (frontend, event) = routing+ .route_message(+ json!({+ "method": "Target.detachedFromTarget",+ "params": {+ "targetId": "TID-1",+ "sessionId": "SID-child-1",+ },+ }),+ None,+ )+ .expect("route owner-qualified root detach");+ assert_eq!(frontend.frontend_id(), 5);+ assert!(event.get("sessionId").is_none());++ assert!(matches!(+ routing.prepare_command(+ 5,+ parsed_command(+ json!({+ "id": 1,+ "method": "Runtime.evaluate",+ "sessionId": "SID-child-1",+ })+ .to_string(),+ ),+ ),+ Some(CdpPreparedFrontendCommand::ImmediateResponse { .. })+ ));+ assert!(matches!(+ routing.prepare_command(+ 6,+ parsed_command(+ json!({+ "id": 1,+ "method": "Runtime.evaluate",+ "sessionId": "SID-child-2",+ })+ .to_string(),+ ),+ ),+ Some(CdpPreparedFrontendCommand::Command(_))+ ));+ }++ #[test]+ fn root_detach_restores_visible_parent_for_nested_child() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink())+ .expect("register browser frontend");+ routing.register_child_session(5, Some("SID-browser"), "SID-child", Some("TID-child"));+ routing.register_child_session(+ 5,+ Some("SID-child"),+ "SID-grandchild",+ Some("TID-grandchild"),+ );++ let (_, event) = routing+ .route_message(+ json!({+ "method": "Target.detachedFromTarget",+ "params": {+ "targetId": "TID-grandchild",+ "sessionId": "SID-grandchild",+ },+ }),+ None,+ )+ .expect("route nested root detach");+ assert_eq!(event["sessionId"], json!("SID-child"));+ }++ #[test]+ fn unregistering_one_browser_drops_only_its_pending_commands() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser-1".to_owned(), test_sink())+ .expect("register first browser frontend");+ routing+ .register_browser_frontend(6, "SID-browser-2".to_owned(), test_sink())+ .expect("register second browser frontend");+ let first = expect_prepared_command(+ routing.prepare_command(+ 5,+ parsed_command(json!({ "id": 1, "method": "Browser.getVersion" }).to_string()),+ ),+ "first browser",+ );+ let second = expect_prepared_command(+ routing.prepare_command(+ 6,+ parsed_command(json!({ "id": 1, "method": "Browser.getVersion" }).to_string()),+ ),+ "second browser",+ );+ let first_internal_id = serde_json::from_str::<Value>(first.json())+ .expect("first command JSON")["id"]+ .as_u64()+ .expect("first internal id");+ let second_internal_id = serde_json::from_str::<Value>(second.json())+ .expect("second command JSON")["id"]+ .as_u64()+ .expect("second internal id");++ assert_eq!(+ routing.unregister_browser_frontend(5).as_deref(),+ Some("SID-browser-1")+ );+ assert!(+ routing+ .route_message(+ json!({+ "id": first_internal_id,+ "result": {},+ "sessionId": "SID-browser-1",+ }),+ Some("SID-browser-1"),+ )+ .is_none()+ );+ let (frontend, response) = routing+ .route_message(+ json!({+ "id": second_internal_id,+ "result": {},+ "sessionId": "SID-browser-2",+ }),+ Some("SID-browser-2"),+ )+ .expect("second browser response remains routable");+ assert_eq!(frontend.frontend_id(), 6);+ assert_eq!(response["id"], json!(1));+ }+#[test]fn browser_child_session_is_preserved_on_browser_frontend() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");- routing.register_child_session(5, None, "SID-client-child");+ routing.register_child_session(+ 5,+ Some("SID-browser"),+ "SID-client-child",+ Some("TID-child"),+ );let command = expect_prepared_command(routing.prepare_command(@@ -673,10 +1071,214 @@ mod tests {}#[test]- fn browser_frontend_preserves_root_wire_shape() {+ fn legacy_target_session_references_cannot_cross_browser_frontends() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser-1".to_owned(), test_sink())+ .expect("register first browser frontend");+ routing+ .register_browser_frontend(6, "SID-browser-2".to_owned(), test_sink())+ .expect("register second browser frontend");+ routing.register_child_session(5, Some("SID-browser-1"), "SID-child-1", Some("TID-shared"));+ routing.register_child_session(6, Some("SID-browser-2"), "SID-child-2", Some("TID-shared"));++ for method in ["Target.detachFromTarget", "Target.sendMessageToTarget"] {+ let Some(CdpPreparedFrontendCommand::ImmediateResponse {+ frontend_id,+ message,+ }) = routing.prepare_command(+ 6,+ parsed_command(+ json!({+ "id": 11,+ "method": method,+ "params": {+ "sessionId": "SID-child-1",+ "message": "{}",+ },+ })+ .to_string(),+ ),+ )+ else {+ panic!("foreign {method} session reference was not rejected");+ };+ assert_eq!(frontend_id, 6);+ assert_eq!(message["id"], json!(11));+ assert_eq!(message["error"]["code"], json!(-32602));+ }++ let command = expect_prepared_command(+ routing.prepare_command(+ 6,+ parsed_command(+ json!({+ "id": 12,+ "method": "Target.detachFromTarget",+ "params": { "targetId": "TID-shared" },+ })+ .to_string(),+ ),+ ),+ "owned target-id detach",+ );+ let command = serde_json::from_str::<Value>(command.json()).expect("detach command JSON");+ assert_eq!(command["sessionId"], json!("SID-browser-2"));+ assert_eq!(command["params"]["sessionId"], json!("SID-child-2"));+ assert_eq!(command["params"]["targetId"], json!("TID-shared"));+ }++ #[test]+ fn legacy_target_id_reference_requires_one_direct_child_session() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink())+ .expect("register browser frontend");+ routing.register_child_session(5, Some("SID-browser"), "SID-child-1", Some("TID-shared"));+ routing.register_child_session(5, Some("SID-browser"), "SID-child-2", Some("TID-shared"));+ routing.register_child_session(+ 5,+ Some("SID-child-1"),+ "SID-grandchild",+ Some("TID-grandchild"),+ );++ let Some(CdpPreparedFrontendCommand::ImmediateResponse { message, .. }) = routing+ .prepare_command(+ 5,+ parsed_command(+ json!({+ "id": 20,+ "method": "Target.detachFromTarget",+ "params": { "targetId": "TID-shared" },+ })+ .to_string(),+ ),+ )+ else {+ panic!("ambiguous target-id detach was not rejected");+ };+ assert_eq!(message["error"]["code"], json!(-32000));++ let Some(CdpPreparedFrontendCommand::ImmediateResponse { message, .. }) = routing+ .prepare_command(+ 5,+ parsed_command(+ json!({+ "id": 21,+ "method": "Target.detachFromTarget",+ "params": { "sessionId": "SID-grandchild" },+ })+ .to_string(),+ ),+ )+ else {+ panic!("non-direct child session was accepted by the base Target handler");+ };+ assert_eq!(message["error"]["code"], json!(-32602));++ let command = expect_prepared_command(+ routing.prepare_command(+ 5,+ parsed_command(+ json!({+ "id": 22,+ "method": "Target.detachFromTarget",+ "sessionId": "SID-child-1",+ "params": { "sessionId": "SID-grandchild" },+ })+ .to_string(),+ ),+ ),+ "direct grandchild detach",+ );+ let command = serde_json::from_str::<Value>(command.json()).expect("detach command JSON");+ assert_eq!(command["sessionId"], json!("SID-child-1"));+ assert_eq!(command["params"]["sessionId"], json!("SID-grandchild"));+ }++ #[test]+ fn attached_event_registers_child_before_attach_response() {+ let mut routing = CdpFrontendRoutingState::default();+ routing+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink())+ .expect("register browser frontend");+ let attach = expect_prepared_command(+ routing.prepare_command(+ 5,+ parsed_command(+ json!({+ "id": 30,+ "method": "Target.attachToTarget",+ "params": { "targetId": "TID-child", "flatten": true },+ })+ .to_string(),+ ),+ ),+ "attach",+ );+ let attach_internal_id = serde_json::from_str::<Value>(attach.json())+ .expect("attach command JSON")["id"]+ .as_u64()+ .expect("attach internal id");++ let (frontend, event) = routing+ .route_message(+ json!({+ "method": "Target.attachedToTarget",+ "sessionId": "SID-browser",+ "params": {+ "sessionId": "SID-child",+ "targetInfo": { "targetId": "TID-child", "type": "page" },+ "waitingForDebugger": false,+ },+ }),+ Some("SID-browser"),+ )+ .expect("route attached event");+ assert_eq!(frontend.frontend_id(), 5);+ assert!(event.get("sessionId").is_none());+ assert_eq!(event["params"]["sessionId"], json!("SID-child"));++ let child_command = expect_prepared_command(+ routing.prepare_command(+ 5,+ parsed_command(+ json!({+ "id": 31,+ "method": "Runtime.evaluate",+ "sessionId": "SID-child",+ "params": { "expression": "1" },+ })+ .to_string(),+ ),+ ),+ "event-registered child",+ );+ assert_eq!(+ serde_json::from_str::<Value>(child_command.json()).expect("child command JSON")["sessionId"],+ json!("SID-child")+ );++ let (_, response) = routing+ .route_message(+ json!({+ "id": attach_internal_id,+ "result": { "sessionId": "SID-child" },+ "sessionId": "SID-browser",+ }),+ Some("SID-browser"),+ )+ .expect("route attach response");+ assert_eq!(response["id"], json!(30));+ assert!(response.get("sessionId").is_none());+ }++ #[test]+ fn browser_frontend_hides_base_session_on_wire() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");let command = expect_prepared_command(@@ -688,7 +1290,7 @@ mod tests {);let command_json =serde_json::from_str::<Value>(command.json()).expect("prepared command JSON");- assert!(command_json.get("sessionId").is_none());+ assert_eq!(command_json["sessionId"], json!("SID-browser"));let internal_id = command_json["id"].as_u64().expect("internal id");let (_, response) = routing@@ -696,8 +1298,9 @@ mod tests {json!({"id": internal_id,"result": {},+ "sessionId": "SID-browser",}),- None,+ Some("SID-browser"),).expect("route browser response");assert_eq!(response["id"], json!(9));@@ -732,7 +1335,7 @@ mod tests {fn malformed_command_keeps_its_originating_frontend() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing.register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())@@ -755,7 +1358,7 @@ mod tests {fn structurally_invalid_command_preserves_frontend_id_in_invalid_request() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");let Some(CdpPreparedFrontendCommand::ImmediateResponse {@@ -783,12 +1386,17 @@ mod tests {fn private_page_session_detach_does_not_fall_back_to_browser_frontend() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing.register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink()).expect("register page frontend");- routing.register_child_session(5, None, "SID-browser-child");+ routing.register_child_session(+ 5,+ Some("SID-browser"),+ "SID-browser-child",+ Some("TID-root"),+ );assert!(routing@@ -810,12 +1418,13 @@ mod tests {.route_message(json!({"method": "Target.detachedFromTarget",+ "sessionId": "SID-browser","params": {"targetId": "TID-root","sessionId": "SID-browser-child",},}),- None,+ Some("SID-browser"),).expect("route browser-owned target detach");assert_eq!(frontend.frontend_id, 5);@@ -935,7 +1544,7 @@ mod tests {let (root_sink, mut root_writer) = CdpSocketSink::with_stalled_writer_for_test(2);let (page_sink, mut page_writer) = CdpSocketSink::with_stalled_writer_for_test(2);router- .register_browser_frontend(5, root_sink)+ .register_browser_frontend(5, "SID-browser".to_owned(), root_sink).expect("register browser frontend");router.register_page_frontend(10, "TID-page".to_owned(), "SID-page".to_owned(), page_sink)@@ -945,6 +1554,7 @@ mod tests {router.enqueue_protocol_output_sequence(ProtocolOutputSequence::from_messages(vec![json!({"method": "Target.targetCreated",+ "sessionId": "SID-browser","params": { "targetInfo": { "targetId": "TID-root" } },}),json!({@@ -967,27 +1577,29 @@ mod tests {}#[test]- fn second_browser_frontend_is_rejected_without_replacing_first() {+ fn browser_frontends_register_with_independent_base_sessions() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser-1".to_owned(), test_sink()).expect("register first browser frontend");-+ routing+ .register_browser_frontend(6, "SID-browser-2".to_owned(), test_sink())+ .expect("register second browser frontend");+ assert!(routing.frontend_by_id(5).is_some());+ assert!(routing.frontend_by_id(6).is_some());assert_eq!(- routing- .register_browser_frontend(6, test_sink())- .expect_err("reject second browser frontend"),- "CDP owner already has a browser frontend"+ routing.unregister_browser_frontend(5).as_deref(),+ Some("SID-browser-1"));- assert!(routing.frontend_by_id(5).is_some());- assert!(routing.frontend_by_id(6).is_none());+ assert!(routing.frontend_by_id(5).is_none());+ assert!(routing.frontend_by_id(6).is_some());}#[test]fn private_control_session_events_do_not_reach_browser_frontend() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing.register_private_session("SID-control".to_owned());@@ -1034,7 +1646,7 @@ mod tests {fn orphaned_responses_and_unknown_session_events_do_not_fall_back_to_browser() {let mut routing = CdpFrontendRoutingState::default();routing- .register_browser_frontend(5, test_sink())+ .register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");assert!(diff --git a/moli-protocol-server/src/cdp_scheduler/frontend_control.rs b/moli-protocol-server/src/cdp_scheduler/frontend_control.rsindex 4097d9cb3..0e0f989be 100644--- a/moli-protocol-server/src/cdp_scheduler/frontend_control.rs+++ b/moli-protocol-server/src/cdp_scheduler/frontend_control.rs@@ -48,23 +48,41 @@ impl CdpFrontendControlState {sink,completion_tx,} => {- let result = self+ let result = match self.target_control- .prepare_browser_frontend(scheduler, frontend_router)+ .attach_browser(scheduler, frontend_router).await- .and_then(|()| {+ {+ Ok(session_id) => {let frontend_id = self.allocate_frontend_id();- frontend_router- .register_browser_frontend(frontend_id, sink)- .map(|()| frontend_id)- });+ match frontend_router.register_browser_frontend(+ frontend_id,+ session_id.clone(),+ sink,+ ) {+ Ok(()) => Ok(frontend_id),+ Err(error) => {+ self.target_control+ .detach_frontend_session(+ scheduler,+ frontend_router,+ &session_id,+ )+ .await;+ Err(error)+ }+ }+ }+ Err(error) => Err(error),+ };match completion_tx.send(result) {Ok(()) => {}Err(Ok(frontend_id)) => {- if frontend_router.unregister_browser_frontend(frontend_id) {- scheduler- .conn- .release_root_target_frontend_state_async()+ if let Some(session_id) =+ frontend_router.unregister_browser_frontend(frontend_id)+ {+ self.target_control+ .detach_frontend_session(scheduler, frontend_router, &session_id).await;}send_cookie_checkpoint(scheduler, owner_lifecycle);@@ -94,7 +112,11 @@ impl CdpFrontendControlState {Ok(()) => Ok(frontend_id),Err(error) => {self.target_control- .detach_page(scheduler, frontend_router, &session_id)+ .detach_frontend_session(+ scheduler,+ frontend_router,+ &session_id,+ ).await;Err(error)}@@ -109,7 +131,7 @@ impl CdpFrontendControlState {frontend_router.unregister_page_frontend(frontend_id){self.target_control- .detach_page(scheduler, frontend_router, &session_id)+ .detach_frontend_session(scheduler, frontend_router, &session_id).await;}send_cookie_checkpoint(scheduler, owner_lifecycle);@@ -119,10 +141,9 @@ impl CdpFrontendControlState {true}CdpFrontendControlRequest::DetachBrowser { frontend_id } => {- if frontend_router.unregister_browser_frontend(frontend_id) {- scheduler- .conn- .release_root_target_frontend_state_async()+ if let Some(session_id) = frontend_router.unregister_browser_frontend(frontend_id) {+ self.target_control+ .detach_frontend_session(scheduler, frontend_router, &session_id).await;send_cookie_checkpoint(scheduler, owner_lifecycle);}@@ -131,7 +152,7 @@ impl CdpFrontendControlState {CdpFrontendControlRequest::DetachPage { frontend_id } => {if let Some(session_id) = frontend_router.unregister_page_frontend(frontend_id) {self.target_control- .detach_page(scheduler, frontend_router, &session_id)+ .detach_frontend_session(scheduler, frontend_router, &session_id).await;send_cookie_checkpoint(scheduler, owner_lifecycle);}diff --git a/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs b/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rsindex 4e1736b0c..840fd6a8b 100644--- a/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs+++ b/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs@@ -1,3 +1,4 @@+use anyhow::{Context, Result, bail};use serde_json::{Value, json};use crate::cdp_frontend_router::CdpFrontendRouter;@@ -26,7 +27,7 @@ impl CdpFrontendTargetControl {scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,target_id: &str,- ) -> Result<String, String> {+ ) -> Result<String> {let control_session_id = self.ensure_page_control_session(scheduler, frontend_router).await?;@@ -41,47 +42,53 @@ impl CdpFrontendTargetControl {.await?;let session_id = response["result"]["sessionId"].as_str()- .map(str::to_owned)- .ok_or_else(|| format!("CDP target {target_id} did not return an attach session"))?;+ .with_context(|| format!("CDP target {target_id} did not return an attach session"))?+ .to_owned();if target_id == scheduler.conn.default_target_id() {self.default_target_materialized = true;}Ok(session_id)}- pub(super) async fn prepare_browser_frontend(+ pub(super) async fn attach_browser(&mut self,scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,- ) -> Result<(), String> {+ ) -> Result<String> {self.ensure_default_target_is_materialized(scheduler, frontend_router)- .await+ .await?;+ let response = self+ .execute_command(+ scheduler,+ frontend_router,+ None,+ "Target.attachToBrowserTarget",+ json!({}),+ )+ .await?;+ response["result"]["sessionId"]+ .as_str()+ .map(str::to_owned)+ .context("CDP browser frontend did not return an attach session")}- pub(super) async fn detach_page(+ pub(super) async fn detach_frontend_session(&mut self,scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,session_id: &str,) {- let Some(control_session_id) = self.page_control_session_id.clone() else {- return;- };if let Err(error) = self.execute_command(scheduler,frontend_router,- Some(&control_session_id),+ None,"Target.detachFromTarget",json!({ "sessionId": session_id }),).await{- tracing::debug!(- session_id,- error,- "failed to detach CDP page frontend session"- );+ tracing::debug!(session_id, ?error, "failed to detach CDP frontend session");}}@@ -90,7 +97,7 @@ impl CdpFrontendTargetControl {scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,target_id: &str,- ) -> Result<(), String> {+ ) -> Result<()> {self.execute_command(scheduler,frontend_router,@@ -107,7 +114,7 @@ impl CdpFrontendTargetControl {scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,target_url: &str,- ) -> Result<String, String> {+ ) -> Result<String> {self.ensure_default_target_is_materialized(scheduler, frontend_router).await?;let response = self@@ -122,7 +129,7 @@ impl CdpFrontendTargetControl {response["result"]["targetId"].as_str().map(str::to_owned)- .ok_or_else(|| "Target.createTarget returned no targetId".to_owned())+ .context("Target.createTarget returned no targetId")}pub(super) async fn close_target(@@ -130,7 +137,7 @@ impl CdpFrontendTargetControl {scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,target_id: &str,- ) -> Result<(), String> {+ ) -> Result<()> {let response = self.execute_command(scheduler,@@ -141,7 +148,7 @@ impl CdpFrontendTargetControl {).await?;if response["result"]["success"].as_bool() == Some(false) {- return Err(format!("Target.closeTarget rejected target {target_id}"));+ bail!("Target.closeTarget rejected target {target_id}");}Ok(())}@@ -150,7 +157,7 @@ impl CdpFrontendTargetControl {&mut self,scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,- ) -> Result<String, String> {+ ) -> Result<String> {if let Some(control_session_id) = self.page_control_session_id.as_ref() {return Ok(control_session_id.clone());}@@ -165,8 +172,8 @@ impl CdpFrontendTargetControl {.await?;let session_id = response["result"]["sessionId"].as_str()- .map(str::to_owned)- .ok_or_else(|| "CDP browser target did not return an attach session".to_owned())?;+ .context("CDP browser target did not return an attach session")?+ .to_owned();self.page_control_session_id = Some(session_id.clone());Ok(session_id)}@@ -175,7 +182,7 @@ impl CdpFrontendTargetControl {&mut self,scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,- ) -> Result<(), String> {+ ) -> Result<()> {if self.default_target_materialized {return Ok(());}@@ -197,8 +204,8 @@ impl CdpFrontendTargetControl {.await?;let reservation_session_id = response["result"]["sessionId"].as_str()- .map(str::to_owned)- .ok_or_else(|| "default target reservation returned no sessionId".to_owned())?;+ .context("default target reservation returned no sessionId")?+ .to_owned();self.execute_command(scheduler,frontend_router,@@ -218,7 +225,7 @@ impl CdpFrontendTargetControl {session_id: Option<&str>,method: &str,params: Value,- ) -> Result<Value, String> {+ ) -> Result<Value> {let command_id = self.next_command_id;self.next_command_id = self.next_command_id.wrapping_sub(1);let mut command = json!({@@ -270,14 +277,14 @@ impl CdpFrontendTargetControl {}}-fn control_command_result(response: Option<Value>, method: &str) -> Result<Value, String> {- let response = response.ok_or_else(|| format!("{method} returned no response"))?;+fn control_command_result(response: Option<Value>, method: &str) -> Result<Value> {+ let response = response.with_context(|| format!("{method} returned no response"))?;if let Some(error) = response.get("error") {- return Err(error+ let message = error.get("message").and_then(Value::as_str)- .unwrap_or("CDP frontend control command failed")- .to_owned());+ .unwrap_or("unknown protocol error");+ bail!("CDP frontend control command {method} failed: {message}");}Ok(response)}diff --git a/moli-protocol-server/src/protocol_server/cdp.rs b/moli-protocol-server/src/protocol_server/cdp.rsindex 5d82cc212..1b596010d 100644--- a/moli-protocol-server/src/protocol_server/cdp.rs+++ b/moli-protocol-server/src/protocol_server/cdp.rs@@ -97,7 +97,7 @@ async fn rollback_unpublished_target(if let Err(error) = endpoint.close_target(target_id.to_owned()).await {tracing::warn!(target_id,- error,+ ?error,"failed to roll back unpublished CDP target");}@@ -245,7 +245,7 @@ async fn run_shared_frontend_socket(let endpoint = match owner_registry.shared_owner() {Ok(endpoint) => endpoint,Err(error) => {- tracing::warn!(error, "failed to start shared CDP owner");+ tracing::warn!(?error, "failed to start shared CDP owner");return;}};diff --git a/moli-protocol-server/src/protocol_server/cdp_owner.rs b/moli-protocol-server/src/protocol_server/cdp_owner.rsindex 56e19536a..807ee6d7c 100644--- a/moli-protocol-server/src/protocol_server/cdp_owner.rs+++ b/moli-protocol-server/src/protocol_server/cdp_owner.rs@@ -3,6 +3,7 @@ use std::{sync::{Arc, Weak, atomic::AtomicU64},};+use anyhow::{Context, Result, bail};use moli_core::runtime::{NavigationRuntimeConfig, storage_partition::StoragePartitionState};use moli_protocol::CdpInitialStoragePartition;use parking_lot::Mutex;@@ -81,17 +82,19 @@ impl SharedCdpOwnerRegistry {}}- pub(super) fn shared_owner(&self) -> Result<CdpFrontendEndpoint, String> {+ pub(super) fn shared_owner(&self) -> Result<CdpFrontendEndpoint> {let mut shared_owner = self.inner.shared_owner.lock();if let Some((_, endpoint)) = shared_owner.as_ref() {return Ok(endpoint.clone());}- let (owner_id, endpoint) = self.spawn_owner()?;+ let (owner_id, endpoint) = self+ .spawn_owner()+ .context("failed to spawn shared CDP owner")?;*shared_owner = Some((owner_id, endpoint.clone()));Ok(endpoint)}- fn spawn_owner(&self) -> Result<(u64, CdpFrontendEndpoint), String> {+ fn spawn_owner(&self) -> Result<(u64, CdpFrontendEndpoint)> {let owner_id = self.inner.config.directory.allocate_owner_id();let (endpoint, receivers) = cdp_frontend_channel();let lifecycle_observer = self@@ -102,7 +105,7 @@ impl SharedCdpOwnerRegistry {{let mut state = self.inner.state.lock();if state.shutting_down {- return Err("CDP owner registry is shutting down".to_owned());+ bail!("CDP owner registry is shutting down");}state.owners.insert(owner_id,diff --git a/moli-protocol-server/src/protocol_server/cdp_socket.rs b/moli-protocol-server/src/protocol_server/cdp_socket.rsindex 162eea7c7..d152f2f09 100644--- a/moli-protocol-server/src/protocol_server/cdp_socket.rs+++ b/moli-protocol-server/src/protocol_server/cdp_socket.rs@@ -26,7 +26,7 @@ pub(super) async fn run_cdp_frontend_socket(let frontend_id = match frontend_id {Ok(frontend_id) => frontend_id,Err(error) => {- tracing::warn!(error, "failed to attach CDP WebSocket frontend");+ tracing::warn!(?error, "failed to attach CDP WebSocket frontend");return false;}};diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rsindex 8789a09ed..11676d518 100644--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs@@ -695,34 +695,268 @@ async fn websocket_cdp_dynamic_page_detach_reconnect_and_target_close_follow_hos}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]-async fn websocket_cdp_rejects_second_concurrent_browser_frontend() {+async fn websocket_cdp_supports_concurrent_browser_frontends_with_isolated_sessions() {let (addr, server) = spawn_test_protocol_server().await;let (mut first_browser, _) =connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}")).await.expect("connect first browser websocket");- let initial_probe =- send_cdp_command(&mut first_browser, 1, "Browser.getVersion", None, json!({})).await;+ let (mut second_browser, _) =+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))+ .await+ .expect("connect second browser websocket");++ for browser in [&mut first_browser, &mut second_browser] {+ browser+ .send(WsMessage::Text(+ json!({ "id": 1, "method": "Browser.getVersion", "params": {} })+ .to_string()+ .into(),+ ))+ .await+ .expect("send colliding browser command id");+ }+ let first_probe = recv_until_id(&mut first_browser, 1).await;+ let second_probe = recv_until_id(&mut second_browser, 1).await;assert!(- response_by_id(&initial_probe, 1)["result"]["product"]+ response_by_id(&first_probe, 1)["result"]["product"].as_str().is_some(),- "first browser frontend did not finish attaching"+ "first browser frontend did not respond"+ );+ assert!(+ response_by_id(&second_probe, 1)["result"]["product"]+ .as_str()+ .is_some(),+ "second browser frontend did not respond"+ );+ assert!(+ first_probe+ .iter()+ .chain(&second_probe)+ .all(|message| message.get("sessionId").is_none()),+ "a hidden browser base session leaked onto the public wire");- let (mut second_browser, _) =+ let discover = send_cdp_command(+ &mut first_browser,+ 2,+ "Target.setDiscoverTargets",+ None,+ json!({ "discover": true, "filter": [{ "type": "page" }] }),+ )+ .await;+ assert_eq!(response_by_id(&discover, 2)["result"], json!({}));+ let create = send_cdp_command(+ &mut second_browser,+ 2,+ "Target.createTarget",+ None,+ json!({ "url": "about:blank" }),+ )+ .await;+ let target_id = response_by_id(&create, 2)["result"]["targetId"]+ .as_str()+ .expect("created target id")+ .to_owned();+ assert!(+ create.iter().all(|message| {+ message["method"] != json!("Target.targetCreated")+ || message["params"]["targetInfo"]["targetId"] != json!(target_id)+ }),+ "second frontend inherited first frontend's discovery state: {create:#?}"+ );+ let discovered = recv_until_match(&mut first_browser, |message| {+ message["method"] == json!("Target.targetCreated")+ && message["params"]["targetInfo"]["targetId"] == json!(target_id)+ })+ .await;+ assert!(+ discovered+ .last()+ .is_some_and(|message| message.get("sessionId").is_none()),+ "discovery event leaked the first browser's hidden base session"+ );++ let first_attach = send_cdp_command(+ &mut first_browser,+ 3,+ "Target.attachToTarget",+ None,+ json!({ "targetId": target_id, "flatten": true }),+ )+ .await;+ let first_session_id = response_by_id(&first_attach, 3)["result"]["sessionId"]+ .as_str()+ .expect("first target session id")+ .to_owned();+ let second_attach = send_cdp_command(+ &mut second_browser,+ 3,+ "Target.attachToTarget",+ None,+ json!({ "targetId": target_id, "flatten": true }),+ )+ .await;+ let second_session_id = response_by_id(&second_attach, 3)["result"]["sessionId"]+ .as_str()+ .expect("second target session id")+ .to_owned();+ assert_ne!(first_session_id, second_session_id);++ let first_write = send_cdp_command(+ &mut first_browser,+ 4,+ "Runtime.evaluate",+ Some(&first_session_id),+ json!({ "expression": "globalThis.__moli_multi_browser = 41" }),+ )+ .await;+ assert_eq!(+ response_by_id(&first_write, 4)["result"]["result"]["value"],+ json!(41)+ );+ let second_read = send_cdp_command(+ &mut second_browser,+ 4,+ "Runtime.evaluate",+ Some(&second_session_id),+ json!({ "expression": "globalThis.__moli_multi_browser" }),+ )+ .await;+ assert_eq!(+ response_by_id(&second_read, 4)["result"]["result"]["value"],+ json!(41),+ "browser frontends did not share the target runtime"+ );++ let foreign_flat_session = send_cdp_command(+ &mut second_browser,+ 5,+ "Runtime.evaluate",+ Some(&first_session_id),+ json!({ "expression": "1" }),+ )+ .await;+ assert_eq!(+ response_by_id(&foreign_flat_session, 5)["error"]["code"],+ json!(-32001)+ );+ let foreign_legacy_session = send_cdp_command(+ &mut second_browser,+ 6,+ "Target.detachFromTarget",+ None,+ json!({ "sessionId": first_session_id }),+ )+ .await;+ assert_eq!(+ response_by_id(&foreign_legacy_session, 6)["error"]["code"],+ json!(-32602)+ );++ first_browser+ .close(None)+ .await+ .expect("close first browser websocket");+ wait_for_websocket_close(&mut first_browser, "first concurrent browser").await;+ let surviving_read = send_cdp_command(+ &mut second_browser,+ 7,+ "Runtime.evaluate",+ Some(&second_session_id),+ json!({ "expression": "globalThis.__moli_multi_browser + 1" }),+ )+ .await;+ assert_eq!(+ response_by_id(&surviving_read, 7)["result"]["result"]["value"],+ json!(42),+ "disconnecting one browser detached another browser's target session"+ );++ let (mut third_browser, _) =connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}")).await- .expect("connect second browser websocket");+ .expect("connect third browser while second remains connected");+ let third_probe =+ send_cdp_command(&mut third_browser, 1, "Browser.getVersion", None, json!({})).await;+ assert!(+ response_by_id(&third_probe, 1)["result"]["product"]+ .as_str()+ .is_some(),+ "replacement browser could not connect alongside surviving browser"+ );+ let third_attach = send_cdp_command(+ &mut third_browser,+ 2,+ "Target.attachToTarget",+ None,+ json!({ "targetId": target_id, "flatten": true }),+ )+ .await;+ let third_session_id = response_by_id(&third_attach, 2)["result"]["sessionId"]+ .as_str()+ .expect("third target session id")+ .to_owned();+ let third_read = send_cdp_command(+ &mut third_browser,+ 3,+ "Runtime.evaluate",+ Some(&third_session_id),+ json!({ "expression": "globalThis.__moli_multi_browser" }),+ )+ .await;+ assert_eq!(+ response_by_id(&third_read, 3)["result"]["result"]["value"],+ json!(41)+ );- wait_for_websocket_close(&mut second_browser, "second concurrent browser").await;- let first_probe =- send_cdp_command(&mut first_browser, 2, "Browser.getVersion", None, json!({})).await;+ let close = send_cdp_command(+ &mut third_browser,+ 4,+ "Target.closeTarget",+ None,+ json!({ "targetId": target_id }),+ )+ .await;+ assert_eq!(response_by_id(&close, 4)["result"]["success"], json!(true));+ let second_detached = recv_until_match(&mut second_browser, |message| {+ message["method"] == json!("Target.detachedFromTarget")+ && message["params"]["sessionId"] == json!(second_session_id)+ })+ .await;+ assert!(+ second_detached+ .last()+ .is_some_and(|message| message.get("sessionId").is_none()),+ "target-close detach leaked the second browser's hidden base session"+ );+ let stale_session = send_cdp_command(+ &mut second_browser,+ 8,+ "Runtime.evaluate",+ Some(&second_session_id),+ json!({ "expression": "1" }),+ )+ .await;+ assert_eq!(+ response_by_id(&stale_session, 8)["error"]["code"],+ json!(-32001),+ "closed target session remained routable"+ );+ let final_second_probe = send_cdp_command(+ &mut second_browser,+ 9,+ "Browser.getVersion",+ None,+ json!({}),+ )+ .await;assert!(- response_by_id(&first_probe, 2)["result"]["product"]+ response_by_id(&final_second_probe, 9)["result"]["product"].as_str().is_some(),- "rejecting a second browser frontend disrupted the active root frontend"+ "closing a shared target disrupted the surviving browser frontend");abort_test_cdp_server(server).await;diff --git a/moli-protocol/src/conn/browser_context/page_owner.rs b/moli-protocol/src/conn/browser_context/page_owner.rsindex 3f88a0aff..3709f9cfa 100644--- a/moli-protocol/src/conn/browser_context/page_owner.rs+++ b/moli-protocol/src/conn/browser_context/page_owner.rs@@ -699,6 +699,9 @@ impl CdpConnection {session_id: Option<&str>,enabled: bool,) -> bool {+ let owner_browser_context_id = self+ .target_owner_identity_for_session(session_id)+ .map(|(browser_context_id, _)| browser_context_id);self.next_page_domain_subscription_generation = self.next_page_domain_subscription_generation.wrapping_add(1);@@ -708,22 +711,14 @@ impl CdpConnection {owner.set_page_domain_enabled(enabled, subscription_generation)}).unwrap_or(false);- if handled {- if enabled {- if let Some(browser_context) = self.browser_context.as_ref() {- browser_context- .renderer_runtime()- .set_javascript_dialog_handler_enabled(true);- }- } else {- self.sync_javascript_dialog_handler_enabled();- }+ if handled && let Some(browser_context_id) = owner_browser_context_id.as_deref() {+ self.sync_javascript_dialog_handler_enabled_for_browser_context(browser_context_id);}handled}- fn sync_javascript_dialog_handler_enabled(&mut self) {- let Some(browser_context) = self.browser_context.as_ref() else {+ fn sync_javascript_dialog_handler_enabled_for_browser_context(&self, browser_context_id: &str) {+ let Some(browser_context) = self.browser_context_by_id(browser_context_id) else {return;};browser_context@@ -816,11 +811,14 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> bool {+ let owner_browser_context_id = self+ .target_owner_identity_for_session(session_id)+ .map(|(browser_context_id, _)| browser_context_id);let handled = self.with_target_session_owner_mut(session_id, |owner| owner.disable_page_domain()).unwrap_or(false);- if handled {- self.sync_javascript_dialog_handler_enabled();+ if handled && let Some(browser_context_id) = owner_browser_context_id.as_deref() {+ self.sync_javascript_dialog_handler_enabled_for_browser_context(browser_context_id);}handled}@@ -1135,6 +1133,47 @@ mod tests {);}+ #[test]+ fn page_domain_dialog_handler_tracks_the_session_owner_browser_context() {+ let mut conn = CdpConnection::default();++ let mut active = BrowserContext::new("BID-active".to_owned());+ active.set_active_target_id("TID-active".to_owned());+ let active_runtime = active.renderer_runtime();++ let mut inactive = BrowserContext::new("BID-inactive".to_owned());+ inactive.set_active_target_id("TID-inactive".to_owned());+ assert!(+ inactive+ .assign_auxiliary_session_to_target("TID-inactive", "SID-inactive-a".to_owned(),)+ );+ assert!(+ inactive+ .assign_auxiliary_session_to_target("TID-inactive", "SID-inactive-b".to_owned(),)+ );+ let inactive_runtime = inactive.renderer_runtime();++ conn.browser_context = Some(active);+ conn.inactive_browser_contexts.push(inactive);++ assert!(conn.set_page_domain_enabled_for_session_owner(Some("SID-inactive-a"), true));+ assert!(inactive_runtime.javascript_dialog_handler_enabled());+ assert!(+ !active_runtime.javascript_dialog_handler_enabled(),+ "enabling an inactive target session must not mutate the active browser context"+ );++ assert!(conn.set_page_domain_enabled_for_session_owner(Some("SID-inactive-b"), true));+ assert!(conn.disable_page_domain_for_session_owner(Some("SID-inactive-a")));+ assert!(+ inactive_runtime.javascript_dialog_handler_enabled(),+ "one frontend must not disable dialog handling while a peer remains subscribed"+ );++ assert!(conn.disable_page_domain_for_session_owner(Some("SID-inactive-b")));+ assert!(!inactive_runtime.javascript_dialog_handler_enabled());+ }+#[test]fn file_dialog_opened_target_listener_can_be_disabled_after_enable() {let mut conn = CdpConnection::default();diff --git a/moli-protocol/src/conn/downloads.rs b/moli-protocol/src/conn/downloads.rsindex 87b08ba48..c593a604a 100644--- a/moli-protocol/src/conn/downloads.rs+++ b/moli-protocol/src/conn/downloads.rs@@ -556,16 +556,12 @@ impl CdpConnection {return Ok(None);};- let frame_id = self- .browser_context- .as_ref()- .and_then(|bc| bc.active_target_id_owned())- .unwrap_or_else(|| state.frame_id.clone());-let (response_body, response_headers) = body_artifact.into_parts();Ok(Some(PreparedNavigationDownload {- frame_id,+ // Navigation may complete after another frontend has changed the active target.+ // The dispatch snapshot is the authority for the frame that initiated this download.+ frame_id: state.frame_id.clone(),response_url: final_url,response_headers,response_body,diff --git a/moli-protocol/src/domains/activity/output_ingress/renderer.rs b/moli-protocol/src/domains/activity/output_ingress/renderer.rsindex 8b92e93ba..1745b2496 100644--- a/moli-protocol/src/domains/activity/output_ingress/renderer.rs+++ b/moli-protocol/src/domains/activity/output_ingress/renderer.rs@@ -9,6 +9,32 @@ use super::super::runtime_command_barrier::RuntimeCommandOutputBarriers;use super::prepared_outputs::PreparedProtocolOutputs;use crate::conn::{BackgroundProtocolEvent, CdpConnection, CommandDispatchContext};+fn renderer_owner_action_session_id(+ conn: &CdpConnection,+ publication_session_id: Option<&str>,+ renderer_cause: Option<&moli_core::RendererRuntimeCommandCausalIdentity>,+) -> Option<String> {+ if let Some(cause) = renderer_cause+ && let Some(attachment) = conn+ .target_page_protocol_attachment_identity_for_renderer_inspector_route(+ publication_session_id,+ cause.inspector_session_id(),+ )+ {+ // `None` is a valid exact attachment for a command sent through the+ // implicit primary inspector session, so do not replace it by a peer.+ return attachment.session_id().map(str::to_owned);+ }+ if let Some(session_id) = publication_session_id {+ return Some(session_id.to_owned());+ }+ let (browser_context_id, target_id) =+ conn.target_owner_identity_for_session(publication_session_id)?;+ let target_id = target_id?;+ conn.target_page_protocol_attachment_identity_for_target(&browser_context_id, &target_id)+ .and_then(|attachment| attachment.session_id().map(str::to_owned))+}+/// Ingests one renderer transport message against only the exact Runtime/// command identity carried by its records.///@@ -150,9 +176,20 @@ async fn project_renderer_output_records_for_route(}match item {RendererOutputItem::OwnerAction(action) => {- let outputs =- PreparedProtocolOutputs::from_renderer_owner_action(conn, session_id, action)- .await;+ // A Page stream can remain bound to its implicit primary owner while a+ // Runtime command arrives through an auxiliary DevTools session. Owner+ // actions caused by that command (notably modal dialogs) belong to the+ // exact inspector attachment, not merely to the stream's base route.+ // Asynchronous actions have no command cause; an unbound stream then+ // selects the target's stable concrete Page attachment.+ let action_session_id =+ renderer_owner_action_session_id(conn, session_id, renderer_cause.as_ref());+ let outputs = PreparedProtocolOutputs::from_renderer_owner_action(+ conn,+ action_session_id.as_deref(),+ action,+ )+ .await;barriers.route_publication_outputs(conn,@@ -204,3 +241,53 @@ async fn project_renderer_output_records_for_route(}}}++#[cfg(test)]+mod tests {+ use moli_core::RendererRuntimeCommandCausalIdentity;++ use crate::conn::{BrowserContext, CdpConnection};++ use super::renderer_owner_action_session_id;++ #[test]+ fn unbound_owner_actions_choose_a_stable_attachment_without_overriding_exact_root_cause() {+ let mut conn = CdpConnection::default();+ let mut browser_context = BrowserContext::new("BID-owner-action".to_owned());+ browser_context.set_active_target_id("TID-owner-action".to_owned());+ assert!(+ browser_context.assign_auxiliary_session_to_target(+ "TID-owner-action",+ "SID-owner-action".to_owned(),+ )+ );+ conn.browser_context = Some(browser_context);++ assert_eq!(+ renderer_owner_action_session_id(&conn, None, None).as_deref(),+ Some("SID-owner-action"),+ "an asynchronous target action should use its concrete attachment"+ );+ assert_eq!(+ renderer_owner_action_session_id(+ &conn,+ None,+ Some(&RendererRuntimeCommandCausalIdentity::new(+ Some("SID-owner-action".to_owned()),+ 1,+ )),+ )+ .as_deref(),+ Some("SID-owner-action"),+ );+ assert_eq!(+ renderer_owner_action_session_id(+ &conn,+ None,+ Some(&RendererRuntimeCommandCausalIdentity::new(None, 2)),+ ),+ None,+ "an exact implicit-primary command must not be reassigned to a peer session"+ );+ }+}