Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(runtime): order binding mutations with subscription delivery

ldm00b11db6cd29f
diff --git a/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs b/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs
index 06200e79f..82c864c07 100644
--- a/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs
+++ b/moli-protocol/src/conn/runtime_eval/runtime_dispatch.rs
@@ -110,6 +110,15 @@ impl CdpConnection {
&mut self,
owner: &CommandOwnerScope,
output: RendererRuntimeCommandOutput,
+ ) -> Result<RuntimeEnableEventsReplay, String> {
+ let _ = self.set_renderer_runtime_agent_owns_page_console_api_events_for_owner(owner, true);
+ self.prepare_runtime_command_events_for_owner(owner, output)
+ }
+
+ pub(crate) fn prepare_runtime_command_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();
@@ -119,7 +128,6 @@ impl CdpConnection {
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);
for event in replay.events_mut() {
match event {
diff --git a/moli-protocol/src/domains/native.rs b/moli-protocol/src/domains/native.rs
index b5a1a82ed..6ff04bc07 100644
--- a/moli-protocol/src/domains/native.rs
+++ b/moli-protocol/src/domains/native.rs
@@ -231,6 +231,27 @@ pub(crate) fn project_terminal_for_owner(
}
for update in std::mem::take(&mut response.state_updates) {
match (owner.as_ref(), update) {
+ (
+ owner,
+ moli_core::RendererNativeProtocolStateUpdate::RuntimeBinding {
+ binding,
+ remove,
+ output,
+ },
+ ) => {
+ match super::runtime::project_binding_terminal(
+ conn, owner, binding, remove, *output,
+ ) {
+ Ok(replay) => events.extend(replay),
+ Err(message) => {
+ response.notifications.clear();
+ response.result = Err(moli_core::RendererNativeProtocolError {
+ code: -32000,
+ message,
+ });
+ }
+ }
+ }
(
owner,
moli_core::RendererNativeProtocolStateUpdate::RuntimeSubscription {
diff --git a/moli-protocol/src/domains/runtime.rs b/moli-protocol/src/domains/runtime.rs
index fe9f2781a..dd16957b9 100644
--- a/moli-protocol/src/domains/runtime.rs
+++ b/moli-protocol/src/domains/runtime.rs
@@ -5,7 +5,9 @@ mod command_classification;
mod dispatcher;
mod evaluate;
mod native;
-pub(in crate::domains) use native::{project_subscription_terminal, try_start_native_command};
+pub(in crate::domains) use native::{
+ project_binding_terminal, project_subscription_terminal, try_start_native_command,
+};
#[cfg(test)]
mod test_support;
diff --git a/moli-protocol/src/domains/runtime/native.rs b/moli-protocol/src/domains/runtime/native.rs
index f3b5ee600..2f196c23a 100644
--- a/moli-protocol/src/domains/runtime/native.rs
+++ b/moli-protocol/src/domains/runtime/native.rs
@@ -1,15 +1,21 @@
-use moli_core::page::RendererRuntimeCommandOutput;
+use moli_core::page::{
+ RendererRuntimeCommandOutput, RendererRuntimeInspectorMessage, RuntimeBindingRegistration,
+};
use moli_core::{
RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererPageCommand,
RendererPageReply,
};
use serde_json::json;
-use super::bindings::clear_runtime_binding_definitions_for_owner;
+use super::bindings::{
+ AddBindingParams, clear_runtime_binding_definitions_for_owner,
+ persist_runtime_binding_definition_for_owner, remove_runtime_binding_definitions_for_owner,
+};
use crate::conn::{
BackgroundProtocolEvent, CdpConnection, Cmd, CommandOwnerScope, RuntimeEnableEventsReplay,
RuntimeEnableReplayEvent, SessionOwnerRuntimeFrontendEnableResult,
};
+use crate::domains::command_output::CommandOutputPlan;
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::{
@@ -22,6 +28,9 @@ pub(in crate::domains) fn try_start_native_command(
conn: &mut CdpConnection,
cmd: &Cmd<'_>,
) -> Option<NativeCommandStep> {
+ if matches!(cmd.action, "addBinding" | "removeBinding") {
+ return try_start_binding(conn, cmd);
+ }
let enabled = match cmd.action {
"enable" => true,
"disable" => false,
@@ -54,6 +63,100 @@ pub(in crate::domains) fn try_start_native_command(
))
}
+fn try_start_binding(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<NativeCommandStep> {
+ let remove = cmd.action == "removeBinding";
+ let (name, execution_context_name) = if remove {
+ match cmd.get_params::<chromiumoxide_cdp::cdp::js_protocol::runtime::RemoveBindingParams>()
+ {
+ Ok(Some(params)) => (params.name, None),
+ _ => {
+ return Some(NativeCommandStep::Complete(CommandOutputPlan::error(
+ -32602,
+ "InvalidParams",
+ )));
+ }
+ }
+ } else {
+ match cmd.get_params::<AddBindingParams>() {
+ // Context-local bindings do not persist. Keep the existing exact
+ // context lookup, including child default worlds, for that route.
+ Ok(Some(params)) if params.execution_context_id.is_some() => return None,
+ Ok(Some(params)) => (params.name, params.execution_context_name),
+ _ => {
+ return Some(NativeCommandStep::Complete(CommandOutputPlan::error(
+ -32602,
+ "InvalidParams",
+ )));
+ }
+ }
+ };
+ let binding = RuntimeBindingRegistration {
+ devtools_session: None,
+ name,
+ execution_context_name,
+ };
+ 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,
+ RendererPageCommand::runtime_binding_events(inspector_session, binding.clone(), remove),
+ move |reply| match reply {
+ Ok(RendererPageReply::RuntimeInspectorProtocolMessages(output)) => {
+ if let Some(error) = output.messages().iter().find_map(|message| match message {
+ RendererRuntimeInspectorMessage::Protocol(message) => message.get("error"),
+ _ => None,
+ }) {
+ return RendererNativeProtocolResponse::error(
+ error["code"]
+ .as_i64()
+ .and_then(|code| i32::try_from(code).ok())
+ .unwrap_or(-32000),
+ error["message"]
+ .as_str()
+ .unwrap_or("Runtime binding command failed"),
+ );
+ }
+ let mut response = RendererNativeProtocolResponse::success(json!({}));
+ response
+ .state_updates
+ .push(RendererNativeProtocolStateUpdate::RuntimeBinding {
+ binding,
+ remove,
+ output: Box::new(output),
+ });
+ response
+ }
+ Err(error) => RendererNativeProtocolResponse::error(-32000, error.to_string()),
+ _ => unreachable!("Runtime binding commands must return frozen inspector output"),
+ },
+ ))
+}
+
+pub(in crate::domains) fn project_binding_terminal(
+ conn: &mut CdpConnection,
+ owner: Option<&CommandOwnerScope>,
+ binding: RuntimeBindingRegistration,
+ remove: bool,
+ output: RendererRuntimeCommandOutput,
+) -> Result<Vec<BackgroundProtocolEvent>, String> {
+ let Some(owner) = owner else {
+ return Ok(Vec::new());
+ };
+ let replay = conn.prepare_runtime_command_events_for_owner(owner, output)?;
+ if remove {
+ remove_runtime_binding_definitions_for_owner(conn, owner, &binding.name)?;
+ } else {
+ persist_runtime_binding_definition_for_owner(
+ conn,
+ owner,
+ binding.name,
+ binding.execution_context_name,
+ )?;
+ }
+ Ok(project_replay_events(conn, owner, replay))
+}
+
pub(in crate::domains) fn project_subscription_terminal(
conn: &mut CdpConnection,
owner: Option<&CommandOwnerScope>,
@@ -62,6 +165,9 @@ pub(in crate::domains) fn project_subscription_terminal(
) -> Result<Vec<BackgroundProtocolEvent>, String> {
let Some(owner) = owner else {
if !enabled {
+ // Disable has already committed in the original renderer. It has
+ // no replay to install on a successor, so retirement preserves
+ // that success. Enable needs its live owner to deliver the replay.
return Ok(Vec::new());
}
return Err("Runtime.enable completed after session owner disappeared".to_owned());
diff --git a/moli-protocol/src/domains/runtime/tests/bindings.rs b/moli-protocol/src/domains/runtime/tests/bindings.rs
index 4257f092d..cc7ca1b99 100644
--- a/moli-protocol/src/domains/runtime/tests/bindings.rs
+++ b/moli-protocol/src/domains/runtime/tests/bindings.rs
@@ -89,6 +89,151 @@ async fn runtime_disable_clears_stored_binding_definitions_when_enabled() {
);
}
+#[tokio::test]
+async fn late_add_binding_completion_cannot_restore_binding_after_disable() {
+ let mut ctx = TestContext::new();
+ with_loaded_document_async(&mut ctx, "<body>ordered binding state</body>").await;
+ enable_runtime_and_take_execution_context_id_async(&mut ctx, 31_950).await;
+ let CdpCommandTaskStep::Pending(add) = ctx.conn.start_command_dispatch(
+ &json!({
+ "id": 31_951,
+ "method": "Runtime.addBinding",
+ "params": {"name": "bindingClearedByLaterDisable"}
+ })
+ .to_string(),
+ ) else {
+ panic!("addBinding must enter the renderer");
+ };
+ // Finish the renderer turn, but hold its adapter before binding persistence.
+ let completed = add.wait().await;
+ ctx.process_async(json!({"id": 31_952, "method": "Runtime.disable"}))
+ .await;
+ assert_eq!(take_response_by_id(&mut ctx, 31_952)["result"], json!({}));
+
+ let step = ctx.conn.complete_pending_command_dispatch(completed).await;
+ ctx.complete_command_task_step_with_events_for_test(step)
+ .await;
+ let stored_names = ctx
+ .conn
+ .browser_context
+ .as_ref()
+ .unwrap()
+ .active_page_target()
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .iter()
+ .map(|binding| binding.name.clone())
+ .collect::<Vec<_>>();
+
+ // Re-enabling must not reactivate a binding restored by the late adapter.
+ ctx.process_async(json!({"id": 31_953, "method": "Runtime.enable"}))
+ .await;
+ ctx.sent.clear();
+ ctx.process_async(json!({
+ "id": 31_954,
+ "method": "Runtime.evaluate",
+ "params": {
+ "expression": "globalThis.bindingClearedByLaterDisable?.('after-disable'); 'done'"
+ }
+ }))
+ .await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, 31_954)["result"]["result"]["value"],
+ "done"
+ );
+ let binding_called = ctx.sent.iter().any(|message| {
+ message["method"] == "Runtime.bindingCalled"
+ && message["params"]["name"] == "bindingClearedByLaterDisable"
+ });
+ assert!(
+ stored_names.is_empty() && !binding_called,
+ "late addBinding restored state: stored={stored_names:?}, binding_called={binding_called}"
+ );
+}
+
+#[tokio::test]
+async fn runtime_binding_mutations_follow_journal_order_without_adapter_completions() {
+ for (first, second, expected_present) in [
+ ("Runtime.addBinding", "Runtime.removeBinding", false),
+ ("Runtime.removeBinding", "Runtime.addBinding", true),
+ ("Runtime.disable", "Runtime.addBinding", true),
+ ] {
+ let mut ctx = TestContext::new();
+ with_loaded_document_async(&mut ctx, "<body>ordered binding mutations</body>").await;
+ enable_runtime_and_take_execution_context_id_async(&mut ctx, 31_955).await;
+ ctx.sent.clear();
+ let mut pending = Vec::new();
+ for (id, method) in [(31_956, first), (31_957, second)] {
+ let step = ctx.conn.start_command_dispatch(
+ &json!({
+ "id": id, "method": method, "params": {"name": "orderedBinding"}
+ })
+ .to_string(),
+ );
+ assert!(matches!(&step, CdpCommandTaskStep::Pending(_)));
+ pending.push(step);
+ }
+ let response = ctx
+ .wait_for_scheduler_message("second binding mutation", |message| {
+ message["id"] == 31_957
+ })
+ .await;
+ assert_eq!(response["result"], json!({}));
+ let has_stored_binding = |ctx: &TestContext| {
+ ctx.conn
+ .browser_context
+ .as_ref()
+ .unwrap()
+ .active_page_target()
+ .devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
+ .runtime_bindings
+ .iter()
+ .any(|binding| binding.name == "orderedBinding")
+ };
+ assert_eq!(
+ has_stored_binding(&ctx),
+ expected_present,
+ "{first} then {second}"
+ );
+ for step in pending.into_iter().rev() {
+ let (messages, _) = ctx
+ .complete_command_task_step_with_events_for_test(step)
+ .await;
+ assert!(
+ !messages
+ .iter()
+ .any(|message| message["id"] == 31_956 || message["id"] == 31_957),
+ "late adapters cannot repeat published responses: {messages:?}"
+ );
+ }
+ assert_eq!(
+ has_stored_binding(&ctx),
+ expected_present,
+ "late completion after {first} then {second}"
+ );
+ ctx.process_async(json!({"id": 31_958, "method": "Runtime.enable"}))
+ .await;
+ ctx.sent.clear();
+ ctx.process_async(json!({
+ "id": 31_959, "method": "Runtime.evaluate",
+ "params": {"expression": "globalThis.orderedBinding?.('ordered-payload'); 'done'"}
+ }))
+ .await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, 31_959)["result"]["result"]["value"],
+ "done"
+ );
+ assert_eq!(
+ ctx.sent.iter().any(|message| {
+ message["method"] == "Runtime.bindingCalled"
+ && message["params"]["name"] == "orderedBinding"
+ }),
+ expected_present,
+ "renderer binding after {first} then {second}"
+ );
+ }
+}
+
#[tokio::test]
async fn playwright_style_binding_call_from_await_promise_command_emits_before_response() {
let mut ctx = TestContext::new();
diff --git a/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs b/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs
index a98a73b4a..454514784 100644
--- a/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs
+++ b/moli-protocol/src/domains/runtime/tests/evaluate/contexts.rs
@@ -185,6 +185,66 @@ async fn runtime_enable_retired_owner_error_keeps_journal_order_and_single_termi
drop(retired);
}
+#[tokio::test]
+async fn runtime_disable_retired_owner_keeps_committed_success_and_single_terminal() {
+ let mut ctx = TestContext::new();
+ with_loaded_document_async(&mut ctx, "<p>retired Runtime.disable</p>").await;
+ ctx.process_async(json!({"id": 11_034, "method": "Runtime.enable"}))
+ .await;
+ ctx.sent.clear();
+ let preceding = ctx
+ .conn
+ .start_command_dispatch(&json!({"id": 11_035, "method": "DOM.getDocument"}).to_string());
+ let CdpCommandTaskStep::Pending(disable) = ctx
+ .conn
+ .start_command_dispatch(&json!({"id": 11_036, "method": "Runtime.disable"}).to_string())
+ else {
+ panic!("Runtime.disable must enter the renderer");
+ };
+ let completed = disable.wait().await;
+ // Retire the Browser owner after renderer commit, before ordered ingress.
+ let retired = ctx.conn.browser_context.take().unwrap();
+ let response = ctx
+ .wait_for_scheduler_message("retired Runtime.disable terminal", |message| {
+ message["id"] == 11_036
+ })
+ .await;
+ assert_eq!(response["result"], json!({}));
+ assert!(
+ ctx.sent
+ .iter()
+ .any(|message| { message["id"] == 11_035 && message.get("result").is_some() }),
+ "the committed disable cannot overtake an earlier terminal: {:?}",
+ ctx.sent
+ );
+ assert!(ctx.conn.browser_context.is_none());
+ assert!(
+ !ctx.sent
+ .iter()
+ .any(|message| message["method"] == "Runtime.executionContextCreated")
+ );
+
+ let CdpCommandTaskStep::Complete(outcome) =
+ ctx.conn.complete_pending_command_dispatch(completed).await
+ else {
+ panic!("the published disable must complete its adapter");
+ };
+ let (messages, scheduler_events, predecessor) = outcome.into_protocol_event_parts();
+ assert!(messages.is_empty() && scheduler_events.is_empty());
+ ctx.route_direct_command_renderer_predecessor_for_test(
+ predecessor.expect("the adapter must acknowledge the committed disable"),
+ )
+ .await;
+ // wait_for_scheduler_message removed the original response above.
+ assert!(!ctx.sent.iter().any(|message| message["id"] == 11_036));
+ assert!(
+ ctx.conn.browser_context.is_none(),
+ "late completion cannot recreate the retired owner"
+ );
+ drop(preceding);
+ drop(retired);
+}
+
#[tokio::test]
async fn runtime_enable_ready_terminal_does_not_wait_for_an_unresolved_expression() {
let mut ctx = TestContext::new();
diff --git a/moli-renderer-v8/src/devtools/command.rs b/moli-renderer-v8/src/devtools/command.rs
index 12737a1a5..d469cba9e 100644
--- a/moli-renderer-v8/src/devtools/command.rs
+++ b/moli-renderer-v8/src/devtools/command.rs
@@ -581,6 +581,9 @@ impl RendererInspectorCommandEnvelope {
match self.main_thread_payload() {
RendererInspectorPageCommand::RuntimeEnableEvents => Some("RuntimeEnableEvents"),
RendererInspectorPageCommand::RuntimeDisableEvents => Some("RuntimeDisableEvents"),
+ RendererInspectorPageCommand::RuntimeBindingEvents { .. } => {
+ Some("RuntimeBindingEvents")
+ }
RendererInspectorPageCommand::ApplyRuntimeProtocolState { .. } => {
Some("ApplyRuntimeProtocolState")
}
diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rs
index d90d1a4d0..79e7be156 100644
--- a/moli-renderer-v8/src/runtime/page_commands.rs
+++ b/moli-renderer-v8/src/runtime/page_commands.rs
@@ -1208,6 +1208,9 @@ impl PageVm {
RendererInspectorPageCommand::RuntimeDisableEvents => self
.runtime_disable_events(inspector_session_id)
.map(RendererPageReply::RuntimeInspectorProtocolMessages),
+ RendererInspectorPageCommand::RuntimeBindingEvents { binding, remove } => self
+ .runtime_binding_events(inspector_session_id, binding, remove)
+ .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.rs
index 87312cf3c..40c578a8a 100644
--- a/moli-renderer-v8/src/runtime/page_dom.rs
+++ b/moli-renderer-v8/src/runtime/page_dom.rs
@@ -1843,18 +1843,37 @@ impl PageVm {
) -> Result<RendererRuntimeCommandOutput> {
const INTERNAL_RUNTIME_DISABLE_ID: u64 = 900_005;
let was_enabled = self.runtime_inspector_frontend_restore_enabled(inspector_session_id);
+ let mut messages = Vec::new();
+ if was_enabled {
+ // Removing the restore metadata alone leaves V8's binding active
+ // after the next enable. Commit removal in this same owner turn.
+ for binding in self
+ .vm()
+ .inspector_session_runtime_bindings(inspector_session_id)
+ {
+ let output = self.runtime_binding_events(inspector_session_id, binding, true)?;
+ anyhow::ensure!(
+ !output.messages().iter().any(|message| matches!(message,
+ RendererRuntimeInspectorMessage::Protocol(message) if message.get("error").is_some()
+ )),
+ "Runtime.disable could not remove a runtime binding"
+ );
+ messages.extend(output.into_messages());
+ }
+ }
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"),
- )?;
+ messages.extend(
+ 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"
@@ -1894,6 +1913,94 @@ impl PageVm {
Ok(output)
}
+ pub(crate) fn runtime_binding_events(
+ &mut self,
+ inspector_session_id: Option<&str>,
+ binding: crate::protocol_types::RuntimeBindingRegistration,
+ remove: bool,
+ ) -> Result<RendererRuntimeCommandOutput> {
+ const INTERNAL_RUNTIME_BINDING_ID: u64 = 900_006;
+ let was_enabled = self.runtime_inspector_frontend_restore_enabled(inspector_session_id);
+ let mut params = json!({"name": binding.name});
+ if let Some(name) = &binding.execution_context_name {
+ params["executionContextName"] = json!(name);
+ }
+ let raw_request = serde_json::to_string(&json!({
+ "id": INTERNAL_RUNTIME_BINDING_ID,
+ "method": if remove { "Runtime.removeBinding" } else { "Runtime.addBinding" },
+ "params": params,
+ }))?;
+ let mut messages = self
+ .vm_mut()
+ .dispatch_internal_inspector_protocol_message_for_session(
+ inspector_session_id,
+ &raw_request,
+ i32::try_from(INTERNAL_RUNTIME_BINDING_ID)
+ .expect("bounded internal Runtime binding call id"),
+ )?;
+ let succeeded =
+ renderer_inspector_response_succeeded(&messages, INTERNAL_RUNTIME_BINDING_ID);
+ anyhow::ensure!(
+ runtime_inspector_response_message(&messages, INTERNAL_RUNTIME_BINDING_ID).is_some(),
+ "Runtime binding command did not complete"
+ );
+ if succeeded {
+ self.record_runtime_inspector_protocol_configuration_command(
+ inspector_session_id,
+ &raw_request,
+ &messages,
+ );
+ if remove && !was_enabled {
+ self.remove_runtime_binding(&binding.name)?;
+ }
+ let session_key = DevToolsSessionKey::from_wire_session_id(inspector_session_id);
+ let mut session_bindings = self
+ .vm()
+ .inspector_session_runtime_bindings(inspector_session_id);
+ if remove {
+ session_bindings.retain(|existing| existing.name != binding.name);
+ self.runtime_bindings.retain(|existing| {
+ existing.devtools_session.as_ref() != Some(&session_key)
+ || existing.name != binding.name
+ });
+ } else {
+ if !session_bindings.contains(&binding) {
+ session_bindings.push(binding.clone());
+ }
+ let stored_binding = binding.with_devtools_session(session_key);
+ if !self.runtime_bindings.contains(&stored_binding) {
+ self.runtime_bindings.push(stored_binding);
+ }
+ }
+ // Commit only this mutation against the renderer's current state.
+ // No later adapter can reapply an older Browser binding snapshot.
+ 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(|message| {
+ message.has_v8_inspector_method()
+ || matches!(message, RendererRuntimeInspectorMessage::Protocol(message)
+ if message.get("error").is_some())
+ })
+ .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.rs
index 2ed05de2c..e2f056849 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -4645,6 +4645,10 @@ pub(crate) enum RendererInspectorPageCommand {
},
RuntimeEnableEvents,
RuntimeDisableEvents,
+ RuntimeBindingEvents {
+ binding: crate::protocol_types::RuntimeBindingRegistration,
+ remove: bool,
+ },
ApplyRuntimeProtocolState {
session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,
@@ -5342,6 +5346,17 @@ impl RendererPageCommand {
)
}
+ pub fn runtime_binding_events(
+ inspector_session_id: Option<String>,
+ binding: crate::protocol_types::RuntimeBindingRegistration,
+ remove: bool,
+ ) -> Self {
+ Self::inspector_command(
+ inspector_session_id,
+ RendererInspectorPageCommand::RuntimeBindingEvents { binding, remove },
+ )
+ }
+
pub fn apply_runtime_protocol_state(
inspector_session_id: Option<String>,
session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
diff --git a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs
index 39ff2af20..f60151487 100644
--- a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs
+++ b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs
@@ -81,6 +81,13 @@ pub enum RendererNativeProtocolStateUpdate {
enabled: bool,
output: Box<crate::runtime::RendererRuntimeCommandOutput>,
},
+ /// Persistent binding mutations share the subscription's ordered ingress;
+ /// adapter completion cannot restore bindings cleared by a later disable.
+ RuntimeBinding {
+ binding: crate::protocol_types::RuntimeBindingRegistration,
+ remove: 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.
diff --git a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs
index 0fe27fda1..ef8040a77 100644
--- a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs
+++ b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs
@@ -35,16 +35,18 @@ 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,
- ))
- },
- )
+ runtime_command_output_charge_bytes(output)
}
+ super::RendererNativeProtocolStateUpdate::RuntimeBinding {
+ binding, output, ..
+ } => runtime_command_output_charge_bytes(output)
+ .saturating_add(string_charge(&binding.name))
+ .saturating_add(
+ binding
+ .execution_context_name
+ .as_deref()
+ .map_or(0, string_charge),
+ ),
super::RendererNativeProtocolStateUpdate::WebMcpEnabled(_) => 0,
super::RendererNativeProtocolStateUpdate::RemoteObjects { object_group } => {
object_group.as_deref().map_or(0, string_charge)
@@ -68,6 +70,18 @@ fn native_terminal_charge_bytes(terminal: &super::RendererNativeCommandTerminal)
charge
}
+fn runtime_command_output_charge_bytes(
+ output: &crate::runtime::RendererRuntimeCommandOutput,
+) -> usize {
+ output.messages().iter().fold(
+ std::mem::size_of_val(output)
+ .saturating_add(output.v8_state_update().map_or(0, |state| state.len())),
+ |total, message| {
+ total.saturating_add(runtime_inspector_message_transport_charge_bytes(message))
+ },
+ )
+}
+
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 while