Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(cdp): publish native terminals through the renderer journal
ldm0a18314640ae0
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/core.py b/moli-cdp-smoke/moli_cdp_smoke/groups/core.pyindex 0e0c869b1..101da9fb9 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/core.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/core.py@@ -394,22 +394,21 @@ async def run_core_group(state: SmokeState) -> None:)await context.route("**/popup-concurrent-*", fulfill_concurrent_popup)+ first_popup_url = f"{fixture}/popup-concurrent-first"+ second_popup_url = f"{fixture}/popup-concurrent-second"first_popup = Nonesecond_popup = Nonetry:- async with page.expect_popup(timeout=5_000) as first_popup_info:- await page.evaluate(- "(url) => window.open(url, '_blank')",- f"{fixture}/popup-concurrent-first",- )- first_popup = await first_popup_info.value+ # Playwright reports a popup once its initial document starts loading.+ # The held response prevents that event, so use route arrival to prove+ # the first request is pending while the second popup completes.+ await page.evaluate("(url) => window.open(url, '_blank')", first_popup_url)await asyncio.wait_for(first_popup_route_seen.wait(), timeout=5)- async with page.expect_popup(timeout=5_000) as second_popup_info:- await page.evaluate(- "(url) => window.open(url, '_blank')",- f"{fixture}/popup-concurrent-second",- )+ async with page.expect_popup(+ predicate=lambda popup: popup.url == second_popup_url, timeout=5_000+ ) as second_popup_info:+ await page.evaluate("(url) => window.open(url, '_blank')", second_popup_url)second_popup = await second_popup_info.valueawait second_popup.wait_for_load_state("load", timeout=10_000)assert_equal(@@ -418,7 +417,11 @@ async def run_core_group(state: SmokeState) -> None:"second popup initial document should load while first popup route is held",)- first_popup_route_release.set()+ async with page.expect_popup(+ predicate=lambda popup: popup.url == first_popup_url, timeout=5_000+ ) as first_popup_info:+ first_popup_route_release.set()+ first_popup = await first_popup_info.valueawait first_popup.wait_for_load_state("load", timeout=10_000)assert_equal(await first_popup.text_content("main", timeout=5_000),@@ -426,6 +429,7 @@ async def run_core_group(state: SmokeState) -> None:"first popup initial document should load after held route resumes",)finally:+ first_popup_route_release.set()for popup in (first_popup, second_popup):if popup is not None:await popup.close()diff --git a/moli-core/src/lib.rs b/moli-core/src/lib.rsindex 675a2518c..732ce1c39 100644--- a/moli-core/src/lib.rs+++ b/moli-core/src/lib.rs@@ -22,8 +22,11 @@ pub use moli_renderer_v8::ProcessEnvironmentOwner;pub use moli_renderer_v8::renderer_output_transport_channel;pub use moli_renderer_v8::{PageId, RendererBrowserContextRuntimeId, RendererDocumentLifecycleIdentity,- RendererDocumentTitleChanged, RendererOutputCursor, RendererOutputFence,- RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,+ RendererDocumentTitleChanged, RendererNativeCommand, RendererNativeCommandReadyResponse,+ RendererNativeCommandResponseGuard, RendererNativeCommandTerminal, RendererNativeOperation,+ RendererNativeOperationStep, RendererNativeProtocolError, RendererNativeProtocolNotification,+ RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererOutputCursor,+ RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,RendererOutputStreamCloseReason, RendererOutputStreamControl, RendererOutputStreamEpoch,RendererOutputStreamIdentity, RendererOutputTransportDiagnostics,@@ -33,4 +36,6 @@ pub use moli_renderer_v8::{RendererOwnerRuntimeActivitySource, RendererProtocolObservation,RendererRuntimeCommandCausalIdentity, RendererRuntimeInspectorAsyncCompletion,RendererRuntimeInspectorResponseChannel, RendererRuntimeInspectorResponseSender,+ RendererRuntimeRemoteObjectResolution,};+pub use moli_renderer_v8::{RendererPageCommand, RendererPageReply};diff --git a/moli-core/src/page/command_dispatch.rs b/moli-core/src/page/command_dispatch.rsindex a10a83629..9973c4221 100644--- a/moli-core/src/page/command_dispatch.rs+++ b/moli-core/src/page/command_dispatch.rs@@ -391,6 +391,7 @@ impl Page {RendererPageReply::AppManifestLoadPreparation(_) => "an app manifest load preparation",RendererPageReply::ChildFrameTreeSnapshots(_) => "child frame tree snapshots",RendererPageReply::OptionalString(_) => "an optional string reply",+ RendererPageReply::SerializedDocument { .. } => "a serialized document reply",RendererPageReply::OptionalU64(_) => "an optional u64 reply",RendererPageReply::Usize(_) => "a usize reply",RendererPageReply::SetDocumentContentResult(_) => "a set-document-content result reply",@@ -402,6 +403,8 @@ impl Page {RendererPageReply::CaptureScreenshot(_) => "a capture screenshot reply",RendererPageReply::CaptureScreencastFrame(_) => "a capture screencast frame reply",RendererPageReply::Unit => "a unit reply",+ RendererPageReply::NativeCommandReady(_) => "an unsettled native frontend reply",+ RendererPageReply::NativeCommandPublished => "a published native frontend reply",}}diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rsindex c0ef0acd6..fa0ec384e 100644--- a/moli-core/src/page/mod.rs+++ b/moli-core/src/page/mod.rs@@ -179,10 +179,10 @@ pub use renderer_command_support::{use crate::renderer::RendererPageTestingHandle;pub use crate::renderer::{- RendererDocumentFrontendNodeIdsResolution, RendererDocumentNodeAttributesResolution,- RendererDocumentNodePropertyResolution, RendererDocumentNodeReference,- RendererDocumentNodeTextResolution, RendererDocumentQuerySelectorNode,- RendererDocumentQuerySelectorResolution,+ RendererDocumentChildNodeSnapshotEvents, RendererDocumentFrontendNodeIdsResolution,+ RendererDocumentNodeAttributesResolution, RendererDocumentNodePropertyResolution,+ RendererDocumentNodeReference, RendererDocumentNodeTextResolution,+ RendererDocumentQuerySelectorNode, RendererDocumentQuerySelectorResolution,RendererDocumentQuerySelectorWithChildNodeSnapshotEvents, RendererDomBidiNodeBindingResolution,RendererDomBidiNodeSharedIdResolution, RendererDomFrontendNodeBindingResolution,RendererDomNodeCreationStackFrame, RendererDomNodeCreationStackTrace,diff --git a/moli-core/src/page/renderer_command_support.rs b/moli-core/src/page/renderer_command_support.rsindex 24770e617..6dd8b9927 100644--- a/moli-core/src/page/renderer_command_support.rs+++ b/moli-core/src/page/renderer_command_support.rs@@ -1730,6 +1730,33 @@ impl Page {self.start_page_command(RendererPageCommand::ChildFrameTreeSnapshot)}+ /// Admit a frontend terminal, distinct from an internal renderer query.+ /// The returned guard must live with the adapter continuation until the+ /// producer has settled; dropping it earlier cancels the publication.+ pub fn start_native_frontend_command(+ &self,+ command_id: u64,+ frontend_session_id: Option<&str>,+ operation: crate::RendererNativeOperation,+ ) -> Result<(+ PendingPageCommand,+ crate::RendererNativeCommandResponseGuard,+ )> {+ let attachment = self.renderer_agent_attachment_id.ok_or_else(|| {+ anyhow::anyhow!("native frontend command requires a renderer attachment")+ })?;+ let (command, guard) = crate::RendererNativeCommand::new(+ moli_page_types::FrontendCommandId::new(command_id),+ moli_page_types::DevToolsSessionKey::from_wire_session_id(frontend_session_id),+ attachment,+ operation,+ );+ Ok((+ self.start_page_command(RendererPageCommand::Native(Box::new(command)))?,+ guard,+ ))+ }+pub fn finish_child_frame_tree_snapshot(&mut self,completion: CompletedPageCommand,diff --git a/moli-core/src/renderer.rs b/moli-core/src/renderer.rsindex e96675a72..8fb459bdd 100644--- a/moli-core/src/renderer.rs+++ b/moli-core/src/renderer.rs@@ -12,26 +12,25 @@ pub(crate) use moli_renderer_v8::{RendererAccessibilityPayloadsForObjectId, RendererAutofillTriggerOutcome,RendererAutofillTriggerRequest, RendererCaptureScreencastFrameReply,RendererCaptureScreencastFrameRequest, RendererCaptureScreenshotReply,- RendererCaptureScreenshotRequest, RendererDocumentChildNodeSnapshotEvents,- RendererDocumentHitTestResult, RendererDocumentNodeClientRect, RendererDocumentNodeGeometry,- RendererDomAttributeMutation, RendererDomAttributeMutationOutcome,- RendererDomDebuggerDomBreakpointResolution, RendererDomDebuggerEventListenerBreakpoint,- RendererDomDebuggerEventListenersResolution, RendererDomDebuggerXhrBreakpoint,- RendererDomFocusOutcome, RendererDomSnapshotCaptureOptions, RendererDomSnapshotCapturePayload,- RendererInspectorCommandEnvelope, RendererInspectorCommandRoute,- RendererInspectorIngressTicket, RendererLayoutMetrics, RendererOwnerCommand,- RendererOwnerHandle, RendererOwnerReply, RendererPageCommand, RendererPageCommandPending,- RendererPageCookieFacadeSnapshotReply, RendererPageDumpOptions, RendererPageHandle,- RendererPageReply, RendererPageState, RendererPendingDownloadActivation,+ RendererCaptureScreenshotRequest, RendererDocumentHitTestResult,+ RendererDocumentNodeClientRect, RendererDocumentNodeGeometry, RendererDomAttributeMutation,+ RendererDomAttributeMutationOutcome, RendererDomDebuggerDomBreakpointResolution,+ RendererDomDebuggerEventListenerBreakpoint, RendererDomDebuggerEventListenersResolution,+ RendererDomDebuggerXhrBreakpoint, RendererDomFocusOutcome, RendererDomSnapshotCaptureOptions,+ RendererDomSnapshotCapturePayload, RendererInspectorCommandEnvelope,+ RendererInspectorCommandRoute, RendererInspectorIngressTicket, RendererLayoutMetrics,+ RendererOwnerCommand, RendererOwnerHandle, RendererOwnerReply, RendererPageCommand,+ RendererPageCommandPending, RendererPageCookieFacadeSnapshotReply, RendererPageDumpOptions,+ RendererPageHandle, RendererPageReply, RendererPageState, RendererPendingDownloadActivation,RendererPerformanceMetricSnapshot, RendererRuntimeHeapUsage,RendererRuntimeInspectorResponseSender, RendererRuntimeRemoteObjectResolution,ScriptRunOutcome,};pub use moli_renderer_v8::{- RendererDocumentFrontendNodeIdsResolution, RendererDocumentNodeAttributesResolution,- RendererDocumentNodePropertyResolution, RendererDocumentNodeReference,- RendererDocumentNodeTextResolution, RendererDocumentQuerySelectorNode,- RendererDocumentQuerySelectorResolution,+ RendererDocumentChildNodeSnapshotEvents, RendererDocumentFrontendNodeIdsResolution,+ RendererDocumentNodeAttributesResolution, RendererDocumentNodePropertyResolution,+ RendererDocumentNodeReference, RendererDocumentNodeTextResolution,+ RendererDocumentQuerySelectorNode, RendererDocumentQuerySelectorResolution,RendererDocumentQuerySelectorWithChildNodeSnapshotEvents, RendererDomBidiNodeBindingResolution,RendererDomBidiNodeSharedIdResolution, RendererDomEdit, RendererDomEditOutcome,RendererDomFrontendNodeBindingResolution, RendererDomNodeCreationStackFrame,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 6af2ef8a3..0996f34b5 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@@ -3,6 +3,50 @@ use super::*;type TestCdpSocket =tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;+async fn navigate_fixture_document(+ browser: &mut TestCdpSocket,+ navigation_id: u64,+ target: &TestCdpTargetSession,+ url: &str,+) {+ let session = Some(target.session_id.as_str());+ for (id, method, params) in [+ (90, "Page.enable", json!({})),+ (+ 91,+ "Page.setLifecycleEventsEnabled",+ json!({"enabled": true}),+ ),+ ] {+ let enabled = send_cdp_command(browser, id, method, session, params).await;+ assert_eq!(response_by_id(&enabled, id)["result"], json!({}));+ }+ let navigation = send_cdp_command(+ browser,+ navigation_id,+ "Page.navigate",+ session,+ json!({"url": url}),+ )+ .await;+ assert!(response_by_id(&navigation, navigation_id)["error"].is_null());+ let loader = response_by_id(&navigation, navigation_id)["result"]["loaderId"]+ .as_str()+ .expect("fixture navigation loader");+ // Navigation can acknowledge before parsing finishes and invalidates an+ // earlier DOM root. Wait for this session and loader's parsed document;+ // an initial-document lifecycle replay must not satisfy the fixture gate.+ let parsed = |message: &serde_json::Value| {+ message["sessionId"] == target.session_id+ && message["method"] == "Page.lifecycleEvent"+ && message["params"]["loaderId"] == loader+ && message["params"]["name"] == "DOMContentLoaded"+ };+ if !navigation.iter().any(parsed) {+ recv_until_match(browser, parsed).await;+ }+}+async fn create_dynamic_target(browser: &mut TestCdpSocket, command_id: u64) -> String {send_cdp_command(browser,@@ -156,6 +200,422 @@ async fn enable_runtime_and_expect_default_context(messages}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn pipelined_frame_tree_replies_precede_runtime_context_replay() {+ let (addr, server) = spawn_test_protocol_server().await;+ let (mut browser, _) =+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))+ .await+ .expect("connect browser websocket");+ let browser_context_id = cdp_create_browser_context(&mut browser, 1).await;+ let target = cdp_create_attached_target(&mut browser, 2, &browser_context_id).await;+ let session_id = Some(target.session_id.as_str());+ let warmup = send_cdp_command(+ &mut browser,+ 4,+ "Runtime.evaluate",+ session_id,+ json!({ "expression": "globalThis.frameTreeReplayMarker = 42" }),+ )+ .await;+ assert_eq!(+ response_by_id(&warmup, 4)["result"]["result"]["value"],+ json!(42)+ );++ // These are real, asynchronous renderer snapshots. Pipeline them with+ // Runtime.enable as clients do during initial page attachment, without+ // waiting for a frame-tree response before sending the next command.+ for round in 0..20_u64 {+ let base = 100 + round * 20;+ let disabled =+ send_cdp_command(&mut browser, base, "Runtime.disable", session_id, json!({})).await;+ assert_eq!(response_by_id(&disabled, base)["result"], json!({}));+ for id in base + 1..=base + 8 {+ send_cdp_command_without_wait(+ &mut browser,+ id,+ "Page.getFrameTree",+ session_id,+ json!({}),+ )+ .await;+ }+ send_cdp_command_without_wait(+ &mut browser,+ base + 9,+ "Runtime.enable",+ session_id,+ json!({}),+ )+ .await;+ // Startup also requests browser-owned target metadata. Its handler+ // may await renderer work while these asynchronous replies are still+ // pending, so receipt must release the Main handoff before decoding.+ send_cdp_command_without_wait(+ &mut browser,+ base + 10,+ "Target.getTargetInfo",+ None,+ json!({ "targetId": target.target_id }),+ )+ .await;+ let mut tree_responses = std::collections::HashSet::new();+ let mut saw_enable_response = false;+ let mut saw_target_info = false;+ let mut context_id = None;+ let messages = recv_until_match(&mut browser, |message| {+ if message["id"] == json!(base + 10) {+ assert_eq!(message["result"]["targetInfo"]["targetId"], json!(target.target_id));+ saw_target_info = true;+ return tree_responses.len() == 8 && saw_enable_response && context_id.is_some();+ }+ if message["sessionId"].as_str() != session_id {+ return false;+ }+ if let Some(id) = message["id"].as_u64()+ && (base + 1..=base + 8).contains(&id)+ {+ assert_eq!(+ message["result"]["frameTree"]["frame"]["id"],+ json!(target.target_id)+ );+ tree_responses.insert(id);+ }+ if message["id"] == json!(base + 9) {+ assert_eq!(message["result"], json!({}));+ assert!(+ context_id.is_some(),+ "Runtime.enable replied before replaying the default context in round {round}"+ );+ saw_enable_response = true;+ }+ if message["method"] == json!("Runtime.executionContextCreated")+ && message["params"]["context"]["auxData"]["isDefault"] == json!(true)+ {+ assert_eq!(+ tree_responses.len(),+ 8,+ "Runtime context replay overtook a frame-tree response in round {round}: {tree_responses:?}"+ );+ context_id = message["params"]["context"]["id"].as_i64();+ }+ tree_responses.len() == 8 && saw_enable_response && saw_target_info && context_id.is_some()+ })+ .await;+ assert!(+ context_id.is_some(),+ "missing default context: {messages:#?}"+ );+ let evaluation = send_cdp_command(+ &mut browser,+ base + 11,+ "Runtime.evaluate",+ session_id,+ json!({ "expression": "frameTreeReplayMarker", "contextId": context_id }),+ )+ .await;+ assert_eq!(+ response_by_id(&evaluation, base + 11)["result"]["result"]["value"],+ json!(42)+ );+ }+ browser.close(None).await.expect("close browser websocket");+ abort_test_cdp_server(server).await;+}++// The ordering contracts below mirror the local Chromium probes documented in+// docs/inner/cdp-command-ordering.md. All fixtures are owned by this test: a+// fresh about:blank target, inline JavaScript, and protocol completion gates.+#[tokio::test(flavor = "current_thread")]+async fn native_snapshot_reply_precedes_later_inspector_context_replay() {+ let (addr, server) = spawn_test_protocol_server().await;+ let (mut browser, _) =+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))+ .await+ .unwrap();+ let context = cdp_create_browser_context(&mut browser, 1).await;+ let target = cdp_create_attached_target(&mut browser, 2, &context).await;+ let session = Some(target.session_id.as_str());+ send_cdp_command(+ &mut browser,+ 4,+ "Runtime.evaluate",+ session,+ json!({"expression": "document.body.innerHTML = '<p>native snapshot</p>'"}),+ )+ .await;+ for id in 10..14 {+ send_cdp_command_without_wait(+ &mut browser,+ id,+ "DOMSnapshot.captureSnapshot",+ session,+ json!({"computedStyles": ["display"]}),+ )+ .await;+ }+ send_cdp_command_without_wait(&mut browser, 20, "Runtime.enable", session, json!({})).await;+ let mut replies = std::collections::HashSet::new();+ let mut saw_context = false;+ recv_until_match(&mut browser, |message| {+ if message["sessionId"] != target.session_id {+ return false;+ }+ if let Some(id) = message["id"].as_u64()+ && (10..14).contains(&id)+ {+ assert!(message["error"].is_null(), "{message}");+ assert!(+ !message["result"]["documents"]+ .as_array()+ .unwrap()+ .is_empty()+ );+ assert!(replies.insert(id), "duplicate native reply: {message}");+ }+ if message["method"] == "Runtime.executionContextCreated"+ && message["params"]["context"]["auxData"]["isDefault"] == true+ {+ assert_eq!(+ replies.len(),+ 4,+ "Inspector event overtook a completed native snapshot"+ );+ saw_context = true;+ }+ if message["id"] == 20 {+ assert!(saw_context);+ return true;+ }+ false+ })+ .await;+ browser.close(None).await.unwrap();+ abort_test_cdp_server(server).await;+}++async fn assert_pause_command_ordering(instrumentation: bool) {+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(+ Router::new().route(+ "/page",+ get(|| async { axum::response::Html("<!doctype html><body>pause fixture</body>") }),+ ),+ "native-pause-snapshot",+ );+ let fixture_url = format!("http://{fixture_addr}/page");+ let (addr, server) = spawn_test_protocol_server().await;+ let (mut browser, _) =+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))+ .await+ .expect("connect browser websocket");+ let context = cdp_create_browser_context(&mut browser, 1).await;+ let target = cdp_create_attached_target(&mut browser, 2, &context).await;+ let session = Some(target.session_id.as_str());+ navigate_fixture_document(&mut browser, 9, &target, &fixture_url).await;++ let dom = send_cdp_command(&mut browser, 5, "DOM.getDocument", session, json!({})).await;+ let root = response_by_id(&dom, 5)["result"]["root"]["nodeId"]+ .as_u64()+ .unwrap();+ let nodes = send_cdp_command(+ &mut browser,+ 6,+ "DOM.querySelector",+ session,+ json!({"nodeId": root, "selector": "body"}),+ )+ .await;+ let body = response_by_id(&nodes, 6)["result"]["nodeId"]+ .as_u64()+ .unwrap();+ let enabled = send_cdp_command(&mut browser, 10, "Debugger.enable", session, json!({})).await;+ assert!(response_by_id(&enabled, 10).get("error").is_none());+ if instrumentation {+ let breakpoint = send_cdp_command(+ &mut browser,+ 11,+ "Debugger.setInstrumentationBreakpoint",+ session,+ json!({ "instrumentation": "beforeScriptExecution" }),+ )+ .await;+ assert!(response_by_id(&breakpoint, 11).get("error").is_none());+ }+ send_cdp_command_without_wait(+ &mut browser,+ 12,+ "Runtime.evaluate",+ session,+ json!({+ "expression": if instrumentation { "21 * 2" } else { "(() => { history.replaceState(null, '', '#paused'); document.body.setAttribute('data-paused', 'ready'); debugger; return 42; })()" },+ "returnByValue": true+ }),+ )+ .await;+ let paused = recv_until_match(&mut browser, |message| {+ message["sessionId"] == json!(target.session_id)+ && message["method"] == json!("Debugger.paused")+ })+ .await;+ assert!(paused.iter().all(|message| message["id"] != json!(12)));+ if instrumentation {+ assert_eq!(+ paused.last().unwrap()["params"]["reason"],+ json!("instrumentation")+ );+ }+ send_cdp_command_without_wait(&mut browser, 13, "Page.getFrameTree", session, json!({})).await;+ // IO completion proves the paused renderer has processed a later command;+ // it is a gate, not a timed assumption about a missing Main response.+ let gate = if instrumentation {+ send_cdp_command(+ &mut browser,+ 14,+ "Performance.getMetrics",+ session,+ json!({}),+ )+ .await+ } else {+ recv_until_id(&mut browser, 13).await+ };+ assert!(gate.iter().all(|message| message["id"] != json!(12)));+ if instrumentation {+ assert!(response_by_id(&gate, 14).get("error").is_none());+ assert!(+ gate.iter().all(|message| message["id"] != json!(13)),+ "instrumentation pause must not pump Main: {gate:#?}"+ );+ } else {+ assert_eq!(+ response_by_id(&gate, 13)["result"]["frameTree"]["frame"]["id"],+ json!(target.target_id)+ );+ }+ if !instrumentation {+ // Native wrapping must preserve the isolate-entry constraint of both+ // an opaque node-resolution chain and a world-creation handler.+ send_cdp_command_without_wait(+ &mut browser,+ 16,+ "DOM.setAttributeValue",+ session,+ json!({"nodeId": body, "name": "data-after-pause", "value": "ready"}),+ )+ .await;+ send_cdp_command_without_wait(+ &mut browser,+ 17,+ "DOM.resolveNode",+ session,+ json!({"nodeId": body}),+ )+ .await;+ send_cdp_command_without_wait(+ &mut browser,+ 18,+ "Page.createIsolatedWorld",+ session,+ json!({"frameId": target.target_id, "worldName": "after-pause"}),+ )+ .await;+ let io = send_cdp_command(+ &mut browser,+ 19,+ "Performance.getMetrics",+ session,+ json!({}),+ )+ .await;+ assert!(+ io.iter()+ .all(|message| message["id"] != 16 && message["id"] != 17 && message["id"] != 18),+ "owner-only native handlers must wait for the enclosing V8 entry: {io:?}"+ );+ }+ send_cdp_command_without_wait(&mut browser, 15, "Debugger.resume", session, json!({})).await;+ let mut completed = std::collections::HashSet::new();+ let resumed = recv_until_match(&mut browser, |message| {+ if message["sessionId"] == json!(target.session_id)+ && let Some(id) = message["id"].as_u64()+ {+ assert!(+ completed.insert(id),+ "duplicate terminal response: {message}"+ );+ }+ completed.contains(&12)+ && completed.contains(&15)+ && (!instrumentation || completed.contains(&13))+ && (instrumentation+ || (completed.contains(&16) && completed.contains(&17) && completed.contains(&18)))+ })+ .await;+ assert_eq!(+ response_by_id(&resumed, 12)["result"]["result"]["value"],+ json!(42)+ );+ assert!(response_by_id(&resumed, 15).get("error").is_none());+ if instrumentation {+ assert_eq!(+ response_by_id(&resumed, 13)["result"]["frameTree"]["frame"]["id"],+ json!(target.target_id)+ );+ }+ if !instrumentation {+ let edited = resumed+ .iter()+ .position(|message| {+ message["method"] == "DOM.attributeModified"+ && message["params"]["name"] == "data-after-pause"+ })+ .expect("resumed mutation notification");+ let edit_response = resumed+ .iter()+ .position(|message| message["id"] == 16)+ .unwrap();+ assert!(+ edited < edit_response,+ "mutation notification precedes response: {resumed:?}"+ );+ assert!(response_by_id(&resumed, 17)["result"]["object"]["objectId"].is_string());+ assert!(response_by_id(&resumed, 18)["result"]["executionContextId"].is_i64());+ let prefix = paused.iter().chain(gate.iter()).collect::<Vec<_>>();+ let event = prefix+ .iter()+ .position(|message| {+ message["method"] == "DOM.attributeModified"+ && message["params"]["name"] == "data-paused"+ })+ .expect("nested mutation must publish before resume");+ let response = prefix+ .iter()+ .position(|message| message["id"] == 13)+ .unwrap();+ assert!(+ event < response,+ "native terminal must flush the suspended turn DOM prefix: {prefix:?}"+ );+ assert_eq!(+ response_by_id(&gate, 13)["result"]["frameTree"]["frame"]["url"],+ format!("{fixture_url}#paused")+ );+ }+ browser.close(None).await.expect("close browser websocket");+ abort_test_cdp_server(server).await;+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn cdp_ordering_normal_pause_allows_nested_main() {+ assert_pause_command_ordering(false).await;+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn cdp_ordering_instrumentation_pause_only_allows_io() {+ assert_pause_command_ordering(true).await;+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn cdp_ordering_deferred_reply_allows_its_later_resolver() {let (addr, server) = spawn_test_protocol_server().await;diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rsindex cf96c84f0..4fd9614c7 100644--- a/moli-protocol/src/conn.rs+++ b/moli-protocol/src/conn.rs@@ -1892,14 +1892,6 @@ impl CdpConnection {/// boundary may use this access path. Ordinary protocol commands must use/// [`Self::loaded_page_mut_for_protocol_access`] so they wait for the/// replacement attachment instead of entering the old renderer.- pub(crate) fn loaded_page_mut_for_interruptible_protocol_access(- &mut self,- session_id: Option<&str>,- ) -> Result<&mut Page, String> {- let owner = CommandOwnerScope::capture(self, session_id);- self.loaded_page_mut_for_interruptible_protocol_access_for_owner(&owner)- }-pub(crate) fn loaded_page_mut_for_interruptible_protocol_access_for_owner(&mut self,owner: &CommandOwnerScope,diff --git a/moli-protocol/src/conn/dispatch.rs b/moli-protocol/src/conn/dispatch.rsindex c45b73948..944fb3f38 100644--- a/moli-protocol/src/conn/dispatch.rs+++ b/moli-protocol/src/conn/dispatch.rs@@ -33,6 +33,7 @@ impl CdpCommandTaskStep {}enum PendingCdpCommandDispatchKind {+ Native(crate::domains::native::PendingNativeCommand),Runtime(Box<crate::domains::runtime::PendingRuntimeCommandDispatch>),Autofill(crate::domains::autofill::PendingAutofillCommandDispatch),Accessibility(crate::domains::accessibility::PendingAccessibilityCommandDispatch),@@ -56,6 +57,7 @@ enum PendingCdpCommandDispatchKind {}enum CompletedCdpCommandDispatchKind {+ Native(crate::domains::native::CompletedNativeCommand),Runtime(Box<crate::domains::runtime::CompletedRuntimeCommandDispatch>),Autofill(crate::domains::autofill::CompletedAutofillCommandDispatch),Accessibility(crate::domains::accessibility::CompletedAccessibilityCommandDispatch),@@ -81,6 +83,7 @@ enum CompletedCdpCommandDispatchKind {impl PendingCdpCommandDispatchKind {fn name(&self) -> &'static str {match self {+ Self::Native(_) => "Native",Self::Runtime(_) => "Runtime",Self::Autofill(_) => "Autofill",Self::Accessibility(_) => "Accessibility",@@ -108,6 +111,7 @@ impl PendingCdpCommandDispatchKind {impl CompletedCdpCommandDispatchKind {fn name(&self) -> &'static str {match self {+ Self::Native(_) => "Native",Self::Runtime(_) => "Runtime",Self::Autofill(_) => "Autofill",Self::Accessibility(_) => "Accessibility",@@ -158,6 +162,7 @@ impl PendingCdpCommandDispatch {pub fn command_id(&self) -> Option<u64> {match &self.inner {+ PendingCdpCommandDispatchKind::Native(pending) => Some(pending.command_id()),PendingCdpCommandDispatchKind::Runtime(pending) => pending.command_id(),_ => None,}@@ -165,6 +170,7 @@ impl PendingCdpCommandDispatch {pub fn session_id(&self) -> Option<&str> {match &self.inner {+ PendingCdpCommandDispatchKind::Native(pending) => pending.session_id(),PendingCdpCommandDispatchKind::Runtime(pending) => pending.session_id(),_ => None,}@@ -266,6 +272,9 @@ impl PendingCdpCommandDispatch {);}let inner = match self.inner {+ PendingCdpCommandDispatchKind::Native(pending) => {+ CompletedCdpCommandDispatchKind::Native(pending.wait().await)+ }PendingCdpCommandDispatchKind::Runtime(pending) => {CompletedCdpCommandDispatchKind::Runtime(Box::new(Box::pin(pending.wait()).await))}@@ -521,6 +530,16 @@ impl CdpConnection {command_context.terminal_response_delivery_override(),);self.record_tracing_command(cmd.method, cmd.session_id);+ if let Some(step) = crate::domains::native::try_start(self, &cmd) {+ return match step {+ crate::domains::native::NativeCommandStep::Pending(pending) => {+ self.pending_step(PendingCdpCommandDispatchKind::Native(pending))+ }+ crate::domains::native::NativeCommandStep::Complete(plan) => {+ self.complete_with_output_plan(command_context, plan, cmd.id, cmd.session_id)+ }+ };+ }let step = match domain {"Browser" => Some(match crate::domains::browser::try_start_browser_command_dispatch(self, &cmd) {@@ -894,6 +913,17 @@ impl CdpConnection {) -> CdpCommandTaskStep {let mut out = Vec::new();match completed.inner {+ CompletedCdpCommandDispatchKind::Native(completed) => {+ let command_id = completed.command_id;+ let session_id = completed.session_id().map(str::to_owned);+ let plan = completed.complete(self, command_context).await;+ return self.complete_with_output_plan(+ command_context,+ plan,+ Some(command_id),+ session_id.as_deref(),+ );+ }CompletedCdpCommandDispatchKind::Runtime(completed) => {let completed = *completed;let command_id = completed.command_id();diff --git a/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs b/moli-protocol/src/conn/dispatch_tests/command_dispatch.rsindex b5d93a93e..9609dbfad 100644--- a/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs+++ b/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs@@ -596,11 +596,9 @@ async fn command_dispatch_completes_live_page_preload_without_legacy_fallback()panic!("live Page.addScriptToEvaluateOnNewDocument should update the live page")}};- let add_step = ctx- .conn- .complete_pending_command_dispatch(add_pending.wait().await)+ let (add_messages, _) = ctx+ .complete_command_task_step_for_test(CdpCommandTaskStep::Pending(add_pending)).await;- let (add_messages, _) = ctx.complete_command_task_step_for_test(add_step).await;assert_eq!(add_messages.len(), 1);assert_eq!(add_messages[0]["id"], json!(42));assert_eq!(add_messages[0]["sessionId"], json!("SID-page-preload-live"));@@ -638,11 +636,9 @@ async fn command_dispatch_completes_live_page_preload_without_legacy_fallback()panic!("live Page.removeScriptToEvaluateOnNewDocument should update the live page")}};- let remove_step = ctx- .conn- .complete_pending_command_dispatch(remove_pending.wait().await)+ let (remove_messages, _) = ctx+ .complete_command_task_step_for_test(CdpCommandTaskStep::Pending(remove_pending)).await;- let (remove_messages, _) = ctx.complete_command_task_step_for_test(remove_step).await;assert_eq!(remove_messages,vec![json!({diff --git a/moli-protocol/src/conn/renderer_command_turn.rs b/moli-protocol/src/conn/renderer_command_turn.rsindex 8fe305786..a03da1036 100644--- a/moli-protocol/src/conn/renderer_command_turn.rs+++ b/moli-protocol/src/conn/renderer_command_turn.rs@@ -2,7 +2,9 @@ use moli_core::page::{CompletedPageCommand, RendererCommandTurnCompletion, RendererCommandTurnOutput,};-use super::{CdpConnection, CommandDispatchContext, TargetPageResidenceIdentity};+use super::{+ CdpConnection, CommandDispatchContext, CommandOwnerScope, TargetPageResidenceIdentity,+};impl CdpConnection {/// Settles a renderer command turn against the Page residence that admitted it.@@ -14,7 +16,6 @@ impl CdpConnection {/// into the replacement Page.pub(crate) fn settle_page_command_turn_for_owner(&mut self,- session_id: Option<&str>,owner: &TargetPageResidenceIdentity,completion: CompletedPageCommand,) -> RendererCommandTurnOutput {@@ -22,7 +23,11 @@ impl CdpConnection {return completion.into_output();}- if let Ok(page) = self.loaded_page_mut_for_interruptible_protocol_access(session_id) {+ // The attachment check and the cache lookup must address the same+ // frozen target. Resolving a missing session through the active Page+ // here would install this result into a newly activated sibling.+ let scope = CommandOwnerScope::for_page_residence(owner);+ if let Ok(page) = self.loaded_page_mut_for_interruptible_protocol_access_for_owner(&scope) {return page.finish_page_command_turn(completion);}diff --git a/moli-protocol/src/domains/activity/output_ingress/renderer.rs b/moli-protocol/src/domains/activity/output_ingress/renderer.rsindex 49cfffe88..88651407d 100644--- a/moli-protocol/src/domains/activity/output_ingress/renderer.rs+++ b/moli-protocol/src/domains/activity/output_ingress/renderer.rs@@ -122,6 +122,16 @@ async fn ingest_renderer_output_publication(// owner has since retired, the cursor is still admitted so response// fences cannot hang, but its historical records must not be projected// into a replacement target or browser context.+ // Native terminals are replies to frozen frontend calls, not live+ // Page observations. Retirement may discard historical events but+ // must still settle replies committed before this stream closed.+ for record in publication.into_records() {+ if let RendererOutputItem::NativeTerminal(terminal) = record.into_parts().1 {+ command_context.protocol_events_mut().extend(+ crate::domains::native::project_terminal_for_owner(conn, None, terminal),+ );+ }+ }return;};let records = publication.into_records();@@ -171,11 +181,28 @@ async fn project_renderer_output_records_for_owner(command_context: &mut CommandDispatchContext,) {for record in records {- let (renderer_cause, mut item) = record.into_parts();+ let (renderer_cause, item) = record.into_parts();+ let mut item = match item {+ RendererOutputItem::NativeTerminal(terminal) => {+ command_context.protocol_events_mut().extend(+ crate::domains::native::project_terminal_for_owner(+ conn,+ (projection != RendererPublicationProjection::RetiringNetworkAndResponses)+ .then_some(owner),+ terminal,+ ),+ );+ continue;+ }+ item => item,+ };if !projection.admit_record(&mut item) {continue;}match item {+ RendererOutputItem::NativeTerminal(_) => {+ unreachable!("terminals were projected in producer order above")+ }RendererOutputItem::OwnerAction(action) => {// A Page stream can remain bound to its implicit primary owner while a// Runtime command arrives through an attached DevTools session. Ownerdiff --git a/moli-protocol/src/domains/command_output.rs b/moli-protocol/src/domains/command_output.rsindex 0ad537d3b..519e58a05 100644--- a/moli-protocol/src/domains/command_output.rs+++ b/moli-protocol/src/domains/command_output.rs@@ -78,6 +78,34 @@ enum CommandOwnerEvent {}impl CommandOutputPlan {+ /// Reuses a pure result formatter inside a renderer-owned handler. A+ /// formatter requiring Browser events, fences or continuations cannot be+ /// moved across this boundary by silently dropping those responsibilities.+ pub(crate) fn into_native_response(self) -> moli_core::RendererNativeProtocolResponse {+ assert!(self.post_response_events.is_empty());+ assert!(self.renderer_output_predecessor.is_none());+ assert!(self.renderer_output_boundary.is_none());+ assert_eq!(+ self.outputs.len(),+ 1,+ "native result formatter has one terminal"+ );+ match self.outputs.into_iter().next().unwrap() {+ CommandOutput::Command(CommandResponseOutput::Success(result)) => {+ moli_core::RendererNativeProtocolResponse::success(match result {+ CommandResponseResult::Empty => json!({}),+ CommandResponseResult::Json(result) => result,+ })+ }+ CommandOutput::Command(CommandResponseOutput::Error {+ code,+ message,+ data: None,+ }) => moli_core::RendererNativeProtocolResponse::error(code, message),+ _ => panic!("native result formatter cannot own Browser output"),+ }+ }+pub(crate) fn success() -> Self {Self::from_devtools_result(DevToolsCommandResult::Empty)}diff --git a/moli-protocol/src/domains/dom.rs b/moli-protocol/src/domains/dom.rsindex f2e367c39..c58b42db8 100644--- a/moli-protocol/src/domains/dom.rs+++ b/moli-protocol/src/domains/dom.rs@@ -222,7 +222,7 @@ fn cached_dom_remote_object_node_for_owner(.cloned()}-fn cache_dom_remote_object_node_for_owner(+pub(in crate::domains) fn cache_dom_remote_object_node_for_owner(conn: &mut CdpConnection,owner: &CommandOwnerScope,object_id: String,diff --git a/moli-protocol/src/domains/dom_snapshot.rs b/moli-protocol/src/domains/dom_snapshot.rsindex 6dde87c2c..cf00ce605 100644--- a/moli-protocol/src/domains/dom_snapshot.rs+++ b/moli-protocol/src/domains/dom_snapshot.rs@@ -13,6 +13,46 @@ use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};use crate::domains::actions::DomSnapshotAction;use crate::domains::command_output::CommandOutputPlan;+pub(crate) fn try_start_native_command(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+) -> Option<super::native::NativeCommandStep> {+ use moli_core::RendererNativeProtocolResponse as Response;+ use moli_core::{RendererPageCommand, RendererPageReply};+ if cmd.parse_action::<DomSnapshotAction>() != Some(DomSnapshotAction::CaptureSnapshot) {+ return None;+ }+ let params = match cmd.get_params::<CaptureSnapshotParams>() {+ Ok(params) => params.unwrap_or_default(),+ Err(_) => {+ return Some(super::native::NativeCommandStep::Complete(+ CommandOutputPlan::error(-32602, "InvalidParams"),+ ));+ }+ };+ let frame_id = top_frame_id_for_session(conn, cmd.session_id).unwrap_or_default();+ Some(super::native::start(+ conn,+ cmd,+ RendererPageCommand::DomSnapshotCapture {+ top_frame_id: frame_id,+ options: params.into(),+ },+ |reply| match reply {+ Ok(RendererPageReply::OptionalDomSnapshotCapturePayload(Some(payload))) => {+ Response::success(payload.into_protocol_payload())+ }+ Ok(RendererPageReply::OptionalDomSnapshotCapturePayload(None)) => {+ Response::error(-32000, "NoDocumentLoaded")+ }+ Ok(_) => unreachable!("DOM snapshot backend returned a different result"),+ Err(error) => {+ Response::error(-32000, format!("Could not capture DOM snapshot: {error}"))+ }+ },+ ))+}+pub(crate) struct PendingDomSnapshotCommandDispatch {command_id: Option<u64>,owner_scope: CommandOwnerScope,@@ -603,7 +643,7 @@ mod tests {.conn.try_start_pending_command_dispatch(&raw).expect("DOMSnapshot.captureSnapshot should await renderer live DOM capture");- assert_eq!(pending.kind_name(), "DOMSnapshot");+ assert_eq!(pending.kind_name(), "Native");let messages = complete_pending_command_task_for_test(&mut ctx, pending).await;assert_eq!(@@ -1025,6 +1065,7 @@ mod tests {).await.expect("background page should load");+ let renderer_page = crate::conn::RendererPageResidenceIdentity::from_page(&page);let mut background = PageTargetHost::with_url("TID-background".to_owned(),@@ -1038,6 +1079,14 @@ mod tests {bc.attach_active_session("SID-active".to_owned());bc.insert_page_target_host(background);ctx.conn.install_browser_context_fixture_for_test(bc);+ // This fixture installs a live Page without the production attachment+ // transaction. Bind its output stream before native replies publish.+ let page_owner = ctx+ .conn+ .target_page_residence_identity_for_session(Some("SID-background"))+ .expect("background fixture has a Page owner");+ ctx.conn+ .bind_renderer_page_output_owner(renderer_page, page_owner);ctx.process_async(json!({"id": 101,@@ -1084,6 +1133,7 @@ mod tests {).await.expect("inactive page should load");+ let renderer_page = crate::conn::RendererPageResidenceIdentity::from_page(&page);let mut active = BrowserContext::new("BID-active".to_owned());active.set_active_target_id("TID-active".to_owned());@@ -1097,6 +1147,12 @@ mod tests {inactive.replace_loaded_page(Some(page));ctx.conn.push_inactive_browser_context_fixture_for_test(inactive);+ let page_owner = ctx+ .conn+ .target_page_residence_identity_for_session(Some("SID-inactive"))+ .expect("inactive fixture has a Page owner");+ ctx.conn+ .bind_renderer_page_output_owner(renderer_page, page_owner);ctx.process_async(json!({"id": 111,diff --git a/moli-protocol/src/domains/input.rs b/moli-protocol/src/domains/input.rsindex fd3ba4df0..1c7857f5e 100644--- a/moli-protocol/src/domains/input.rs+++ b/moli-protocol/src/domains/input.rs@@ -1385,13 +1385,8 @@ async fn complete_pending_input_command(match completed_page_command_result(completed_operation) {Err(error) => Err(error),Ok(result) => {- let completion = settle_completed_input_page_command(- conn,- session_id,- &owner,- result,- command_context,- );+ let completion =+ settle_completed_input_page_command(conn, &owner, result, command_context);if matches!(kind, PendingInputCommandKind::PrepareElementClick) {decode_element_click_preparation_completion(completion).map(DevToolsCommandResult::ElementClickPreparation)@@ -1439,13 +1434,8 @@ async fn complete_pending_input_command(};}};- let completion = settle_completed_input_page_command(- conn,- session_id,- &owner,- result,- command_context,- );+ let completion =+ settle_completed_input_page_command(conn, &owner, result, command_context);let operation = match kind {PendingInputCommandKind::DispatchMouseEvent => "mouse event page command",PendingInputCommandKind::DispatchTouchEvent@@ -1496,13 +1486,8 @@ async fn complete_pending_input_command(};}};- let completion = settle_completed_input_page_command(- conn,- session_id,- &owner,- result,- command_context,- );+ let completion =+ settle_completed_input_page_command(conn, &owner, result, command_context);let outcome =decode_input_dispatch_outcome_completion(completion, "key event page command");match outcome {@@ -1542,13 +1527,8 @@ async fn complete_pending_input_command(};}};- let completion = settle_completed_input_page_command(- conn,- session_id,- &owner,- result,- command_context,- );+ let completion =+ settle_completed_input_page_command(conn, &owner, result, command_context);let result = decode_insert_text_completion(completion);match result {Ok(_) => Ok(DevToolsCommandResult::Empty),@@ -1569,12 +1549,11 @@ async fn complete_pending_input_command(fn settle_completed_input_page_command(conn: &mut CdpConnection,- session_id: Option<&str>,owner: &TargetPageResidenceIdentity,completion: CompletedPageCommand,command_context: &mut CommandDispatchContext,) -> RendererCommandTurnCompletion {- let output = conn.settle_page_command_turn_for_owner(session_id, owner, completion);+ let output = conn.settle_page_command_turn_for_owner(owner, completion);command_context.consume_renderer_command_turn_output(output)}diff --git a/moli-protocol/src/domains/mod.rs b/moli-protocol/src/domains/mod.rsindex f923cc547..3998bbf98 100644--- a/moli-protocol/src/domains/mod.rs+++ b/moli-protocol/src/domains/mod.rs@@ -22,6 +22,7 @@ pub mod inspector;pub mod io;pub mod log;pub(crate) mod log_output_state;+pub(crate) mod native;pub mod network;pub(crate) mod observable_output;pub mod page;diff --git a/moli-protocol/src/domains/native.rs b/moli-protocol/src/domains/native.rsnew file mode 100644index 000000000..d9335ffa8--- /dev/null+++ b/moli-protocol/src/domains/native.rs@@ -0,0 +1,339 @@+//! Native frontend commands publish from the renderer, just like Inspector.+//!+//! The pending adapter retains only cancellation and Page-cache bookkeeping.+//! Its wake-up order cannot decide when a successful reply reaches the client.+//! Internal queries deliberately keep their ordinary typed result channel.++use serde_json::json;++use moli_core::page::{CompletedPageCommand, PendingPageCommand};+use moli_core::{RendererNativeCommandResponseGuard, RendererNativeProtocolResponse};+use moli_core::{RendererPageCommand, RendererPageReply};++use super::command_output::CommandOutputPlan;+use crate::conn::{+ BackgroundProtocolEvent, CdpConnection, Cmd, CommandDispatchContext, CommandOwnerScope,+ TargetPageResidenceIdentity,+};++pub(crate) enum NativeCommandStep {+ Pending(PendingNativeCommand),+ Complete(CommandOutputPlan),+}++pub(crate) struct PendingNativeCommand {+ // Retain wire routing only; Page settlement uses the exact residence.+ session_id: Option<String>,+ residence: TargetPageResidenceIdentity,+ command_id: u64,+ pending: PendingPageCommand,+ guard: RendererNativeCommandResponseGuard,+}++pub(crate) struct CompletedNativeCommand {+ session_id: Option<String>,+ residence: TargetPageResidenceIdentity,+ pub(crate) command_id: u64,+ result: Result<CompletedPageCommand, String>,+ guard: RendererNativeCommandResponseGuard,+}++impl PendingNativeCommand {+ pub(crate) fn command_id(&self) -> u64 {+ self.command_id+ }++ pub(crate) fn session_id(&self) -> Option<&str> {+ self.session_id.as_deref()+ }++ pub(crate) async fn wait(self) -> CompletedNativeCommand {+ CompletedNativeCommand {+ session_id: self.session_id,+ residence: self.residence,+ command_id: self.command_id,+ result: self.pending.wait().await.map_err(|error| error.to_string()),+ guard: self.guard,+ }+ }+}++impl CompletedNativeCommand {+ pub(crate) fn session_id(&self) -> Option<&str> {+ self.session_id.as_deref()+ }++ pub(crate) async fn complete(+ self,+ conn: &mut CdpConnection,+ context: &mut CommandDispatchContext,+ ) -> CommandOutputPlan {+ match self.result {+ Ok(completed) => {+ let output = conn.settle_page_command_turn_for_owner(&self.residence, completed);+ let completion = context.consume_renderer_command_turn_output(output);+ assert!(completion.native_response_was_published());+ CommandOutputPlan::default()+ }+ Err(error) => match self.guard.cancel_or_published().await {+ Some(fence) => {+ context.set_renderer_output_predecessor(fence);+ CommandOutputPlan::default()+ }+ None => CommandOutputPlan::error(-32000, error),+ },+ }+ }+}++pub(crate) fn start(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ operation: RendererPageCommand,+ project: impl FnOnce(anyhow::Result<RendererPageReply>) -> RendererNativeProtocolResponse+ + Send+ + 'static,+) -> NativeCommandStep {+ start_operation(+ conn,+ cmd,+ moli_core::RendererNativeOperation::new(operation, project),+ )+}++pub(crate) fn start_operation(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ operation: moli_core::RendererNativeOperation,+) -> NativeCommandStep {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let Some(residence) = conn.target_page_residence_identity_for_owner(&owner) else {+ return NativeCommandStep::Complete(CommandOutputPlan::error(-32000, "NoDocumentLoaded"));+ };+ let page = match conn.loaded_page_mut_for_protocol_access_for_owner(&owner) {+ Ok(page) => page,+ Err(error) => return NativeCommandStep::Complete(CommandOutputPlan::error(-32000, error)),+ };+ let command_id = cmd.id.expect("a native frontend command has a call id");+ match page.start_native_frontend_command(command_id, cmd.session_id, operation) {+ Ok((pending, guard)) => NativeCommandStep::Pending(PendingNativeCommand {+ session_id: cmd.session_id.map(str::to_owned),+ residence,+ command_id,+ pending,+ guard,+ }),+ Err(error) => {+ NativeCommandStep::Complete(CommandOutputPlan::error(-32000, error.to_string()))+ }+ }+}++/// Admit only frontend calls with an accessible document and renderer.+/// Return the checked attachment so configuration can retain its replay identity+/// without probing the Page a second time.+pub(crate) fn frontend_attachment(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+) -> Option<moli_page_types::RendererAgentAttachmentId> {+ if cmd.id.is_none()+ || cmd.terminal_response_delivery()+ != moli_page_types::RendererInspectorResponseDelivery::SessionSink+ {+ return None;+ }+ conn.loaded_page_mut_for_protocol_access_for_owner(&CommandOwnerScope::capture(+ conn,+ cmd.session_id,+ ))+ .ok()?+ .renderer_agent_attachment_id()+}++pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<NativeCommandStep> {+ let start: fn(&mut CdpConnection, &Cmd<'_>) -> Option<NativeCommandStep> =+ match cmd.method.split_once('.')?.0 {+ "Page" => super::page::native::try_start,+ "DOMSnapshot" => super::dom_snapshot::try_start_native_command,+ _ => return None,+ };+ frontend_attachment(conn, cmd)?;+ start(conn, cmd)+}++/// Apply Browser mirrors at the same ordered boundary as the response. The+/// immutable result survives retirement, while document caches and node events+/// are valid only for the exact attachment that produced them.+pub(crate) fn project_terminal_for_owner(+ conn: &mut CdpConnection,+ publication_owner: Option<&CommandOwnerScope>,+ mut terminal: moli_core::RendererNativeCommandTerminal,+) -> Vec<BackgroundProtocolEvent> {+ let owner = publication_owner.map(|owner| match terminal.session.wire_session_id() {+ Some(session) => CommandOwnerScope::for_session(session),+ None => owner.clone(),+ });+ let owner = owner.filter(|owner| {+ conn.runtime_session_owner_slot_for_owner(owner)+ .is_ok_and(|slot| {+ slot.has_loaded_page()+ && slot+ .current_renderer_attachment()+ .is_some_and(|attachment| attachment.id() == terminal.attachment_id)+ })+ });+ let response = &mut terminal.reply;+ if owner.is_none() {+ response.notifications.clear();+ }+ for update in std::mem::take(&mut response.state_updates) {+ let Some(owner) = owner.as_ref() else {+ continue;+ };+ match update {+ moli_core::RendererNativeProtocolStateUpdate::RemoteObjects {+ result,+ object_group,+ } => {+ if let Some(group) = object_group {+ conn.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner, &result, &group,+ );+ } else {+ conn.register_runtime_remote_object_ids_from_value_for_owner(owner, &result);+ }+ }+ moli_core::RendererNativeProtocolStateUpdate::DomRemoteObjectNode {+ object_id,+ node,+ } => {+ super::dom::cache_dom_remote_object_node_for_owner(conn, owner, object_id, node);+ }+ }+ }+ project_terminal(terminal)+}++/// Bounded projection of a terminal already committed by its renderer owner.+/// It intentionally needs no live Page: replacing a document cannot change+/// an earlier snapshot or steal the original frontend call's response.+pub(crate) fn project_terminal(+ terminal: moli_core::RendererNativeCommandTerminal,+) -> Vec<BackgroundProtocolEvent> {+ let mut events = Vec::new();+ for notification in terminal.reply.notifications {+ let session = terminal.session.wire_session_id();+ events.push(match notification {+ moli_core::RendererNativeProtocolNotification::Json(mut notification) => {+ if let Some(session) = session {+ notification["sessionId"] = json!(session);+ }+ BackgroundProtocolEvent::immediate(notification)+ }+ moli_core::RendererNativeProtocolNotification::DomSetChildNodes {+ parent_node_id,+ nodes,+ } => BackgroundProtocolEvent::dom_set_child_nodes(session, parent_node_id, nodes),+ });+ }+ let mut message = json!({ "id": terminal.command_id.get() });+ match terminal.reply.result {+ Ok(result) => message["result"] = result,+ Err(error) => message["error"] = json!({ "code": error.code, "message": error.message }),+ }+ if let Some(session) = terminal.session.wire_session_id() {+ message["sessionId"] = json!(session);+ }+ events.push(BackgroundProtocolEvent::immediate(message));+ events+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn retired_native_terminal_keeps_response_and_discards_document_side_effects() {+ use moli_core::{+ RendererNativeCommandTerminal, RendererNativeProtocolNotification,+ RendererNativeProtocolStateUpdate,+ };+ use moli_page_types::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId};+ let mut ctx = crate::testing::TestContext::new();+ let mut response = RendererNativeProtocolResponse::success(+ json!({"object": {"objectId": "retired-object"}}),+ );+ response+ .notifications+ .push(RendererNativeProtocolNotification::DomSetChildNodes {+ parent_node_id: 3,+ nodes: vec![json!({"nodeId": 7})],+ });+ response+ .state_updates+ .push(RendererNativeProtocolStateUpdate::DomRemoteObjectNode {+ object_id: "retired-object".to_owned(),+ node: json!({"nodeId": 7}),+ });+ let messages = project_terminal_for_owner(+ &mut ctx.conn,+ None,+ RendererNativeCommandTerminal {+ command_id: FrontendCommandId::new(42),+ session: DevToolsSessionKey::Attached("retired-session".to_owned()),+ attachment_id: RendererAgentAttachmentId::allocate(),+ reply: response,+ },+ );+ assert_eq!(+ messages.len(),+ 1,+ "a retired document cannot emit node notifications"+ );+ assert_eq!(+ messages.into_iter().next().unwrap().into_parts().0,+ json!({+ "id": 42, "sessionId": "retired-session", "result": {"object": {"objectId": "retired-object"}},+ })+ );+ assert!(+ ctx.conn.browser_context.is_none(),+ "projection cannot recreate a retired owner"+ );+ }++ #[test]+ fn native_dom_notification_keeps_automation_sidecar_before_terminal() {+ use moli_core::{RendererNativeCommandTerminal, RendererNativeProtocolNotification};+ use moli_page_types::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId};+ let nodes = vec![json!({"nodeId": 7, "nodeName": "BUTTON"})];+ let mut response = RendererNativeProtocolResponse::success(json!({"nodeId": 7}));+ response+ .notifications+ .push(RendererNativeProtocolNotification::DomSetChildNodes {+ parent_node_id: 3,+ nodes: nodes.clone(),+ });+ let mut events = project_terminal(RendererNativeCommandTerminal {+ command_id: FrontendCommandId::new(42),+ session: DevToolsSessionKey::Attached("SID-native".to_owned()),+ attachment_id: RendererAgentAttachmentId::allocate(),+ reply: response,+ })+ .into_iter();+ let (event, sidecar) = events.next().unwrap().into_parts();+ assert_eq!(event["method"], "DOM.setChildNodes");+ assert_eq!(event["sessionId"], "SID-native");+ let Some(crate::devtools_runtime::AutomationEvent::DomSetChildNodes(sidecar)) = sidecar+ else {+ panic!("native DOM notifications retain their typed automation event");+ };+ assert_eq!(sidecar.parent_node_id, 3);+ assert_eq!(sidecar.nodes, nodes);+ let (terminal, _) = events.next().unwrap().into_parts();+ assert_eq!(terminal["id"], 42);+ assert_eq!(terminal["sessionId"], "SID-native");+ assert_eq!(terminal["result"]["nodeId"], 7);+ assert!(events.next().is_none());+ }+}diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rsindex ebbc3eed6..621444397 100644--- a/moli-protocol/src/domains/page.rs+++ b/moli-protocol/src/domains/page.rs@@ -56,6 +56,7 @@ use javascript_dialog::*;mod capture;mod lifecycle;mod main_document_commit;+pub(crate) mod native;mod navigation;mod output;use capture::*;diff --git a/moli-protocol/src/domains/page/native.rs b/moli-protocol/src/domains/page/native.rsnew file mode 100644index 000000000..2efeb5e69--- /dev/null+++ b/moli-protocol/src/domains/page/native.rs@@ -0,0 +1,201 @@+//! Page handlers whose terminal result is produced entirely by the renderer.+//! Browser-owned options are frozen at admission; observations generated by+//! the operation are settled before the handler publishes its response.++use super::*;+use crate::domains::native::{self, NativeCommandStep};+use moli_core::{+ RendererNativeOperation as Operation, RendererNativeProtocolResponse as Response,+ RendererPageCommand as Command, RendererPageReply as Reply,+};++pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<NativeCommandStep> {+ let action = cmd.parse_action::<PageAction>()?;+ if matches!(+ action,+ PageAction::CreateIsolatedWorld+ | PageAction::AddScriptToEvaluateOnNewDocument+ | PageAction::RemoveScriptToEvaluateOnNewDocument+ ) {+ return preload::native::try_start(conn, cmd, action);+ }++ if !matches!(+ action,+ PageAction::GetFrameTree+ | PageAction::GetResourceTree+ | PageAction::GetLayoutMetrics+ | PageAction::CaptureScreenshot+ | PageAction::CaptureSnapshot+ | PageAction::SetDocumentContent+ | PageAction::SetBypassCsp+ | PageAction::ResetNavigationHistory+ ) {+ return None;+ }+ Some(match prepare(conn, cmd, action) {+ Ok(operation) => native::start_operation(conn, cmd, operation),+ Err(plan) => NativeCommandStep::Complete(plan),+ })+}++fn prepare(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ action: PageAction,+) -> Result<Operation, CommandOutputPlan> {+ match action {+ PageAction::GetFrameTree | PageAction::GetResourceTree => {+ resource_tree::prepare_native_tree(conn, cmd, action == PageAction::GetResourceTree)+ }+ PageAction::GetLayoutMetrics => {+ Ok(Operation::new(+ Command::LayoutMetrics,+ |reply| match reply {+ Ok(Reply::LayoutMetrics(metrics)) => CommandOutputPlan::from_devtools_result(+ DevToolsCommandResult::LayoutMetrics(layout_metrics_result_from_renderer(+ metrics,+ )),+ )+ .into_native_response(),+ Err(error) => Response::error(+ -32000,+ format!("Failed to produce layout metrics: {error}"),+ ),+ _ => unreachable!("Page layout metrics reply"),+ },+ ))+ }+ PageAction::CaptureScreenshot => {+ let command = capture::build_cdp_capture_screenshot_command(conn, cmd)?;+ capture::validate_page_capture_target_context(conn, &command.context)+ .map_err(CommandOutputPlan::from_devtools_error)?;+ if conn.layout_policy() == moli_core::LayoutPolicy::Mock {+ return Err(CommandOutputPlan::error(+ -32000,+ CAPTURE_SCREENSHOT_LAYOUT_DISABLED_MESSAGE,+ ));+ }+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let request = renderer_screenshot_request(+ &command,+ conn.default_background_color_for_owner(&owner),+ )+ .map_err(CommandOutputPlan::from_devtools_error)?;+ Ok(Operation::new(+ Command::CaptureScreenshot(request),+ |reply| match reply {+ Ok(Reply::CaptureScreenshot(RendererCaptureScreenshotReply::Captured(+ image,+ ))) => CommandOutputPlan::from_devtools_result(+ DevToolsCommandResult::CaptureScreenshot(DevToolsCaptureScreenshotResult {+ mime_type: image.mime_type,+ width: image.width,+ height: image.height,+ bytes: image.bytes,+ }),+ )+ .into_native_response(),+ Ok(Reply::CaptureScreenshot(+ RendererCaptureScreenshotReply::LayoutDisabled,+ )) => Response::error(-32000, CAPTURE_SCREENSHOT_LAYOUT_DISABLED_MESSAGE),+ Ok(Reply::CaptureScreenshot(RendererCaptureScreenshotReply::NoDocument)) => {+ Response::error(-32000, "NoDocumentLoaded")+ }+ Err(error) => Response::error(+ -32000,+ format!("Failed to capture page screenshot: {error}"),+ ),+ _ => unreachable!("Page screenshot reply"),+ },+ ))+ }+ PageAction::CaptureSnapshot => {+ #[derive(Default, Deserialize)]+ struct Params {+ #[serde(default)]+ format: Option<String>,+ }+ let params: Params = cmd+ .get_params()+ .map_err(|error| CommandOutputPlan::error(-32602, error))?+ .unwrap_or_default();+ if !matches!(params.format.as_deref(), None | Some("mhtml")) {+ return Err(CommandOutputPlan::error(+ -32000,+ "unsupported snapshot format.",+ ));+ }+ Ok(Operation::new(+ Command::SerializeDocument,+ |reply| match reply {+ Ok(Reply::SerializedDocument { url, html }) => {+ Response::success(json!({"data": build_mhtml_snapshot(&url, &html)}))+ }+ Err(error) => Response::error(+ -32000,+ format!("Failed to serialize page snapshot: {error}"),+ ),+ _ => unreachable!("Page snapshot reply"),+ },+ ))+ }+ PageAction::SetDocumentContent => {+ let params: SetDocumentContentParams = cmd+ .get_params()+ .ok()+ .flatten()+ .ok_or_else(|| CommandOutputPlan::error(-32602, "Invalid parameters"))?;+ Ok(Operation::new(+ Command::SetDocumentContent {+ frame_id: params.frame_id.into(),+ html: params.html,+ },+ |reply| match reply {+ Ok(Reply::SetDocumentContentResult(+ RendererSetDocumentContentResult::Updated,+ )) => Response::success(json!({})),+ Ok(Reply::SetDocumentContentResult(+ RendererSetDocumentContentResult::FrameNotFound,+ )) => Response::error(-32000, "No frame for given id found"),+ Ok(Reply::SetDocumentContentResult(+ RendererSetDocumentContentResult::DocumentNotFound,+ )) => Response::error(-32000, "No Document instance to set HTML for"),+ Err(error) => Response::error(-32000, error.to_string()),+ _ => unreachable!("Page content reply"),+ },+ ))+ }+ PageAction::SetBypassCsp => {+ let params: SetBypassCspParams = cmd+ .get_params()+ .ok()+ .flatten()+ .ok_or_else(|| CommandOutputPlan::error(-32602, "InvalidParams"))?;+ if !conn.set_page_bypass_csp_enabled_for_session_owner(cmd.session_id, params.enabled) {+ return Err(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));+ }+ let enabled = conn+ .effective_page_bypass_csp_enabled_for_session_owner(cmd.session_id)+ .ok_or_else(|| CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"))?;+ Ok(Operation::new(+ Command::SetBypassContentSecurityPolicy(enabled),+ |reply| match reply {+ Ok(Reply::Unit) => Response::success(json!({})),+ Err(error) => Response::error(-32000, error.to_string()),+ _ => unreachable!("Page CSP configuration reply"),+ },+ ))+ }+ PageAction::ResetNavigationHistory => Ok(Operation::new(+ Command::ResetNavigationHistory,+ |reply| match reply {+ Ok(Reply::Bool(true)) => Response::success(json!({})),+ Ok(Reply::Bool(false)) => Response::error(-32000, "History cannot be pruned"),+ Err(error) => Response::error(-32000, error.to_string()),+ _ => unreachable!("Page history reset reply"),+ },+ )),+ _ => unreachable!("Page native preparation handles its admitted actions"),+ }+}diff --git a/moli-protocol/src/domains/page/preload.rs b/moli-protocol/src/domains/page/preload.rsindex 0d97fed15..e03bfdf56 100644--- a/moli-protocol/src/domains/page/preload.rs+++ b/moli-protocol/src/domains/page/preload.rs@@ -1,3 +1,5 @@+pub(super) mod native;+use crate::devtools_runtime::{DevToolsAddPreloadScriptCommand, DevToolsAddPreloadScriptResult, DevToolsCommand,DevToolsCommandResult, DevToolsError, DevToolsErrorKind, DevToolsPreloadScriptId,@@ -1060,6 +1062,19 @@ fn start_devtools_remove_preload_script_command(command_session_id: Option<&str>,command: DevToolsRemovePreloadScriptCommand,) -> PageCommandTaskStep {+ match remove_preload_script_registration(conn, command_session_id, command) {+ Ok(registry_key) => {+ start_document_start_script_remove(conn, command_id, command_session_id, registry_key)+ }+ Err(plan) => PageCommandTaskStep::Complete(plan),+ }+}++fn remove_preload_script_registration(+ conn: &mut CdpConnection,+ command_session_id: Option<&str>,+ command: DevToolsRemovePreloadScriptCommand,+) -> Result<Option<String>, CommandOutputPlan> {let protocol = command.context.protocol;let script_id = command.script_id.into_string();let renderer_inspector_session_id =@@ -1086,12 +1101,9 @@ fn start_devtools_remove_preload_script_command(});let Some((mut removed, mut registry_key)) = remove_result else {if conn.browser_context.is_none() {- return PageCommandTaskStep::Complete(CommandOutputPlan::error(- -31998,- "BrowserContextNotLoaded",- ));+ return Err(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));}- return PageCommandTaskStep::Complete(CommandOutputPlan::error(-31998, "TargetNotLoaded"));+ return Err(CommandOutputPlan::error(-31998, "TargetNotLoaded"));};if !removed&& let Some((browser_context_id, _)) = owner_identity.as_ref()@@ -1107,9 +1119,9 @@ fn start_devtools_remove_preload_script_command(DevToolsProtocol::Cdp => "Script not found",DevToolsProtocol::WebDriverClassic | DevToolsProtocol::WebDriverBidi => "NoSuchScript",};- return PageCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message));+ return Err(CommandOutputPlan::error(-32000, message));}- start_document_start_script_remove(conn, command_id, command_session_id, registry_key)+ Ok(registry_key)}fn remove_stored_document_start_script_registry_key(diff --git a/moli-protocol/src/domains/page/preload/native.rs b/moli-protocol/src/domains/page/preload/native.rsnew file mode 100644index 000000000..48d05c649--- /dev/null+++ b/moli-protocol/src/domains/page/preload/native.rs@@ -0,0 +1,137 @@+//! CDP world/preload handlers finish at the renderer. Browser keeps only the+//! desired preload registry for future documents. BiDi channel installation+//! and initial navigation remain explicitly Browser-owned composite tasks.+use super::*;+use crate::domains::native::{self, NativeCommandStep};+use moli_core::{+ RendererNativeOperation as Operation, RendererNativeProtocolResponse as Response,+ RendererPageCommand as Command, RendererPageReply as Reply,+};++pub(in crate::domains::page) fn try_start(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ action: crate::domains::actions::PageAction,+) -> Option<NativeCommandStep> {+ use crate::domains::actions::PageAction;+ let operation = match action {+ PageAction::CreateIsolatedWorld => {+ let params: CreateIsolatedWorldParams = match cmd.get_params() {+ Ok(Some(params)) => params,+ _ => {+ return Some(NativeCommandStep::Complete(CommandOutputPlan::error(+ -32602,+ "InvalidParams",+ )));+ }+ };+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let (_, Some(target_id)) = conn.target_owner_identity_for_owner(&owner)? else {+ return None;+ };+ let task = prepare_create_isolated_world_task(conn, cmd.session_id, target_id, params)?;+ if task.has_bidi_channel_argument+ || conn+ .runtime_session_owner_can_start_initial_document_navigation_for_owner(&owner)+ {+ return None;+ }+ let child = task.params.frame_id != task.target_id;+ let session = conn.target_renderer_runtime_inspector_session_id_for_owner(&owner);+ Ok(Operation::new(+ Command::CreateIsolatedWorldRuntimeActivity {+ inspector_session_id: session,+ frame_id: child.then_some(task.params.frame_id),+ name: task.params.world_name,+ grant_universal_access: task.params.grant_universal_access,+ },+ move |reply| match reply {+ Ok(Reply::ExecutionContextId(id)) => {+ Response::success(json!({"executionContextId": id}))+ }+ Err(error) => Response::error(+ -32000,+ if child {+ "NoFrameForGivenId".to_owned()+ } else {+ error.to_string()+ },+ ),+ _ => unreachable!("Page isolated world reply"),+ },+ ))+ }+ PageAction::AddScriptToEvaluateOnNewDocument => add(conn, cmd),+ PageAction::RemoveScriptToEvaluateOnNewDocument => remove(conn, cmd),+ _ => return None,+ };+ Some(match operation {+ // World creation and immediate preloads acquire the document isolate.+ Ok(operation) => native::start_operation(conn, cmd, operation),+ Err(plan) => NativeCommandStep::Complete(plan),+ })+}++fn add(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Result<Operation, CommandOutputPlan> {+ let params: AddScriptToEvaluateOnNewDocumentParams = cmd+ .get_params()+ .ok()+ .flatten()+ .ok_or_else(|| CommandOutputPlan::error(-32602, "InvalidParams"))?;+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let (context, target) = conn+ .target_owner_identity_for_owner(&owner)+ .ok_or_else(|| CommandOutputPlan::error(-31998, "TargetNotLoaded"))?;+ let command =+ build_cdp_add_preload_script_command(cmd, target.as_deref(), Some(&context), params);+ let script = document_start_script_from_add_preload_command(&command)+ .map_err(CommandOutputPlan::from_devtools_error)?;+ let session = conn.target_renderer_runtime_inspector_session_id_for_owner(&owner);+ let script_owner = DevToolsSessionKey::from_wire_session_id(session.as_deref());+ let recorded = conn+ .with_target_owner_state_for_owner_mut(&owner, |state| {+ record_document_start_script(state, target.as_deref(), Some(&script_owner), &script)+ })+ .ok_or_else(|| CommandOutputPlan::error(-31998, "TargetNotLoaded"))?;+ let identifier = recorded.identifier;+ if !recorded.inserted {+ return Err(add_preload_script_result_plan(identifier));+ }+ Ok(Operation::new(+ Command::AddDocumentStartScriptRuntimeActivity {+ inspector_session_id: session,+ script: recorded.script,+ run_immediately: command.run_immediately,+ },+ move |reply| match reply {+ Ok(Reply::DocumentStartScriptResult(_)) => {+ add_preload_script_result_plan(identifier).into_native_response()+ }+ Err(error) => Response::error(-32000, error.to_string()),+ _ => unreachable!("Page preload append reply"),+ },+ ))+}++fn remove(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Result<Operation, CommandOutputPlan> {+ let params: RemoveScriptToEvaluateOnNewDocumentParams = cmd+ .get_params()+ .ok()+ .flatten()+ .ok_or_else(|| CommandOutputPlan::error(-32602, "InvalidParams"))?;+ let (context, target) = conn+ .target_owner_identity_for_session(cmd.session_id)+ .ok_or_else(|| CommandOutputPlan::error(-31998, "TargetNotLoaded"))?;+ let command =+ build_cdp_remove_preload_script_command(cmd, target.as_deref(), Some(&context), params);+ let registry_key = remove_preload_script_registration(conn, cmd.session_id, command)?+ .ok_or_else(CommandOutputPlan::success)?;+ Ok(Operation::new(+ Command::RemoveDocumentStartScriptByRegistryKey(registry_key),+ |reply| match reply {+ Ok(Reply::Unit) => Response::success(json!({})),+ Err(error) => Response::error(-32000, error.to_string()),+ _ => unreachable!("Page preload remove reply"),+ },+ ))+}diff --git a/moli-protocol/src/domains/page/resource_tree.rs b/moli-protocol/src/domains/page/resource_tree.rsindex 18a4be3c7..9ca98fa1e 100644--- a/moli-protocol/src/domains/page/resource_tree.rs+++ b/moli-protocol/src/domains/page/resource_tree.rs@@ -33,7 +33,7 @@ pub(super) fn get_frame_tree_command_output_plan(}))}-pub(super) fn frame_tree_payload(+fn frame_tree_payload(target_id: String,target_loader_id: String,target_url: String,@@ -470,6 +470,11 @@ pub(super) fn start_devtools_get_frame_tree_command(}};let target_unreachable_url = network_error_page_unreachable_url(conn, &owner, &target_url);+ let target_url = if pending_initial_document_url(conn, &owner).is_some() {+ ":".to_owned()+ } else {+ target_url+ };let target_loader_id = frame_tree_loader_id_for_current_owner(conn, &owner);if conn.ensure_document_accessible_for_owner(&owner).is_err() {return PageCommandTaskStep::Complete(get_frame_tree_command_output_plan(@@ -657,6 +662,80 @@ fn attach_resources_to_frame(}}+/// Blink initializes a DocumentLoader with an empty URL, while the initial+/// DOM document exposes about:blank. InspectorPageAgent serializes that empty+/// loader URL as ":". Moli materializes both using the initial document URL,+/// so retain the lifecycle distinction until the target's first navigation+/// replaces it. An ordinary ready about:blank target needs no replacement.+/// This is independent of debugger suspension and response delivery mode.+fn pending_initial_document_url(conn: &CdpConnection, owner: &CommandOwnerScope) -> Option<String> {+ conn.runtime_session_owner_initial_empty_document_has_replacement_url_for_owner(owner)+ .then(|| conn.runtime_session_owner_record_initial_empty_document_url_for_owner(owner))+ .flatten()+}++/// Resolve both children and resource records before publishing the terminal.+/// Browser identity is fixed at admission; URL, MIME and resource content come+/// from the renderer's immutable state for the completed command turn.+pub(super) fn prepare_native_tree(+ conn: &CdpConnection,+ cmd: &Cmd<'_>,+ resources: bool,+) -> Result<moli_core::RendererNativeOperation, CommandOutputPlan> {+ use moli_core::{+ RendererNativeOperation as Operation, RendererNativeProtocolResponse as Response,+ RendererPageCommand as Command, RendererPageReply as Reply,+ };+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let (target_id, target_url, security_origin, secure_context_type) = conn+ .target_session_owner_frame_tree_identity_for_owner(&owner)+ .ok_or_else(|| CommandOutputPlan::error(-31998, "TargetNotLoaded"))?;+ let unreachable_url = network_error_page_unreachable_url(conn, &owner, &target_url);+ let loader_id = frame_tree_loader_id_for_current_owner(conn, &owner);+ let initial_document_url = pending_initial_document_url(conn, &owner);+ Ok(Operation::with_page_state(+ Command::ChildFrameTreeSnapshot,+ move |reply, state| match reply {+ Ok(Reply::ChildFrameTreeSnapshots(children)) => {+ // A preceding renderer command may already have changed the+ // document URL before its Browser adapter applies the state.+ // Only project the initial loader while that document is current.+ let document_url =+ if initial_document_url.as_deref() == Some(state.final_url.as_str()) {+ ":".to_owned()+ } else {+ state.final_url.to_string()+ };+ let tree = frame_tree_payload(+ target_id,+ loader_id,+ document_url,+ unreachable_url,+ security_origin,+ secure_context_type,+ moli_web_mime::effective_response_mime_essence(&state.headers, None)+ .unwrap_or_else(default_document_mime_type),+ children,+ );+ let tree = if resources {+ attach_frame_resources(+ tree,+ state.script_execution.subresource_network_records(),+ )+ } else {+ tree+ };+ Response::success(json!({"frameTree": tree}))+ }+ Err(error) => Response::error(+ -32000,+ format!("Failed to snapshot child frame tree: {error}"),+ ),+ _ => unreachable!("Page frame tree reply"),+ },+ ))+}+#[cfg(test)]mod tests {use super::*;diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rsindex b91493412..2e3dd6770 100644--- a/moli-protocol/src/domains/page/tests/capture.rs+++ b/moli-protocol/src/domains/page/tests/capture.rs@@ -7,6 +7,98 @@ use serde_json::Value;mod emulation;+#[tokio::test(flavor = "multi_thread")]+async fn native_snapshot_reads_live_url_and_html_before_adapter_settlement() {+ use moli_core::{RendererNativeOperation, RendererNativeProtocolResponse, RendererPageCommand};+ let mut ctx = TestContext::new();+ let original_url = "https://snapshot.test/start";+ load_bc_with_target(&mut ctx, "BID-SNAPSHOT", "TID-SNAPSHOT", original_url);+ ctx.install_buffered_navigation_fixture_for_session_owner(+ url::Url::parse(original_url).unwrap(),+ "<!doctype html><body>original</body>".to_owned(),+ None,+ )+ .await;+ let (pending, guard) = ctx.conn.loaded_page_mut_for_protocol_access(None).unwrap()+ .start_native_frontend_command(1200, None, RendererNativeOperation::new(+ RendererPageCommand::EvaluateExpression {+ expression: "history.replaceState(null, '', '#current'); document.body.innerHTML = '<p>snapshot current</p>'".to_owned(),+ await_promise: false,+ },+ |reply| { reply.unwrap(); RendererNativeProtocolResponse::success(json!({})) },+ )).unwrap();+ // The renderer is done, but its adapter has not applied the new Page state.+ // A later handler must capture live document metadata independently.+ let held_completion = pending.wait().await.unwrap();+ assert_eq!(+ ctx.conn+ .loaded_page_mut_for_protocol_access(None)+ .unwrap()+ .final_url()+ .as_str(),+ original_url+ );+ let commands = [+ (1201, "Page.captureSnapshot"),+ (1202, "Page.getFrameTree"),+ (1203, "Page.getResourceTree"),+ ]+ .into_iter()+ .map(|(id, method)| {+ let raw = json!({"id": id, "method": method}).to_string();+ let pending = ctx.conn.try_start_pending_command_dispatch(&raw).unwrap();+ assert_eq!(pending.kind_name(), "Native");+ pending+ })+ .collect::<Vec<_>>();+ let mut commands = commands.into_iter();+ let pending = commands.next().unwrap();+ let (messages, _) = ctx+ .complete_command_task_step_for_test(crate::conn::CdpCommandTaskStep::Pending(Box::new(+ pending,+ )))+ .await;+ let response = messages+ .iter()+ .find(|message| message["id"] == 1201)+ .unwrap();+ let snapshot = response["result"]["data"].as_str().unwrap();+ assert!(+ snapshot.contains("Content-Location: https://snapshot.test/start#current\r\n"),+ "{snapshot}"+ );+ let html = snapshot+ .split("\r\n\r\n")+ .nth(2)+ .unwrap()+ .split("\r\n--")+ .next()+ .unwrap();+ let html = BASE64_STANDARD.decode(html).unwrap();+ assert!(+ String::from_utf8(html)+ .unwrap()+ .contains("<p>snapshot current</p>")+ );+ for (id, pending) in [1202, 1203].into_iter().zip(commands) {+ let (messages, _) = ctx+ .complete_command_task_step_for_test(crate::conn::CdpCommandTaskStep::Pending(+ Box::new(pending),+ ))+ .await;+ let response = messages.iter().find(|message| message["id"] == id).unwrap();+ assert_eq!(+ response["result"]["frameTree"]["frame"]["url"],+ "https://snapshot.test/start#current"+ );+ if id == 1203 {+ assert!(response["result"]["frameTree"]["resources"].is_array());+ }+ }+ assert!(guard.cancel_or_published().await.is_some());+ drop(held_completion);+}+/// cdp.page: captureScreenshot – invalid image format#[tokio::test(flavor = "multi_thread")]async fn capture_screenshot_bad_format() {diff --git a/moli-protocol/src/domains/page/tests/frame_tree.rs b/moli-protocol/src/domains/page/tests/frame_tree.rsindex c0d59d40f..a2ed98d2b 100644--- a/moli-protocol/src/domains/page/tests/frame_tree.rs+++ b/moli-protocol/src/domains/page/tests/frame_tree.rs@@ -1,5 +1,144 @@use super::*;+async fn assert_initial_document_frame_tree_waits_for_navigation(popup: bool) {+ let mut ctx = TestContext::new();+ ctx.enable_background_navigation_scheduler_for_test();+ load_bc_with_target(&mut ctx, "BID-INITIAL-TREE", "TID-OPENER", "about:blank");+ ctx.install_navigation_fixture_for_session_owner("about:blank", None)+ .await;+ ctx.process_async(json!({+ "id": 2000,+ "method": "Target.setAutoAttach",+ "params": { "autoAttach": true, "waitForDebuggerOnStart": true, "flatten": true }+ }))+ .await;+ ctx.take_all();+ let url = "data:text/html,<title>initial-tree-committed</title>";+ let create = if popup {+ json!({+ "id": 2001,+ "method": "Runtime.evaluate",+ "params": { "expression": format!("void window.open({})", json!(url)) }+ })+ } else {+ json!({ "id": 2001, "method": "Target.createTarget", "params": { "url": url } })+ };+ ctx.process_async(create).await;+ let created = ctx.take_all();+ let attached = created+ .iter()+ .find(|message| {+ message["method"] == "Target.attachedToTarget"+ && message["params"]["targetInfo"]["url"] == url+ })+ .expect("initial target attachment");+ assert_eq!(attached["params"]["waitingForDebugger"], true);+ let session = attached["params"]["sessionId"].as_str().unwrap();+ let target = attached["params"]["targetInfo"]["targetId"]+ .as_str()+ .unwrap();+ ctx.process_async(json!({ "id": 2002, "method": "Page.enable", "sessionId": session }))+ .await;+ ctx.take_all();++ // Chromium's initial DocumentLoader URL serializes as ":", although the+ // initial DOM document has location.href == "about:blank". Playwright+ // uses this distinction to wait for the popup's first real commit.+ let mut initial_loader = None;+ for (id, method) in [(2003, "Page.getFrameTree"), (2004, "Page.getResourceTree")] {+ let raw = json!({ "id": id, "method": method, "sessionId": session }).to_string();+ let pending = ctx.conn.try_start_pending_command_dispatch(&raw).unwrap();+ assert_eq!(pending.kind_name(), "Native");+ let (messages, _) = ctx+ .complete_command_task_step_for_test(crate::conn::CdpCommandTaskStep::Pending(+ Box::new(pending),+ ))+ .await;+ let reply = messages.iter().find(|message| message["id"] == id).unwrap();+ let frame = &reply["result"]["frameTree"]["frame"];+ assert_eq!(frame["id"], target);+ assert_eq!(frame["url"], ":", "{method}: {reply}");+ if let Some(loader) = &initial_loader {+ assert_eq!(&frame["loaderId"], loader);+ } else {+ assert!(!frame["loaderId"].as_str().unwrap().is_empty());+ initial_loader = Some(frame["loaderId"].clone());+ }+ }+ ctx.process_async(json!({+ "id": 2005, "method": "Runtime.evaluate", "sessionId": session,+ "params": { "expression": "location.href", "returnByValue": true }+ }))+ .await;+ assert_eq!(+ take_response_by_id(&mut ctx, 2005)["result"]["result"]["value"],+ "about:blank"+ );+ ctx.process_async(json!({+ "id": 2006, "method": "Runtime.runIfWaitingForDebugger", "sessionId": session+ }))+ .await;+ let committed = ctx+ .wait_for_scheduler_message("first target document commit", |message| {+ message["method"] == "Page.frameNavigated"+ && message["sessionId"] == session+ && message["params"]["frame"]["url"] == url+ })+ .await;+ let committed_loader = committed["params"]["frame"]["loaderId"].clone();+ assert_ne!(Some(&committed_loader), initial_loader.as_ref());+ for (id, method) in [(2007, "Page.getFrameTree"), (2008, "Page.getResourceTree")] {+ ctx.process_async(json!({ "id": id, "method": method, "sessionId": session }))+ .await;+ let reply = take_response_by_id(&mut ctx, id);+ let frame = &reply["result"]["frameTree"]["frame"];+ assert_eq!(frame["url"], url);+ assert_eq!(frame["loaderId"], committed_loader);+ }+}++#[tokio::test(flavor = "multi_thread")]+async fn native_popup_frame_tree_distinguishes_initial_document_from_first_commit() {+ tokio::task::LocalSet::new()+ .run_until(assert_initial_document_frame_tree_waits_for_navigation(+ true,+ ))+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn native_created_target_frame_tree_distinguishes_initial_document_from_first_commit() {+ tokio::task::LocalSet::new()+ .run_until(assert_initial_document_frame_tree_waits_for_navigation(+ false,+ ))+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn initial_document_frame_tree_without_renderer_does_not_claim_the_destination_url() {+ let mut ctx = TestContext::new();+ load_bc_with_target(+ &mut ctx,+ "BID-INITIAL-TREE-METADATA",+ "TID-INITIAL-TREE-METADATA",+ "https://initial.test/not-committed",+ );+ ctx.conn+ .browser_context+ .as_mut()+ .unwrap()+ .begin_active_target_initial_empty_document("about:blank".to_owned());+ for (id, method) in [(2010, "Page.getFrameTree"), (2011, "Page.getResourceTree")] {+ ctx.process_async(json!({ "id": id, "method": method }))+ .await;+ let reply = take_response_by_id(&mut ctx, id);+ let frame = &reply["result"]["frameTree"]["frame"];+ assert_eq!(frame["url"], ":");+ assert!(!frame["loaderId"].as_str().unwrap().is_empty());+ }+}+async fn complete_child_frame_lifecycle(ctx: &mut TestContext) {let owner = crate::conn::CommandOwnerScope::capture(&ctx.conn, None);let pending = ctx@@ -486,7 +625,7 @@ async fn get_frame_tree_can_complete_through_pending_command_dispatch() {);}#[tokio::test(flavor = "multi_thread")]-async fn pending_get_frame_tree_after_page_unload_returns_empty_target_tree() {+async fn completed_get_frame_tree_survives_page_unload_before_projection() {let mut ctx = TestContext::new();let page_url = "data:text/html,<iframe name='pending-child'></iframe>";load_bc_with_session(@@ -519,6 +658,10 @@ async fn pending_get_frame_tree_after_page_unload_returns_empty_target_tree() {.conn.try_start_pending_command_dispatch(&raw).expect("Page.getFrameTree should start as a pending command for loaded pages");+ // The producer has committed a complete snapshot; protocol has not+ // projected it yet. Removing the Page now must neither rewrite that+ // result to an empty tree nor install its state onto a replacement Page.+ let completed = pending.wait().await;ctx.conn.browser_context.as_mut()@@ -527,8 +670,12 @@ async fn pending_get_frame_tree_after_page_unload_returns_empty_target_tree() {.runtime_slot.clear_loaded_page_for_test_fixture();- let (messages, scheduler_events) =- complete_pending_command_task_for_test(&mut ctx, pending).await;+ let CdpCommandTaskStep::Complete(outcome) =+ ctx.conn.complete_pending_command_dispatch(completed).await+ else {+ panic!("a published frame tree must require no further renderer work");+ };+ let (messages, scheduler_events) = ctx.route_completed_command_outcome_for_test(outcome).await;assert!(scheduler_events.is_empty(),"Page.getFrameTree should not enqueue scheduler events: {scheduler_events:?}"@@ -545,9 +692,21 @@ async fn pending_get_frame_tree_after_page_unload_returns_empty_target_tree() {response["result"]["frameTree"]["frame"]["id"],json!("TID-PENDING-FRAME-TREE-UNLOAD"));- assert!(- response["result"]["frameTree"].get("childFrames").is_none(),- "unloaded page should match the legacy empty child frame tree path: {response}"+ assert_eq!(+ response["result"]["frameTree"]["frame"]["url"],+ json!(page_url)+ );+ assert_eq!(+ response["result"]["frameTree"]["childFrames"][0]["frame"]["name"],+ json!("pending-child")+ );+ assert_eq!(+ messages+ .iter()+ .filter(|message| message["id"] == json!(1206))+ .count(),+ 1,+ "a committed snapshot must have exactly one response: {messages:#?}");}#[tokio::test(flavor = "multi_thread")]diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rsindex 92edc037d..4d7427d25 100644--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs@@ -258,7 +258,7 @@ async fn rust_cdp_chromiumoxide_loaded_target_replays_renderer_lifecycle_when_en}#[tokio::test(flavor = "multi_thread")]-async fn create_isolated_world_restart_does_not_inherit_the_stale_renderer_stream() {+async fn internal_create_isolated_world_restart_does_not_inherit_the_stale_renderer_stream() {let fixture = SmokeFixtureServer::start().await;let mut ctx = TestContext::new_with_target_discovery(false);let target_id = create_target(&mut ctx, 2_600_070, None, "about:blank").await;@@ -280,6 +280,11 @@ async fn create_isolated_world_restart_does_not_inherit_the_stale_renderer_strea})).expect("createIsolatedWorld command should parse");let mut command_context = CommandDispatchContext::default();+ // An internal composite query has no frontend terminal until its Browser+ // continuation settles. Its stale attachment must still restart correctly.+ command_context.set_terminal_response_delivery_override(+ moli_page_types::RendererInspectorResponseDelivery::AdapterReply,+ );let CdpCommandTaskStep::Pending(first_pending) = ctx.conn.start_parsed_command_dispatch_with_context(&command, &mut command_context)@@ -326,6 +331,63 @@ async fn create_isolated_world_restart_does_not_inherit_the_stale_renderer_strea);}+#[tokio::test(flavor = "multi_thread")]+async fn published_create_isolated_world_response_survives_navigation_without_restarting() {+ let fixture = SmokeFixtureServer::start().await;+ let mut ctx = TestContext::new_with_target_discovery(false);+ let target = create_target(&mut ctx, 2_600_080, None, "about:blank").await;+ let session = attach_to_target(&mut ctx, 2_600_081, None, &target).await;+ ctx.take_all();+ let raw = json!({"id": 2_600_082, "sessionId": session, "method": "Page.createIsolatedWorld",+ "params": {"frameId": target, "worldName": "published-world"}})+ .to_string();+ let pending = ctx.conn.try_start_pending_command_dispatch(&raw).unwrap();+ assert_eq!(pending.kind_name(), "Native");+ // Publication has won, but the adapter remains deliberately unprocessed.+ let completed = pending.wait().await;+ ctx.process_async(+ json!({"id": 2_600_083, "sessionId": session, "method": "Page.navigate",+ "params": {"url": fixture.url("/plain?replacement=published-world")}}),+ )+ .await;+ let messages = ctx.take_all();+ let terminals = messages+ .iter()+ .filter(|message| message["id"] == 2_600_082)+ .collect::<Vec<_>>();+ assert_eq!(terminals.len(), 1, "{messages:?}");+ assert!(terminals[0]["result"]["executionContextId"].is_i64());+ let CdpCommandTaskStep::Complete(outcome) =+ ctx.conn.complete_pending_command_dispatch(completed).await+ else {+ panic!("a published frontend response must never restart");+ };+ let (trailing, _) = ctx.route_completed_command_outcome_for_test(outcome).await;+ assert!(+ trailing.iter().all(|message| message["id"] != 2_600_082),+ "{trailing:?}"+ );+ ctx.process_async(+ json!({"id": 2_600_084, "sessionId": session, "method": "Page.createIsolatedWorld",+ "params": {"frameId": target, "worldName": "published-world"}}),+ )+ .await;+ let current = take_response_by_id(&mut ctx, 2_600_084);+ let context = current["result"]["executionContextId"].as_i64().unwrap();+ // Numeric context ids belong to an isolate and can be reused by the new+ // renderer. Verify that the world actually belongs to the new document.+ ctx.process_async(json!({+ "id": 2_600_085, "sessionId": session, "method": "Runtime.evaluate",+ "params": {"contextId": context, "expression": "location.href", "returnByValue": true}+ }))+ .await;+ let evaluation = take_response_by_id(&mut ctx, 2_600_085);+ assert_eq!(+ evaluation["result"]["result"]["value"],+ fixture.url("/plain?replacement=published-world")+ );+}+#[tokio::test(flavor = "multi_thread")]async fn rust_cdp_chromiumoxide_loaded_background_target_replays_own_renderer_lifecycle() {let mut ctx = TestContext::new_with_target_discovery(false);diff --git a/moli-renderer-v8/src/devtools/command.rs b/moli-renderer-v8/src/devtools/command.rsindex 9962e30ef..d39672495 100644--- a/moli-renderer-v8/src/devtools/command.rs+++ b/moli-renderer-v8/src/devtools/command.rs@@ -1,5 +1,7 @@//! Typed metadata and payloads crossing the renderer DevTools ingress boundary.+mod nested;+use crate::runtime::{RendererInspectorPageCommand, RendererPageCommand, RendererRuntimeInspectorResponseSender,};@@ -288,8 +290,8 @@ impl RendererDevToolsIoCommandEnvelope {/// Unlike `RendererInspectorCommandEnvelope`, this envelope is deliberately/// agent-neutral: protocol commands that ultimately need the renderer Page,/// DOM, CSS, Accessibility, or V8 agents all enter the same Main receiver.-/// The boxed payload keeps that admission boundary structural without adding-/// a second allowlist of `RendererPageCommand` variants.+/// The payload retains the backend entry requirement for both internal queries+/// and frontend native operations; wrapping a command cannot make it reentrant.#[doc(hidden)]pub struct RendererDevToolsMainCommandEnvelope {ticket: RendererInspectorIngressTicket,@@ -331,15 +333,7 @@ impl RendererDevToolsMainCommandEnvelope {}pub(crate) fn nested_dispatch(&self) -> RendererDevToolsMainNestedDispatch {- match self.payload.as_ref() {- RendererPageCommand::Inspector(envelope)- if envelope.can_dispatch_at_nested_inspector_session_boundary() =>- {- RendererDevToolsMainNestedDispatch::InspectorSession- }- RendererPageCommand::Inspector(_) => RendererDevToolsMainNestedDispatch::OwnerOnly,- _ => RendererDevToolsMainNestedDispatch::PageAgent,- }+ self.payload.nested_dispatch()}pub(crate) fn inspector_envelope(&self) -> Option<&RendererInspectorCommandEnvelope> {diff --git a/moli-renderer-v8/src/devtools/command/nested.rs b/moli-renderer-v8/src/devtools/command/nested.rsnew file mode 100644index 000000000..3e2464266--- /dev/null+++ b/moli-renderer-v8/src/devtools/command/nested.rs@@ -0,0 +1,201 @@+//! Backend entry requirements shared by internal queries and native frontend+//! operations. They are independent of who owns the terminal response.++use super::RendererDevToolsMainNestedDispatch;+use crate::runtime::{RendererPageCommand, RendererScreenshotPurpose};++impl RendererPageCommand {+ pub(crate) fn nested_dispatch(&self) -> RendererDevToolsMainNestedDispatch {+ use RendererDevToolsMainNestedDispatch::{InspectorSession, OwnerOnly, PageAgent};+ match self {+ Self::Native(command) => {+ if command.operation.can_dispatch_on_nested_main() {+ PageAgent+ } else {+ OwnerOnly+ }+ }+ Self::Inspector(envelope)+ if envelope.can_dispatch_at_nested_inspector_session_boundary() =>+ {+ InspectorSession+ }+ Self::Inspector(_) => OwnerOnly,+ // Printing temporarily switches media and synchronizes document+ // fonts through V8. A regular screenshot only reads native layout.+ Self::CaptureScreenshot(request)+ if matches!(request.purpose, RendererScreenshotPurpose::Screenshot) =>+ {+ PageAgent+ }+ // These handlers read native document/agent state without entering+ // a new V8 scope. They can use the existing pause callback boundary.+ Self::HasPendingLocationNavigation+ | Self::DomDebuggerConfigureEventListenerBreakpoint { .. }+ | Self::DomDebuggerConfigureXhrBreakpoint { .. }+ | Self::DomDebuggerConfigureDomBreakpoint { .. }+ | Self::ComputedStylePropertiesForBackendNodeId { .. }+ | Self::ClientRectForBackendNodeId { .. }+ | Self::DocumentGeometryForBackendNodeId { .. }+ | Self::DocumentHitTest { .. }+ | Self::NodeHasGeometryForBackendNodeId { .. }+ | Self::DocumentNodeSnapshotForBackendNodeId { .. }+ | Self::DocumentNodeSnapshotForBackendNodeIdInInspectorSession { .. }+ | Self::DocumentNodeSnapshotForDocument { .. }+ | Self::DiscardDomAgentFrontendBindings { .. }+ | Self::DomSnapshotCapture { .. }+ | Self::DocumentChildNodeSnapshotEventsForBackendNodeId { .. }+ | Self::DocumentQuerySelectorForDocument { .. }+ | Self::DocumentQuerySelectorForChildFrameBackendNodeId { .. }+ | Self::DocumentQuerySelectorForBackendNodeId { .. }+ | Self::DocumentQuerySelectorWithChildNodeSnapshotEventsForBackendNodeId { .. }+ | Self::DocumentPerformSearch { .. }+ | Self::DocumentGetSearchResults { .. }+ | Self::DocumentDiscardSearchResults { .. }+ | Self::DocumentSetNodeStackTracesEnabled { .. }+ | Self::DocumentNodeStackTrace { .. }+ | Self::DocumentFrontendNodeBinding { .. }+ | Self::RegisterDocumentBidiNodeBinding { .. }+ | Self::DocumentBidiNodeBinding { .. }+ | Self::DocumentBidiNodeSharedIdForBackendNodeId { .. }+ | Self::DocumentNodeAttributesForBackendNodeId { .. }+ | Self::DocumentNodeTextForBackendNodeId { .. }+ | Self::DocumentNodePropertyForBackendNodeId { .. }+ | Self::AccessibilityTreePayloadsForDocument { .. }+ | Self::AccessibilityNodePayloadForDocument+ | Self::AccessibilityTreePayloadsForBackendNodeId { .. }+ | Self::AccessibilityNodePayloadForBackendNodeId { .. }+ | Self::AccessibilityNodeAndAncestorPayloadsForBackendNodeId { .. }+ | Self::AccessibilityChildNodePayloadsForBackendNodeId { .. }+ | Self::AccessibilityPartialTreePayloadsForBackendNodeId { .. }+ | Self::AccessibilityTreePayloadsForChildFrame { .. }+ | Self::AccessibilityNodePayloadForChildFrame { .. }+ | Self::StyleSheetPayloadForStyleSheetId { .. }+ | Self::StyleSheetInventoryForDocument { .. }+ | Self::ResetCssAgentSession { .. }+ | Self::OuterHtmlForDocument { .. }+ | Self::OuterHtmlForBackendNodeId { .. }+ | Self::SerializeHtml+ | Self::SerializeDocument+ | Self::LayoutMetrics+ | Self::PublishLayout+ | Self::CaptureScreencastFrame(..)+ | Self::BlobBytesForUuid { .. }+ | Self::DocumentFrontendNodeIdsForBackendNodeIds { .. }+ | Self::DocumentStorageKeySnapshot+ | Self::ChildFrameTreeSnapshot+ | Self::ChildFrameOwnerNodeReference { .. }+ | Self::ChildFrameDocumentRootNodeReference { .. }+ | Self::PendingSubresourceRequestCount+ | Self::SetFetchSubresourceInterception { .. }+ | Self::SetJavaScriptDialogHandlerEnabled(..)+ | Self::SetExtraHttpHeaders(..)+ | Self::SetNetworkRequestPolicy { .. }+ | Self::SetPermissionOverrides(..)+ | Self::SetScriptExecutionDisabled(..)+ | Self::SetBypassContentSecurityPolicy(..)+ | Self::SetNetworkOffline(..)+ | Self::SetBypassServiceWorker(..)+ | Self::SetBlockedUrlPatterns(..)+ | Self::MsToNextTimeout => PageAgent,++ // These handlers enter V8, run script/lifecycle continuations, or+ // own work whose nested execution has no supported entry point.+ // Keep this match exhaustive: a new backend command must declare+ // its entry requirement instead of inheriting PageAgent by default.+ Self::EvaluateExpression { .. }+ | Self::EvaluateExpressionByValue { .. }+ | Self::EvaluateExpressionAndFollowPendingNavigation { .. }+ | Self::EvaluateExpressionInExecutionContext { .. }+ | Self::EvaluateExpressionInExecutionContextAndFollowPendingNavigation { .. }+ | Self::WaitForSelector { .. }+ | Self::WaitForScriptTruthy { .. }+ | Self::WaitForSubresourceResponse { .. }+ | Self::CompleteChildFrameLifecycleWorkBestEffort { .. }+ | Self::SetDocumentContent { .. }+ | Self::NavigateChildFrame { .. }+ | Self::NavigateTopLevelSameDocument { .. }+ | Self::RefreshFullPageState+ | Self::PageDiagnosticsSnapshot+ | Self::DispatchPreparedElementClick(..)+ | Self::DispatchMouseEventAtPoint { .. }+ | Self::DispatchTouchEvent { .. }+ | Self::DispatchDragEventAtPoint { .. }+ | Self::ClearActiveDragDataTransfer+ | Self::InsertTextIntoActiveControl(..)+ | Self::DispatchKeyEvent { .. }+ | Self::CreateIsolatedWorld { .. }+ | Self::CreateIsolatedWorldRuntimeActivity { .. }+ | Self::InstallRuntimeBinding { .. }+ | Self::RemoveRuntimeBinding(..)+ | Self::RemoveDefaultRuntimeBinding(..)+ | Self::QueueTopLevelHistoryTraversalByDelta(..)+ | Self::RunPageSurfaceOverrideScript { .. }+ | Self::AddDocumentStartScriptRuntimeActivity { .. }+ | Self::RemoveDocumentStartScriptByRegistryKey(..)+ | Self::SetRuntimeBindingState { .. }+ | Self::DefaultExecutionContextId+ | Self::DefaultOrInitialExecutionContextId+ | Self::HasIsolatedWorldNamed { .. }+ | Self::HasIsolatedExecutionContextId(..)+ | Self::EnsureIsolatedWorldsAttachedToInspector+ | Self::InspectorExecutionContextIdForIsolatedContext(..)+ | Self::IsolatedExecutionContextIdForInspectorContext(..)+ | Self::RuntimeRealmInventory+ | Self::LiveChildDefaultRuntimeRealmInventory+ | Self::ChildFrameIdForDefaultExecutionContextId(..)+ | Self::ChildDefaultExecutionContextIdForFrameId(..)+ | Self::RuntimeConsoleMessagesWithContext+ | Self::RuntimeHeapUsage+ | Self::PerformanceMetricSnapshot+ | Self::RuntimeCollectGarbage+ | Self::StopDocumentLifecycle+ | Self::SetInlineStyleSheetTextForStyleSheetId { .. }+ | Self::ScrollBackendNodeIntoViewIfNeeded { .. }+ | Self::RemoveDocumentBackendNodeId { .. }+ | Self::MutateDocumentBackendNodeAttribute { .. }+ | Self::EditDocumentNode { .. }+ | Self::FocusDocumentBackendNode { .. }+ | Self::TriggerAutofill(..)+ | Self::ResetNavigationHistory+ | Self::SetFileInputFilesForBackendNodeId { .. }+ | Self::RenderPageDump { .. }+ | Self::CaptureScreenshot(..)+ | Self::SearchTextByLines { .. }+ | Self::SearchChildFrameResourceByLines { .. }+ | Self::ContinuePendingSubresourceFetch { .. }+ | Self::ContinuePendingSubresourceAuth { .. }+ | Self::CancelPendingSubresourceAuth { .. }+ | Self::FailPendingSubresourceAuth { .. }+ | Self::FailPendingSubresourceFetch { .. }+ | Self::FulfillPendingSubresourceFetch { .. }+ | Self::ContinuePendingSubresourceResponse { .. }+ | Self::FailPendingSubresourceResponse { .. }+ | Self::FulfillPendingSubresourceResponse { .. }+ | Self::ReceiveSyntheticWebSocketText { .. }+ | Self::ReceiveSyntheticWebSocketBinary { .. }+ | Self::CloseSyntheticWebSocketFromServer { .. }+ | Self::ReplaceBrowserResourceRuntime { .. }+ | Self::RetireDocumentResourceAuthorities+ | Self::ApplyDocumentCookieFacadeOverrides(..)+ | Self::ClearDocumentCookieFacadeOverrides+ | Self::DocumentCookieTelemetrySnapshot+ | Self::DocumentCookieOwnerSnapshot+ | Self::PrepareNetworkResourceLoad { .. }+ | Self::PrepareAppManifestLoad+ | Self::PublishAppManifestLoad(..)+ | Self::SetIdleOverride(..)+ | Self::SetNavigatorOverrides(..)+ | Self::SetDocumentActivity(..)+ | Self::SetEmulatedMedia(..)+ | Self::SetViewportSurface(..) => OwnerOnly,++ #[cfg(test)]+ Self::SetStoredDocumentStartScripts(..) | Self::TakeDocumentLifecycleEvents => {+ OwnerOnly+ }+ #[cfg(debug_assertions)]+ Self::PanicForTesting => OwnerOnly,+ }+ }+}diff --git a/moli-renderer-v8/src/devtools/ingress/io.rs b/moli-renderer-v8/src/devtools/ingress/io.rsindex 80b93402b..6032c063b 100644--- a/moli-renderer-v8/src/devtools/ingress/io.rs+++ b/moli-renderer-v8/src/devtools/ingress/io.rs@@ -301,10 +301,6 @@ pub(crate) struct RendererInspectorIoFirstDispatchGuard {first_dispatch_tx: Option<RendererInspectorIoFirstDispatchSender>,}-pub(crate) struct RendererInspectorIoPostDispatchWakeGuard {- ingress: Option<RendererInspectorIoIngress>,-}-impl Drop for RendererInspectorIoFirstDispatchGuard {fn drop(&mut self) {let has_ready = self.finish_task(RendererRuntimeInspectorIoCommandClaim::Canceled(@@ -317,6 +313,9 @@ impl Drop for RendererInspectorIoFirstDispatchGuard {}impl RendererInspectorIoFirstDispatchGuard {+ /// Release IO admission at backend entry. Wakes post owner work, queue a+ /// V8 interrupt, or signal the pause loop; they do not dispatch inline.+ /// The next IO command must not wait for this command's response.pub(crate) fn release(&mut self) {let has_ready = self.finish_task(RendererRuntimeInspectorIoCommandClaim::Dispatched);if has_ready {@@ -324,17 +323,6 @@ impl RendererInspectorIoFirstDispatchGuard {}}- /// Releases the receiver slot and publishes first-dispatch immediately- /// before entering V8, but keeps the next execution wake behind the return- /// from this dispatch. V8 may enter a nested debugger loop before the call- /// returns, so the command's ingress lifecycle must already be settled.- pub(crate) fn release_for_dispatch(&mut self) -> RendererInspectorIoPostDispatchWakeGuard {- let has_ready = self.finish_task(RendererRuntimeInspectorIoCommandClaim::Dispatched);- RendererInspectorIoPostDispatchWakeGuard {- ingress: has_ready.then(|| self.ingress.clone()),- }- }-pub(crate) fn reject(&mut self, message: impl Into<String>) {let has_ready = self.finish_task(RendererRuntimeInspectorIoCommandClaim::Canceled(message.into(),@@ -362,14 +350,6 @@ impl RendererInspectorIoFirstDispatchGuard {}}-impl Drop for RendererInspectorIoPostDispatchWakeGuard {- fn drop(&mut self) {- if let Some(ingress) = self.ingress.take() {- ingress.notify_execution_opportunities();- }- }-}-impl RendererInspectorIoIngress {pub(crate) fn new(pause_wake: RendererInspectorPauseLoopWake,diff --git a/moli-renderer-v8/src/devtools/ingress/lane.rs b/moli-renderer-v8/src/devtools/ingress/lane.rsindex 458f8c3ba..3eafe3137 100644--- a/moli-renderer-v8/src/devtools/ingress/lane.rs+++ b/moli-renderer-v8/src/devtools/ingress/lane.rs@@ -51,6 +51,12 @@ impl<C> Default for RendererDevToolsSessionLane<C> {/// ends when a command first reaches the target agent; asynchronous response/// completion is deliberately outside that lifetime so a later resume command/// can enter a nested pause loop.+///+/// Native frontend responses and Inspector output are committed to the same+/// renderer journal by their producer. Internal typed completions may be+/// collected in any order by Browser continuations; their receiver polling+/// never gates Main admission. Detach barriers remain attachment cleanup,+/// independent from response delivery.pub(crate) struct RendererDevToolsSessionLanes<C> {sessions: BTreeMap<RendererDevToolsSessionLaneKey, RendererDevToolsSessionLane<C>>,ready_sessions: VecDeque<RendererDevToolsSessionLaneKey>,diff --git a/moli-renderer-v8/src/devtools/ingress/main.rs b/moli-renderer-v8/src/devtools/ingress/main.rsindex d8090dad8..445be50a9 100644--- a/moli-renderer-v8/src/devtools/ingress/main.rs+++ b/moli-renderer-v8/src/devtools/ingress/main.rs@@ -329,10 +329,6 @@ pub(crate) struct RendererInspectorMainFirstDispatchGuard {claim_tx: Option<tokio::sync::oneshot::Sender<RendererInspectorMainCommandClaim>>,}-pub(crate) struct RendererInspectorMainPostDispatchWakeGuard {- ingress: Option<RendererInspectorMainIngress>,-}-pub(crate) struct RendererInspectorMainOwnerDispatch {page_token: RendererPageToken,capture_policy: RendererPageStateCapturePolicy,@@ -375,6 +371,9 @@ impl Drop for RendererInspectorMainFirstDispatchGuard {}impl RendererInspectorMainFirstDispatchGuard {+ /// Release Main admission at backend entry. A wake only queues an owner+ /// turn or signals the pause loop; it cannot dispatch another command+ /// inline, so no separate post-dispatch wake capability is needed.pub(crate) fn release(&mut self) {self.publish_first_dispatch();if self.release_lane() {@@ -382,14 +381,6 @@ impl RendererInspectorMainFirstDispatchGuard {}}- pub(crate) fn release_for_dispatch(&mut self) -> RendererInspectorMainPostDispatchWakeGuard {- self.publish_first_dispatch();- let has_ready = self.release_lane();- RendererInspectorMainPostDispatchWakeGuard {- ingress: has_ready.then(|| self.ingress.clone()),- }- }-pub(crate) fn reject(&mut self, message: impl Into<String>) {if let Some(claim_tx) = self.claim_tx.take() {let _ = claim_tx.send(RendererInspectorMainCommandClaim::Canceled(message.into()));@@ -413,14 +404,6 @@ impl RendererInspectorMainFirstDispatchGuard {}}-impl Drop for RendererInspectorMainPostDispatchWakeGuard {- fn drop(&mut self) {- if let Some(ingress) = self.ingress.take() {- ingress.notify_execution_opportunities();- }- }-}-impl RendererInspectorMainIngress {pub(crate) fn new(route_id: RendererInspectorSessionExecutorRouteId,@@ -1143,6 +1126,53 @@ mod tests {));}+ #[test]+ fn retained_internal_reply_does_not_block_queued_or_new_main_commands() {+ let ingress = ingress();+ let agent = RendererDevToolsAgentToken::allocate();+ let _first = enqueue(+ &ingress,+ agent,+ Some("session-a"),+ r#"{"id":1,"method":"Runtime.getProperties"}"#,+ );+ let _queued = enqueue(+ &ingress,+ agent,+ Some("session-a"),+ r#"{"id":2,"method":"Runtime.getProperties"}"#,+ );+ let mut first = ingress.claim_for_owner().expect("claim first command");+ ingress.first_dispatch_guard(&mut first).release();+ let output = RendererCommandTurnOutput::new(+ RendererPageReply::Unit,+ page_state(),+ RendererRuntimeCommandOutput::default(),+ None,+ None,+ )+ .expect("native reply");+ let reply = RendererOwnerReply::AsyncPageCommandRan(Box::new(output));+ let _new = enqueue(+ &ingress,+ agent,+ Some("session-a"),+ r#"{"id":3,"method":"Runtime.getProperties"}"#,+ );+ // The payload is deliberately still retained while subsequent Main+ // dispatch proceeds. No receiver acknowledgement is an ingress barrier.+ let mut queued = ingress.claim_for_owner().expect("queued command resumes");+ assert!(queued.raw_json().contains(r#""id":2"#));+ ingress.first_dispatch_guard(&mut queued).release();+ let mut new = ingress+ .claim_for_owner()+ .expect("new command follows queued command");+ assert!(new.raw_json().contains(r#""id":3"#));+ ingress.first_dispatch_guard(&mut new).release();+ assert_eq!(ingress.shared.state.lock().lanes.session_count(), 0);+ drop(reply);+ }+#[test]fn mixed_v8_and_page_agents_share_one_main_session_lane() {let ingress = ingress();@@ -1152,7 +1182,7 @@ mod tests {let _page = ingress.enqueue_protocol_page_command(page_token,agent,- RendererPageCommand::PerformanceMetricSnapshot,+ RendererPageCommand::ChildFrameTreeSnapshot,Some("session-a".to_owned()),RendererPageStateCapturePolicy::ProtocolTurn,);@@ -1182,21 +1212,16 @@ mod tests {None,None,)- .expect("test Page-agent output")- .hold_until_protocol_handoff(ingress.first_dispatch_guard(&mut page));- assert!(- ingress.claim_for_pause().is_none(),- "settled Page output must retain the lane until protocol consumes it"- );-- let (_completion, _predecessor) = output.into_completion_and_predecessor();+ .expect("test Page-agent output");+ ingress.first_dispatch_guard(&mut page).release();let v8 = ingress.claim_for_pause()- .expect("the V8 command should follow the Page protocol handoff");+ .expect("the V8 command should follow Page dispatch while its reply is retained");assert_eq!(v8.nested_dispatch(),RendererDevToolsMainNestedDispatch::InspectorSession);+ let (_completion, _predecessor) = output.into_completion_and_predecessor();}#[test]diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rsindex 40a233921..0b7794780 100644--- a/moli-renderer-v8/src/lib.rs+++ b/moli-renderer-v8/src/lib.rs@@ -270,7 +270,11 @@ pub use runtime::{RendererLifecycleEpoch, RendererLifecycleEventStamp, RendererLifecycleSnapshot,RendererLifecycleStartReason, RendererLifecycleTerminationStamp, RendererMainDocumentCommit,RendererMoliDomMemoryDiagnostics, RendererMoliMemoryDiagnostics,- RendererMoliMemoryScopeDiagnostics, RendererMoliRuntimeMemoryDiagnostics, RendererOutputCursor,+ RendererMoliMemoryScopeDiagnostics, RendererMoliRuntimeMemoryDiagnostics,+ RendererNativeCommand, RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard,+ RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep,+ RendererNativeProtocolError, RendererNativeProtocolNotification,+ RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererOutputCursor,RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,RendererOutputStreamCloseReason, RendererOutputStreamControl, RendererOutputStreamEpoch,diff --git a/moli-renderer-v8/src/native_bridge/context_host/activity.rs b/moli-renderer-v8/src/native_bridge/context_host/activity.rsindex cc7fc6b52..2f2d767cb 100644--- a/moli-renderer-v8/src/native_bridge/context_host/activity.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/activity.rs@@ -188,12 +188,19 @@ impl JsContextHost {let Some(output_journal) = self.output_journal.as_ref() else {return false;};- if let Some(recorder) = self.command_turn_output.as_ref() {- output_journal.append_records(recorder.drain_records());- }+ self.append_live_turn_output_prefix();output_journal.publish_pending().is_some()}+ /// Move the completed prefix without ending the active command recorder.+ /// A nested DevTools handler must also resolve DOM facts and Inspector+ /// state before publishing that prefix with its terminal response.+ pub(crate) fn append_live_turn_output_prefix(&self) {+ if let (Some(journal), Some(recorder)) = (&self.output_journal, &self.command_turn_output) {+ journal.append_records(recorder.drain_records());+ }+ }+pub(crate) fn begin_command_turn_output(&mut self,recorder: crate::runtime::RendererCommandTurnOutputRecorder,diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rsindex 7d823993c..2687583cf 100644--- a/moli-renderer-v8/src/runtime/mod.rs+++ b/moli-renderer-v8/src/runtime/mod.rs@@ -411,8 +411,11 @@ pub(in crate::runtime) use self::phase_one::{};pub(crate) use self::protocol_output::{PendingRendererOutputRecord, RendererTurnOutputJournal};pub use self::protocol_output::{- RendererDocumentTitleChanged, RendererOutputCursor, RendererOutputFence,- RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,+ RendererDocumentTitleChanged, RendererNativeCommand, RendererNativeCommandReadyResponse,+ RendererNativeCommandResponseGuard, RendererNativeCommandTerminal, RendererNativeOperation,+ RendererNativeOperationStep, RendererNativeProtocolError, RendererNativeProtocolNotification,+ RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererOutputCursor,+ RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,RendererOutputStreamCloseReason, RendererOutputStreamControl, RendererOutputStreamEpoch,RendererOutputStreamIdentity, RendererOutputTransportDiagnostics,diff --git a/moli-renderer-v8/src/runtime/nested_main.rs b/moli-renderer-v8/src/runtime/nested_main.rsindex 5c37b0a21..4d6012c88 100644--- a/moli-renderer-v8/src/runtime/nested_main.rs+++ b/moli-renderer-v8/src/runtime/nested_main.rs@@ -52,7 +52,7 @@ pub(super) fn bind_active_nested_main_page(entry: &mut LivePageEntry) -> ActiveNpub(crate) fn dispatch_nested_main_page_command(command: RendererPageCommand,- first_dispatch: RendererInspectorMainFirstDispatchGuard,+ mut first_dispatch: RendererInspectorMainFirstDispatchGuard,) -> Result<RendererCommandTurnOutput> {let active = ACTIVE_NESTED_MAIN_PAGE.try_with(|active| active.borrow().clone())@@ -68,20 +68,31 @@ pub(crate) fn dispatch_nested_main_page_command(// the outer Page call.let page_vm = unsafe { active.page_vm.as_ptr().as_mut() }.ok_or_else(|| anyhow!("nested Main Page pointer was unexpectedly null"))?;+ first_dispatch.release();let reply: RendererPageReply = page_vm.dispatch_renderer_page_command(command)?;- let page_state = active.entry_slot.active_page_state()?;+ // The enclosing turn is suspended inside V8, so its owner-slot snapshot+ // still describes the state before the pause. Capture the live VM for this+ // nested handler without committing/replacing the enclosing owner turn.+ let previous = active.entry_slot.active_page_state()?;+ let capture = page_vm.capture_nested_page_state()?;+ let page_state = super::RendererPageState::from_vm_state_capture(+ previous.requested_url.clone(),+ previous.navigation_initiator_url.clone(),+ previous.navigation_redirected,+ previous.navigation_redirect_count,+ previous.status,+ previous.headers.clone(),+ capture,+ );+ let predecessor = page_vm.publish_nested_command_output_prefix();let output = RendererCommandTurnOutput::new(reply,page_state,RendererRuntimeCommandOutput::default(),None,- None,+ predecessor,)?;- // Chromium's synchronous non-V8 agent dispatch sends its response before- // returning to the nested Main receiver. Moli decodes the typed reply in- // the protocol actor, so retain the receiver slot with the immutable- // result. Consuming or abandoning that result releases fail-open; the- // actor cannot observe a later renderer publication before it has handled- // this handoff.- Ok(output.hold_until_protocol_handoff(first_dispatch))+ // Ready frontend output is already in the journal. A typed internal reply+ // is only a Browser continuation value, so neither needs a receipt gate.+ Ok(output)}diff --git a/moli-renderer-v8/src/runtime/owner.rs b/moli-renderer-v8/src/runtime/owner.rsindex 62ceeddec..b7e0078d7 100644--- a/moli-renderer-v8/src/runtime/owner.rs+++ b/moli-renderer-v8/src/runtime/owner.rs@@ -937,7 +937,13 @@ fn live_page_command_should_follow_pending_navigation(command: &RendererPageComm}fn live_page_command_requires_materialized_child_realms(command: &RendererPageCommand) -> bool {- matches!(command, RendererPageCommand::Inspector(envelope) if envelope.requires_materialized_child_realms())+ match command {+ RendererPageCommand::Native(command) => {+ live_page_command_requires_materialized_child_realms(&command.operation.command)+ }+ RendererPageCommand::Inspector(envelope) => envelope.requires_materialized_child_realms(),+ _ => false,+ }}const fn page_creation_navigation_reply_policy(diff --git a/moli-renderer-v8/src/runtime/owner/owner_loop.rs b/moli-renderer-v8/src/runtime/owner/owner_loop.rsindex 8ff2f3368..f2b5cba41 100644--- a/moli-renderer-v8/src/runtime/owner/owner_loop.rs+++ b/moli-renderer-v8/src/runtime/owner/owner_loop.rs@@ -1056,9 +1056,10 @@ impl RendererOwnerHandle {mut first_dispatch,capture_policy,} => {- // Crossing into the Page owner's concrete command dispatcher- // is the Main receiver's first-dispatch boundary.- let _post_dispatch_wake = first_dispatch.release_for_dispatch();+ // First dispatch ends at backend entry. Producer publication+ // orders frontend output; Browser polling of an internal reply+ // must never keep this renderer's Main receiver blocked.+ first_dispatch.release();self.run_live_page_command_turn(token, command, capture_policy).await}diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rsindex 5dfe3a281..1ac198518 100644--- a/moli-renderer-v8/src/runtime/page_commands.rs+++ b/moli-renderer-v8/src/runtime/page_commands.rs@@ -10,6 +10,9 @@ impl PageVm {self.flush_page_action_window(barrier)?;}match command {+ RendererPageCommand::Native(command) => {+ Ok(RendererPageReply::NativeCommandReady(Box::new(command.dispatch(self))))+ }RendererPageCommand::Inspector(command) => {self.dispatch_renderer_inspector_command(command)}@@ -853,6 +856,14 @@ impl PageVm {RendererPageCommand::SerializeHtml => {Ok(RendererPageReply::OptionalString(Some(self.serialize_html())))}+ RendererPageCommand::SerializeDocument => {+ // Capture both from the live document in this handler turn.+ // Browser admission metadata may precede a queued history update.+ Ok(RendererPageReply::SerializedDocument {+ url: self.vm().document_runtime.host_document().url().to_string(),+ html: self.serialize_html(),+ })+ }RendererPageCommand::LayoutMetrics => {Ok(RendererPageReply::LayoutMetrics(self.layout_metrics()?))}@@ -1398,6 +1409,9 @@ fn renderer_page_command_action_barrier(command: &RendererPageCommand,) -> Option<moli_action_window::ActionBarrier> {match command {+ // The underlying operation flushes its own barrier. Wrapping it must+ // not turn a wheel event into an explicit action-window flush.+ RendererPageCommand::Native(_) => None,RendererPageCommand::DispatchMouseEventAtPoint { event_name, .. }if event_name == "wheel" =>{diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rsindex e677729d6..70ec919be 100644--- a/moli-renderer-v8/src/runtime/page_surface.rs+++ b/moli-renderer-v8/src/runtime/page_surface.rs@@ -1,5 +1,5 @@+use super::protocol_output::{RendererCommandResponseAuthority, RendererCommandResponseLease};use super::*;-use crate::devtools::ingress::main::RendererInspectorMainFirstDispatchGuard;use crate::native_bridge::{PendingRuntimeObservableConsoleSourceEvent, RuntimeObservableContextToken,};@@ -921,6 +921,7 @@ impl RendererRuntimeCommandOutput {self.v8_state_update = Some(state);}+ #[doc(hidden)]#[doc(hidden)]pub fn bind_renderer_agent_attachment(&mut self, id: RendererAgentAttachmentId) {match self.renderer_agent_attachment_id {@@ -1521,6 +1522,9 @@ pub struct RendererCommandTurnCompletion {}impl RendererCommandTurnCompletion {+ pub fn native_response_was_published(&self) -> bool {+ matches!(self.reply, RendererPageReply::NativeCommandPublished)+ }pub fn reply(&self) -> &RendererPageReply {&self.reply}@@ -1580,13 +1584,6 @@ impl RendererCommandTurnCompletion {pub struct RendererCommandTurnOutput {completion: RendererCommandTurnCompletion,renderer_output_predecessor: Option<RendererOutputFence>,- // A nested synchronous DevTools agent call must keep its per-session Main- // receiver slot until the protocol actor owns the settled result. This is- // deliberately distinct from a post-response continuation: dropping the- // result at the protocol handoff is enough to preserve receiver order,- // while waiting for the frontend response would deadlock multi-stage- // commands that need to enter the same receiver again.- protocol_handoff: Option<Box<RendererInspectorMainFirstDispatchGuard>>,}impl RendererCommandTurnOutput {@@ -1595,7 +1592,7 @@ impl RendererCommandTurnOutput {page_state: Arc<RendererPageState>,runtime_command_output: RendererRuntimeCommandOutput,post_response_continuation: Option<RendererPageCommandPostResponseContinuation>,- renderer_output_predecessor: Option<RendererOutputFence>,+ mut renderer_output_predecessor: Option<RendererOutputFence>,) -> Result<Self> {let reply = match reply {RendererPageReply::RuntimeInspectorProtocolMessages(reply_messages) => {@@ -1611,6 +1608,18 @@ impl RendererCommandTurnOutput {reply}};+ let reply = match reply {+ RendererPageReply::NativeCommandReady(ready) => {+ // Settlement has already published this turn's earlier facts.+ // Publish the ready reply here, before a later Main command+ // can append its output, regardless of adapter waiter polling.+ ready+ .publish(&page_state)?+ .merge_into_same_stream_tail(&mut renderer_output_predecessor);+ RendererPageReply::NativeCommandPublished+ }+ reply => reply,+ };Ok(Self {completion: RendererCommandTurnCompletion {reply,@@ -1618,23 +1627,9 @@ impl RendererCommandTurnOutput {post_response_continuation,},renderer_output_predecessor,- protocol_handoff: None,})}- pub(crate) fn hold_until_protocol_handoff(- mut self,- handoff: RendererInspectorMainFirstDispatchGuard,- ) -> Self {- debug_assert!(- self.protocol_handoff.is_none(),- "a renderer command turn may hold only one protocol handoff"- );- self.protocol_handoff = Some(Box::new(handoff));- self- }-- #[doc(hidden)]pub fn bind_renderer_agent_attachment(&mut self, id: RendererAgentAttachmentId) {if let RendererPageReply::RuntimeInspectorProtocolMessages(output) =&mut self.completion.reply@@ -1676,7 +1671,6 @@ impl RendererCommandTurnOutput {let Self {completion,renderer_output_predecessor,- protocol_handoff: _,} = self;(completion, renderer_output_predecessor)}@@ -3044,40 +3038,19 @@ impl RendererRuntimeCommandOutputRecorder {}}-struct RendererRuntimeInspectorResponseChannelState {- next_lease_id: u64,- active_lease_id: Option<u64>,- open: bool,- tx: Option<oneshot::Sender<RendererRuntimeInspectorAsyncCompletion>>,- session_response_settlement_tx:- Option<oneshot::Sender<RendererRuntimeInspectorSessionResponseSettlement>>,-}--#[derive(Clone)]+#[derive(Clone, Debug, PartialEq, Eq)]pub struct RendererRuntimeInspectorResponseChannel {delivery: moli_page_types::RendererInspectorResponseDelivery,- state: Arc<Mutex<RendererRuntimeInspectorResponseChannelState>>,-}--impl std::fmt::Debug for RendererRuntimeInspectorResponseChannel {- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- let state = self.state.lock();- formatter- .debug_struct("RendererRuntimeInspectorResponseChannel")- .field("delivery", &self.delivery)- .field("active_lease_id", &state.active_lease_id)- .field("has_receiver", &state.tx.is_some())- .finish()- }-}--impl PartialEq for RendererRuntimeInspectorResponseChannel {- fn eq(&self, other: &Self) -> bool {- Arc::ptr_eq(&self.state, &other.state)- }+ authority: RendererCommandResponseAuthority<+ RendererRuntimeInspectorAsyncCompletion,+ RendererRuntimeInspectorSessionResponseSettlement,+ >,}-impl Eq for RendererRuntimeInspectorResponseChannel {}+type RendererRuntimeInspectorResponseLease = RendererCommandResponseLease<+ RendererRuntimeInspectorAsyncCompletion,+ RendererRuntimeInspectorSessionResponseSettlement,+>;impl RendererRuntimeInspectorResponseChannel {pub fn new() -> (@@ -3088,13 +3061,7 @@ impl RendererRuntimeInspectorResponseChannel {(Self {delivery: moli_page_types::RendererInspectorResponseDelivery::AdapterReply,- state: Arc::new(Mutex::new(RendererRuntimeInspectorResponseChannelState {- next_lease_id: 1,- active_lease_id: None,- open: true,- tx: Some(tx),- session_response_settlement_tx: None,- })),+ authority: RendererCommandResponseAuthority::adapter(tx),},rx,)@@ -3114,13 +3081,7 @@ impl RendererRuntimeInspectorResponseChannel {moli_page_types::RendererInspectorResponseDelivery::SessionSink => (Self {delivery,- state: Arc::new(Mutex::new(RendererRuntimeInspectorResponseChannelState {- next_lease_id: 1,- active_lease_id: None,- open: true,- tx: None,- session_response_settlement_tx: None,- })),+ authority: RendererCommandResponseAuthority::session(),},None,),@@ -3141,19 +3102,7 @@ impl RendererRuntimeInspectorResponseChannel {call_id: i32,attachment_id: Option<RendererAgentAttachmentId>,) -> Option<RendererRuntimeInspectorResponseSender> {- let lease_id = {- let mut state = self.state.lock();- if !state.open {- return None;- }- let lease_id = state.next_lease_id;- state.next_lease_id = lease_id- .checked_add(1)- .expect("renderer response lease id exhausted");- state.active_lease_id = Some(lease_id);- lease_id- };- let lease = RendererRuntimeInspectorResponseLease::new(lease_id, self.clone());+ let lease = self.authority.activate()?;let destination = match self.delivery {moli_page_types::RendererInspectorResponseDelivery::AdapterReply => {RendererRuntimeInspectorResponseDestination::AdapterReply(lease)@@ -3176,133 +3125,11 @@ impl RendererRuntimeInspectorResponseChannel {/// publishing while the protocol session still owns terminal completion./// A response that already claimed the channel wins and returns `false`.pub fn try_revoke_active_lease(&self) -> bool {- let mut state = self.state.lock();- if !state.open || state.active_lease_id.is_none() {- return false;- }- state.active_lease_id = None;- true+ self.authority.try_revoke_active_lease()}pub fn cancel(&self) {- let mut state = self.state.lock();- state.open = false;- state.active_lease_id = None;- state.tx.take();- state.session_response_settlement_tx.take();- }-- fn send(- &self,- lease_id: u64,- completion: RendererRuntimeInspectorAsyncCompletion,- ) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {- let tx = {- let mut state = self.state.lock();- if state.active_lease_id != Some(lease_id) {- return Err(completion);- }- state.open = false;- state.active_lease_id = None;- state.tx.take()- };- let Some(tx) = tx else {- return Err(completion);- };- tx.send(completion)- }-- fn take_session_response_settlement_receiver(- &self,- lease_id: u64,- ) -> Option<oneshot::Receiver<RendererRuntimeInspectorSessionResponseSettlement>> {- let mut state = self.state.lock();- if !state.open- || state.active_lease_id != Some(lease_id)- || state.session_response_settlement_tx.is_some()- {- return None;- }- let (tx, rx) = oneshot::channel();- state.session_response_settlement_tx = Some(tx);- Some(rx)- }-- fn cancel_lease(&self, lease_id: u64) -> bool {- let mut state = self.state.lock();- if !state.open || state.active_lease_id != Some(lease_id) {- return false;- }- state.open = false;- state.active_lease_id = None;- state.tx.take();- state.session_response_settlement_tx.take();- true- }-- fn claim_session_lease(- &self,- lease_id: u64,- ) -> Result<Option<oneshot::Sender<RendererRuntimeInspectorSessionResponseSettlement>>, ()>- {- let mut state = self.state.lock();- if !state.open || state.active_lease_id != Some(lease_id) {- return Err(());- }- state.open = false;- state.active_lease_id = None;- Ok(state.session_response_settlement_tx.take())- }-}--#[derive(Debug)]-struct RendererRuntimeInspectorResponseLeaseLifetime {- lease_id: u64,- channel: RendererRuntimeInspectorResponseChannel,-}--impl Drop for RendererRuntimeInspectorResponseLeaseLifetime {- fn drop(&mut self) {- self.channel.cancel_lease(self.lease_id);- }-}--#[derive(Clone, Debug)]-struct RendererRuntimeInspectorResponseLease {- lifetime: Arc<RendererRuntimeInspectorResponseLeaseLifetime>,-}--impl RendererRuntimeInspectorResponseLease {- fn new(lease_id: u64, channel: RendererRuntimeInspectorResponseChannel) -> Self {- Self {- lifetime: Arc::new(RendererRuntimeInspectorResponseLeaseLifetime { lease_id, channel }),- }- }-- fn send_adapter_reply(- self,- completion: RendererRuntimeInspectorAsyncCompletion,- ) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {- self.lifetime- .channel- .send(self.lifetime.lease_id, completion)- }-- fn take_session_response_settlement_receiver(- &self,- ) -> Option<oneshot::Receiver<RendererRuntimeInspectorSessionResponseSettlement>> {- self.lifetime- .channel- .take_session_response_settlement_receiver(self.lifetime.lease_id)- }-- fn claim_session(- &self,- ) -> Result<Option<oneshot::Sender<RendererRuntimeInspectorSessionResponseSettlement>>, ()>- {- self.lifetime- .channel- .claim_session_lease(self.lifetime.lease_id)+ self.authority.cancel();}}@@ -3484,24 +3311,11 @@ impl std::fmt::Debug for RendererRuntimeInspectorResponseSender {impl RendererRuntimeInspectorResponseSender {pub fn new(call_id: i32, tx: oneshot::Sender<RendererRuntimeInspectorAsyncCompletion>) -> Self {- let channel = RendererRuntimeInspectorResponseChannel {+ RendererRuntimeInspectorResponseChannel {delivery: moli_page_types::RendererInspectorResponseDelivery::AdapterReply,- state: Arc::new(Mutex::new(RendererRuntimeInspectorResponseChannelState {- next_lease_id: 2,- active_lease_id: Some(1),- open: true,- tx: Some(tx),- session_response_settlement_tx: None,- })),- };- Self {- call_id,- attachment_id: None,- destination: RendererRuntimeInspectorResponseDestination::AdapterReply(- RendererRuntimeInspectorResponseLease::new(1, channel),- ),- publication_boundary: RendererRuntimeInspectorResponsePublicationBoundary::Immediate,+ authority: RendererCommandResponseAuthority::adapter(tx),}+ .activate_sender(call_id, None)}pub fn call_id(&self) -> i32 {@@ -4822,6 +4636,7 @@ pub(crate) enum RendererInspectorPageCommand {#[non_exhaustive]pub enum RendererPageCommand {+ Native(Box<RendererNativeCommand>),Inspector(RendererInspectorCommandEnvelope),EvaluateExpression {expression: String,@@ -5194,6 +5009,7 @@ pub enum RendererPageCommand {options: RendererPageDumpOptions,},SerializeHtml,+ SerializeDocument,LayoutMetrics,PublishLayout,CaptureScreenshot(RendererCaptureScreenshotRequest),@@ -5677,12 +5493,25 @@ impl RendererPageCommand {}pub fn bind_inspector_attachment(&mut self, attachment: RendererAgentAttachmentId) {+ if let Self::Native(command) = self {+ command+ .operation+ .command+ .bind_inspector_attachment(attachment);+ return;+ }if let Self::Inspector(envelope) = self {envelope.bind_attachment(attachment);}}pub(crate) fn interruptible_by_javascript_dialog(&self) -> bool {+ if let Self::Native(command) = self {+ return command+ .operation+ .command+ .interruptible_by_javascript_dialog();+ }#[cfg(test)]if matches!(self, Self::TakeDocumentLifecycleEvents) {return true;@@ -5700,6 +5529,7 @@ impl RendererPageCommand {pub(crate) fn cdp_nav_timing_label(&self) -> Option<&'static str> {match self {+ Self::Native(command) => command.operation.command.cdp_nav_timing_label(),Self::Inspector(envelope) => envelope.cdp_nav_timing_label(),Self::DocumentStorageKeySnapshot => Some("DocumentStorageKeySnapshot"),Self::CreateIsolatedWorldRuntimeActivity { .. } => {@@ -5794,6 +5624,7 @@ impl RendererPageCommand {Self::OuterHtmlForBackendNodeId { .. } => Some("OuterHtmlForBackendNodeId"),Self::RenderPageDump { .. } => Some("RenderPageDump"),Self::SerializeHtml => Some("SerializeHtml"),+ Self::SerializeDocument => Some("SerializeDocument"),Self::LayoutMetrics => Some("LayoutMetrics"),Self::PublishLayout => Some("PublishLayout"),Self::CaptureScreenshot(_) => Some("CaptureScreenshot"),@@ -6119,6 +5950,8 @@ pub enum RendererCaptureScreencastFrameReply {}pub enum RendererPageReply {+ NativeCommandReady(Box<RendererNativeCommandReadyResponse>),+ NativeCommandPublished,ElementClickPreparation(Result<RendererElementClickTarget, RendererElementClickError>),ElementClickDispatch(Result<RendererInputDispatchOutcome, RendererElementClickError>),RuntimeEvaluationResult(RendererRuntimeEvaluationResult),@@ -6188,6 +6021,10 @@ pub enum RendererPageReply {Bool(bool),OptionalBool(Option<bool>),OptionalString(Option<String>),+ SerializedDocument {+ url: String,+ html: String,+ },OptionalU64(Option<u64>),Usize(usize),CookieFacadeSnapshot(Box<RendererPageCookieFacadeSnapshotReply>),@@ -6363,6 +6200,7 @@ impl RendererPageReply {Self::InputDispatchOutcome(outcome) | Self::ElementClickDispatch(Ok(outcome)) => {Some(outcome)}+ Self::NativeCommandReady(ready) => ready.input_dispatch_outcome(),_ => None,}}@@ -6374,6 +6212,7 @@ impl RendererPageReply {Self::InputDispatchOutcome(outcome) | Self::ElementClickDispatch(Ok(outcome)) => {Some(outcome)}+ Self::NativeCommandReady(ready) => ready.input_dispatch_outcome_mut(),_ => None,}}diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rsindex d7f620759..aea2654a1 100644--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs@@ -1786,6 +1786,23 @@ impl PageVm {self.vm_mut().settle_renderer_output_publication()}+ /// Nested Main dispatch cannot end the suspended outer command scope.+ /// Drain its ready prefix, materialize native DOM facts, and use the same+ /// Inspector-state resolution as ordinary owner settlement before replying.+ pub(super) fn publish_nested_command_output_prefix(+ &mut self,+ ) -> Option<super::RendererOutputFence> {+ self.vm().append_live_command_output_prefix();+ self.absorb_pending_dom_mutations_into_output_journal();+ self.record_document_title_change_if_needed();+ let publication = self.vm_mut().settle_renderer_output_prefix()?;+ let journal = self.vm().renderer_command_output_journal();+ let cursor = publication.cursor();+ journal+ .publish_resolved_prefix(publication)+ .then(|| journal.declare_fence(cursor))+ }+fn record_document_title_change_if_needed(&mut self) {// A PageVm can exist without a DevTools-facing Page residence in// standalone embeddings and owner-boundary unit tests. Lifecycle@@ -3893,11 +3910,20 @@ impl PageVm {is_on_named_owner_execution_lane_for(&self.local_executor),"document URL refresh must execute on the matching named owner lane");+ self.refresh_document_url_from_location();self.capture_page_state_with_policy(capture_policy)}+ /// A debugger callback already holds the document isolate. The nested+ /// handler can capture native metadata/reports, but must not read JS+ /// location objects or snapshot globals through another isolate borrow.+ pub(super) fn capture_nested_page_state(&mut self) -> Result<PageVmStateCapture> {+ self.capture_page_state_with_policy(super::RendererPageStateCapturePolicy::ProtocolTurn)+ }+#[cfg(test)]fn capture_page_state(&mut self) -> Result<PageVmStateCapture> {+ self.refresh_document_url_from_location();self.capture_page_state_with_policy(super::RendererPageStateCapturePolicy::FullReport)}@@ -3908,7 +3934,6 @@ impl PageVm {let profile_enabled = moli_trace::cpu_profile_enabled();let total_started = profile_enabled.then(Instant::now);self.absorb_parser_no_execution_runs();- self.refresh_document_url_from_location();let globals_started = profile_enabled.then(Instant::now);match capture_policy {super::RendererPageStateCapturePolicy::FullReport => {diff --git a/moli-renderer-v8/src/runtime/protocol_output/item.rs b/moli-renderer-v8/src/runtime/protocol_output/item.rsindex 553a22e3b..c26f7b5c3 100644--- a/moli-renderer-v8/src/runtime/protocol_output/item.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/item.rs@@ -109,6 +109,7 @@ pub enum RendererProtocolObservation {pub enum RendererOutputItem {OwnerAction(RendererOwnerAction),Observation(RendererProtocolObservation),+ NativeTerminal(super::RendererNativeCommandTerminal),}/// One record in exact producer append order.@@ -204,7 +205,9 @@ impl PendingRendererOutputRecord {crate::runtime::RendererRuntimeInspectorMessage::has_resolved_source_identity,)).then_some(RendererOutputResolutionError::DedicatedWorkerRuntimeInspector),- RendererOutputItem::OwnerAction(_) | RendererOutputItem::Observation(_) => None,+ RendererOutputItem::OwnerAction(_)+ | RendererOutputItem::Observation(_)+ | RendererOutputItem::NativeTerminal(_) => None,}}diff --git a/moli-renderer-v8/src/runtime/protocol_output/mod.rs b/moli-renderer-v8/src/runtime/protocol_output/mod.rsindex afaaa0248..2e1f02550 100644--- a/moli-renderer-v8/src/runtime/protocol_output/mod.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/mod.rs@@ -1,10 +1,16 @@mod fence;mod identity;mod item;+mod native_response;+mod response_authority;mod transport;mod transport_memory;mod turn_journal;+pub(crate) use response_authority::{+ RendererCommandResponseAuthority, RendererCommandResponseLease,+};+pub use fence::RendererOutputFence;pub use identity::{RendererOutputCursor, RendererOutputFenceLeaseId, RendererOutputResidenceIdentity,@@ -16,6 +22,12 @@ pub use item::{RendererDocumentTitleChanged, RendererOutputItem, RendererOutputRecord, RendererOwnerAction,RendererProtocolObservation,};+pub use native_response::{+ RendererNativeCommand, RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard,+ RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep,+ RendererNativeProtocolError, RendererNativeProtocolNotification,+ RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate,+};pub use transport::{RendererOutputTransportDiagnostics, RendererOutputTransportMessage,RendererOutputTransportReceiver, RendererOutputTransportSendError,diff --git a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs b/moli-renderer-v8/src/runtime/protocol_output/native_response.rsnew file mode 100644index 000000000..81743279a--- /dev/null+++ b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs@@ -0,0 +1,401 @@+//! Ready native replies share the renderer's producer-ordered output journal.+//!+//! The adapter chooses terminal delivery at admission and freezes Browser+//! metadata here. Internal queries continue to return their typed values to+//! their continuation; they never acquire this frontend publication capability.++use std::convert::Infallible;++use moli_page_types::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId};++use super::{+ PendingRendererOutputRecord, RendererCommandResponseAuthority, RendererCommandResponseLease,+ RendererOutputFence, RendererOutputItem, RendererTurnOutputJournal,+};+use crate::runtime::{RendererPageCommand, RendererPageReply};++/// A resolved native frontend reply. The projection captures only immutable+/// protocol metadata at admission; it cannot borrow a Browser or live Page.+/// Both success and backend errors are published at the renderer boundary.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RendererNativeProtocolResponse {+ pub result: Result<serde_json::Value, RendererNativeProtocolError>,+ pub notifications: Vec<RendererNativeProtocolNotification>,+ pub state_updates: Vec<RendererNativeProtocolStateUpdate>,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RendererNativeProtocolError {+ pub code: i32,+ pub message: String,+}++/// Native notifications keep the semantic sidecars needed by non-CDP+/// observers. JSON-only events and DOM automation events share one ordered+/// prefix; neither can be reconstructed from mutable Page state at drain.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum RendererNativeProtocolNotification {+ Json(serde_json::Value),+ DomSetChildNodes {+ parent_node_id: u32,+ nodes: Vec<serde_json::Value>,+ },+}++impl From<serde_json::Value> for RendererNativeProtocolNotification {+ fn from(value: serde_json::Value) -> Self {+ Self::Json(value)+ }+}++impl RendererNativeProtocolResponse {+ pub fn success(result: serde_json::Value) -> Self {+ Self {+ result: Ok(result),+ notifications: Vec::new(),+ state_updates: Vec::new(),+ }+ }++ pub fn error(code: i32, message: impl Into<String>) -> Self {+ Self {+ result: Err(RendererNativeProtocolError {+ code,+ message: message.into(),+ }),+ notifications: Vec::new(),+ state_updates: Vec::new(),+ }+ }+}++/// Browser mirrors committed with a native terminal. These are frozen data,+/// never callbacks into a live Page, and are discarded on attachment retirement.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum RendererNativeProtocolStateUpdate {+ RemoteObjects {+ result: serde_json::Value,+ object_group: Option<String>,+ },+ DomRemoteObjectNode {+ object_id: String,+ node: serde_json::Value,+ },+}++type NativeResponseProjection = Box<+ dyn FnOnce(+ anyhow::Result<RendererPageReply>,+ &crate::runtime::RendererPageState,+ ) -> RendererNativeProtocolResponse+ + Send,+>;++/// A complete reply to the original frontend call, not a live Page observation.+/// Its metadata remains valid even if the Page is replaced before projection.+/// The frontend router uses its globally allocated call id to deliver it once.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RendererNativeCommandTerminal {+ pub command_id: FrontendCommandId,+ pub session: DevToolsSessionKey,+ pub attachment_id: RendererAgentAttachmentId,+ pub reply: RendererNativeProtocolResponse,+}++type Authority = RendererCommandResponseAuthority<Infallible, RendererOutputFence>;+type Lease = RendererCommandResponseLease<Infallible, RendererOutputFence>;++/// Kept by the adapter continuation until its native operation settles.+/// Dropping a pending continuation cancels publication. Dropping it after the+/// producer claimed completion cannot undo the already committed terminal.+pub struct RendererNativeCommandResponseGuard {+ authority: Authority,+ publication: Option<tokio::sync::oneshot::Receiver<RendererOutputFence>>,+}++impl RendererNativeCommandResponseGuard {+ /// After losing the adapter result, cancel only work that has not claimed+ /// completion. If publication won that race, return its exact fence so the+ /// adapter cannot generate a second terminal error. This never delays the+ /// renderer or allocates a journal slot for unfinished work.+ pub async fn cancel_or_published(mut self) -> Option<RendererOutputFence> {+ self.authority.cancel();+ self.publication+ .take()+ .expect("native publication receipt is consumed once")+ .await+ .ok()+ }+}++impl Drop for RendererNativeCommandResponseGuard {+ fn drop(&mut self) {+ self.authority.cancel();+ }+}++/// Native frontend operations use their ordinary backend dispatch. The+/// synchronous projection freezes the complete response before it enters+/// the common journal, without involving an adapter waiter.+pub struct RendererNativeCommand {+ pub(crate) operation: RendererNativeOperation,+ response: RendererNativeCommandResponse,+}++struct RendererNativeCommandResponse {+ command_id: FrontendCommandId,+ session: DevToolsSessionKey,+ attachment_id: RendererAgentAttachmentId,+ lease: Lease,+}++impl RendererNativeCommand {+ pub fn new(+ command_id: FrontendCommandId,+ session: DevToolsSessionKey,+ attachment_id: RendererAgentAttachmentId,+ operation: RendererNativeOperation,+ ) -> (Self, RendererNativeCommandResponseGuard) {+ let authority = Authority::session();+ let lease = authority+ .activate()+ .expect("new native response authority is open");+ let publication = lease+ .take_session_response_settlement_receiver()+ .expect("native frontend calls retain a publication receipt");+ (+ Self {+ operation,+ response: RendererNativeCommandResponse {+ command_id,+ session,+ attachment_id,+ lease,+ },+ },+ RendererNativeCommandResponseGuard {+ authority,+ publication: Some(publication),+ },+ )+ }+}++/// Created by the native backend with fully resolved payload, then published+/// by command-turn settlement after earlier facts have reached the journal.+/// Creating this value neither reserves a sequence nor blocks later commands.+pub struct RendererNativeCommandReadyResponse {+ response: RendererNativeCommandResponse,+ reply: NativeReadyReply,+ journal: RendererTurnOutputJournal,+}++impl RendererNativeCommandReadyResponse {+ pub(crate) fn publish(+ self,+ page_state: &crate::runtime::RendererPageState,+ ) -> anyhow::Result<RendererOutputFence> {+ let Self {+ response,+ reply,+ journal,+ } = self;+ let receipt = response+ .lease+ .claim_session()+ .map_err(|()| anyhow::anyhow!("native response was canceled"))?+ .expect("native frontend calls retain a publication receipt");+ // Keep the backend reply alive through owner lifecycle settlement.+ // In particular input navigation is reconciled before projection.+ let reply = match reply {+ NativeReadyReply::Resolved(reply) => reply,+ NativeReadyReply::Projected { reply, project } => project(reply, page_state),+ };+ let terminal = RendererNativeCommandTerminal {+ command_id: response.command_id,+ session: response.session,+ attachment_id: response.attachment_id,+ reply,+ };+ let fence = journal+ .try_publish_terminal_records_and_declare_fence([+ PendingRendererOutputRecord::from_parts(+ None,+ RendererOutputItem::NativeTerminal(terminal),+ ),+ ])+ .ok_or_else(|| anyhow::anyhow!("native response output stream closed"))?;+ let _ = receipt.send(fence.clone());+ Ok(fence)+ }+}++/// A bounded native handler. Lookups may select the next backend operation+/// inside the same renderer turn; only the terminal projection can publish a+/// frontend response. These continuations never await Browser state or I/O.+pub struct RendererNativeOperation {+ pub(crate) command: Box<RendererPageCommand>,+ completion: NativeOperationCompletion,+ nested_main: bool,+}++pub enum RendererNativeOperationStep {+ Continue(RendererNativeOperation),+ Complete(RendererNativeProtocolResponse),+}++enum NativeOperationCompletion {+ Terminal(NativeResponseProjection),+ Lookup(+ Box<dyn FnOnce(anyhow::Result<RendererPageReply>) -> RendererNativeOperationStep + Send>,+ ),+}++impl RendererNativeOperation {+ pub fn new(+ command: RendererPageCommand,+ project: impl FnOnce(anyhow::Result<RendererPageReply>) -> RendererNativeProtocolResponse+ + Send+ + 'static,+ ) -> Self {+ Self::with_page_state(command, move |reply, _state| project(reply))+ }++ /// A terminal may use the immutable state captured by this renderer turn.+ /// This avoids consulting a lagging Browser Page mirror, and ensures the+ /// reply and its earlier observations describe the same completed turn.+ pub fn with_page_state(+ command: RendererPageCommand,+ project: impl FnOnce(+ anyhow::Result<RendererPageReply>,+ &crate::runtime::RendererPageState,+ ) -> RendererNativeProtocolResponse+ + Send+ + 'static,+ ) -> Self {+ let nested_main = command.nested_dispatch()+ == crate::devtools::command::RendererDevToolsMainNestedDispatch::PageAgent;+ Self {+ nested_main,+ command: Box::new(command),+ completion: NativeOperationCompletion::Terminal(Box::new(project)),+ }+ }++ /// An opaque continuation may enter the isolate. Keep the entire chain+ /// on the owner turn unless its author explicitly supplies a native-only+ /// continuation with `then_on_nested_main`.+ pub fn then(+ command: RendererPageCommand,+ next: impl FnOnce(anyhow::Result<RendererPageReply>) -> RendererNativeOperationStep+ + Send+ + 'static,+ ) -> Self {+ Self {+ command: Box::new(command),+ completion: NativeOperationCompletion::Lookup(Box::new(next)),+ nested_main: false,+ }+ }++ /// The lookup and every continuation use the existing nested Page-agent+ /// boundary. They must not acquire an owner-only Inspector/isolate borrow.+ pub fn then_on_nested_main(+ command: RendererPageCommand,+ next: impl FnOnce(anyhow::Result<RendererPageReply>) -> RendererNativeOperationStep+ + Send+ + 'static,+ ) -> Self {+ let nested_main = command.nested_dispatch()+ == crate::devtools::command::RendererDevToolsMainNestedDispatch::PageAgent;+ let mut operation = Self::then(command, next);+ operation.nested_main = nested_main;+ operation+ }++ /// Preserve an enclosing handler's isolate-entry requirement even when+ /// its first lookup happens to be a native node/realm query.+ pub fn require_owner_turn(mut self) -> Self {+ self.nested_main = false;+ self+ }++ pub(crate) fn can_dispatch_on_nested_main(&self) -> bool {+ self.nested_main+ }+}++enum NativeReadyReply {+ Resolved(RendererNativeProtocolResponse),+ Projected {+ reply: anyhow::Result<RendererPageReply>,+ project: NativeResponseProjection,+ },+}++impl RendererNativeCommand {+ pub(crate) fn dispatch(+ self,+ vm: &mut crate::runtime::PageVm,+ ) -> RendererNativeCommandReadyResponse {+ let Self {+ mut operation,+ response,+ } = self;+ let nested_main = operation.nested_main;+ let reply = loop {+ // A lookup may construct another Inspector operation. Bind+ // each one to the attachment captured for the original call.+ operation+ .command+ .bind_inspector_attachment(response.attachment_id);+ let reply = vm.dispatch_renderer_page_command(*operation.command);+ match operation.completion {+ NativeOperationCompletion::Terminal(project) => {+ break NativeReadyReply::Projected { reply, project };+ }+ NativeOperationCompletion::Lookup(next) => match next(reply) {+ RendererNativeOperationStep::Continue(next) => {+ assert!(+ !nested_main || next.nested_main,+ "a nested native continuation cannot acquire an owner-only isolate"+ );+ operation = next;+ }+ RendererNativeOperationStep::Complete(reply) => {+ break NativeReadyReply::Resolved(reply);+ }+ },+ }+ };+ RendererNativeCommandReadyResponse {+ response,+ reply,+ journal: vm.vm().renderer_command_output_journal(),+ }+ }+}++impl RendererNativeCommandReadyResponse {+ pub(crate) fn input_dispatch_outcome(+ &self,+ ) -> Option<&crate::runtime::RendererInputDispatchOutcome> {+ match &self.reply {+ NativeReadyReply::Projected {+ reply: Ok(reply), ..+ } => reply.input_dispatch_outcome(),+ _ => None,+ }+ }++ pub(crate) fn input_dispatch_outcome_mut(+ &mut self,+ ) -> Option<&mut crate::runtime::RendererInputDispatchOutcome> {+ match &mut self.reply {+ NativeReadyReply::Projected {+ reply: Ok(reply), ..+ } => reply.input_dispatch_outcome_mut(),+ _ => None,+ }+ }+}diff --git a/moli-renderer-v8/src/runtime/protocol_output/response_authority.rs b/moli-renderer-v8/src/runtime/protocol_output/response_authority.rsnew file mode 100644index 000000000..f224ae47f--- /dev/null+++ b/moli-renderer-v8/src/runtime/protocol_output/response_authority.rs@@ -0,0 +1,201 @@+//! Completion ownership, independent of the backend and its execution lane.+//!+//! An internal operation returns a value to its adapter. A frontend call owns+//! a terminal publication and returns only its publication receipt to a waiter.+//! Neither receipt is an execution lock or an acknowledgement from the socket.++use std::sync::Arc;++use parking_lot::Mutex;+use tokio::sync::oneshot;++/// The two destinations are exclusive. An internal query cannot claim a+/// frontend terminal, and a published frontend reply cannot also be returned+/// through an adapter value channel.+enum Destination<Completion, Settlement> {+ Adapter(oneshot::Sender<Completion>),+ Session(Option<oneshot::Sender<Settlement>>),+}++struct State<Completion, Settlement> {+ next_lease_id: u64,+ active_lease_id: Option<u64>,+ // Taking this destination is the linearization point for completion or+ // cancellation. Revocation only clears the active lease: replacement may+ // acquire a new lease for the same still-open frontend call.+ destination: Option<Destination<Completion, Settlement>>,+}++pub(crate) struct RendererCommandResponseAuthority<Completion, Settlement> {+ state: Arc<Mutex<State<Completion, Settlement>>>,+}++impl<C, S> Clone for RendererCommandResponseAuthority<C, S> {+ fn clone(&self) -> Self {+ Self {+ state: self.state.clone(),+ }+ }+}++impl<C, S> std::fmt::Debug for RendererCommandResponseAuthority<C, S> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let state = self.state.lock();+ f.debug_struct("RendererCommandResponseAuthority")+ .field("active_lease_id", &state.active_lease_id)+ .field("open", &state.destination.is_some())+ .finish()+ }+}++impl<C, S> PartialEq for RendererCommandResponseAuthority<C, S> {+ fn eq(&self, other: &Self) -> bool {+ Arc::ptr_eq(&self.state, &other.state)+ }+}++impl<C, S> Eq for RendererCommandResponseAuthority<C, S> {}++impl<C, S> RendererCommandResponseAuthority<C, S> {+ fn new(destination: Destination<C, S>) -> Self {+ Self {+ state: Arc::new(Mutex::new(State {+ next_lease_id: 1,+ active_lease_id: None,+ destination: Some(destination),+ })),+ }+ }++ pub(crate) fn adapter(tx: oneshot::Sender<C>) -> Self {+ Self::new(Destination::Adapter(tx))+ }++ pub(crate) fn session() -> Self {+ Self::new(Destination::Session(None))+ }++ pub(crate) fn activate(&self) -> Option<RendererCommandResponseLease<C, S>> {+ let lease_id = {+ let mut state = self.state.lock();+ state.destination.as_ref()?;+ let id = state.next_lease_id;+ state.next_lease_id = id+ .checked_add(1)+ .expect("renderer response lease id exhausted");+ state.active_lease_id = Some(id);+ id+ };+ Some(RendererCommandResponseLease {+ lifetime: Arc::new(LeaseLifetime {+ lease_id,+ authority: self.clone(),+ }),+ })+ }++ pub(crate) fn try_revoke_active_lease(&self) -> bool {+ self.state.lock().active_lease_id.take().is_some()+ }++ pub(crate) fn cancel(&self) {+ let destination = {+ let mut state = self.state.lock();+ state.active_lease_id = None;+ state.destination.take()+ };+ drop(destination);+ }++ fn cancel_lease(&self, lease_id: u64) {+ let destination = {+ let mut state = self.state.lock();+ if state.active_lease_id != Some(lease_id) {+ return;+ }+ state.active_lease_id = None;+ state.destination.take()+ };+ drop(destination);+ }+}++struct LeaseLifetime<C, S> {+ lease_id: u64,+ authority: RendererCommandResponseAuthority<C, S>,+}++impl<C, S> Drop for LeaseLifetime<C, S> {+ fn drop(&mut self) {+ // Only the last copy of the active lease abandons this call. Dropping+ // a retired renderer's lease must not cancel its replacement.+ self.authority.cancel_lease(self.lease_id);+ }+}++pub(crate) struct RendererCommandResponseLease<C, S> {+ lifetime: Arc<LeaseLifetime<C, S>>,+}++impl<C, S> Clone for RendererCommandResponseLease<C, S> {+ fn clone(&self) -> Self {+ Self {+ lifetime: self.lifetime.clone(),+ }+ }+}++impl<C, S> std::fmt::Debug for RendererCommandResponseLease<C, S> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("RendererCommandResponseLease")+ .field("lease_id", &self.lifetime.lease_id)+ .field("authority", &self.lifetime.authority)+ .finish()+ }+}++impl<C, S> RendererCommandResponseLease<C, S> {+ pub(crate) fn send_adapter_reply(self, completion: C) -> Result<(), C> {+ let tx = {+ let mut state = self.lifetime.authority.state.lock();+ if state.active_lease_id != Some(self.lifetime.lease_id)+ || !matches!(state.destination, Some(Destination::Adapter(_)))+ {+ return Err(completion);+ }+ state.active_lease_id = None;+ let Some(Destination::Adapter(tx)) = state.destination.take() else {+ unreachable!("destination was checked under the same lock")+ };+ tx+ };+ tx.send(completion)+ }++ pub(crate) fn take_session_response_settlement_receiver(&self) -> Option<oneshot::Receiver<S>> {+ let mut state = self.lifetime.authority.state.lock();+ if state.active_lease_id != Some(self.lifetime.lease_id) {+ return None;+ }+ let Some(Destination::Session(tx @ None)) = &mut state.destination else {+ return None;+ };+ let (sender, receiver) = oneshot::channel();+ *tx = Some(sender);+ Some(receiver)+ }++ pub(crate) fn claim_session(&self) -> Result<Option<oneshot::Sender<S>>, ()> {+ let mut state = self.lifetime.authority.state.lock();+ if state.active_lease_id != Some(self.lifetime.lease_id)+ || !matches!(state.destination, Some(Destination::Session(_)))+ {+ return Err(());+ }+ state.active_lease_id = None;+ let Some(Destination::Session(tx)) = state.destination.take() else {+ unreachable!("destination was checked under the same lock")+ };+ Ok(tx)+ }+}diff --git a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rsindex 51f94f8c7..b552a1b9c 100644--- a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs@@ -17,6 +17,7 @@ impl RendererOutputRecord {observation_transport_charge_bytes(observation)}RendererOutputItem::OwnerAction(action) => owner_action_transport_charge_bytes(action),+ RendererOutputItem::NativeTerminal(terminal) => native_terminal_charge_bytes(terminal),};std::mem::size_of::<Self>().saturating_add(payload)@@ -24,6 +25,40 @@ impl RendererOutputRecord {}}+fn native_terminal_charge_bytes(terminal: &super::RendererNativeCommandTerminal) -> usize {+ let mut charge = terminal.session.wire_session_id().map_or(0, string_charge);+ let response = &terminal.reply;+ charge = charge.saturating_add(match &response.result {+ Ok(value) => json_charge(value),+ Err(error) => string_charge(&error.message),+ });+ for update in &response.state_updates {+ charge = charge.saturating_add(match update {+ super::RendererNativeProtocolStateUpdate::RemoteObjects {+ result,+ object_group,+ } => {+ json_charge(result).saturating_add(object_group.as_deref().map_or(0, string_charge))+ }+ super::RendererNativeProtocolStateUpdate::DomRemoteObjectNode { object_id, node } => {+ string_charge(object_id).saturating_add(json_charge(node))+ }+ });+ }+ for notification in &response.notifications {+ charge = charge.saturating_add(match notification {+ super::RendererNativeProtocolNotification::Json(value) => json_charge(value),+ super::RendererNativeProtocolNotification::DomSetChildNodes { nodes, .. } => {+ nodes.iter().fold(+ std::mem::size_of::<super::RendererNativeProtocolNotification>(),+ |charge, node| charge.saturating_add(json_charge(node)),+ )+ }+ });+ }+ charge+}+fn string_charge(value: &str) -> usize {// String capacity is not exposed through every borrowed payload. Charging// twice the visible UTF-8 length covers ordinary geometric growth whilediff --git a/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs b/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rsindex 8285d03f4..7ffd95e83 100644--- a/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs@@ -202,6 +202,23 @@ impl RendererTurnOutputJournal {Some(cursor)}+ /// Admit a prefix whose cursor was already allocated by+ /// `take_pending_for_resolution`. Resolution updates Inspector mirrors+ /// outside the journal lock and must not allocate a second cursor.+ pub(crate) fn publish_resolved_prefix(&self, publication: RendererOutputPublication) -> bool {+ let mut state = self.state.lock();+ assert_eq!(publication.cursor().stream(), state.stream);+ if state.closed {+ return false;+ }+ if let Some(transport) = state.transport.as_ref() {+ publication.publish_to(transport).is_ok()+ } else {+ state.deferred_publications.push(publication);+ true+ }+ }+/// Atomically appends and publishes one already-resolved producer batch.////// A DevTools session response is a terminal renderer observation, not adiff --git a/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rs b/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rsindex b33a93faf..5a7feafd1 100644--- a/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rs+++ b/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rs@@ -2585,6 +2585,290 @@ __lm_snapshot_revocable_array.revoke();.await.expect("unsupported globals snapshot test page should close");}+#[tokio::test(flavor = "multi_thread")]+async fn native_terminals_publish_before_waiters_are_polled() {+ use super::{RendererNativeCommand, RendererNativeOperation, RendererNativeProtocolResponse};+ use moli_page_types::{DevToolsSessionKey, RendererAgentAttachmentId};+ let runtime = JsRuntime::initialize();+ let (output_tx, mut output_rx) = renderer_external_activity_test_channel();+ runtime.set_renderer_output_transport_sender(output_tx);+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut page = create_test_html_page(+ &runtime,+ &loader,+ url::Url::parse("https://example.test/native-terminals").unwrap(),+ "<!doctype html><title>Native terminals</title>",+ )+ .await;+ output_rx.drain();+ let attachment = RendererAgentAttachmentId::allocate();+ let mut pending = Vec::new();+ let mut guards = Vec::new();+ for command_id in [100, 101, 102] {+ let (command, guard) = RendererNativeCommand::new(+ moli_page_types::FrontendCommandId::new(command_id),+ DevToolsSessionKey::Attached("session-a".to_owned()),+ attachment,+ RendererNativeOperation::new(RendererPageCommand::ChildFrameTreeSnapshot, |reply| {+ let RendererPageReply::ChildFrameTreeSnapshots(children) = reply.unwrap() else {+ panic!("child frame tree snapshot reply");+ };+ RendererNativeProtocolResponse::success(serde_json::json!({+ "childCount": children.len(),+ }))+ }),+ );+ if command_id == 100 {+ // Cancellation precedes admission, so no scheduling race can+ // decide whether this request may publish a terminal.+ drop(guard);+ } else {+ guards.push(guard);+ }+ pending.push((+ command_id,+ page.enqueue_protocol_command_in_inspector_session(+ RendererPageCommand::Native(Box::new(command)),+ Some("session-a".to_owned()),+ )+ .expect("enqueue native terminal"),+ ));+ }+ let later = page+ .enqueue_protocol_command_in_inspector_session(+ RendererPageCommand::EvaluateExpression {+ expression: "42".to_owned(),+ await_promise: false,+ },+ Some("session-a".to_owned()),+ )+ .expect("enqueue concrete same-session gate");+ // Intentionally poll the last command before either native waiter. A+ // receipt/decode handoff would deadlock here. The timeout only diagnoses+ // a blocked gate; no ordering assertion depends on an elapsed interval.+ let later = tokio::time::timeout(std::time::Duration::from_secs(3), later.wait())+ .await+ .expect("published terminals must not retain the Main lane")+ .expect("later evaluation completes");+ assert_eq!(+ renderer_json_value(later.into_reply_and_state().0),+ Some(serde_json::json!(42))+ );+ let terminals = output_rx+ .drain()+ .into_iter()+ .flat_map(|publication| {+ let cursor = publication.cursor();+ publication+ .into_records()+ .into_iter()+ .filter_map(move |record| match record.into_parts().1 {+ RendererOutputItem::NativeTerminal(terminal) => Some((cursor, terminal)),+ _ => None,+ })+ })+ .collect::<Vec<_>>();+ assert_eq!(+ terminals+ .iter()+ .map(|(_, reply)| reply.command_id.get())+ .collect::<Vec<_>>(),+ [101, 102]+ );+ for ((cursor, terminal), guard) in terminals.iter().zip(guards) {+ assert_eq!(terminal.attachment_id, attachment);+ assert_eq!(terminal.session.wire_session_id(), Some("session-a"));+ assert_eq!(+ terminal.reply.result,+ Ok(serde_json::json!({ "childCount": 0 })),+ );+ // Even if an adapter loses its value channel, a committed publication+ // wins over cancellation and suppresses a second terminal error.+ assert_eq!(+ guard+ .cancel_or_published()+ .await+ .expect("publication already committed")+ .cursor(),+ *cursor+ );+ }+ // Decode in reverse order, with a scheduler yield between receives. It+ // cannot change the producer order already observed on the journal.+ while let Some((command_id, pending)) = pending.pop() {+ tokio::task::yield_now().await;+ if command_id == 100 {+ let Err(error) = pending.wait().await else {+ panic!("a canceled native response must not publish");+ };+ assert!(error.to_string().contains("native response was canceled"));+ continue;+ }+ let reply = pending+ .wait()+ .await+ .expect("receive native completion")+ .into_reply_and_state()+ .0;+ assert!(matches!(reply, RendererPageReply::NativeCommandPublished));+ }+ page.close_async().await.expect("close page");+}++#[tokio::test(flavor = "multi_thread")]+async fn projected_native_success_and_error_publish_without_adapter_receipt() {+ use super::{RendererNativeCommand, RendererNativeOperation, RendererNativeProtocolResponse};+ use moli_page_types::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId};+ let runtime = JsRuntime::initialize();+ let (output_tx, mut output_rx) = renderer_external_activity_test_channel();+ runtime.set_renderer_output_transport_sender(output_tx);+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let mut page = create_test_html_page(+ &runtime,+ &loader,+ url::Url::parse("https://example.test/native-projection").unwrap(),+ "<!doctype html><title>Native projection</title>",+ )+ .await;+ output_rx.drain();+ let attachment = RendererAgentAttachmentId::allocate();+ let mut waiters = Vec::new();+ let mut guards = Vec::new();+ for id in [1, 2] {+ let (command, guard) = RendererNativeCommand::new(+ FrontendCommandId::new(id),+ DevToolsSessionKey::Attached("native".to_owned()),+ attachment,+ RendererNativeOperation::new(+ RendererPageCommand::ComputedStylePropertiesForBackendNodeId {+ backend_node_id: u32::MAX,+ },+ move |reply| {+ assert!(matches!(+ reply.unwrap(),+ RendererPageReply::ComputedStyleProperties(None)+ ));+ if id == 1 {+ RendererNativeProtocolResponse::success(serde_json::json!({"found": false}))+ } else {+ RendererNativeProtocolResponse::error(+ -32000,+ "Could not find node with given id",+ )+ }+ },+ ),+ );+ guards.push(guard);+ waiters.push(+ page.enqueue_protocol_command_in_inspector_session(+ RendererPageCommand::Native(Box::new(command)),+ Some("native".to_owned()),+ )+ .unwrap(),+ );+ }+ let gate = page+ .enqueue_protocol_command_in_inspector_session(+ RendererPageCommand::EvaluateExpression {+ expression: "42".to_owned(),+ await_promise: false,+ },+ Some("native".to_owned()),+ )+ .unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(3), gate.wait())+ .await+ .expect("native publication cannot wait for adapter receipt")+ .unwrap();+ let terminals = output_rx+ .drain()+ .into_iter()+ .flat_map(|publication| publication.into_records())+ .filter_map(|record| match record.into_parts().1 {+ RendererOutputItem::NativeTerminal(terminal) => Some(terminal),+ _ => None,+ })+ .collect::<Vec<_>>();+ assert_eq!(+ terminals+ .iter()+ .map(|terminal| terminal.command_id.get())+ .collect::<Vec<_>>(),+ [1, 2]+ );+ let first = &terminals[0].reply;+ assert_eq!(+ first.result.as_ref().unwrap(),+ &serde_json::json!({"found": false})+ );+ let second = &terminals[1].reply;+ assert_eq!(second.result.as_ref().unwrap_err().code, -32000);+ for guard in guards {+ assert!(guard.cancel_or_published().await.is_some());+ }+ for waiter in waiters.into_iter().rev() {+ tokio::task::yield_now().await;+ assert!(matches!(+ waiter.wait().await.unwrap().into_reply_and_state().0,+ RendererPageReply::NativeCommandPublished+ ));+ }+ page.close_async().await.unwrap();+}++#[tokio::test(flavor = "multi_thread")]+async fn unpolled_internal_reply_does_not_block_later_main_dispatch() {+ let runtime = JsRuntime::initialize();+ let loader =+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");+ let mut page = create_test_html_page(+ &runtime,+ &loader,+ url::Url::parse("https://example.test/main-reply-handoff").expect("page url"),+ "<!doctype html><title>Main reply handoff</title>",+ )+ .await;++ let snapshot = page+ .enqueue_protocol_command_in_inspector_session(+ RendererPageCommand::ChildFrameTreeSnapshot,+ Some("session-a".to_owned()),+ )+ .expect("enqueue snapshot without polling its reply receiver");+ let later = page+ .enqueue_protocol_command_in_inspector_session(+ RendererPageCommand::EvaluateExpression {+ expression: "globalThis.handoffMarker = 42".to_owned(),+ await_promise: false,+ },+ Some("session-a".to_owned()),+ )+ .expect("enqueue later command in the same session");++ // Complete the later command without polling the earlier typed reply.+ // The timeout diagnoses a receiver gate; it is not an ordering assertion.+ let (later_reply, _) = tokio::time::timeout(std::time::Duration::from_secs(5), later.wait())+ .await+ .expect("internal reply polling must not gate Main dispatch")+ .expect("later command")+ .into_reply_and_state();+ assert_eq!(+ renderer_json_value(later_reply),+ Some(serde_json::json!(42))+ );+ let snapshot = snapshot+ .wait()+ .await+ .expect("receive retained snapshot reply");+ let (snapshot_reply, _) = snapshot.into_reply_and_state();+ assert!(matches!(+ snapshot_reply,+ RendererPageReply::ChildFrameTreeSnapshots(_)+ ));+ page.close_async().await.expect("close test page");+}+#[tokio::test(flavor = "multi_thread")]async fn protocol_turn_keeps_page_facts_current_and_marks_globals_snapshot_dirty() {let runtime = JsRuntime::initialize();diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rsindex ee244ba96..d5548975d 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs@@ -359,7 +359,7 @@ impl RendererInspectorSessionExecutorLocal {session.outbound.register_frontend_response_callback(response);- let _post_dispatch_wake = first_dispatch.release_for_dispatch();+ first_dispatch.release();v8_session.dispatch_protocol_message(v8::inspector::StringView::from(raw_json.as_bytes()));self.target.pause_ref().record_v8_state_update(session.agent_token,@@ -450,7 +450,7 @@ impl RendererInspectorSessionExecutorLocal {.outbound.register_frontend_response_callback(response);}- let _post_dispatch_wake = first_dispatch.release_for_dispatch();+ first_dispatch.release();v8_session.dispatch_protocol_message(v8::inspector::StringView::from(command.raw_json().as_bytes(),));diff --git a/moli-renderer-v8/src/script_vm/runtime_observability.rs b/moli-renderer-v8/src/script_vm/runtime_observability.rsindex cff213dcb..a81c5715d 100644--- a/moli-renderer-v8/src/script_vm/runtime_observability.rs+++ b/moli-renderer-v8/src/script_vm/runtime_observability.rs@@ -228,6 +228,20 @@ impl ScriptVm {.devtools_target().pause_ref().finish_owner_turn();+ let isolate = self.renderer_document_isolate.clone();+ isolate.with_renderer_document_isolate_and_inspector_mut(|_, _| {+ self.settle_renderer_output_prefix()+ })+ }++ /// Resolve a nested handler's prefix while its enclosing V8 turn remains+ /// paused. The caller must already be on the entered isolate (ordinary+ /// settlement enters above; nested Main runs within V8's pause loop).+ /// Do not borrow the suspended isolate holder or clear its resume/step+ /// transition while reading session state.+ pub(crate) fn settle_renderer_output_prefix(+ &mut self,+ ) -> Option<crate::runtime::RendererOutputPublication> {self.sync_runtime_observable_source_events().expect("runtime observable source synchronization should be infallible");let environment = self.renderer_page_script_environment.as_ref()?;@@ -248,14 +262,19 @@ impl ScriptVm {self.page_isolated_world_contexts.record_inspector_context_state(&raw_messages, self.root_frame_id.as_deref());if batch.agent_token == current_agent_token {- batch.v8_state_update =- self.inspector_v8_session_state(batch.session.wire_session_id());+ batch.v8_state_update = self+ .page_inspector+ .v8_session_state(batch.session.wire_session_id());}});}Some(pending.finish())}+ pub(crate) fn append_live_command_output_prefix(&self) {+ self._context_host.borrow().append_live_turn_output_prefix();+ }+pub(crate) fn append_renderer_output_records(&self,records: impl IntoIterator<Item = crate::runtime::PendingRendererOutputRecord>,@@ -282,6 +301,16 @@ impl ScriptVm {self.renderer_page_script_environment.is_some()}+ pub(crate) fn renderer_command_output_journal(+ &self,+ ) -> crate::runtime::RendererTurnOutputJournal {+ self.renderer_page_script_environment+ .as_ref()+ .expect("a live native frontend command requires a Page output journal")+ .output_journal()+ .clone()+ }+#[cfg(test)]pub(crate) fn bind_renderer_output_journal_for_test(&mut self,