Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(runtime): unify turn output and Runtime subscription delivery
ldm08d58d0fd591f
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rsindex 9690d096b..f633f266a 100644--- a/moli-protocol/src/conn.rs+++ b/moli-protocol/src/conn.rs@@ -524,8 +524,8 @@ pub(crate) use popup_navigation_work::{};pub(crate) use runtime_eval::{ClaimedPendingInspectorAwait, ClaimedPendingInspectorAwaitOwner, RuntimeBindingCallEvent,- RuntimeEnableReplayEvent, renderer_command_turn_frontend_protocol_response,- runtime_remote_object_ids_in_map,+ RuntimeEnableEventsReplay, RuntimeEnableReplayEvent,+ renderer_command_turn_frontend_protocol_response, runtime_remote_object_ids_in_map,};pub use runtime_eval::{CompletedMoliDiagnosticsDispatch, CompletedRuntimeBindingPageCommandDispatch,diff --git a/moli-protocol/src/conn/dispatch_tests/runtime.rs b/moli-protocol/src/conn/dispatch_tests/runtime.rsindex f6149684c..a49837994 100644--- a/moli-protocol/src/conn/dispatch_tests/runtime.rs+++ b/moli-protocol/src/conn/dispatch_tests/runtime.rs@@ -422,7 +422,7 @@ async fn pending_runtime_binding_page_phase_keeps_background_owner_route_across_#[tokio::test]async fn runtime_enable_uses_background_initial_document_through_attached_session() {- let mut conn = CdpConnection::new();+ let mut ctx = crate::testing::TestContext::new();let context = AutomationContext {protocol: FrontendProtocol::WebDriverBidi,session_id: Some(DevToolsSessionId::from("bidi-runtime-enable-normal-route")),@@ -432,7 +432,7 @@ async fn runtime_enable_uses_background_initial_document_through_attached_sessiolet (first_result, _) =crate::domains::target::execute_immediate_devtools_target_command_with_protocol_events(- &mut conn,+ &mut ctx.conn,AutomationCommand::CreateTarget(DevToolsCreateTargetCommand {context: context.clone(),url: "about:blank".to_owned(),@@ -449,7 +449,7 @@ async fn runtime_enable_uses_background_initial_document_through_attached_sessiolet (second_result, _) =crate::domains::target::execute_immediate_devtools_target_command_with_protocol_events(- &mut conn,+ &mut ctx.conn,AutomationCommand::CreateTarget(DevToolsCreateTargetCommand {context,url: "about:blank".to_owned(),@@ -464,11 +464,13 @@ async fn runtime_enable_uses_background_initial_document_through_attached_sessio};let second_target_id = second_result.target_id;- let background_route = conn+ let background_route = ctx+ .conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");let background_owner = CommandOwnerScope::for_route(background_route.clone());- let pending_initial_document = conn+ let pending_initial_document = ctx+ .conn.start_initial_document_page_ensure_for_owner(&background_owner).expect("background target lifecycle ensure should start").expect("fresh background target should need an initial document page build");@@ -476,36 +478,35 @@ async fn runtime_enable_uses_background_initial_document_through_attached_sessio.wait().await.expect("background initial document page build should complete");- conn.complete_initial_document_page_build_for_owner(completed_initial_document)+ ctx.conn+ .complete_initial_document_page_build_for_owner(completed_initial_document).await.expect("background initial document should install on captured owner");let background_session =- attach_page_session_for_test(&mut conn, second_target_id.as_str()).await;+ attach_page_session_for_test(&mut ctx.conn, second_target_id.as_str()).await;let raw = serde_json::to_string(&json!({"id": 1270,"method": "Runtime.enable","sessionId": background_session})).unwrap();- let pending = match conn.start_command_dispatch(&raw) {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Runtime.enable should replay the existing initial context through V8: {:?}",- outcome.into_parts().0- )- }- };-- let messages = complete_command_task_for_test(&mut conn, *pending).await;+ let step = ctx.conn.start_command_dispatch(&raw);+ assert!(+ matches!(&step, CdpCommandTaskStep::Pending(_)),+ "background Runtime.enable must replay its existing initial context through V8"+ );+ let (messages, scheduler_events) = ctx+ .complete_command_task_step_with_events_for_test(step)+ .await;+ assert!(scheduler_events.is_empty());assert!(messages.iter().any(|message| message["id"] == json!(1270) && message.get("error").is_none()),"Runtime.enable should complete successfully on the original background owner: {messages:?}");- let browser_context = conn.browser_context.as_ref().expect("browser context");+ let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");assert_eq!(browser_context.active_target_id(),Some(first_target_id.as_str()),@@ -525,12 +526,14 @@ async fn runtime_enable_uses_background_initial_document_through_attached_sessio"Runtime.enable must not install a page on the active target");assert!(- conn.target_runtime_session_state_for_session(None)+ ctx.conn+ .target_runtime_session_state_for_session(None).is_none_or(|state| !state.runtime_frontend_enabled),"Runtime.enable completion must not enable Runtime on the active owner");assert!(- conn.target_runtime_session_state_for_session(Some(&background_session))+ ctx.conn+ .target_runtime_session_state_for_session(Some(&background_session)).is_some_and(|state| state.runtime_frontend_enabled),"Runtime.enable completion should enable Runtime on the original background owner");diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rsindex 8bb42db5b..9d6e2efa7 100644--- a/moli-protocol/src/conn/runtime_eval.rs+++ b/moli-protocol/src/conn/runtime_eval.rs@@ -497,6 +497,12 @@ pub struct CompletedRuntimeEnableEventsDispatch {completion: moli_core::page::CompletedPageCommand,}+impl CompletedRuntimeEnableEventsDispatch {+ pub(crate) fn renderer_output_predecessor(&self) -> Option<moli_core::RendererOutputFence> {+ self.completion.renderer_output_predecessor()+ }+}+pub(crate) struct RuntimeEnableEventsReplay {events: Vec<RuntimeEnableReplayEvent>,}diff --git a/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs b/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rsindex f2b54d4ac..06200e79f 100644--- a/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs+++ b/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs@@ -91,30 +91,40 @@ impl CdpConnection {completed: CompletedRuntimeEnableEventsDispatch,) -> Result<RuntimeEnableEventsReplay, String> {let owner = completed.owner;- let session_id = owner.session_id();let page = self.runtime_protocol_message_started_page_mut(&completed.route)?;let output = page.finish_runtime_enable_output(completed.completion).map_err(|error| format!("runtime enable event replay failed: {error}"))?;- let (attachment_id, v8_state_update, messages) = output.into_parts();+ let attachment_id = output.renderer_agent_attachment_id();if attachment_id != Some(completed.route.renderer_agent_attachment_id) {return Err("Runtime.enable completed from an unexpected renderer attachment".to_owned(),);}+ self.prepare_runtime_subscription_events_for_owner(&owner, output)+ }++ /// Project the frozen replay from either an internal completion or an+ /// ordered frontend terminal. The caller has validated the exact attachment.+ pub(crate) fn prepare_runtime_subscription_events_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ output: RendererRuntimeCommandOutput,+ ) -> Result<RuntimeEnableEventsReplay, String> {+ let session_id = owner.session_id();+ let (_, v8_state_update, messages) = output.into_parts();if let Some(state) = v8_state_update- && !self.merge_v8_inspector_session_state_for_owner(&owner, state)+ && !self.merge_v8_inspector_session_state_for_owner(owner, state){return Err("Runtime.enable completed after session owner disappeared".to_owned());}let mut replay = RuntimeEnableEventsReplay::from_renderer_messages(messages);- let _ =- self.set_renderer_runtime_agent_owns_page_console_api_events_for_owner(&owner, true);- self.ingest_runtime_session_owner_output_updates_for_owner(&owner);+ let _ = self.set_renderer_runtime_agent_owns_page_console_api_events_for_owner(owner, true);+ self.ingest_runtime_session_owner_output_updates_for_owner(owner);for event in replay.events_mut() {match event {RuntimeEnableReplayEvent::Context(event) => {- qualify_runtime_context_protocol_event_for_owner_typed(self, event, &owner);+ qualify_runtime_context_protocol_event_for_owner_typed(self, event, owner);}RuntimeEnableReplayEvent::Background(event) => {event.ensure_protocol_session_id(session_id);diff --git a/moli-protocol/src/conn/tests/mod.rs b/moli-protocol/src/conn/tests/mod.rsindex 60d157ba3..042790451 100644--- a/moli-protocol/src/conn/tests/mod.rs+++ b/moli-protocol/src/conn/tests/mod.rs@@ -929,21 +929,15 @@ async fn replacing_or_retiring_a_loaded_page_changes_its_attachment_identity() {#[tokio::test(flavor = "multi_thread")]async fn moli_diagnostics_preserves_runtime_observable_diagnostics() {let mut ctx = TestContext::new();- let page = ctx- .conn- .load_page_via_runtime_async("data:text/html,<body>diagnostics capture</body>")- .await- .expect("diagnostics capture page should load");let mut browser_context = BrowserContext::new("BID-diagnostics-capture".to_owned());browser_context.set_active_target_id("TID-diagnostics-capture");browser_context.attach_active_session("SID-diagnostics-capture");- browser_context.set_target_url(page.final_url().as_str().to_owned());- let _ = browser_context- .active_page_target_mut()- .runtime_slot- .replace_loaded_page(Some(page));- ctx.conn- .install_browser_context_fixture_for_test(browser_context);+ ctx.conn.insert_browser_context(browser_context);+ ctx.install_navigation_fixture_for_session_owner(+ "data:text/html,<body>diagnostics capture</body>",+ Some("SID-diagnostics-capture"),+ )+ .await;ctx.process_async(json!({"id": 44_100,diff --git a/moli-protocol/src/domains/native.rs b/moli-protocol/src/domains/native.rsindex 18e3b9a89..b5a1a82ed 100644--- a/moli-protocol/src/domains/native.rs+++ b/moli-protocol/src/domains/native.rs@@ -194,6 +194,7 @@ pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<Nativ"DOMSnapshot" => super::dom_snapshot::try_start_native_command,"CSS" => super::css::native::try_start,"Accessibility" => super::accessibility::native::try_start,+ "Runtime" => super::runtime::try_start_native_command,_ => return None,};frontend_attachment(conn, cmd)?;@@ -201,8 +202,10 @@ pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<Nativ}/// 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.+/// Snapshot results survive retirement; document caches and node events are+/// valid only for the exact attachment that produced them. Runtime.enable also+/// commits session state and projects its frozen replay here, or fails the+/// terminal if its original owner has retired.pub(crate) fn project_terminal_for_owner(conn: &mut CdpConnection,publication_owner: Option<&CommandOwnerScope>,@@ -222,20 +225,39 @@ pub(crate) fn project_terminal_for_owner(})});let response = &mut terminal.reply;+ let mut events = Vec::new();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::WebMcpEnabled(enabled) => {+ match (owner.as_ref(), update) {+ (+ owner,+ moli_core::RendererNativeProtocolStateUpdate::RuntimeSubscription {+ enabled,+ output,+ },+ ) => {+ match super::runtime::project_subscription_terminal(conn, owner, enabled, *output) {+ Ok(replay) => events.extend(replay),+ Err(message) => {+ response.notifications.clear();+ response.result = Err(moli_core::RendererNativeProtocolError {+ code: -32000,+ message,+ });+ }+ }+ }+ (Some(owner), moli_core::RendererNativeProtocolStateUpdate::WebMcpEnabled(enabled)) => {conn.with_target_devtools_session_state_for_owner_mut(owner, |state| {state.web_mcp_enabled = enabled});}- moli_core::RendererNativeProtocolStateUpdate::RemoteObjects { object_group } => {+ (+ Some(owner),+ moli_core::RendererNativeProtocolStateUpdate::RemoteObjects { object_group },+ ) => {let Ok(result) = &response.result else {continue;};@@ -247,15 +269,20 @@ pub(crate) fn project_terminal_for_owner(conn.register_runtime_remote_object_ids_from_value_for_owner(owner, result);}}- moli_core::RendererNativeProtocolStateUpdate::DomRemoteObjectNode {- object_id,- node,- } => {+ (+ Some(owner),+ moli_core::RendererNativeProtocolStateUpdate::DomRemoteObjectNode {+ object_id,+ node,+ },+ ) => {super::dom::cache_dom_remote_object_node_for_owner(conn, owner, object_id, node);}+ (None, _) => {}}}- project_terminal(terminal)+ events.extend(project_terminal(terminal));+ events}/// Bounded projection of a terminal already committed by its renderer owner.diff --git a/moli-protocol/src/domains/runtime.rs b/moli-protocol/src/domains/runtime.rsindex a2e335c99..fe9f2781a 100644--- a/moli-protocol/src/domains/runtime.rs+++ b/moli-protocol/src/domains/runtime.rs@@ -4,6 +4,8 @@ mod bindings;mod command_classification;mod dispatcher;mod evaluate;+mod native;+pub(in crate::domains) use native::{project_subscription_terminal, try_start_native_command};#[cfg(test)]mod test_support;diff --git a/moli-protocol/src/domains/runtime/dispatcher.rs b/moli-protocol/src/domains/runtime/dispatcher.rsindex 7fcbb6a40..5bd326e1a 100644--- a/moli-protocol/src/domains/runtime/dispatcher.rs+++ b/moli-protocol/src/domains/runtime/dispatcher.rs@@ -36,11 +36,10 @@ use crate::conn::{PendingRuntimeChildDefaultContextLookupDispatch, PendingRuntimeEnableEventsDispatch,PendingRuntimeProtocolMessageDispatch, PendingServiceWorkerRuntimeProtocolMessageDispatch,PendingSharedWorkerRuntimeProtocolMessageDispatch, ProfilerInspectorCommand,- RendererCommandDescriptor, RuntimeBindingDefinition, RuntimeEnableReplayEvent,- RuntimeInspectorAsyncCompletionReceiver, RuntimeInspectorResponseReady,- ServiceWorkerRuntimeExceptionSnapshot, SessionOwnerRuntimeFrontendEnableResult,- monotonic_timestamp_seconds, renderer_command_turn_frontend_protocol_response,- runtime_remote_object_ids_in_map,+ RendererCommandDescriptor, RuntimeBindingDefinition, RuntimeInspectorAsyncCompletionReceiver,+ RuntimeInspectorResponseReady, ServiceWorkerRuntimeExceptionSnapshot,+ SessionOwnerRuntimeFrontendEnableResult, monotonic_timestamp_seconds,+ renderer_command_turn_frontend_protocol_response, runtime_remote_object_ids_in_map,};use crate::domains::actions::{ConsoleAction, HeapProfilerAction, RuntimeAction};use crate::domains::command_output::{@@ -56,9 +55,7 @@ use crate::domains::observable_output::{runtime_exception_thrown_background_event,};use crate::domains::runtime_context_events::{- RuntimeContextProtocolEvent, apply_runtime_context_protocol_event_side_effects_for_owner_typed,- emit_runtime_context_protocol_background_event_typed,- should_emit_child_default_context_inventory_replay_once_for_owner,+ RuntimeContextProtocolEvent, emit_runtime_context_protocol_background_event_typed,};const SHARED_WORKER_RUNTIME_BINDING_REPLAY_COMMAND_ID_BASE: u64 = 900_000_000;@@ -78,8 +75,8 @@ use super::{devtools_serialization_options_for_node_probe,},bindings::{- AddBindingParams, clear_runtime_binding_definitions_for_owner,- persist_runtime_binding_definition_for_owner, remove_runtime_binding_definitions_for_owner,+ AddBindingParams, persist_runtime_binding_definition_for_owner,+ remove_runtime_binding_definitions_for_owner,},command_classification::{MainRuntimeCommand, MainRuntimeInspectorCommand, RuntimeBindingCommand,@@ -87,6 +84,7 @@ use super::{WorkerRuntimeCommandKind,},evaluate::can_dispatch,+ native::apply_runtime_disable_projection_after_success_for_owner,};mod bidi_channels;@@ -2148,6 +2146,63 @@ mod protocol_neutral_tests {use crate::domains::actions::ConsoleAction;use crate::testing::TestContext;+ async fn assert_internal_runtime_enable_retains_output_fence(retire_owner: bool) {+ let mut ctx = TestContext::new();+ crate::domains::runtime::test_support::with_loaded_document_async(+ &mut ctx,+ "<p>Internal Runtime replay predecessor</p>",+ )+ .await;+ let owner = CommandOwnerScope::capture(&ctx.conn, None);+ let RuntimeCommandTaskStep::Pending(pending) =+ super::start_runtime_enable_command_for_owner(&mut ctx.conn, Some(79), owner)+ else {+ panic!("internal Runtime.enable must enter the renderer");+ };+ let completed = pending.wait().await;+ let super::CompletedRuntimeCommandKind::Enable(Ok(enable)) = &completed.completed else {+ panic!("Runtime.enable must complete its renderer replay");+ };+ let predecessor = enable+ .renderer_output_predecessor()+ .expect("internal replay must retain its exact output fence");+ let retired = if retire_owner {+ ctx.conn.browser_context.take()+ } else {+ None+ };+ let RuntimeCommandTaskStep::Complete(mut plan) =+ super::complete_pending_runtime_command(&mut ctx.conn, completed).await+ else {+ panic!("internal Runtime.enable must produce one terminal plan");+ };+ assert_eq!(plan.take_renderer_output_predecessor(), Some(predecessor));+ let mut messages = Vec::new();+ plan.emit_into(&mut messages, Some(79), None);+ if retire_owner {+ assert_eq!(messages.len(), 1);+ assert_eq!(messages[0]["error"]["code"], -32000);+ } else {+ assert!(+ messages+ .iter()+ .any(|message| message["method"] == "Runtime.executionContextCreated")+ );+ assert_eq!(messages.last().unwrap()["result"], json!({}));+ }+ drop(retired);+ }++ #[tokio::test]+ async fn internal_runtime_enable_replay_retains_output_fence() {+ assert_internal_runtime_enable_retains_output_fence(false).await;+ }++ #[tokio::test]+ async fn internal_runtime_enable_projection_error_retains_output_fence() {+ assert_internal_runtime_enable_retains_output_fence(true).await;+ }+use super::super::bidi_nodes::{BidiIncludeShadowTree, BidiNodeSerializationOptions,devtools_serialization_options_for_node_probe,diff --git a/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs b/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rsindex bef41bca5..0b10f8a1d 100644--- a/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs+++ b/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs@@ -824,75 +824,34 @@ pub(super) fn complete_pending_runtime_enable_command(completed: RuntimeCommandCompletionMeta,completed_enable: Result<CompletedRuntimeEnableEventsDispatch, String>,) -> CommandOutputPlan {- let replay = match completed_enable {- Ok(completed_enable) => match conn.complete_runtime_enable_events(completed_enable) {- Ok(replay) => replay,- Err(message) => return CommandOutputPlan::error(-32000, message),- },+ let completed_enable = match completed_enable {+ Ok(completed_enable) => completed_enable,Err(message) => return CommandOutputPlan::error(-32000, message),};- if let Err(message) =- apply_runtime_enable_projection_after_success(conn, &completed.owner_scope)- {- return CommandOutputPlan::error(-32000, message);- }- let frame_id = conn.runtime_session_owner_frame_id_for_owner(&completed.owner_scope);-- // Runtime.enable reports its existing inventory before acknowledging the- // enable. Keep replay and reply in one ordered plan, including worker- // adapters that synthesize the replay outside the V8 session sink.- let mut plan = CommandOutputPlan::default();- for event in replay.into_events() {- match event {- RuntimeEnableReplayEvent::Context(event) => {- if !should_emit_child_default_context_inventory_replay_once_for_owner(- conn,- &completed.owner_scope,- frame_id.as_deref(),- &event,- ) {- continue;- }- // Runtime.enable is a command-local replay, not a second live- // context producer. Record delivery only after the replay- // cursor accepts this exact event; marking it while merely- // preparing the replay would suppress the first delivery.- apply_runtime_context_protocol_event_side_effects_for_owner_typed(- conn,- &event,- &completed.owner_scope,- );- let mut background_events = Vec::new();- emit_runtime_context_protocol_background_event_typed(- &mut background_events,- event,- completed.session_id(),- );- for event in background_events {- plan.push_background_event(event);- }- }- RuntimeEnableReplayEvent::Background(event) => {- plan.push_background_event(event);- }+ // Internal/collector callers still return typed results on an independent+ // channel. Keep the dependency even if replay projection fails. Frontend+ // session-sink commands publish their replay and terminal in the journal.+ let predecessor = completed_enable.renderer_output_predecessor();+ let replay = conn+ .complete_runtime_enable_events(completed_enable)+ .and_then(|replay| {+ super::super::native::project_enable_replay(conn, &completed.owner_scope, replay)+ });+ let mut plan = match replay {+ Ok(events) => {+ let mut plan = CommandOutputPlan::default();+ plan.extend_background_events(events);+ plan.push_success();+ plan}+ Err(message) => CommandOutputPlan::error(-32000, message),+ };+ if let Some(predecessor) = predecessor {+ plan.set_renderer_output_predecessor(predecessor);}- plan.push_success();plan}-pub(super) fn apply_runtime_enable_projection_after_success(- conn: &mut CdpConnection,- owner: &CommandOwnerScope,-) -> Result<(), String> {- match conn.set_runtime_frontend_enabled_for_owner(owner, true) {- SessionOwnerRuntimeFrontendEnableResult::Handled => Ok(()),- SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {- Err("Runtime.enable succeeded after session owner disappeared".to_owned())- }- }-}-pub(super) fn complete_pending_runtime_binding_context_lookup_command(conn: &mut CdpConnection,completed: RuntimeCommandCompletionMeta,diff --git a/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs b/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rsindex dbcafc196..a5d94ff9d 100644--- a/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs+++ b/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs@@ -109,27 +109,6 @@ pub(super) fn start_runtime_run_if_waiting_for_debugger_command(}))}-pub(super) fn apply_runtime_disable_projection_after_success_for_owner(- conn: &mut CdpConnection,- owner: &CommandOwnerScope,-) -> Result<(), String> {- let was_enabled = conn- .target_runtime_session_state_for_owner(owner)- .is_some_and(|state| state.runtime_frontend_enabled);- match conn.set_runtime_frontend_enabled_for_owner(owner, false) {- SessionOwnerRuntimeFrontendEnableResult::Handled => {- advance_runtime_observable_cursors_to_current_for_owner(conn, owner);- if was_enabled {- clear_runtime_binding_definitions_for_owner(conn, owner)?;- }- Ok(())- }- SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {- Err("Runtime.disable succeeded after session owner disappeared".to_owned())- }- }-}-pub(super) fn start_runtime_discard_console_entries_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,diff --git a/moli-protocol/src/domains/runtime/native.rs b/moli-protocol/src/domains/runtime/native.rsnew file mode 100644index 000000000..f3b5ee600--- /dev/null+++ b/moli-protocol/src/domains/runtime/native.rs@@ -0,0 +1,146 @@+use moli_core::page::RendererRuntimeCommandOutput;+use moli_core::{+ RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererPageCommand,+ RendererPageReply,+};+use serde_json::json;++use super::bindings::clear_runtime_binding_definitions_for_owner;+use crate::conn::{+ BackgroundProtocolEvent, CdpConnection, Cmd, CommandOwnerScope, RuntimeEnableEventsReplay,+ RuntimeEnableReplayEvent, SessionOwnerRuntimeFrontendEnableResult,+};+use crate::domains::native::{self, NativeCommandStep};+use crate::domains::observable_output::advance_runtime_observable_cursors_to_current_for_owner;+use crate::domains::runtime_context_events::{+ apply_runtime_context_protocol_event_side_effects_for_owner_typed,+ emit_runtime_context_protocol_background_event_typed,+ should_emit_child_default_context_inventory_replay_once_for_owner,+};++pub(in crate::domains) fn try_start_native_command(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+) -> Option<NativeCommandStep> {+ let enabled = match cmd.action {+ "enable" => true,+ "disable" => false,+ _ => return None,+ };+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let inspector_session = conn.target_renderer_runtime_inspector_session_id_for_owner(&owner);+ Some(native::start(+ conn,+ cmd,+ if enabled {+ RendererPageCommand::runtime_enable_events(inspector_session)+ } else {+ RendererPageCommand::runtime_disable_events(inspector_session)+ },+ move |reply| match reply {+ Ok(RendererPageReply::RuntimeInspectorProtocolMessages(output)) => {+ let mut response = RendererNativeProtocolResponse::success(json!({}));+ response.state_updates.push(+ RendererNativeProtocolStateUpdate::RuntimeSubscription {+ enabled,+ output: Box::new(output),+ },+ );+ response+ }+ Err(error) => RendererNativeProtocolResponse::error(-32000, error.to_string()),+ _ => unreachable!("Runtime subscription commands must return frozen inspector output"),+ },+ ))+}++pub(in crate::domains) fn project_subscription_terminal(+ conn: &mut CdpConnection,+ owner: Option<&CommandOwnerScope>,+ enabled: bool,+ output: RendererRuntimeCommandOutput,+) -> Result<Vec<BackgroundProtocolEvent>, String> {+ let Some(owner) = owner else {+ if !enabled {+ return Ok(Vec::new());+ }+ return Err("Runtime.enable completed after session owner disappeared".to_owned());+ };+ let replay = conn.prepare_runtime_subscription_events_for_owner(owner, output)?;+ if enabled {+ project_enable_replay(conn, owner, replay)+ } else {+ apply_runtime_disable_projection_after_success_for_owner(conn, owner)?;+ Ok(project_replay_events(conn, owner, replay))+ }+}++/// All replay state and deduplication advance at the same delivery boundary as+/// the frozen replay. There is no dependency on polling the adapter completion.+pub(super) fn project_enable_replay(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+ replay: RuntimeEnableEventsReplay,+) -> Result<Vec<BackgroundProtocolEvent>, String> {+ match conn.set_runtime_frontend_enabled_for_owner(owner, true) {+ SessionOwnerRuntimeFrontendEnableResult::Handled => {}+ SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {+ return Err("Runtime.enable succeeded after session owner disappeared".to_owned());+ }+ }+ Ok(project_replay_events(conn, owner, replay))+}++fn project_replay_events(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+ replay: RuntimeEnableEventsReplay,+) -> Vec<BackgroundProtocolEvent> {+ let frame_id = conn.runtime_session_owner_frame_id_for_owner(owner);+ let mut events = Vec::new();+ for event in replay.into_events() {+ match event {+ RuntimeEnableReplayEvent::Context(event) => {+ if !should_emit_child_default_context_inventory_replay_once_for_owner(+ conn,+ owner,+ frame_id.as_deref(),+ &event,+ ) {+ continue;+ }+ apply_runtime_context_protocol_event_side_effects_for_owner_typed(+ conn, &event, owner,+ );+ emit_runtime_context_protocol_background_event_typed(+ &mut events,+ event,+ owner.session_id(),+ );+ }+ RuntimeEnableReplayEvent::Background(event) => events.push(event),+ }+ }+ events+}++pub(super) fn apply_runtime_disable_projection_after_success_for_owner(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+) -> Result<(), String> {+ let was_enabled = conn+ .target_runtime_session_state_for_owner(owner)+ .is_some_and(|state| state.runtime_frontend_enabled);+ match conn.set_runtime_frontend_enabled_for_owner(owner, false) {+ SessionOwnerRuntimeFrontendEnableResult::Handled => {+ advance_runtime_observable_cursors_to_current_for_owner(conn, owner);+ if was_enabled {+ clear_runtime_binding_definitions_for_owner(conn, owner)?;+ }+ Ok(())+ }+ SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {+ Err("Runtime.disable succeeded after session owner disappeared".to_owned())+ }+ }+}diff --git a/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs b/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rsindex f64f9fc33..a98a73b4a 100644--- a/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs+++ b/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs@@ -29,6 +29,244 @@ async fn enable_with_page_emits_execution_context_created() {);}+#[tokio::test]+async fn runtime_enable_publishes_ordered_replay_without_polling_command_completions() {+ let mut ctx = TestContext::new();+ with_loaded_document_for_active_target_async(+ &mut ctx,+ "<!doctype html><script>console.log('buffered-enable-replay')</script>",+ "SID-enable-order",+ "TID-enable-order",+ )+ .await;+ ctx.sent.clear();++ // Hold all adapter completions. Only the renderer journal is allowed to+ // deliver the replies, including Runtime.enable's replay and state changes.+ let mut pending = Vec::new();+ for (id, method) in [+ (11_021, "DOM.getDocument"),+ (11_022, "Runtime.enable"),+ (11_023, "DOM.getDocument"),+ ] {+ let step = ctx.conn.start_command_dispatch(+ &json!({"id": id, "method": method, "sessionId": "SID-enable-order"}).to_string(),+ );+ assert!(matches!(&step, CdpCommandTaskStep::Pending(_)));+ pending.push(step);+ }+ let following = ctx+ .wait_for_scheduler_message("terminal after Runtime.enable replay", |message| {+ message["id"] == 11_023+ })+ .await;+ assert!(following.get("result").is_some(), "{following:?}");++ let preceding = ctx+ .sent+ .iter()+ .position(|message| message["id"] == 11_021)+ .expect("the earlier renderer terminal must already be delivered");+ let context = ctx+ .sent+ .iter()+ .position(|message| message["method"] == "Runtime.executionContextCreated")+ .expect("Runtime.enable must deliver its frozen context replay");+ let console = ctx+ .sent+ .iter()+ .position(|message| {+ message["method"] == "Runtime.consoleAPICalled"+ && message["params"]["args"][0]["value"] == "buffered-enable-replay"+ })+ .expect("Runtime.enable must deliver buffered console replay");+ let terminal = ctx+ .sent+ .iter()+ .position(|message| message["id"] == 11_022)+ .expect("Runtime.enable must publish without its completion being polled");+ assert!(preceding < context && context < terminal, "{:?}", ctx.sent);+ assert!(preceding < console && console < terminal, "{:?}", ctx.sent);+ assert_eq!(ctx.sent[terminal]["result"], json!({}));+ assert!(+ ctx.sent+ .iter()+ .all(|message| message["sessionId"] == "SID-enable-order")+ );+ let owner = crate::conn::CommandOwnerScope::for_session("SID-enable-order");+ let state = ctx+ .conn+ .target_runtime_session_state_for_owner(&owner)+ .unwrap();+ assert!(state.runtime_frontend_enabled && state.runtime_contexts_reported_to_frontend);++ // Cancel adapters after publication, then observe another concrete output.+ // Cancellation cannot retract replay or produce a second terminal.+ drop(pending);+ ctx.process_async(json!({+ "id": 11_024, "method": "DOM.getDocument", "sessionId": "SID-enable-order"+ }))+ .await;+ assert_eq!(+ ctx.sent+ .iter()+ .filter(|message| message["id"] == 11_022)+ .count(),+ 1+ );+}++#[tokio::test]+async fn runtime_enable_retired_owner_error_keeps_journal_order_and_single_terminal() {+ let mut ctx = TestContext::new();+ with_loaded_document_async(&mut ctx, "<p>retired Runtime.enable replay</p>").await;+ // Admit the live stream's owner before retiring it with output in flight.+ ctx.process_async(json!({"id": 11_025, "method": "DOM.getDocument"}))+ .await;+ ctx.sent.clear();+ let preceding = ctx+ .conn+ .start_command_dispatch(&json!({"id": 11_026, "method": "DOM.getDocument"}).to_string());+ let CdpCommandTaskStep::Pending(enable) = ctx+ .conn+ .start_command_dispatch(&json!({"id": 11_027, "method": "Runtime.enable"}).to_string())+ else {+ panic!("Runtime.enable must enter the renderer");+ };+ // This receipt proves the journal commit. Leave protocol ingress unpolled+ // until the original Browser owner has disappeared.+ let completed = enable.wait().await;+ let retired = ctx.conn.browser_context.take().unwrap();+ let error = ctx+ .wait_for_scheduler_message("retired Runtime.enable terminal", |message| {+ message["id"] == 11_027+ })+ .await;+ assert_eq!(error["error"]["code"], -32000);+ assert!(+ ctx.sent+ .iter()+ .any(|message| { message["id"] == 11_026 && message.get("result").is_some() }),+ "the retired error cannot overtake the earlier terminal: {:?}",+ ctx.sent+ );+ assert!(+ !ctx.sent+ .iter()+ .any(|message| message["method"] == "Runtime.executionContextCreated")+ );+ assert!(+ ctx.conn.browser_context.is_none(),+ "replay cannot recreate a retired owner"+ );++ let CdpCommandTaskStep::Complete(outcome) =+ ctx.conn.complete_pending_command_dispatch(completed).await+ else {+ panic!("published native terminal must complete its adapter");+ };+ let (messages, scheduler_events, predecessor) = outcome.into_protocol_event_parts();+ assert!(+ messages.is_empty(),+ "adapter completion cannot emit a second terminal: {messages:?}"+ );+ assert!(scheduler_events.is_empty());+ let sent_start = ctx.sent.len();+ ctx.route_direct_command_renderer_predecessor_for_test(+ predecessor.expect("the adapter must acknowledge its published terminal"),+ )+ .await;+ assert!(+ !ctx.sent[sent_start..]+ .iter()+ .any(|message| message["id"] == 11_027)+ );+ drop(preceding);+ drop(retired);+}++#[tokio::test]+async fn runtime_enable_ready_terminal_does_not_wait_for_an_unresolved_expression() {+ let mut ctx = TestContext::new();+ with_loaded_document_async(&mut ctx, "<p>pending expression and ready enable</p>").await;+ enable_runtime_and_take_execution_context_id_async(&mut ctx, 11_028).await;+ ctx.sent.clear();+ ctx.process_async(json!({+ "id": 11_029, "method": "Runtime.evaluate",+ "params": {+ "expression": "new Promise(resolve => { globalThis.__resolveEnablePending = resolve; console.log('enable-pending-started'); })",+ "awaitPromise": true, "returnByValue": true+ }+ })).await;+ ctx.wait_for_scheduler_message("console output from unresolved expression", |message| {+ message["method"] == "Runtime.consoleAPICalled"+ && message["params"]["args"][0]["value"] == "enable-pending-started"+ })+ .await;++ ctx.process_async(json!({"id": 11_030, "method": "Runtime.enable"}))+ .await;+ assert_eq!(take_response_by_id(&mut ctx, 11_030)["result"], json!({}));+ assert!(ctx.conn.has_pending_inspector_awaits());+ assert!(!ctx.sent.iter().any(|message| message["id"] == 11_029));++ ctx.process_async(json!({+ "id": 11_031, "method": "Runtime.evaluate",+ "params": {"expression": "globalThis.__resolveEnablePending('settled-explicitly')"}+ }))+ .await;+ let settled = wait_for_response_by_id_async(&mut ctx, None, 11_029).await;+ assert_eq!(settled["result"]["result"]["value"], "settled-explicitly");+}++#[tokio::test]+async fn runtime_enable_then_disable_keeps_state_in_delivery_order() {+ for (first, second, expected_enabled) in [+ ("Runtime.enable", "Runtime.disable", false),+ ("Runtime.disable", "Runtime.enable", true),+ ] {+ let mut ctx = TestContext::new();+ with_loaded_document_async(&mut ctx, "<p>ordered Runtime state</p>").await;+ let first = ctx+ .conn+ .start_command_dispatch(&json!({"id": 11_032, "method": first}).to_string());+ let second = ctx+ .conn+ .start_command_dispatch(&json!({"id": 11_033, "method": second}).to_string());+ let (messages, _) = ctx+ .complete_command_task_step_with_events_for_test(second)+ .await;+ assert!(+ messages+ .iter()+ .any(|message| message["id"] == 11_033 && message["result"] == json!({}))+ );+ assert_eq!(+ ctx.conn+ .target_runtime_session_state_for_session(None)+ .unwrap()+ .runtime_frontend_enabled,+ expected_enabled,+ "subscription state must follow journal delivery: {messages:?}"+ );+ let (late, _) = ctx+ .complete_command_task_step_with_events_for_test(first)+ .await;+ assert!(+ !late.iter().any(|message| message["id"] == 11_032),+ "late adapter completion cannot repeat a committed terminal: {late:?}"+ );+ assert_eq!(+ ctx.conn+ .target_runtime_session_state_for_session(None)+ .unwrap()+ .runtime_frontend_enabled,+ expected_enabled,+ "late completion cannot reverse a delivered subscription change"+ );+ }+}+#[tokio::test]async fn devtools_console_runtime_commands_accept_emitted_unique_context_id() {let mut ctx = TestContext::new();@@ -296,7 +534,9 @@ async fn enable_with_page_can_complete_through_pending_command_task() {let raw = json!({"id": 11_001, "method": "Runtime.enable"}).to_string();let step = ctx.conn.start_command_dispatch(&raw);- let (messages, scheduler_events) = complete_command_task_step_for_test(&mut ctx, step).await;+ let (messages, scheduler_events) = ctx+ .complete_command_task_step_with_events_for_test(step)+ .await;assert!(scheduler_events.is_empty(),diff --git a/moli-protocol/src/domains/runtime/tests/navigation.rs b/moli-protocol/src/domains/runtime/tests/navigation.rsindex 3712007a2..1cd48b337 100644--- a/moli-protocol/src/domains/runtime/tests/navigation.rs+++ b/moli-protocol/src/domains/runtime/tests/navigation.rs@@ -55,7 +55,9 @@ async fn enable_uses_fresh_initial_document_without_adapter() {}).to_string();let step = ctx.conn.start_command_dispatch(&raw);- let (messages, scheduler_events) = complete_command_task_step_for_test(&mut ctx, step).await;+ let (messages, scheduler_events) = ctx+ .complete_command_task_step_with_events_for_test(step)+ .await;assert!(scheduler_events.is_empty(),diff --git a/moli-renderer-v8/src/devtools/command.rs b/moli-renderer-v8/src/devtools/command.rsindex d39672495..12737a1a5 100644--- a/moli-renderer-v8/src/devtools/command.rs+++ b/moli-renderer-v8/src/devtools/command.rs@@ -580,6 +580,7 @@ impl RendererInspectorCommandEnvelope {pub(crate) fn cdp_nav_timing_label(&self) -> Option<&'static str> {match self.main_thread_payload() {RendererInspectorPageCommand::RuntimeEnableEvents => Some("RuntimeEnableEvents"),+ RendererInspectorPageCommand::RuntimeDisableEvents => Some("RuntimeDisableEvents"),RendererInspectorPageCommand::ApplyRuntimeProtocolState { .. } => {Some("ApplyRuntimeProtocolState")}diff --git a/moli-renderer-v8/src/runtime/owner.rs b/moli-renderer-v8/src/runtime/owner.rsindex b50918c1c..129242691 100644--- a/moli-renderer-v8/src/runtime/owner.rs+++ b/moli-renderer-v8/src/runtime/owner.rs@@ -728,7 +728,7 @@ enum RenderRuntimeTurn {scope_id: PageVmRuntimeCommandOutputScopeId,reply: Box<RendererPageReply>,should_follow_pending_navigation: bool,- turn_records: Vec<PendingRendererOutputRecord>,+ command_output_cursor: Option<RendererOutputCursor>,capture_policy: super::RendererPageStateCapturePolicy,},ResumeLivePageDocumentLifecycleAfterReply {diff --git a/moli-renderer-v8/src/runtime/owner/owner_loop.rs b/moli-renderer-v8/src/runtime/owner/owner_loop.rsindex 63cc0cd50..514b534a1 100644--- a/moli-renderer-v8/src/runtime/owner/owner_loop.rs+++ b/moli-renderer-v8/src/runtime/owner/owner_loop.rs@@ -1119,7 +1119,7 @@ impl RendererOwnerHandle {scope_id,reply,should_follow_pending_navigation,- turn_records,+ command_output_cursor,capture_policy,} => {self.continue_live_page_runtime_command_lifecycle_turn(@@ -1127,7 +1127,7 @@ impl RendererOwnerHandle {scope_id,*reply,should_follow_pending_navigation,- turn_records,+ command_output_cursor,capture_policy,).awaitdiff --git a/moli-renderer-v8/src/runtime/owner/page_commands.rs b/moli-renderer-v8/src/runtime/owner/page_commands.rsindex 85518c722..35c3b4987 100644--- a/moli-renderer-v8/src/runtime/owner/page_commands.rs+++ b/moli-renderer-v8/src/runtime/owner/page_commands.rs@@ -275,7 +275,7 @@ impl RendererOwnerHandle {let RendererPageCommandDispatch {reply,replacement_lifecycle,- turn_records,+ command_output_cursor,} = match reply_result {Ok(dispatch) => dispatch,Err(error) => {@@ -301,7 +301,7 @@ impl RendererOwnerHandle {scope_id,reply: Box::new(reply),should_follow_pending_navigation,- turn_records,+ command_output_cursor,capture_policy,}),wake_token: token,@@ -312,7 +312,7 @@ impl RendererOwnerHandle {entry,reply,should_follow_pending_navigation,- turn_records,+ command_output_cursor,replacement_lifecycle,capture_policy,)@@ -325,7 +325,7 @@ impl RendererOwnerHandle {scope_id: PageVmRuntimeCommandOutputScopeId,reply: RendererPageReply,should_follow_pending_navigation: bool,- turn_records: Vec<PendingRendererOutputRecord>,+ command_output_cursor: Option<RendererOutputCursor>,capture_policy: super::RendererPageStateCapturePolicy,) -> RenderRuntimeDispatchOutcome {let entry = match take_entry_for_command_on_bound_owner_local_store(token) {@@ -347,7 +347,7 @@ impl RendererOwnerHandle {scope_id,reply: Box::new(reply),should_follow_pending_navigation,- turn_records,+ command_output_cursor,capture_policy,}),wake_token: token,@@ -359,7 +359,7 @@ impl RendererOwnerHandle {entry,reply,should_follow_pending_navigation,- turn_records,+ command_output_cursor,None,capture_policy,)@@ -378,23 +378,13 @@ impl RendererOwnerHandle {mut entry: LivePageEntry,reply: RendererPageReply,should_follow_pending_navigation: bool,- turn_records: Vec<PendingRendererOutputRecord>,+ command_output_cursor: Option<RendererOutputCursor>,replacement_lifecycle: Option<DocumentLifecycleTurnOutcome>,capture_policy: super::RendererPageStateCapturePolicy,) -> RenderRuntimeDispatchOutcome {if should_follow_pending_navigation&& entry.page_vm().vm().has_pending_location_navigation(){- // Preserve the old Document's ordered actions before following its- // navigation, including stop() actions and no-document responses.- if !turn_records.is_empty() {- entry- .page_vm()- .append_renderer_command_output_records(turn_records);- if let Some(output) = entry.page_vm_mut().settle_renderer_output_publication() {- self.publish_renderer_output(output);- }- }return self.continue_live_page_pending_navigation(token,entry,@@ -429,7 +419,7 @@ impl RendererOwnerHandle {token,entry,reply,- turn_records,+ command_output_cursor,post_response_continuation,capture_policy,)@@ -465,7 +455,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::Unit,- Vec::new(),+ None,).await}@@ -546,7 +536,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::Unit,- Vec::new(),+ None,).await}@@ -628,7 +618,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::DocumentQuerySelectorNode(node),- Vec::new(),+ None,None,capture_policy,)@@ -692,7 +682,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::Bool(true),- Vec::new(),+ None,None,capture_policy,)@@ -704,7 +694,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::Bool(false),- Vec::new(),+ None,None,capture_policy,)@@ -759,7 +749,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::Unit,- Vec::new(),+ None,None,capture_policy,)@@ -877,7 +867,7 @@ impl RendererOwnerHandle {token,entry,reply,- Vec::new(),+ None,None,capture_policy,)@@ -885,12 +875,7 @@ impl RendererOwnerHandle {}}Ok(PageVmRuntimeExpressionAwaitAdvance::Progressed { pending_call }) => {- entry.page_vm().vm().append_live_command_output_prefix();- let output = entry.page_vm_mut().settle_renderer_output_publication();self.restore_live_page_entry(token, entry);- if let Some(output) = output {- self.publish_renderer_output(output);- }RenderRuntimeDispatchOutcome::ContinueNextTurn(Box::new(RenderRuntimeTurn::WaitLivePageRuntimeExpressionAwait {token,@@ -918,12 +903,7 @@ impl RendererOwnerHandle {)).into()} else {- entry.page_vm().vm().append_live_command_output_prefix();- let output = entry.page_vm_mut().settle_renderer_output_publication();self.restore_live_page_entry(token, entry);- if let Some(output) = output {- self.publish_renderer_output(output);- }let ready_at = Instant::now().checked_add(sleep_for).unwrap_or(deadline)@@ -984,7 +964,7 @@ impl RendererOwnerHandle {token,entry,RendererPageReply::Unit,- Vec::new(),+ None,None,capture_policy,)diff --git a/moli-renderer-v8/src/runtime/owner/page_turn_completion.rs b/moli-renderer-v8/src/runtime/owner/page_turn_completion.rsindex 07de54088..db24a3815 100644--- a/moli-renderer-v8/src/runtime/owner/page_turn_completion.rs+++ b/moli-renderer-v8/src/runtime/owner/page_turn_completion.rs@@ -152,13 +152,13 @@ impl RendererOwnerHandle {token: RendererPageToken,entry: LivePageEntry,reply: RendererPageReply,- turn_records: Vec<PendingRendererOutputRecord>,+ command_output_cursor: Option<RendererOutputCursor>,) -> RenderRuntimeDispatchOutcome {self.finish_live_page_entry_with_page_state_and_continuation(token,entry,reply,- turn_records,+ command_output_cursor,None,super::RendererPageStateCapturePolicy::FullReport,)@@ -170,21 +170,13 @@ impl RendererOwnerHandle {token: RendererPageToken,mut entry: LivePageEntry,reply: RendererPageReply,- turn_records: Vec<PendingRendererOutputRecord>,+ command_output_cursor: Option<RendererOutputCursor>,post_response_continuation: Option<RendererPageCommandPostResponseContinuation>,capture_policy: super::RendererPageStateCapturePolicy,) -> RenderRuntimeDispatchOutcome {let (runtime_command_output, runtime_session_response) =entry.page_vm_mut().take_runtime_command_settlement();- let expected_command_output_cursor = if turn_records.is_empty() {- None- } else {- Some(- entry- .page_vm()- .append_renderer_command_output_records(turn_records),- )- };+ let expected_command_output_cursor = command_output_cursor;#[cfg(test)]if self.state@@ -382,7 +374,7 @@ impl RendererOwnerHandle {token,entry,*reply,- Vec::new(),+ None,None,capture_policy,)@@ -489,7 +481,7 @@ impl RendererOwnerHandle {token,entry,reply,- Vec::new(),+ None,None,capture_policy,)diff --git a/moli-renderer-v8/src/runtime/owner_local_store/bound.rs b/moli-renderer-v8/src/runtime/owner_local_store/bound.rsindex 4ac07710a..c1ecf33c3 100644--- a/moli-renderer-v8/src/runtime/owner_local_store/bound.rs+++ b/moli-renderer-v8/src/runtime/owner_local_store/bound.rs@@ -461,7 +461,9 @@ pub(in crate::runtime) async fn dispatch_async_command_on_entry_via_local_task(pub(in crate::runtime) struct RendererPageCommandDispatch {pub(in crate::runtime) reply: RendererPageReply,pub(in crate::runtime) replacement_lifecycle: Option<DocumentLifecycleTurnOutcome>,- pub(in crate::runtime) turn_records: Vec<PendingRendererOutputRecord>,+ /// Records already belong to the Page journal; only their exact completion+ /// dependency crosses owner continuations.+ pub(in crate::runtime) command_output_cursor: Option<RendererOutputCursor>,}pub(in crate::runtime) async fn advance_runtime_command_lifecycle_on_entry_via_local_task(diff --git a/moli-renderer-v8/src/runtime/owner_local_store/mod.rs b/moli-renderer-v8/src/runtime/owner_local_store/mod.rsindex 1876f74a4..104a0d95e 100644--- a/moli-renderer-v8/src/runtime/owner_local_store/mod.rs+++ b/moli-renderer-v8/src/runtime/owner_local_store/mod.rs@@ -2817,7 +2817,7 @@ impl RendererOwnerLocalStore {} else {Ok(())};- let turn_records = entry+ let command_output_cursor = entry.page_vm_mut().finish_command_turn_output_scope(command_turn_output_scope);let replacement_lifecycle = replacement_lifecycle?;@@ -2826,7 +2826,7 @@ impl RendererOwnerLocalStore {Ok(RendererPageCommandDispatch {reply: reply?,replacement_lifecycle,- turn_records,+ command_output_cursor,})}diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rsindex 550b2e021..d90d1a4d0 100644--- a/moli-renderer-v8/src/runtime/page_commands.rs+++ b/moli-renderer-v8/src/runtime/page_commands.rs@@ -1205,6 +1205,9 @@ impl PageVm {RendererInspectorPageCommand::RuntimeEnableEvents => self.runtime_enable_events(inspector_session_id).map(RendererPageReply::RuntimeInspectorProtocolMessages),+ RendererInspectorPageCommand::RuntimeDisableEvents => self+ .runtime_disable_events(inspector_session_id)+ .map(RendererPageReply::RuntimeInspectorProtocolMessages),RendererInspectorPageCommand::ApplyRuntimeProtocolState {session_restore_snapshots,isolated_worlds,diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rsindex 8260c949d..87312cf3c 100644--- a/moli-renderer-v8/src/runtime/page_dom.rs+++ b/moli-renderer-v8/src/runtime/page_dom.rs@@ -1837,6 +1837,63 @@ impl PageVm {Ok(output)}+ pub(crate) fn runtime_disable_events(+ &mut self,+ inspector_session_id: Option<&str>,+ ) -> Result<RendererRuntimeCommandOutput> {+ const INTERNAL_RUNTIME_DISABLE_ID: u64 = 900_005;+ let was_enabled = self.runtime_inspector_frontend_restore_enabled(inspector_session_id);+ let raw_request = serde_json::to_string(&json!({+ "id": INTERNAL_RUNTIME_DISABLE_ID,+ "method": "Runtime.disable",+ }))?;+ let mut messages = self+ .vm_mut()+ .dispatch_internal_inspector_protocol_message_for_session(+ inspector_session_id,+ &raw_request,+ i32::try_from(INTERNAL_RUNTIME_DISABLE_ID)+ .expect("bounded internal Runtime.disable call id"),+ )?;+ anyhow::ensure!(+ renderer_inspector_response_succeeded(&messages, INTERNAL_RUNTIME_DISABLE_ID),+ "Runtime.disable did not complete successfully"+ );+ self.record_runtime_inspector_protocol_configuration_command(+ inspector_session_id,+ &raw_request,+ &messages,+ );++ // Keep binding work on this renderer turn. Rebuilding it later from a+ // Browser completion could restore stale bindings after another call.+ let session_key = DevToolsSessionKey::from_wire_session_id(inspector_session_id);+ let session_bindings = if was_enabled {+ self.runtime_bindings+ .retain(|binding| binding.devtools_session.as_ref() != Some(&session_key));+ Vec::new()+ } else {+ self.vm()+ .inspector_session_runtime_bindings(inspector_session_id)+ };+ let stored_bindings = self.runtime_bindings.clone();+ self.set_runtime_binding_state(inspector_session_id, &stored_bindings, &session_bindings);+ messages.extend(+ self.vm_mut()+ .take_runtime_inspector_messages(inspector_session_id),+ );+ let mut output = RendererRuntimeCommandOutput::from_messages(+ messages+ .into_iter()+ .filter(RendererRuntimeInspectorMessage::has_v8_inspector_method)+ .collect(),+ );+ if let Some(state) = self.vm().inspector_v8_session_state(inspector_session_id) {+ output.set_v8_state_update(state);+ }+ Ok(output)+ }+pub(crate) fn add_runtime_binding(&mut self,inspector_session_id: Option<&str>,diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rsindex 6f849fe6d..2ed05de2c 100644--- a/moli-renderer-v8/src/runtime/page_surface.rs+++ b/moli-renderer-v8/src/runtime/page_surface.rs@@ -4644,6 +4644,7 @@ pub(crate) enum RendererInspectorPageCommand {deferred_response: RendererRuntimeInspectorResponseSender,},RuntimeEnableEvents,+ RuntimeDisableEvents,ApplyRuntimeProtocolState {session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,@@ -5334,6 +5335,13 @@ impl RendererPageCommand {)}+ pub fn runtime_disable_events(inspector_session_id: Option<String>) -> Self {+ Self::inspector_command(+ inspector_session_id,+ RendererInspectorPageCommand::RuntimeDisableEvents,+ )+ }+pub fn apply_runtime_protocol_state(inspector_session_id: Option<String>,session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,diff --git a/moli-renderer-v8/src/runtime/page_vm/command_turn_output.rs b/moli-renderer-v8/src/runtime/page_vm/command_turn_output.rsindex 39ac99c45..f4d6998de 100644--- a/moli-renderer-v8/src/runtime/page_vm/command_turn_output.rs+++ b/moli-renderer-v8/src/runtime/page_vm/command_turn_output.rs@@ -78,7 +78,7 @@ impl PageVm {pub(crate) fn finish_command_turn_output_scope(&mut self,scope: RendererCommandTurnOutputScope,- ) -> Vec<PendingRendererOutputRecord> {+ ) -> Option<RendererOutputCursor> {self.flush_pending_dom_mutation_event_batches();assert!(scope.pending_dom_mutation_batch_start <= self.pending_dom_mutation_event_batches.len(),@@ -87,6 +87,10 @@ impl PageVm {let dom_mutation_batches = self.pending_dom_mutation_event_batches.split_off(scope.pending_dom_mutation_batch_start);- scope.finish(dom_mutation_batches)+ let records = scope.finish(dom_mutation_batches);+ // The Page journal owns ready output even when the command must yield+ // or follow a navigation. Continuations retain only the exact cursor+ // needed by the independent internal completion channel.+ (!records.is_empty()).then(|| self.append_renderer_command_output_records(records))}}diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rsindex 371014fe0..4467d86a7 100644--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs@@ -1845,6 +1845,10 @@ impl PageVm {pub(super) fn settle_renderer_output_publication(&mut self,) -> Option<crate::runtime::RendererOutputPublication> {+ // A command can still be pending when its owner yields. Its ready+ // prefix belongs in this turn's publication, ahead of the DOM facts,+ // rather than waiting for the command's eventual completion.+ self.vm().append_live_command_output_prefix();// Every owner turn must freeze its DOM facts into the same ordered// stream as its other observations before settlement. Command turns// have already moved their causal suffix into command records; thisdiff --git a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs b/moli-renderer-v8/src/runtime/protocol_output/native_response.rsindex e1326ddfe..39ff2af20 100644--- a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs@@ -17,7 +17,7 @@ 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)]+#[derive(Clone, Debug, PartialEq)]pub struct RendererNativeProtocolResponse {pub result: Result<serde_json::Value, RendererNativeProtocolError>,pub notifications: Vec<RendererNativeProtocolNotification>,@@ -70,9 +70,17 @@ impl RendererNativeProtocolResponse {}/// 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)]+/// never callbacks into a live Page. Attachment retirement discards document+/// updates; command-local replay can instead fail the terminal at projection.+#[derive(Clone, Debug, PartialEq)]pub enum RendererNativeProtocolStateUpdate {+ /// Frozen V8 replay and state, projected by the ordered protocol consumer+ /// before this terminal. Retirement can still turn enable into an error;+ /// neither the adapter waiter nor a replacement attachment owns that choice.+ RuntimeSubscription {+ enabled: bool,+ output: Box<crate::runtime::RendererRuntimeCommandOutput>,+ },WebMcpEnabled(bool),/// Register object IDs from the successful terminal result before delivery./// The reply already owns the payload; this update only retains its group.@@ -96,7 +104,7 @@ type NativeResponseProjection = Box</// 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)]+#[derive(Clone, Debug, PartialEq)]pub struct RendererNativeCommandTerminal {pub command_id: FrontendCommandId,pub session: DevToolsSessionKey,diff --git a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rsindex 435d9cf2a..0fe27fda1 100644--- a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs@@ -34,6 +34,17 @@ fn native_terminal_charge_bytes(terminal: &super::RendererNativeCommandTerminal)});for update in &response.state_updates {charge = charge.saturating_add(match update {+ super::RendererNativeProtocolStateUpdate::RuntimeSubscription { output, .. } => {+ output.messages().iter().fold(+ std::mem::size_of_val(output.as_ref())+ .saturating_add(output.v8_state_update().map_or(0, |state| state.len())),+ |total, message| {+ total.saturating_add(runtime_inspector_message_transport_charge_bytes(+ message,+ ))+ },+ )+ }super::RendererNativeProtocolStateUpdate::WebMcpEnabled(_) => 0,super::RendererNativeProtocolStateUpdate::RemoteObjects { object_group } => {object_group.as_deref().map_or(0, string_charge)diff --git a/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rs b/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rsindex e68f2c3cd..8473489be 100644--- a/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rs+++ b/moli-renderer-v8/src/runtime/tests/extracted/runtime_scripts.rs@@ -4053,29 +4053,166 @@ async fn pending_expression_publishes_console_output_before_settlement() {.await;dispatch_runtime_protocol_with_output_for_test(&page,- serde_json::json!({"id":731,"method":"Runtime.enable"}),+ serde_json::json!({"id": 731, "method": "Runtime.enable"}),).await.unwrap();output_rx.drain();- let pending=page.enqueue_async_command(RendererPageCommand::EvaluateExpression {- expression:"new Promise(resolve => setTimeout(() => { console.log('owner-output-during-await'); setTimeout(() => resolve('done'), 60000); }, 0))".to_owned(),- await_promise:true,- }).unwrap();- let observed=tokio::time::timeout(Duration::from_secs(3),async {- while let Some(output)=output_rx.recv().await {- if output.records().iter().any(|record|matches!(record.item(),- RendererOutputItem::Observation(RendererProtocolObservation::RuntimeInspector(batch))- if batch.messages.iter().any(|message|matches!(message,- RendererRuntimeInspectorMessage::Protocol(message)- if message.get("method")==Some(&serde_json::json!("Runtime.consoleAPICalled"))- && message.to_string().contains("owner-output-during-await"))))) {return true;}+ let pending = page+ .enqueue_async_command(RendererPageCommand::EvaluateExpression {+ expression: r#"new Promise(resolve => {+ globalThis.__resolvePendingExpression = resolve;+ console.log('owner-output-before-await');+ setTimeout(() => console.log('owner-output-during-await'), 0);+ })"#+ .to_owned(),+ await_promise: true,+ })+ .expect("the pending expression should enqueue");+ let mut completion = Box::pin(pending.wait());+ let observed = tokio::time::timeout(Duration::from_secs(3), async {+ let mut observed = Vec::new();+ while observed.len() < 2 {+ let output = tokio::select! {+ result = &mut completion => panic!("the unresolved expression completed; error: {:?}", result.err()),+ output = output_rx.recv() => output.expect("the output stream should stay open"),+ };+ for record in output.records() {+ let RendererOutputItem::Observation(RendererProtocolObservation::RuntimeInspector(batch)) = record.item() else {+ continue;+ };+ for message in &batch.messages {+ let RendererRuntimeInspectorMessage::Protocol(message) = message else {+ continue;+ };+ if message.get("method").and_then(serde_json::Value::as_str)+ == Some("Runtime.consoleAPICalled")+ && let Some(value) = message["params"]["args"][0]["value"].as_str()+ {+ observed.push(value.to_owned());+ }+ }+ }}- false- }).await;+ observed+ })+ .await+ .expect("console output must arrive before promise settlement");+ assert_eq!(+ observed,+ ["owner-output-before-await", "owner-output-during-await"]+ );++ tokio::time::timeout(+ Duration::from_secs(3),+ page.run_async_command(RendererPageCommand::EvaluateExpression {+ expression: "__resolvePendingExpression('done'); 'resolved'".to_owned(),+ await_promise: false,+ }),+ )+ .await+ .expect("a pending expression must allow another command to run")+ .expect("the resolver command should succeed");+ let output = tokio::time::timeout(Duration::from_secs(3), &mut completion)+ .await+ .expect("the expression should complete after its explicit resolution")+ .expect("the resolved expression should succeed");+ let (completion, _) = output.into_completion_and_predecessor();+ let (reply, _, _) = completion.into_parts();+ assert_eq!(renderer_json_value(reply), Some(serde_json::json!("done")));page.close_async().await.expect("close pending-expression page");- let _ = pending.wait().await;- assert!(observed.expect("output must arrive without promise settlement"));+}++#[tokio::test(flavor = "multi_thread")]+async fn navigation_follow_publishes_command_output_before_replacing_document() {+ 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 url = url::Url::parse("https://example.test/navigation-command-output").unwrap();+ let mut page =+ create_test_html_page(&runtime, &loader, url, "<!doctype html><body>source</body>").await;+ dispatch_runtime_protocol_with_output_for_test(+ &page,+ serde_json::json!({"id": 732, "method": "Runtime.enable"}),+ )+ .await+ .unwrap();+ page.run_async_command(RendererPageCommand::EvaluateExpression {+ expression: "document.title = 'source document'".to_owned(),+ await_promise: false,+ })+ .await+ .expect("the source Document title should publish");+ let initial_publications = output_rx.drain();+ let source_stream = initial_publications+ .last()+ .expect("Runtime.enable must publish the source Document's output")+ .cursor()+ .stream();+ let source_document = initial_publications+ .iter()+ .flat_map(|publication| publication.records())+ .find_map(|record| match record.item() {+ RendererOutputItem::Observation(RendererProtocolObservation::DocumentTitleChanged(+ change,+ )) if change.title == "source document" => Some(change.source_document),+ _ => None,+ })+ .expect("the source title observation must identify its exact Document");+ let replacement_url = "data:text/html;charset=utf-8,%3C!doctype%20html%3E%3Ctitle%3Ereplacement%3C/title%3E%3Cbody%3Ereplacement%3C/body%3E";+ let (reply, state) = tokio::time::timeout(+ Duration::from_secs(3),+ page.run_async_command(RendererPageCommand::EvaluateExpressionAndFollowPendingNavigation {+ expression: format!(+ "console.log('command-output-before-navigation'); location.href = {replacement_url:?}; 'navigating'"+ ),+ await_promise: false,+ }),+ )+ .await+ .expect("navigation follow should complete")+ .expect("the command should survive its navigation");+ assert_eq!(+ renderer_json_value(reply),+ Some(serde_json::json!("navigating"))+ );+ assert_eq!(state.document_title, "replacement");++ let publications = output_rx.drain();+ let source_output = publications+ .iter()+ .position(|publication| {+ publication.records().iter().any(|record| matches!(+ record.item(),+ RendererOutputItem::Observation(RendererProtocolObservation::RuntimeInspector(batch))+ if batch.messages.iter().any(|message| matches!(+ message,+ RendererRuntimeInspectorMessage::Protocol(message)+ if message["method"] == "Runtime.consoleAPICalled"+ && message["params"]["args"][0]["value"] == "command-output-before-navigation"+ ))+ ))+ })+ .expect("the source command's console notification must be retained");+ assert_eq!(publications[source_output].cursor().stream(), source_stream);+ let replacement_output = publications+ .iter()+ .position(|publication| {+ publication.records().iter().any(|record| matches!(+ record.item(),+ RendererOutputItem::Observation(RendererProtocolObservation::DocumentTitleChanged(change))+ if change.title == "replacement" && change.source_document != source_document+ ))+ })+ .expect("the replacement title observation must identify its new Document");+ assert!(+ source_output < replacement_output,+ "command output must be published before replacing its source Document"+ );+ page.close_async()+ .await+ .expect("close navigation-output page");}