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): allow removing bindings while debugger is paused

ldm020b9a7a33c86
diff --git a/moli-protocol-server/src/protocol_server/tests/websocket/parser_replacement_and_debugger.rs b/moli-protocol-server/src/protocol_server/tests/websocket/parser_replacement_and_debugger.rs
index bee017006..866529aff 100644
--- a/moli-protocol-server/src/protocol_server/tests/websocket/parser_replacement_and_debugger.rs
+++ b/moli-protocol-server/src/protocol_server/tests/websocket/parser_replacement_and_debugger.rs
@@ -1584,6 +1584,188 @@ async fn websocket_cdp_debugger_step_out_responds_before_resumed_and_caller_paus
protocol_server.abort();
}
+#[tokio::test]
+async fn websocket_cdp_remove_binding_completes_while_debugger_is_paused() {
+ let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;
+ let (mut socket, _) = connect_async(format!(
+ "ws://{cdp_addr}/devtools/browser/{DEFAULT_BROWSER_ID}"
+ ))
+ .await
+ .expect("connect to cdp websocket");
+ let browser_context_id = cdp_create_browser_context(&mut socket, 1).await;
+ let session = cdp_create_attached_target(&mut socket, 2, &browser_context_id).await;
+ let session_id = session.session_id;
+ for (id, method, params) in [
+ (10, "Runtime.enable", json!({})),
+ (11, "Debugger.enable", json!({})),
+ (12, "Runtime.addBinding", json!({"name": "pausedBinding"})),
+ (9, "Runtime.addBinding", json!({"name": "keptBinding"})),
+ ] {
+ let messages = send_cdp_command(&mut socket, id, method, Some(&session_id), params).await;
+ assert!(
+ messages
+ .iter()
+ .any(|message| { message["id"] == id && message.get("error").is_none() }),
+ "{method} must succeed: {messages:#?}"
+ );
+ }
+ let before = send_cdp_command(
+ &mut socket,
+ 13,
+ "Runtime.evaluate",
+ Some(&session_id),
+ json!({"expression": "pausedBinding('before')"}),
+ )
+ .await;
+ assert!(
+ before.iter().any(|message| {
+ message["method"] == "Runtime.bindingCalled" && message["params"]["payload"] == "before"
+ }),
+ "the binding must initially notify: {before:#?}"
+ );
+
+ send_cdp_command_without_wait(
+ &mut socket,
+ 14,
+ "Runtime.evaluate",
+ Some(&session_id),
+ json!({"expression": "debugger; 42", "returnByValue": true}),
+ )
+ .await;
+ let mut observed = recv_until_match(&mut socket, |message| {
+ message["sessionId"] == session_id && message["method"] == "Debugger.paused"
+ })
+ .await;
+ let removed = timeout(
+ Duration::from_secs(5),
+ send_cdp_command(
+ &mut socket,
+ 15,
+ "Runtime.removeBinding",
+ Some(&session_id),
+ json!({"name": "pausedBinding"}),
+ ),
+ )
+ .await;
+ if removed.is_err() {
+ // Release the suspended owner even when the regression is present.
+ send_cdp_command(
+ &mut socket,
+ 90,
+ "Debugger.resume",
+ Some(&session_id),
+ json!({"terminateOnResume": true}),
+ )
+ .await;
+ let _ = socket.close(None).await;
+ abort_test_cdp_server(protocol_server).await;
+ panic!("Runtime.removeBinding must complete before resuming the debugger");
+ }
+ observed.extend(removed.unwrap());
+ let removed = observed.iter().find(|message| message["id"] == 15).unwrap();
+ assert_eq!(removed["result"], json!({}), "{observed:#?}");
+ assert!(
+ !observed
+ .iter()
+ .any(|message| { message["id"] == 14 || message["method"] == "Debugger.resumed" }),
+ "removal must complete while the original evaluation remains paused: {observed:#?}"
+ );
+
+ // The next Main request in this same session must also pass the lane head.
+ observed.extend(
+ send_cdp_command(
+ &mut socket,
+ 16,
+ "Runtime.evaluate",
+ Some(&session_id),
+ json!({"expression": "typeof pausedBinding", "returnByValue": true}),
+ )
+ .await,
+ );
+ assert!(
+ observed.iter().any(|message| {
+ message["id"] == 16 && message["result"]["result"]["value"] == "function"
+ }),
+ "removeBinding leaves the installed function in the current document: {observed:#?}"
+ );
+ observed.extend(
+ send_cdp_command(
+ &mut socket,
+ 17,
+ "Debugger.resume",
+ Some(&session_id),
+ json!({}),
+ )
+ .await,
+ );
+ if !observed.iter().any(|message| message["id"] == 14) {
+ observed.extend(recv_until_id(&mut socket, 14).await);
+ }
+ assert!(
+ observed
+ .iter()
+ .any(|message| { message["id"] == 14 && message["result"]["result"]["value"] == 42 }),
+ "resume must complete the original evaluation successfully: {observed:#?}"
+ );
+ observed.extend(
+ send_cdp_command(
+ &mut socket,
+ 18,
+ "Runtime.evaluate",
+ Some(&session_id),
+ json!({"expression": "pausedBinding('after'); 42", "returnByValue": true}),
+ )
+ .await,
+ );
+ assert!(
+ observed.iter().any(|message| {
+ message["id"] == 18
+ && message["result"]["result"]["value"] == 42
+ && message["result"].get("exceptionDetails").is_none()
+ }),
+ "the residual function must remain callable after resume: {observed:#?}"
+ );
+ assert!(
+ !observed
+ .iter()
+ .any(|message| message["method"] == "Runtime.bindingCalled"),
+ "the removed binding must stop notifying: {observed:#?}"
+ );
+
+ observed.extend(
+ send_cdp_command(&mut socket, 19, "Page.reload", Some(&session_id), json!({})).await,
+ );
+ observed.extend(
+ send_cdp_command(
+ &mut socket,
+ 20,
+ "Runtime.evaluate",
+ Some(&session_id),
+ json!({"expression": "[typeof pausedBinding, typeof keptBinding]", "returnByValue": true}),
+ )
+ .await,
+ );
+ assert!(
+ observed.iter().any(|message| {
+ message["id"] == 20
+ && message["result"]["result"]["value"] == json!(["undefined", "function"])
+ }),
+ "reload must restore only the binding whose definition remains committed: {observed:#?}"
+ );
+ for id in 14..=20 {
+ assert_eq!(
+ observed
+ .iter()
+ .filter(|message| message["id"] == id)
+ .count(),
+ 1,
+ "each command must publish exactly one response: {observed:#?}"
+ );
+ }
+ let _ = socket.close(None).await;
+ abort_test_cdp_server(protocol_server).await;
+}
+
#[tokio::test]
async fn websocket_cdp_debugger_pause_allows_attached_main_thread_commands() {
let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;
diff --git a/moli-renderer-v8/src/devtools/command.rs b/moli-renderer-v8/src/devtools/command.rs
index d469cba9e..bfb79d634 100644
--- a/moli-renderer-v8/src/devtools/command.rs
+++ b/moli-renderer-v8/src/devtools/command.rs
@@ -301,6 +301,8 @@ pub struct RendererDevToolsMainCommandEnvelope {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum RendererDevToolsMainNestedDispatch {
InspectorSession,
+ /// V8 session dispatch followed by a native terminal in the same Main turn.
+ NativeInspectorSession,
PageAgent,
OwnerOnly,
}
@@ -360,11 +362,14 @@ impl RendererDevToolsMainCommandEnvelope {
envelope
}
- pub(crate) fn into_nested_page_command(self) -> RendererPageCommand {
- assert_eq!(
- self.nested_dispatch(),
- RendererDevToolsMainNestedDispatch::PageAgent,
- "only a non-V8 Main agent command may enter nested Page dispatch"
+ pub(crate) fn into_nested_agent_command(self) -> RendererPageCommand {
+ assert!(
+ matches!(
+ self.nested_dispatch(),
+ RendererDevToolsMainNestedDispatch::PageAgent
+ | RendererDevToolsMainNestedDispatch::NativeInspectorSession
+ ),
+ "only a supported Main agent command may enter nested agent dispatch"
);
*self.payload
}
@@ -488,6 +493,41 @@ impl RendererInspectorCommandEnvelope {
self.main_dispatch_boundary == RendererInspectorMainDispatchBoundary::InspectorSession
}
+ pub(crate) fn runtime_binding_removal_name(&self) -> Option<&str> {
+ match &self.payload {
+ RendererInspectorCommandPayload::MainThread(
+ RendererInspectorPageCommand::RuntimeBindingEvents {
+ binding,
+ remove: true,
+ },
+ ) => Some(&binding.name),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn is_runtime_binding_removal_commit(&self) -> bool {
+ matches!(
+ self.payload,
+ RendererInspectorCommandPayload::MainThread(
+ RendererInspectorPageCommand::CommitRuntimeBindingRemoval { .. }
+ )
+ )
+ }
+
+ pub(crate) fn into_runtime_binding_removal_commit(
+ mut self,
+ output: Result<crate::runtime::RendererRuntimeCommandOutput, String>,
+ ) -> Self {
+ let name = self
+ .runtime_binding_removal_name()
+ .expect("only removeBinding can finish nested Inspector dispatch")
+ .to_owned();
+ self.payload = RendererInspectorCommandPayload::MainThread(
+ RendererInspectorPageCommand::CommitRuntimeBindingRemoval { name, output },
+ );
+ self
+ }
+
pub(crate) fn bind_attachment(&mut self, attachment: RendererAgentAttachmentId) {
self.ticket.bind_attachment(attachment);
}
@@ -584,6 +624,9 @@ impl RendererInspectorCommandEnvelope {
RendererInspectorPageCommand::RuntimeBindingEvents { .. } => {
Some("RuntimeBindingEvents")
}
+ RendererInspectorPageCommand::CommitRuntimeBindingRemoval { .. } => {
+ Some("CommitRuntimeBindingRemoval")
+ }
RendererInspectorPageCommand::ApplyRuntimeProtocolState { .. } => {
Some("ApplyRuntimeProtocolState")
}
diff --git a/moli-renderer-v8/src/devtools/command/nested.rs b/moli-renderer-v8/src/devtools/command/nested.rs
index edf5001f5..54fedc25a 100644
--- a/moli-renderer-v8/src/devtools/command/nested.rs
+++ b/moli-renderer-v8/src/devtools/command/nested.rs
@@ -9,18 +9,13 @@ impl RendererPageCommand {
use RendererDevToolsMainNestedDispatch::{InspectorSession, OwnerOnly, PageAgent};
match self {
Self::WebMcp { .. } => OwnerOnly,
- Self::Native(command) => {
- if command.operation.can_dispatch_on_nested_main() {
- PageAgent
- } else {
- OwnerOnly
- }
- }
+ Self::Native(command) => command.operation.nested_dispatch(),
Self::Inspector(envelope)
if envelope.can_dispatch_at_nested_inspector_session_boundary() =>
{
InspectorSession
}
+ Self::Inspector(envelope) if envelope.is_runtime_binding_removal_commit() => PageAgent,
Self::Inspector(_) => OwnerOnly,
// Printing temporarily switches media and synchronizes document
// fonts through V8. A regular screenshot only reads native layout.
diff --git a/moli-renderer-v8/src/devtools/ingress/main.rs b/moli-renderer-v8/src/devtools/ingress/main.rs
index f109006c2..fb9e5a20d 100644
--- a/moli-renderer-v8/src/devtools/ingress/main.rs
+++ b/moli-renderer-v8/src/devtools/ingress/main.rs
@@ -114,17 +114,17 @@ impl RendererInspectorMainCommand {
.into_main_protocol_parts()
}
- pub(crate) fn into_nested_page_parts(
+ pub(crate) fn into_nested_agent_parts(
mut self,
) -> (
RendererPageCommand,
tokio::sync::oneshot::Sender<anyhow::Result<RendererOwnerReply>>,
) {
- let command = self.envelope.into_nested_page_command();
+ let command = self.envelope.into_nested_agent_command();
let reply_tx = self
.owner_reply_tx
.take()
- .expect("a nested Page command must retain its completion sender");
+ .expect("a nested agent command must retain its completion sender");
(command, reply_tx)
}
@@ -563,7 +563,8 @@ impl RendererInspectorMainIngress {
}
RendererInspectorMainCommandConsumer::Pause => match command.nested_dispatch() {
RendererDevToolsMainNestedDispatch::InspectorSession => None,
- RendererDevToolsMainNestedDispatch::PageAgent => {
+ RendererDevToolsMainNestedDispatch::PageAgent
+ | RendererDevToolsMainNestedDispatch::NativeInspectorSession => {
Some(RendererInspectorMainCommandClaim::Page)
}
RendererDevToolsMainNestedDispatch::OwnerOnly => {
diff --git a/moli-renderer-v8/src/runtime/nested_main.rs b/moli-renderer-v8/src/runtime/nested_main.rs
index 4d6012c88..c38f48133 100644
--- a/moli-renderer-v8/src/runtime/nested_main.rs
+++ b/moli-renderer-v8/src/runtime/nested_main.rs
@@ -54,6 +54,11 @@ pub(crate) fn dispatch_nested_main_page_command(
command: RendererPageCommand,
mut first_dispatch: RendererInspectorMainFirstDispatchGuard,
) -> Result<RendererCommandTurnOutput> {
+ assert_eq!(
+ command.nested_dispatch(),
+ super::RendererDevToolsMainNestedDispatch::PageAgent,
+ "nested Page dispatch must not enter V8 through the suspended Page owner"
+ );
let active = ACTIVE_NESTED_MAIN_PAGE
.try_with(|active| active.borrow().clone())
.ok()
diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rs
index 79e7be156..6d6ee8968 100644
--- a/moli-renderer-v8/src/runtime/page_commands.rs
+++ b/moli-renderer-v8/src/runtime/page_commands.rs
@@ -1211,6 +1211,9 @@ impl PageVm {
RendererInspectorPageCommand::RuntimeBindingEvents { binding, remove } => self
.runtime_binding_events(inspector_session_id, binding, remove)
.map(RendererPageReply::RuntimeInspectorProtocolMessages),
+ RendererInspectorPageCommand::CommitRuntimeBindingRemoval { name, output } => self
+ .commit_runtime_binding_removal(inspector_session_id, &name, output)
+ .map(RendererPageReply::RuntimeInspectorProtocolMessages),
RendererInspectorPageCommand::ApplyRuntimeProtocolState {
session_restore_snapshots,
isolated_worlds,
@@ -1394,6 +1397,14 @@ fn renderer_page_command_action_barrier(
// The underlying operation flushes its own barrier. Wrapping it must
// not turn a wheel event into an explicit action-window flush.
RendererPageCommand::Native(_) => None,
+ // V8 already removed this binding at the Inspector-session boundary.
+ // Finishing its metadata must not flush script-bearing Page actions
+ // through the suspended owner stack.
+ RendererPageCommand::Inspector(envelope)
+ if envelope.is_runtime_binding_removal_commit() =>
+ {
+ None
+ }
RendererPageCommand::DispatchMouseEventAtPoint { event_name, .. }
if event_name == "wheel" =>
{
diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rs
index e2cc208b6..7441b734a 100644
--- a/moli-renderer-v8/src/runtime/page_dom.rs
+++ b/moli-renderer-v8/src/runtime/page_dom.rs
@@ -1983,6 +1983,35 @@ impl PageVm {
Ok(output)
}
+ pub(crate) fn commit_runtime_binding_removal(
+ &mut self,
+ inspector_session_id: Option<&str>,
+ name: &str,
+ output: Result<RendererRuntimeCommandOutput, String>,
+ ) -> Result<RendererRuntimeCommandOutput> {
+ let output = output.map_err(anyhow::Error::msg)?;
+ if !output.messages().iter().any(|message| {
+ matches!(message, RendererRuntimeInspectorMessage::Protocol(message)
+ if message.get("error").is_some())
+ }) {
+ let session_key = DevToolsSessionKey::from_wire_session_id(inspector_session_id);
+ let mut session_bindings = self
+ .vm()
+ .inspector_session_runtime_bindings(inspector_session_id);
+ session_bindings.retain(|binding| binding.name != name);
+ self.runtime_bindings.retain(|binding| {
+ binding.devtools_session.as_ref() != Some(&session_key) || binding.name != name
+ });
+ // The existing Inspector session executed V8 removal above the
+ // suspended Page stack. This stage must not enter a new V8 scope
+ // (including ensure_runtime_inspector_session).
+ let stored_bindings = self.runtime_bindings.clone();
+ self.set_stored_runtime_bindings(&stored_bindings);
+ self.set_inspector_session_runtime_bindings(inspector_session_id, &session_bindings);
+ }
+ 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 e2f056849..c0e760b03 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -4649,6 +4649,12 @@ pub(crate) enum RendererInspectorPageCommand {
binding: crate::protocol_types::RuntimeBindingRegistration,
remove: bool,
},
+ /// The V8 session already executed removal. Only native restore metadata
+ /// remains to be committed before publishing the original native terminal.
+ CommitRuntimeBindingRemoval {
+ name: String,
+ output: Result<RendererRuntimeCommandOutput, String>,
+ },
ApplyRuntimeProtocolState {
session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,
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 f60151487..0c3014e25 100644
--- a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs
+++ b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs
@@ -8,6 +8,8 @@ use std::convert::Infallible;
use moli_page_types::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId};
+use crate::devtools::command::RendererDevToolsMainNestedDispatch;
+
use super::{
PendingRendererOutputRecord, RendererCommandResponseAuthority, RendererCommandResponseLease,
RendererOutputFence, RendererOutputItem, RendererTurnOutputJournal,
@@ -254,7 +256,7 @@ pub struct RendererNativeOperation {
// Breaks the Native call -> operation -> page command type cycle.
pub(crate) command: Box<RendererPageCommand>,
completion: NativeOperationCompletion,
- nested_main: bool,
+ nested_dispatch: RendererDevToolsMainNestedDispatch,
}
pub enum RendererNativeOperationStep {
@@ -291,10 +293,19 @@ impl RendererNativeOperation {
+ Send
+ 'static,
) -> Self {
- let nested_main = command.nested_dispatch()
- == crate::devtools::command::RendererDevToolsMainNestedDispatch::PageAgent;
+ let nested_dispatch = match &command {
+ RendererPageCommand::Inspector(envelope)
+ if envelope.runtime_binding_removal_name().is_some() =>
+ {
+ RendererDevToolsMainNestedDispatch::NativeInspectorSession
+ }
+ _ if command.nested_dispatch() == RendererDevToolsMainNestedDispatch::PageAgent => {
+ RendererDevToolsMainNestedDispatch::PageAgent
+ }
+ _ => RendererDevToolsMainNestedDispatch::OwnerOnly,
+ };
Self {
- nested_main,
+ nested_dispatch,
command: Box::new(command),
completion: NativeOperationCompletion::Terminal(Box::new(project)),
}
@@ -312,7 +323,7 @@ impl RendererNativeOperation {
Self {
command: Box::new(command),
completion: NativeOperationCompletion::Lookup(Box::new(next)),
- nested_main: false,
+ nested_dispatch: RendererDevToolsMainNestedDispatch::OwnerOnly,
}
}
@@ -324,22 +335,26 @@ impl RendererNativeOperation {
+ Send
+ 'static,
) -> Self {
- let nested_main = command.nested_dispatch()
- == crate::devtools::command::RendererDevToolsMainNestedDispatch::PageAgent;
+ let nested_dispatch =
+ if command.nested_dispatch() == RendererDevToolsMainNestedDispatch::PageAgent {
+ RendererDevToolsMainNestedDispatch::PageAgent
+ } else {
+ RendererDevToolsMainNestedDispatch::OwnerOnly
+ };
let mut operation = Self::then(command, next);
- operation.nested_main = nested_main;
+ operation.nested_dispatch = nested_dispatch;
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.nested_dispatch = RendererDevToolsMainNestedDispatch::OwnerOnly;
self
}
- pub(crate) fn can_dispatch_on_nested_main(&self) -> bool {
- self.nested_main
+ pub(crate) fn nested_dispatch(&self) -> RendererDevToolsMainNestedDispatch {
+ self.nested_dispatch
}
}
@@ -352,6 +367,31 @@ enum NativeReadyReply {
}
impl RendererCdpCall {
+ pub(crate) fn runtime_binding_removal_name(&self) -> &str {
+ let RendererPageCommand::Inspector(envelope) = self.operation.command.as_ref() else {
+ unreachable!("nested native Inspector dispatch requires an Inspector payload")
+ };
+ envelope
+ .runtime_binding_removal_name()
+ .expect("only removeBinding supports nested native Inspector dispatch")
+ }
+
+ pub(crate) fn into_runtime_binding_removal_commit(
+ mut self,
+ output: Result<crate::runtime::RendererRuntimeCommandOutput, String>,
+ ) -> RendererPageCommand {
+ let RendererPageCommand::Inspector(envelope) = *self.operation.command else {
+ unreachable!("nested native Inspector dispatch requires an Inspector payload")
+ };
+ self.operation.command = Box::new(RendererPageCommand::Inspector(
+ envelope.into_runtime_binding_removal_commit(output),
+ ));
+ self.operation.nested_dispatch = RendererDevToolsMainNestedDispatch::PageAgent;
+ // Keep the original response lease and terminal projection. Neither
+ // the V8 response capture nor the adapter can publish another reply.
+ RendererPageCommand::Native(self)
+ }
+
pub(crate) fn dispatch(
self,
vm: &mut crate::runtime::PageVm,
@@ -360,7 +400,8 @@ impl RendererCdpCall {
mut operation,
response,
} = self;
- let nested_main = operation.nested_main;
+ let nested_main =
+ operation.nested_dispatch == RendererDevToolsMainNestedDispatch::PageAgent;
let reply = loop {
// A lookup may construct another Inspector operation. Bind
// each one to the attachment captured for the original call.
@@ -375,7 +416,9 @@ impl RendererCdpCall {
NativeOperationCompletion::Lookup(next) => match next(reply) {
RendererNativeOperationStep::Continue(next) => {
assert!(
- !nested_main || next.nested_main,
+ !nested_main
+ || next.nested_dispatch
+ == RendererDevToolsMainNestedDispatch::PageAgent,
"a nested native continuation cannot acquire an owner-only isolate"
);
operation = next;
diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs
index 0b615c207..7febcb73b 100644
--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs
+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs
@@ -24,9 +24,11 @@ use crate::{
target::RendererDevToolsTargetHandle,
},
inspector_microtasks::with_scoped_inspector_microtasks,
+ inspector_session::InspectorSessionOutput,
runtime::{
RendererDevToolsIoCommandKind, RendererDevToolsIoCommandPayload,
- RendererDevToolsMainNestedDispatch, RendererOwnerReply,
+ RendererDevToolsMainNestedDispatch, RendererOwnerReply, RendererPageCommand,
+ RendererRuntimeCommandOutput, RendererRuntimeInspectorMessage,
RendererRuntimeInspectorResponseSender, dispatch_nested_main_page_command,
},
};
@@ -303,13 +305,14 @@ impl RendererInspectorSessionExecutorLocal {
match command.nested_dispatch() {
RendererDevToolsMainNestedDispatch::PageAgent => {
let first_dispatch = self.target.main_ref().first_dispatch_guard(&mut command);
- let (page_command, reply_tx) = command.into_nested_page_parts();
+ let (page_command, reply_tx) = command.into_nested_agent_parts();
let result = dispatch_nested_main_page_command(page_command, first_dispatch)
.map(|output| RendererOwnerReply::AsyncPageCommandRan(Box::new(output)));
let _ = reply_tx.send(result);
return;
}
- RendererDevToolsMainNestedDispatch::InspectorSession => {}
+ RendererDevToolsMainNestedDispatch::InspectorSession
+ | RendererDevToolsMainNestedDispatch::NativeInspectorSession => {}
RendererDevToolsMainNestedDispatch::OwnerOnly => {
unreachable!("an owner-only Main command cannot be claimed by the pause loop")
}
@@ -321,7 +324,65 @@ impl RendererInspectorSessionExecutorLocal {
.get(&(context_group_id, session_key))
.filter(|session| session.agent_token == command.agent_token)
.cloned();
- self.dispatch_main_command_to_session(command, session);
+ if command.nested_dispatch() == RendererDevToolsMainNestedDispatch::NativeInspectorSession {
+ self.dispatch_native_main_command_to_session(command, session);
+ } else {
+ self.dispatch_main_command_to_session(command, session);
+ }
+ }
+
+ fn dispatch_native_main_command_to_session(
+ &self,
+ mut command: RendererInspectorMainCommand,
+ session: Option<RendererInspectorSessionRoute>,
+ ) {
+ let mut first_dispatch = self.target.main_ref().first_dispatch_guard(&mut command);
+ let (page_command, reply_tx) = command.into_nested_agent_parts();
+ let RendererPageCommand::Native(call) = page_command else {
+ unreachable!("native Inspector dispatch must retain its native terminal")
+ };
+ first_dispatch.release();
+ let output = (|| {
+ const INTERNAL_REMOVE_BINDING_ID: i32 = 900_006;
+ let session = session.ok_or("Inspector session is not available")?;
+ let v8_session = session
+ .session
+ .upgrade()
+ .ok_or("Inspector session has been detached")?;
+ let raw_json = json!({
+ "id": INTERNAL_REMOVE_BINDING_ID,
+ "method": "Runtime.removeBinding",
+ "params": {"name": call.runtime_binding_removal_name()},
+ })
+ .to_string();
+ // Enter the already live V8 Inspector session, just like ordinary
+ // nested protocol dispatch. Do not borrow the suspended Page's
+ // isolate or report this V8 handler as a native Page agent.
+ let response = session
+ .outbound
+ .capture_internal_response(INTERNAL_REMOVE_BINDING_ID, || {
+ v8_session.dispatch_protocol_message(v8::inspector::StringView::from(
+ raw_json.as_bytes(),
+ ));
+ })
+ .ok_or("Runtime binding command did not complete")?;
+ let messages = if response.get("error").is_some() {
+ vec![RendererRuntimeInspectorMessage::protocol(response)]
+ } else {
+ Vec::new()
+ };
+ let mut output = RendererRuntimeCommandOutput::from_messages(messages);
+ output.set_v8_state_update(V8InspectorSessionState::from_bytes(v8_session.state()));
+ Ok(output)
+ })()
+ .map_err(str::to_owned);
+ // Only the remaining Rust metadata mutation uses the Page-agent
+ // boundary. Its original NativeTerminal still commits state and the
+ // single frontend response through ordered journal ingress.
+ let command = call.into_runtime_binding_removal_commit(output);
+ let result = dispatch_nested_main_page_command(command, first_dispatch)
+ .map(|output| RendererOwnerReply::AsyncPageCommandRan(Box::new(output)));
+ let _ = reply_tx.send(result);
}
fn dispatch_next_io_command_from_interrupt(&self) {