Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(devtools): align inspector session routing with Chromium
ldm0d28c20ef870a
diff --git a/moli-core/src/page/js_evaluation.rs b/moli-core/src/page/js_evaluation.rsindex bcb9140cc..23639b962 100644--- a/moli-core/src/page/js_evaluation.rs+++ b/moli-core/src/page/js_evaluation.rs@@ -1,4 +1,5 @@use anyhow::{Result, anyhow};+use moli_page_types::RendererInspectorResponseDelivery;use serde_json::{Value, json};use super::Page;@@ -516,9 +517,15 @@ impl Page {owner_context_resolution_action: Option<String>,raw_json: String,deferred_response: RendererRuntimeInspectorResponseSender,+ response_delivery: RendererInspectorResponseDelivery,) -> Result<PendingRuntimeInspectorCommandDispatch> {match inspector_route {RendererInspectorCommandRoute::MainThread => {+ debug_assert_eq!(+ response_delivery,+ RendererInspectorResponseDelivery::CommandReply,+ "Main Inspector responses have not migrated to session output"+ );let route = self.handle.enqueue_runtime_inspector_main_command(RendererInspectorCommandEnvelope::new_main_protocol(RendererInspectorIngressTicket::new(@@ -548,6 +555,7 @@ impl Page {),raw_json,Some(deferred_response),+ response_delivery,),);Ok(Self::pending_io_runtime_inspector_command_dispatch(route))@@ -569,6 +577,7 @@ impl Page {),raw_json,None,+ RendererInspectorResponseDelivery::CommandReply,),);Ok(Self::pending_io_runtime_inspector_command_dispatch(route))@@ -827,7 +836,7 @@ impl Page {self.start_page_command(RendererPageCommand::PerformanceMetricSnapshot)}- /// Admits `Performance.getMetrics` through the same IO session lane used+ /// Admits `Performance.getMetrics` through the same target IO task FIFO used/// by interruptible V8 Inspector commands. The snapshot remains the latest/// owner-published value because collecting a fresh JS-derived snapshot is/// not re-entrant while the isolate is executing JavaScript.diff --git a/moli-core/src/page/settings_support.rs b/moli-core/src/page/settings_support.rsindex c7a902636..4ef54e4e8 100644--- a/moli-core/src/page/settings_support.rs+++ b/moli-core/src/page/settings_support.rs@@ -236,7 +236,7 @@ impl Page {}/// Admits the DevTools IO-agent setting through the target's shared IO- /// session lane without entering the renderer owner's Main command queue.+ /// task FIFO without entering the renderer owner's Main command queue.pub fn start_set_script_execution_disabled_from_io(&self,disabled: bool,diff --git a/moli-page-types/src/inspector_identity.rs b/moli-page-types/src/inspector_identity.rsindex e4c3992ab..b64faf223 100644--- a/moli-page-types/src/inspector_identity.rs+++ b/moli-page-types/src/inspector_identity.rs@@ -4,8 +4,21 @@ use std::{sync::atomic::{AtomicU64, Ordering},};+/// Destination that owns the terminal response of one renderer Inspector+/// command.+///+/// Frontend DevTools commands may publish directly through their concrete+/// session capability. Internal protocol adapters retain a private command+/// reply channel even when they synthesize the same CDP method.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum RendererInspectorResponseDelivery {+ CommandReply,+ DevToolsSession,+}+static NEXT_RENDERER_DEVTOOLS_AGENT_TOKEN: AtomicU64 = AtomicU64::new(1);static NEXT_RENDERER_AGENT_ATTACHMENT_ID: AtomicU64 = AtomicU64::new(1);+static NEXT_RENDERER_DEVTOOLS_COMMAND_ID: AtomicU64 = AtomicU64::new(1);#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]pub enum DevToolsSessionKey {@@ -45,6 +58,12 @@ impl RendererDevToolsAgentToken {}}+/// Identity of one live browser-to-renderer DevTools attachment.+///+/// This is a capability identity, not a chronological epoch. A replacement+/// renderer receives a different identity, but callers must establish+/// equality before comparing any attachment-local ingress or output position;+/// the numeric value does not define ordering between attachments.#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]pub struct RendererAgentAttachmentId(NonZeroU64);@@ -61,6 +80,28 @@ impl RendererAgentAttachmentId {}}+/// Process-unique identity of one command admitted to a renderer DevTools+/// endpoint.+///+/// This is deliberately not an ordering primitive. Receiver-local ingress+/// order and session-local output order use their own types below, so a+/// process-global allocation gap can never be mistaken for a missing command.+#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]+pub struct RendererDevToolsCommandId(NonZeroU64);++impl RendererDevToolsCommandId {+ pub fn allocate() -> Self {+ Self(allocate_nonzero_u64(+ &NEXT_RENDERER_DEVTOOLS_COMMAND_ID,+ "renderer DevTools command id",+ ))+ }++ pub const fn get(self) -> u64 {+ self.0.get()+ }+}+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]pub struct FrontendCommandId(u64);@@ -163,6 +204,11 @@ mod tests {let second_attachment = RendererAgentAttachmentId::allocate();assert_ne!(first_attachment, second_attachment);assert_ne!(first_attachment.get(), 0);++ let first_command = RendererDevToolsCommandId::allocate();+ let second_command = RendererDevToolsCommandId::allocate();+ assert_ne!(first_command, second_command);+ assert_ne!(first_command.get(), 0);}#[test]@@ -175,6 +221,10 @@ mod tests {size_of::<Option<RendererAgentAttachmentId>>(),size_of::<RendererAgentAttachmentId>());+ assert_eq!(+ size_of::<Option<RendererDevToolsCommandId>>(),+ size_of::<RendererDevToolsCommandId>()+ );}#[test]diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rsindex c0dca9e50..546733522 100644--- a/moli-page-types/src/lib.rs+++ b/moli-page-types/src/lib.rs@@ -45,7 +45,8 @@ static NEXT_SUBRESOURCE_RESPONSE_BODY_SPOOL_ID: AtomicU64 = AtomicU64::new(1);pub use inspector_identity::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId, RendererCallId,- RendererCallIdOutOfRange, RendererDevToolsAgentToken,+ RendererCallIdOutOfRange, RendererDevToolsAgentToken, RendererDevToolsCommandId,+ RendererInspectorResponseDelivery,};pub use layout::LayoutPolicy;diff --git a/moli-protocol-cdp/src/lib.rs b/moli-protocol-cdp/src/lib.rsindex 2f5324c96..565e875a9 100644--- a/moli-protocol-cdp/src/lib.rs+++ b/moli-protocol-cdp/src/lib.rs@@ -20,6 +20,6 @@ pub use runtime::remote_object_from_json_value;pub use target::{CdpTargetKindWire, CdpTargetType, cdp_target_type_wire_value};pub use time::{DEFAULT_LOADER_ID, monotonic_timestamp_seconds};pub use wire::{- CdpRendererCommandAccess, CdpRendererCommandPolicy, CdpRendererCommandReplacement,- CdpRendererCommandReplayDispatch, CdpRequest, ParsedCdpCommand,+ CdpInspectorTaskMode, CdpRendererCommandAccess, CdpRendererCommandPolicy,+ CdpRendererCommandReplacement, CdpRendererCommandReplayDispatch, CdpRequest, ParsedCdpCommand,};diff --git a/moli-protocol-cdp/src/wire.rs b/moli-protocol-cdp/src/wire.rsindex 1f27ed0a8..75155a422 100644--- a/moli-protocol-cdp/src/wire.rs+++ b/moli-protocol-cdp/src/wire.rs@@ -1,3 +1,4 @@+use moli_page_types::RendererInspectorResponseDelivery;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use std::{error::Error, fmt};@@ -173,6 +174,32 @@ pub enum CdpRendererCommandAccess {Io,}+/// V8 execution capability of a command delivered through a renderer+/// DevTools IO receiver.+///+/// This dimension is independent from the browser-side Main/IO transport+/// route. Chromium sends every Worker command over IO, then uses this catalog+/// to decide whether the task may interrupt active JavaScript.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum CdpInspectorTaskMode {+ Interrupt,+ DontInterrupt,+}++impl CdpInspectorTaskMode {+ /// Mirrors Blink's `ShouldInterruptForMethod` catalog.+ pub fn for_method(method: &str) -> Self {+ match method {+ "Debugger.evaluateOnCallFrame"+ | "Runtime.evaluate"+ | "Runtime.callFunctionOn"+ | "Runtime.getProperties"+ | "Runtime.runScript" => Self::DontInterrupt,+ _ => Self::Interrupt,+ }+ }+}+/// Fate of an in-flight renderer command when navigation replaces its/// renderer attachment.#[derive(Clone, Copy, Debug, Eq, PartialEq)]@@ -202,8 +229,10 @@ pub enum CdpRendererCommandReplayDispatch {#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub struct CdpRendererCommandPolicy {renderer_access: CdpRendererCommandAccess,+ inspector_task_mode: CdpInspectorTaskMode,renderer_replacement: CdpRendererCommandReplacement,renderer_replay_dispatch: CdpRendererCommandReplayDispatch,+ response_delivery: RendererInspectorResponseDelivery,executes_page_javascript: bool,}@@ -212,6 +241,10 @@ impl CdpRendererCommandPolicy {self.renderer_access}+ pub const fn inspector_task_mode(self) -> CdpInspectorTaskMode {+ self.inspector_task_mode+ }+pub const fn replacement(self) -> CdpRendererCommandReplacement {self.renderer_replacement}@@ -220,6 +253,10 @@ impl CdpRendererCommandPolicy {self.renderer_replay_dispatch}+ pub const fn response_delivery(self) -> RendererInspectorResponseDelivery {+ self.response_delivery+ }+pub const fn executes_page_javascript(self) -> bool {self.executes_page_javascript}@@ -356,6 +393,10 @@ impl ParsedCdpCommand {self.renderer_policy.access()}+ pub fn inspector_task_mode(&self) -> CdpInspectorTaskMode {+ self.renderer_policy.inspector_task_mode()+ }+pub fn renderer_replacement(&self) -> CdpRendererCommandReplacement {self.renderer_policy.replacement()}@@ -534,8 +575,10 @@ impl CdpRendererCommandPolicy {let Some((domain, action)) = method.split_once('.') else {return Self {renderer_access: CdpRendererCommandAccess::OwnerIndependent,+ inspector_task_mode: CdpInspectorTaskMode::for_method(method),renderer_replacement: CdpRendererCommandReplacement::Replay,renderer_replay_dispatch: CdpRendererCommandReplayDispatch::Direct,+ response_delivery: RendererInspectorResponseDelivery::CommandReply,executes_page_javascript: false,};};@@ -591,6 +634,7 @@ impl CdpRendererCommandPolicy {};Self {renderer_access,+ inspector_task_mode: CdpInspectorTaskMode::for_method(method),renderer_replacement: if runtime_action.is_some_and(|action| {matches!(action,@@ -610,6 +654,21 @@ impl CdpRendererCommandPolicy {} else {CdpRendererCommandReplayDispatch::Direct},+ response_delivery: if domain == CdpMethodDomain::Debugger+ && matches!(+ action,+ "getPossibleBreakpoints"+ | "getScriptSource"+ | "getStackTrace"+ | "removeBreakpoint"+ | "setBreakpoint"+ | "setBreakpointByUrl"+ | "setBreakpointsActive"+ ) {+ RendererInspectorResponseDelivery::DevToolsSession+ } else {+ RendererInspectorResponseDelivery::CommandReply+ },executes_page_javascript: runtime_action.is_some_and(RuntimeWireAction::executes_page_javascript)|| debugger_action.is_some_and(DebuggerWireAction::executes_page_javascript),@@ -713,6 +772,40 @@ mod tests {}}+ #[test]+ fn inspector_execution_mode_matches_chromium_worker_catalog() {+ for method in [+ "Debugger.evaluateOnCallFrame",+ "Runtime.evaluate",+ "Runtime.callFunctionOn",+ "Runtime.getProperties",+ "Runtime.runScript",+ ] {+ let command = parse(format!(r#"{{"id":12,"method":"{method}"}}"#));+ assert_eq!(+ command.inspector_task_mode(),+ CdpInspectorTaskMode::DontInterrupt,+ "{method} must wait for the ordinary isolate task runner"+ );+ }++ for method in [+ "Debugger.pause",+ "Debugger.resume",+ "Debugger.stepInto",+ "Runtime.enable",+ "Runtime.terminateExecution",+ "Inspector.disable",+ ] {+ let command = parse(format!(r#"{{"id":13,"method":"{method}"}}"#));+ assert_eq!(+ command.inspector_task_mode(),+ CdpInspectorTaskMode::Interrupt,+ "{method} must be allowed to interrupt active JavaScript"+ );+ }+ }+#[test]fn debugger_execution_controls_admit_exact_command_output_barriers() {for method in [@@ -735,6 +828,41 @@ mod tests {);}+ #[test]+ fn synchronous_interruptible_frontend_v8_responses_use_session_output_as_one_family() {+ for method in [+ "Debugger.getPossibleBreakpoints",+ "Debugger.getScriptSource",+ "Debugger.getStackTrace",+ "Debugger.removeBreakpoint",+ "Debugger.setBreakpoint",+ "Debugger.setBreakpointByUrl",+ "Debugger.setBreakpointsActive",+ ] {+ assert_eq!(+ parse(format!(r#"{{"id":18,"method":"{method}"}}"#))+ .renderer_policy()+ .response_delivery(),+ RendererInspectorResponseDelivery::DevToolsSession,+ "{method} must share the same session output path as adjacent synchronous V8 IO commands"+ );+ }+ for method in [+ "Debugger.enable",+ "Debugger.pause",+ "Debugger.resume",+ "Runtime.getIsolateId",+ ] {+ assert_eq!(+ parse(format!(r#"{{"id":19,"method":"{method}"}}"#))+ .renderer_policy()+ .response_delivery(),+ RendererInspectorResponseDelivery::CommandReply,+ "{method} still requires the command-reply completion path"+ );+ }+ }+#[test]fn renderer_replacement_traits_are_computed_at_the_wire_boundary() {for method in [diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rsindex df1e3f6a5..d03a90e49 100644--- a/moli-protocol/src/conn/runtime_eval.rs+++ b/moli-protocol/src/conn/runtime_eval.rs@@ -1,6 +1,6 @@use std::{collections::hash_map::Entry, future::Future, pin::Pin};-use moli_page_types::{FrontendCommandId, RendererCallId};+use moli_page_types::{FrontendCommandId, RendererCallId, RendererInspectorResponseDelivery};use moli_protocol_cdp::CdpRendererCommandReplayDispatch;use moli_shared_worker::SharedWorkerInstanceId;use serde_json::{Map, Value, json};@@ -336,6 +336,7 @@ pub struct PendingRuntimeProtocolMessageDispatch {route: RuntimeProtocolMessagePageRoute,pending: PendingRuntimeProtocolMessageDispatchKind,deferred_response_rx: Option<RuntimeInspectorResponseReceiver>,+ response_delivery: RendererInspectorResponseDelivery,}enum PendingRuntimeProtocolMessageDispatchKind {@@ -387,6 +388,7 @@ pub struct CompletedRuntimeProtocolMessageDispatch {route: RuntimeProtocolMessagePageRoute,completion: moli_core::page::CompletedRuntimeInspectorCommandDispatch,deferred_response_rx: Option<RuntimeInspectorResponseReceiver>,+ response_delivery: RendererInspectorResponseDelivery,}pub struct CompletedSharedWorkerRuntimeProtocolMessageDispatch {@@ -540,6 +542,7 @@ impl PendingRuntimeProtocolMessageDispatch {route: self.route,completion,deferred_response_rx: self.deferred_response_rx,+ response_delivery: self.response_delivery,})}}@@ -581,6 +584,10 @@ impl CompletedRuntimeProtocolMessageDispatch {) -> Option<RuntimeInspectorResponseReceiver> {self.deferred_response_rx.take()}++ pub(crate) const fn response_delivery(&self) -> RendererInspectorResponseDelivery {+ self.response_delivery+ }}impl CompletedSharedWorkerRuntimeProtocolMessageDispatch {@@ -949,10 +956,12 @@ impl CdpConnection {String,RendererRuntimeInspectorResponseSender,RuntimeInspectorResponseReceiver,+ RendererInspectorResponseDelivery,),String,> {let raw_json = descriptor.frontend_payload().to_owned();+ let response_delivery = descriptor.response_delivery();let prepared = self.try_register_renderer_call_for_session_owner(session_id,cdp_request_id,@@ -970,7 +979,13 @@ impl CdpConnection {) {Ok(raw_json) => {let (correlation, response_sender, response_receiver) = prepared.into_parts();- Ok((correlation, raw_json, response_sender, response_receiver))+ Ok((+ correlation,+ raw_json,+ response_sender,+ response_receiver,+ response_delivery,+ ))}Err(error) => {let removed = self@@ -2948,6 +2963,45 @@ impl CdpConnection {}}+ /// Resolves terminal responses carried by the renderer's concrete+ /// DevTools session output stream.+ ///+ /// Notifications have no renderer call id and remain in place. A response+ /// without an exact `(session, attachment, renderer call)` registration is+ /// stale and must not expose the renderer-private id on the wire.+ pub(crate) fn restore_frontend_command_ids_in_devtools_session_output(+ &mut self,+ session_id: Option<&str>,+ dispatched_attachment_id: RendererAgentAttachmentId,+ messages: &mut Vec<RendererRuntimeInspectorMessage>,+ ) {+ messages.retain_mut(|message| {+ let RendererRuntimeInspectorMessage::Protocol(message) = message else {+ return true;+ };+ let Some(renderer_call_id) = message.renderer_call_id() else {+ return true;+ };+ let Some(correlation) = self+ .take_frontend_command_for_renderer_if_attachment_matches_for_session_owner(+ session_id,+ renderer_call_id,+ Some(dispatched_attachment_id),+ )+ else {+ tracing::debug!(+ session_id,+ renderer_call_id = renderer_call_id.get(),+ attachment_id = dispatched_attachment_id.get(),+ "dropping DevTools session response without a live renderer correlation"+ );+ return false;+ };+ message.value_mut()["id"] = json!(correlation.frontend_command_id().get());+ true+ });+ }+fn start_or_enqueue_registered_runtime_inspector_response_ready(&self,command_id: u64,@@ -3754,8 +3808,13 @@ impl CdpConnection {command_id: u64,) -> Result<PendingSharedWorkerRuntimeProtocolMessageDispatch, String> {self.shared_worker_runtime_target_for_session(session_id)?;- let (correlation, raw_json, response_sender, response_receiver) =+ let (correlation, raw_json, response_sender, response_receiver, response_delivery) =self.prepare_renderer_call_for_session_owner(session_id, descriptor, command_id, None)?;+ debug_assert_eq!(+ response_delivery,+ RendererInspectorResponseDelivery::CommandReply,+ "worker responses have not migrated to the page DevTools session output"+ );let result = self.start_shared_worker_runtime_protocol_message_for_session_with_optional_deferred_response(session_id,raw_json,@@ -3902,8 +3961,13 @@ impl CdpConnection {command_id: u64,) -> Result<PendingServiceWorkerRuntimeProtocolMessageDispatch, String> {self.service_worker_runtime_target_for_session(session_id)?;- let (correlation, raw_json, response_sender, response_receiver) =+ let (correlation, raw_json, response_sender, response_receiver, response_delivery) =self.prepare_renderer_call_for_session_owner(session_id, descriptor, command_id, None)?;+ debug_assert_eq!(+ response_delivery,+ RendererInspectorResponseDelivery::CommandReply,+ "worker responses have not migrated to the page DevTools session output"+ );let result = self.start_service_worker_runtime_protocol_message_for_session_with_optional_deferred_response(session_id,raw_json,@@ -4300,6 +4364,7 @@ impl CdpConnection {route,pending,deferred_response_rx: None,+ response_delivery: RendererInspectorResponseDelivery::CommandReply,})}@@ -4339,13 +4404,13 @@ impl CdpConnection {inspector_route: RendererInspectorCommandRoute,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;- let (correlation, raw_json, response_sender, response_receiver) = self+ let (correlation, raw_json, response_sender, response_receiver, response_delivery) = self.prepare_renderer_call_for_session_owner(- session_id,- descriptor,- command_id,- Some(route.renderer_agent_attachment_id),- )?;+ session_id,+ descriptor,+ command_id,+ Some(route.renderer_agent_attachment_id),+ )?;let inspector_session_id =self.target_renderer_runtime_inspector_session_id_for_session(session_id);let page_result = match inspector_route {@@ -4371,6 +4436,7 @@ impl CdpConnection {None,raw_json,response_sender,+ response_delivery,) {Ok(pending) => pending,Err(error) => {@@ -4385,6 +4451,7 @@ impl CdpConnection {route,pending: PendingRuntimeProtocolMessageDispatchKind::Routable(pending),deferred_response_rx: Some(response_receiver),+ response_delivery,})}@@ -4412,6 +4479,7 @@ impl CdpConnection {route,pending: PendingRuntimeProtocolMessageDispatchKind::Page(pending),deferred_response_rx: None,+ response_delivery: RendererInspectorResponseDelivery::CommandReply,})}@@ -4423,13 +4491,13 @@ impl CdpConnection {command_id: u64,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;- let (correlation, raw_json, response_sender, response_receiver) = self+ let (correlation, raw_json, response_sender, response_receiver, response_delivery) = self.prepare_renderer_call_for_session_owner(- session_id,- descriptor,- command_id,- Some(route.renderer_agent_attachment_id),- )?;+ session_id,+ descriptor,+ command_id,+ Some(route.renderer_agent_attachment_id),+ )?;let inspector_session_id =self.target_renderer_runtime_inspector_session_id_for_session(session_id);let page = match self.runtime_session_owner_page_mut(session_id) {@@ -4447,6 +4515,7 @@ impl CdpConnection {Some(action.to_owned()),raw_json,response_sender,+ response_delivery,) {Ok(pending) => pending,Err(error) => {@@ -4461,6 +4530,7 @@ impl CdpConnection {route,pending: PendingRuntimeProtocolMessageDispatchKind::Routable(pending),deferred_response_rx: Some(response_receiver),+ response_delivery,})}@@ -4549,7 +4619,7 @@ impl CdpConnection {let frontend_session_id = replay.frontend_session_id().map(str::to_owned);let renderer_inspector_session_id =replay.renderer_inspector_session_id().map(str::to_owned);- let (correlation, dispatch, frontend_payload, response_sender) =+ let (correlation, dispatch, response_delivery, frontend_payload, response_sender) =replay.into_replay().into_parts();let raw_json = match self.rewrite_runtime_inspector_command_for_session_owner(frontend_session_id.as_deref(),@@ -4561,7 +4631,14 @@ impl CdpConnection {) {Ok(raw_json) => raw_json,Err(error) => {- send_renderer_replay_error(&response_sender, correlation, &error);+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,+ &response_sender,+ correlation,+ &error,+ );continue;}};@@ -4570,12 +4647,22 @@ impl CdpConnection {) {Ok(route) => route,Err(error) => {- send_renderer_replay_error(&response_sender, correlation, &error);+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,+ &response_sender,+ correlation,+ &error,+ );continue;}};if route.renderer_agent_attachment_id != new_attachment_id {- send_renderer_replay_error(+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,&response_sender,correlation,"renderer replay attachment is no longer current",@@ -4587,34 +4674,67 @@ impl CdpConnection {{Ok(page) => page,Err(error) => {- send_renderer_replay_error(&response_sender, correlation, &error);+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,+ &response_sender,+ correlation,+ &error,+ );continue;}};let dispatch_sender = response_sender.clone();- match dispatch {- CdpRendererCommandReplayDispatch::ResolveRuntimeContext => page.start_runtime_protocol_message_for_inspector_session_with_context_resolution_and_deferred_response(- renderer_inspector_session_id,- "addBinding".to_owned(),- raw_json,- dispatch_sender,- ),- CdpRendererCommandReplayDispatch::Direct => page.start_runtime_protocol_message_for_inspector_session_with_deferred_response(- renderer_inspector_session_id,- raw_json,- dispatch_sender,- ),+ match response_delivery {+ RendererInspectorResponseDelivery::CommandReply => match dispatch {+ CdpRendererCommandReplayDispatch::ResolveRuntimeContext => page+ .start_runtime_protocol_message_for_inspector_session_with_context_resolution_and_deferred_response(+ renderer_inspector_session_id,+ "addBinding".to_owned(),+ raw_json,+ dispatch_sender,+ )+ .map(PendingRuntimeProtocolMessageDispatchKind::Page),+ CdpRendererCommandReplayDispatch::Direct => page+ .start_runtime_protocol_message_for_inspector_session_with_deferred_response(+ renderer_inspector_session_id,+ raw_json,+ dispatch_sender,+ )+ .map(PendingRuntimeProtocolMessageDispatchKind::Page),+ },+ RendererInspectorResponseDelivery::DevToolsSession => {+ debug_assert_eq!(+ dispatch,+ CdpRendererCommandReplayDispatch::Direct,+ "the migrated synchronous IO family must replay directly"+ );+ page.start_routable_runtime_protocol_message_for_inspector_session(+ renderer_inspector_session_id,+ RendererInspectorCommandRoute::Io,+ None,+ raw_json,+ dispatch_sender,+ response_delivery,+ )+ .map(PendingRuntimeProtocolMessageDispatchKind::Routable)+ }}};let pending = match pending {Ok(pending) => PendingRuntimeProtocolMessageDispatch {session_id: frontend_session_id.clone(),route,- pending: PendingRuntimeProtocolMessageDispatchKind::Page(pending),+ pending,deferred_response_rx: None,+ response_delivery,},Err(error) => {- send_renderer_replay_error(+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,&response_sender,correlation,&format!("runtime inspector replay dispatch failed: {error}"),@@ -4625,7 +4745,14 @@ impl CdpConnection {let completed = match pending.wait().await {Ok(completed) => completed,Err(error) => {- send_renderer_replay_error(&response_sender, correlation, &error);+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,+ &response_sender,+ correlation,+ &error,+ );continue;}};@@ -4633,8 +4760,18 @@ impl CdpConnection {moli_core::page::CompletedRuntimeInspectorCommandDispatch::Owner(completion) => {*completion}- moli_core::page::CompletedRuntimeInspectorCommandDispatch::Inspector- | moli_core::page::CompletedRuntimeInspectorCommandDispatch::Canceled => {+ moli_core::page::CompletedRuntimeInspectorCommandDispatch::Inspector => {+ continue;+ }+ moli_core::page::CompletedRuntimeInspectorCommandDispatch::Canceled => {+ self.settle_renderer_replay_error(+ &mut events,+ frontend_session_id.as_deref(),+ response_delivery,+ &response_sender,+ correlation,+ "Inspected target navigated or closed",+ );continue;}};@@ -4684,6 +4821,43 @@ impl CdpConnection {Ok(events)}+ fn settle_renderer_replay_error(+ &mut self,+ events: &mut Vec<BackgroundProtocolEvent>,+ frontend_session_id: Option<&str>,+ response_delivery: RendererInspectorResponseDelivery,+ response_sender: &RendererRuntimeInspectorResponseSender,+ correlation: RendererCommandCorrelation,+ message: &str,+ ) {+ if response_delivery == RendererInspectorResponseDelivery::CommandReply {+ send_renderer_replay_error(response_sender, correlation, message);+ return;+ }++ let Some(resolved) = self+ .take_frontend_command_for_renderer_if_attachment_matches_for_session_owner(+ frontend_session_id,+ correlation.renderer_call_id(),+ correlation.dispatched_attachment_id(),+ )+ else {+ return;+ };+ debug_assert_eq!(resolved, correlation);+ let mut response = json!({+ "id": resolved.frontend_command_id().get(),+ "error": {+ "code": -32000,+ "message": message,+ },+ });+ if let Some(session_id) = frontend_session_id {+ response["sessionId"] = json!(session_id);+ }+ events.push(protocol_message_background_event(response));+ }+pub(crate) fn terminate_prepared_renderer_calls_after_navigation(&mut self,terminations: Vec<PreparedRendererCallTermination>,@@ -5839,6 +6013,73 @@ mod tests {.unwrap()}+ #[tokio::test]+ async fn devtools_session_output_restores_only_the_exact_registered_frontend_response() {+ let mut conn = CdpConnection::default();+ let mut browser_context = BrowserContext::new("BID-session-output".to_owned());+ browser_context.set_active_target_id("TID-session-output".to_owned());+ browser_context.attach_active_session("SID-session-output".to_owned());+ conn.browser_context = Some(browser_context);++ let attachment_id = RendererAgentAttachmentId::allocate();+ let frontend = ParsedCdpCommand::parse_str(+ r#"{"id":44,"method":"Debugger.getScriptSource","params":{"scriptId":"7"}}"#,+ )+ .expect("frontend command should parse");+ let prepared = conn+ .try_register_renderer_call_for_session_owner(+ Some("SID-session-output"),+ 44,+ Some(attachment_id),+ RendererCommandDescriptor::from_frontend_policy(+ frontend.json().to_owned(),+ frontend.renderer_policy(),+ ),+ )+ .expect("frontend response correlation should register");+ let (correlation, response_sender, response_receiver) = prepared.into_parts();+ drop(response_sender);+ let mut messages = vec![+ RendererRuntimeInspectorMessage::protocol(json!({+ "method": "Debugger.scriptParsed",+ "params": { "scriptId": "7" },+ })),+ RendererRuntimeInspectorMessage::protocol(json!({+ "id": correlation.renderer_call_id().get(),+ "result": { "scriptSource": "source" },+ })),+ RendererRuntimeInspectorMessage::protocol(json!({+ "id": correlation.renderer_call_id().get() + 1,+ "result": { "scriptSource": "stale" },+ })),+ ];++ conn.restore_frontend_command_ids_in_devtools_session_output(+ Some("SID-session-output"),+ attachment_id,+ &mut messages,+ );++ assert_eq!(+ messages.len(),+ 2,+ "stale renderer responses must be dropped"+ );+ let RendererRuntimeInspectorMessage::Protocol(response) = &messages[1] else {+ panic!("expected a protocol response");+ };+ assert_eq!(response.value()["id"], json!(44));+ assert!(+ conn.renderer_runtime_command_cause_for_frontend(Some("SID-session-output"), 44,)+ .is_none(),+ "publishing the session response must consume its exact correlation"+ );+ assert!(+ response_receiver.await.is_err(),+ "the legacy reply receiver should close after session output takes ownership"+ );+ }+fn bidi_channel_listener_residence_for_test(conn: &CdpConnection,session_id: &str,diff --git a/moli-protocol/src/conn/state/devtools_renderer_channel.rs b/moli-protocol/src/conn/state/devtools_renderer_channel.rsindex 857c6f321..8dfee565f 100644--- a/moli-protocol/src/conn/state/devtools_renderer_channel.rs+++ b/moli-protocol/src/conn/state/devtools_renderer_channel.rs@@ -298,14 +298,9 @@ impl DevToolsRendererChannel {self.buffered_output.clear();return Vec::new();};- self.buffered_output- .drain(..)- .filter_map(|buffered| {- (buffered.attachment_id == current.id()- && buffered.batch.agent_token == current.agent_token())- .then_some(buffered.batch)- })- .collect()+ let released = self.take_buffered_current_output(current);+ self.buffered_output.clear();+ released}pub(crate) fn detach_current(@@ -369,12 +364,42 @@ impl DevToolsRendererChannel {return Err(DevToolsRendererChannelError::MismatchedAgent);}if self.output_is_suspended() {+ let releases_current_prefix = batches+ .iter()+ .any(RendererRuntimeInspectorMessageBatch::has_renderer_protocol_response);self.buffer_output(attachment_id, batches);+ if releases_current_prefix {+ // Main ingress remains suspended, but Chromium's existing+ // renderer session pipe can still return IO responses until+ // endpoint replacement. Release the whole current-attachment+ // prefix so the response cannot overtake notifications that+ // preceded it in the same renderer journal.+ return Ok(self.take_buffered_current_output(current));+ }return Ok(Vec::new());}Ok(batches)}+ fn take_buffered_current_output(+ &mut self,+ current: RendererAgentAttachment,+ ) -> Vec<RendererRuntimeInspectorMessageBatch> {+ let mut released = Vec::new();+ let mut retained = Vec::new();+ for buffered in self.buffered_output.drain(..) {+ if buffered.attachment_id == current.id()+ && buffered.batch.agent_token == current.agent_token()+ {+ released.push(buffered.batch);+ } else {+ retained.push(buffered);+ }+ }+ self.buffered_output = retained;+ released+ }+fn buffer_output(&mut self,attachment_id: RendererAgentAttachmentId,@@ -471,6 +496,20 @@ mod tests {.and_then(serde_json::Value::as_str)}+ fn response_batch(+ agent_token: RendererDevToolsAgentToken,+ call_id: i32,+ ) -> RendererRuntimeInspectorMessageBatch {+ RendererRuntimeInspectorMessageBatch::new(+ agent_token,+ DevToolsSessionKey::Primary,+ vec![RendererRuntimeInspectorMessage::protocol(json!({+ "id": call_id,+ "result": {},+ }))],+ )+ }+#[test]fn initial_attach_and_reattach_allocate_distinct_route_leases() {let agent = RendererDevToolsAgentToken::allocate();@@ -794,6 +833,34 @@ mod tests {assert_eq!(batch_marker(&released[0]), Some("retained"));}+ #[test]+ fn current_session_response_releases_its_buffered_prefix_during_navigation() {+ let agent = RendererDevToolsAgentToken::allocate();+ let request = navigation(1);+ let mut channel = DevToolsRendererChannel::default();+ channel.attach_current(agent).expect("current attach");+ let attachment = channel.current().expect("current attachment");+ channel+ .navigation_started(request.clone())+ .expect("navigation start");++ assert!(+ channel+ .route_current_output(attachment.id(), vec![batch(agent, "before-response")])+ .expect("route notification prefix")+ .is_empty()+ );+ let released = channel+ .route_current_output(attachment.id(), vec![response_batch(agent, 17)])+ .expect("route session response");++ assert_eq!(released.len(), 2);+ assert_eq!(batch_marker(&released[0]), Some("before-response"));+ assert!(released[1].has_renderer_protocol_response());+ assert!(channel.output_is_suspended());+ assert!(channel.take_released_output().is_empty());+ }+#[test]fn stale_attachment_and_mismatched_agent_are_rejected() {let agent = RendererDevToolsAgentToken::allocate();diff --git a/moli-protocol/src/conn/state/pending_renderer_command.rs b/moli-protocol/src/conn/state/pending_renderer_command.rsindex 48a32fa65..9b51cd780 100644--- a/moli-protocol/src/conn/state/pending_renderer_command.rs+++ b/moli-protocol/src/conn/state/pending_renderer_command.rs@@ -10,6 +10,7 @@ use moli_core::{};use moli_page_types::{DevToolsSessionKey, FrontendCommandId, RendererAgentAttachmentId, RendererCallId,+ RendererInspectorResponseDelivery,};use moli_protocol_cdp::{CdpRendererCommandPolicy, CdpRendererCommandReplacement, CdpRendererCommandReplayDispatch,@@ -22,16 +23,21 @@ use serde_json::Value;pub(crate) struct RendererCommandDescriptor {replacement: CdpRendererCommandReplacement,replay_dispatch: CdpRendererCommandReplayDispatch,+ response_delivery: RendererInspectorResponseDelivery,frontend_payload: String,}impl RendererCommandDescriptor {/// Builds a replay descriptor from the policy already derived at typed CDP/// ingress. Production frontend commands must use this constructor.- pub(crate) fn from_policy(frontend_payload: String, policy: CdpRendererCommandPolicy) -> Self {+ pub(crate) fn from_frontend_policy(+ frontend_payload: String,+ policy: CdpRendererCommandPolicy,+ ) -> Self {Self {replacement: policy.replacement(),replay_dispatch: policy.replay_dispatch(),+ response_delivery: policy.response_delivery(),frontend_payload,}}@@ -44,10 +50,16 @@ impl RendererCommandDescriptor {pub(crate) fn from_synthesized_payload(frontend_payload: String) -> Result<Self, String> {let command = ParsedCdpCommand::parse_str(&frontend_payload).map_err(|error| format!("invalid renderer Inspector command JSON: {error}"))?;- Ok(Self::from_policy(+ let policy = command.renderer_policy();+ Ok(Self {+ replacement: policy.replacement(),+ replay_dispatch: policy.replay_dispatch(),+ // Internal Classic/BiDi adapters own their reply channel. A+ // method being eligible for frontend session output must never+ // redirect a synthesized adapter command implicitly.+ response_delivery: RendererInspectorResponseDelivery::CommandReply,frontend_payload,- command.renderer_policy(),- ))+ })}pub(crate) const fn replacement(&self) -> CdpRendererCommandReplacement {@@ -58,6 +70,10 @@ impl RendererCommandDescriptor {self.replay_dispatch}+ pub(crate) const fn response_delivery(&self) -> RendererInspectorResponseDelivery {+ self.response_delivery+ }+pub(crate) fn frontend_payload(&self) -> &str {&self.frontend_payload}@@ -178,6 +194,7 @@ impl PreparedRendererCallDispatch {pub(crate) struct PreparedRendererCallReplay {correlation: RendererCommandCorrelation,dispatch: CdpRendererCommandReplayDispatch,+ response_delivery: RendererInspectorResponseDelivery,frontend_payload: String,response_sender: RendererRuntimeInspectorResponseSender,}@@ -209,6 +226,11 @@ impl PreparedRendererCallReplay {&self.frontend_payload}+ #[cfg(test)]+ pub(crate) const fn response_delivery(&self) -> RendererInspectorResponseDelivery {+ self.response_delivery+ }+#[cfg(test)]pub(crate) fn into_response_sender(self) -> RendererRuntimeInspectorResponseSender {self.response_sender@@ -219,12 +241,14 @@ impl PreparedRendererCallReplay {) -> (RendererCommandCorrelation,CdpRendererCommandReplayDispatch,+ RendererInspectorResponseDelivery,String,RendererRuntimeInspectorResponseSender,) {(self.correlation,self.dispatch,+ self.response_delivery,self.frontend_payload,self.response_sender,)@@ -375,6 +399,7 @@ impl<T> PendingRendererCommandRegistry<T> {dispatched_attachment_id: Some(new_attachment_id),},dispatch: call.descriptor.replay_dispatch(),+ response_delivery: call.descriptor.response_delivery(),frontend_payload: call.descriptor.frontend_payload().to_owned(),response_sender,});@@ -813,7 +838,7 @@ mod tests {let normalized_payload =r#"{"id":91,"method":"Runtime.evaluate","params":{"expression":"1"}}"#.to_owned();- let descriptor = RendererCommandDescriptor::from_policy(+ let descriptor = RendererCommandDescriptor::from_frontend_policy(normalized_payload.clone(),ingress.renderer_policy(),);@@ -826,17 +851,54 @@ mod tests {);}+ #[test]+ fn synthesized_adapter_command_keeps_its_explicit_reply_sink() {+ let frontend = ParsedCdpCommand::parse_str(+ r#"{"id":33,"method":"Debugger.getScriptSource","params":{"scriptId":"1"}}"#,+ )+ .expect("frontend command must parse at ingress");+ let frontend_descriptor = RendererCommandDescriptor::from_frontend_policy(+ frontend.json().to_owned(),+ frontend.renderer_policy(),+ );+ let adapter_descriptor =+ RendererCommandDescriptor::from_synthesized_payload(frontend.json().to_owned())+ .expect("adapter payload must be valid Inspector JSON");++ assert_eq!(+ frontend_descriptor.response_delivery(),+ RendererInspectorResponseDelivery::DevToolsSession+ );+ assert_eq!(+ adapter_descriptor.response_delivery(),+ RendererInspectorResponseDelivery::CommandReply,+ "method policy must not redirect an internal adapter reply to a frontend session"+ );+ }+#[tokio::test]async fn replay_rotates_renderer_id_attachment_and_response_lease() {let frontend_id = FrontendCommandId::new(41);let old_attachment = RendererAgentAttachmentId::allocate();let new_attachment = RendererAgentAttachmentId::allocate();let mut registry = PendingRendererCommandRegistry::<()>::default();+ let frontend = ParsedCdpCommand::parse_str(+ serde_json::json!({+ "id": frontend_id.get(),+ "method": "Debugger.getScriptSource",+ "params": { "scriptId": "1" },+ })+ .to_string(),+ )+ .expect("frontend command must parse at ingress");let prepared = registry.try_register_renderer_call(frontend_id,Some(old_attachment),- descriptor(frontend_id.get(), "Profiler.stop"),+ RendererCommandDescriptor::from_frontend_policy(+ frontend.json().to_owned(),+ frontend.renderer_policy(),+ ),).unwrap();let (old_correlation, old_sender, response_receiver) = prepared.into_parts();@@ -859,6 +921,11 @@ mod tests {);let payload: Value = serde_json::from_str(replay.frontend_payload()).unwrap();assert_eq!(payload["id"], frontend_id.get());+ assert_eq!(+ replay.response_delivery(),+ RendererInspectorResponseDelivery::DevToolsSession,+ "attachment replacement must preserve the frontend session output capability"+ );assert!(old_senderdiff --git a/moli-protocol/src/domains/debugger.rs b/moli-protocol/src/domains/debugger.rsindex a70ce09b1..b18dc3adc 100644--- a/moli-protocol/src/domains/debugger.rs+++ b/moli-protocol/src/domains/debugger.rs@@ -54,7 +54,7 @@ mod tests {}async fn command(ctx: &mut TestContext, message: Value, command_id: u64) -> Value {- ctx.process_async(message).await;+ ctx.process_and_wait_for_response_async(message).await;let position = ctx.sent.iter()diff --git a/moli-protocol/src/domains/page/termination.rs b/moli-protocol/src/domains/page/termination.rsindex ce1a0102b..6f15648bc 100644--- a/moli-protocol/src/domains/page/termination.rs+++ b/moli-protocol/src/domains/page/termination.rs@@ -475,7 +475,7 @@ pub(super) async fn complete_crash_command_dispatch() = take_pending_fetch_state(conn, session_id);// Chromium handles Page.crash directly at the renderer IO-agent boundary;- // it never enters a V8InspectorSession or an ordinary per-session IO lane.+ // it never enters a V8InspectorSession or the ordinary target IO task FIFO.// Seal both DevTools receivers and interrupt active V8 synchronously so// target retirement cannot wait behind earlier JavaScript or IO work.if let Ok(page) = conn.loaded_page_mut_for_interruptible_protocol_access(session_id) {diff --git a/moli-protocol/src/domains/runtime/activity.rs b/moli-protocol/src/domains/runtime/activity.rsindex bba4645f3..f83d6b477 100644--- a/moli-protocol/src/domains/runtime/activity.rs+++ b/moli-protocol/src/domains/runtime/activity.rs@@ -234,7 +234,7 @@ impl RuntimePreparedOutputs {}pub(crate) fn from_renderer_runtime_inspector_message_batches(- conn: &CdpConnection,+ conn: &mut CdpConnection,source_session_id: Option<&str>,batches: &[RendererRuntimeInspectorMessageBatch],) -> Self {@@ -248,10 +248,19 @@ impl RuntimePreparedOutputs {else {continue;};- let messages = batch- .messages- .iter()- .cloned()+ let mut renderer_messages = batch.messages.clone();+ if let Some(renderer_agent_attachment_id) = batch.renderer_agent_attachment_id() {+ conn.restore_frontend_command_ids_in_devtools_session_output(+ attachment.session_id(),+ renderer_agent_attachment_id,+ &mut renderer_messages,+ );+ }+ if renderer_messages.is_empty() {+ continue;+ }+ let messages = renderer_messages+ .into_iter().map(|message| {RuntimeInspectorMessage::from_renderer_message(message,@@ -513,7 +522,7 @@ mod tests {}fn renderer_inspector_outputs(- conn: &CdpConnection,+ conn: &mut CdpConnection,source_session_id: Option<&str>,renderer_inspector_session_id: Option<&str>,messages: Vec<Value>,@@ -536,7 +545,7 @@ mod tests {#[test]fn renderer_inspector_batches_keep_their_command_response_side() {- let (conn, _) = runtime_binding_attachment_fixture();+ let (mut conn, _) = runtime_binding_attachment_fixture();let agent_token = RendererDevToolsAgentToken::allocate();let session = DevToolsSessionKey::Primary;let batches = vec![@@ -559,7 +568,7 @@ mod tests {];let outputs = RuntimePreparedOutputs::from_renderer_runtime_inspector_message_batches(- &conn,+ &mut conn,Some("SID-1"),&batches,);@@ -766,7 +775,7 @@ mod tests {async fn runtime_inspector_activity_uses_capture_time_attachment() {let (mut conn, _attachment) = runtime_binding_attachment_fixture();let outputs = renderer_inspector_outputs(- &conn,+ &mut conn,Some("SID-1"),None,vec![json!({@@ -802,7 +811,7 @@ mod tests {async fn runtime_inspector_activity_discards_replaced_page_output() {let (mut conn, _attachment) = runtime_binding_attachment_fixture();let outputs = renderer_inspector_outputs(- &conn,+ &mut conn,Some("SID-1"),None,vec![json!({@@ -825,7 +834,7 @@ mod tests {async fn runtime_inspector_activity_discards_detached_attachment() {let (mut conn, _attachment) = runtime_binding_attachment_fixture();let outputs = renderer_inspector_outputs(- &conn,+ &mut conn,Some("SID-1"),None,vec![json!({@@ -859,7 +868,7 @@ mod tests {.assign_auxiliary_session_to_target("TID-1", "SID-aux".to_owned()));let outputs = renderer_inspector_outputs(- &conn,+ &mut conn,Some("SID-1"),Some("SID-aux"),vec![json!({@@ -886,7 +895,7 @@ mod tests {async fn runtime_inspector_activity_authorizes_each_page_batch_independently() {let (mut conn, _attachment) = runtime_binding_attachment_fixture();let mut outputs = renderer_inspector_outputs(- &conn,+ &mut conn,Some("SID-1"),None,vec![json!({@@ -898,7 +907,7 @@ mod tests {.expect("Runtime inspector target").replace_page_attachment_id_for_test();outputs.extend(renderer_inspector_outputs(- &conn,+ &mut conn,Some("SID-1"),None,vec![json!({diff --git a/moli-protocol/src/domains/runtime/dispatcher.rs b/moli-protocol/src/domains/runtime/dispatcher.rsindex 88e065850..2933c10a9 100644--- a/moli-protocol/src/domains/runtime/dispatcher.rs+++ b/moli-protocol/src/domains/runtime/dispatcher.rs@@ -20,6 +20,7 @@ use moli_core::page::{RendererDomBidiNodeBindingResolution, RendererRuntimeCommandOutput,RendererRuntimeInspectorMessage,};+use moli_page_types::RendererInspectorResponseDelivery;use crate::conn::{BackgroundCommandResponsePayload, BackgroundCommandResponsePayloadRef, BackgroundProtocolEvent,@@ -1871,7 +1872,7 @@ fn start_pending_runtime_io_inspector_dispatch() -> Result<PendingRuntimeProtocolMessageDispatch, String> {if let Some(command_id) = cmd.id {let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, cmd.renderer_policy());+ RendererCommandDescriptor::from_frontend_policy(inspector_json, cmd.renderer_policy());conn.start_runtime_io_protocol_message_for_session_owner_with_deferred_response(cmd.session_id,descriptor,@@ -1890,7 +1891,7 @@ fn start_pending_runtime_context_resolved_inspector_dispatch() -> Result<PendingRuntimeProtocolMessageDispatch, String> {if let Some(command_id) = cmd.id {let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, cmd.renderer_policy());+ RendererCommandDescriptor::from_frontend_policy(inspector_json, cmd.renderer_policy());conn.start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(cmd.session_id,action,@@ -1913,7 +1914,7 @@ fn start_pending_runtime_inspector_dispatch() -> Result<PendingRuntimeProtocolMessageDispatch, String> {if let Some(command_id) = cmd.id {let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, cmd.renderer_policy());+ RendererCommandDescriptor::from_frontend_policy(inspector_json, cmd.renderer_policy());conn.start_runtime_protocol_message_for_session_owner_with_deferred_response(cmd.session_id,descriptor,@@ -1931,7 +1932,7 @@ fn start_shared_worker_frontend_inspector_dispatch() -> Result<PendingSharedWorkerRuntimeProtocolMessageDispatch, String> {if let Some(command_id) = cmd.id {let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, cmd.renderer_policy());+ RendererCommandDescriptor::from_frontend_policy(inspector_json, cmd.renderer_policy());conn.start_shared_worker_runtime_protocol_message_for_session_with_deferred_response(cmd.session_id,descriptor,@@ -1952,7 +1953,7 @@ fn start_service_worker_frontend_inspector_dispatch() -> Result<PendingServiceWorkerRuntimeProtocolMessageDispatch, String> {if let Some(command_id) = cmd.id {let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, cmd.renderer_policy());+ RendererCommandDescriptor::from_frontend_policy(inspector_json, cmd.renderer_policy());conn.start_service_worker_runtime_protocol_message_for_session_with_deferred_response(cmd.session_id,descriptor,@@ -7611,8 +7612,10 @@ fn start_pending_runtime_binding_inspector_phase(let result = match task.action {RuntimeBindingCommand::Add => {if let Some(command_id) = completed.command_id {- let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, task.renderer_policy);+ let descriptor = RendererCommandDescriptor::from_frontend_policy(+ inspector_json,+ task.renderer_policy,+ );conn.start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(completed.session_id(),"addBinding",@@ -7629,8 +7632,10 @@ fn start_pending_runtime_binding_inspector_phase(}RuntimeBindingCommand::Remove => {if let Some(command_id) = completed.command_id {- let descriptor =- RendererCommandDescriptor::from_policy(inspector_json, task.renderer_policy);+ let descriptor = RendererCommandDescriptor::from_frontend_policy(+ inspector_json,+ task.renderer_policy,+ );conn.start_runtime_protocol_message_for_session_owner_with_deferred_response(completed.session_id(),descriptor,@@ -8137,37 +8142,43 @@ async fn complete_pending_runtime_inspector_command(timing_started: Option<std::time::Instant>,response_flush: &crate::conn::CommandResponseFlushContext,) -> RuntimeCommandTaskStep {- let (messages, mut renderer_response_rx, page_owner_access_allowed) = match completed_inspector- {- Ok(mut completed_protocol) => {- let page_owner_access_allowed = completed_protocol.page_owner_access_allowed();- let renderer_response_rx = completed_protocol.take_deferred_response_receiver();- match conn- .complete_runtime_protocol_message_for_session_owner_async(completed_protocol)- .await- {- Ok(messages) => (messages, renderer_response_rx, page_owner_access_allowed),- Err(message) => {- if let Some(command_id) = completed.command_id {- conn.forget_pending_inspector_await(command_id, completed.session_id());+ let (messages, mut renderer_response_rx, page_owner_access_allowed, response_delivery) =+ match completed_inspector {+ Ok(mut completed_protocol) => {+ let page_owner_access_allowed = completed_protocol.page_owner_access_allowed();+ let response_delivery = completed_protocol.response_delivery();+ let renderer_response_rx = completed_protocol.take_deferred_response_receiver();+ match conn+ .complete_runtime_protocol_message_for_session_owner_async(completed_protocol)+ .await+ {+ Ok(messages) => (+ messages,+ renderer_response_rx,+ page_owner_access_allowed,+ response_delivery,+ ),+ Err(message) => {+ if let Some(command_id) = completed.command_id {+ conn.forget_pending_inspector_await(command_id, completed.session_id());+ }+ return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(+ completed.command_id,+ message,+ ));}- return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(- completed.command_id,- message,- ));}}- }- Err(message) => {- if let Some(command_id) = completed.command_id {- conn.forget_pending_inspector_await(command_id, completed.session_id());+ Err(message) => {+ if let Some(command_id) = completed.command_id {+ conn.forget_pending_inspector_await(command_id, completed.session_id());+ }+ return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(+ completed.command_id,+ message,+ ));}- return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(- completed.command_id,- message,- ));- }- };+ };let initial_message_count = messages.as_ref().map_or(0, |messages| {messages.runtime_inspector_output()@@ -8220,7 +8231,14 @@ async fn complete_pending_runtime_inspector_command(renderer_response_rx.take();saw_current_response = true;}- if !completed.wait_for_deferred_reply+ if response_delivery == RendererInspectorResponseDelivery::DevToolsSession {+ // The attachment-scoped renderer session stream owns the terminal+ // response. The typed Page completion remains internal state only and+ // must not join or await the legacy per-command receiver.+ renderer_response_rx.take();+ }+ if response_delivery == RendererInspectorResponseDelivery::CommandReply+ && !completed.wait_for_deferred_reply&& let Some(renderer_response_rx) = renderer_response_rx.take(){let saw_deferred_response = route_registered_runtime_response_receiver_into(diff --git a/moli-protocol/src/testing.rs b/moli-protocol/src/testing.rsindex 707eb6757..7461645d3 100644--- a/moli-protocol/src/testing.rs+++ b/moli-protocol/src/testing.rs@@ -23,6 +23,7 @@ use moli_core::{RendererOutputStreamIdentity, RendererOutputTransportMessage, runtime::NavigationRuntimeConfig,};use moli_fetch::FetchConfig;+use moli_page_types::RendererInspectorResponseDelivery;#[cfg(test)]use std::net::SocketAddr;#[cfg(test)]@@ -392,8 +393,15 @@ impl TestContext {.expect("test message must be a valid serialisable CDP command");let command_id = command.request().id();let response_start = self.sent.len();+ let response_uses_renderer_publication = command.renderer_policy().response_delivery()+ == RendererInspectorResponseDelivery::DevToolsSession;Box::pin(self.process_parsed_command_like_scheduler(&command, true)).await;- Box::pin(self.wait_for_test_command_response(command_id, response_start)).await;+ Box::pin(self.wait_for_test_command_response(+ command_id,+ response_start,+ response_uses_renderer_publication,+ ))+ .await;}#[cfg(test)]@@ -1216,7 +1224,12 @@ impl TestContext {TestSchedulerTurnOutcome::Processed(input_kind)}- async fn wait_for_test_command_response(&mut self, command_id: u64, response_start: usize) {+ async fn wait_for_test_command_response(+ &mut self,+ command_id: u64,+ response_start: usize,+ response_uses_renderer_publication: bool,+ ) {loop {if self.sent@@ -1229,6 +1242,7 @@ impl TestContext {}assert!(self.background_navigation_scheduler_enabled+ || response_uses_renderer_publication|| self.pending_runtime_deferred_replies.iter()diff --git a/moli-renderer-v8/src/devtools/command.rs b/moli-renderer-v8/src/devtools/command.rsindex ed6a15294..1dff3b5c9 100644--- a/moli-renderer-v8/src/devtools/command.rs+++ b/moli-renderer-v8/src/devtools/command.rs@@ -4,24 +4,26 @@ use crate::runtime::{RendererInspectorPageCommand, RendererPageCommand, RendererRuntimeInspectorResponseSender,};use crate::script_execution_control::RendererScriptExecutionControl;-use moli_page_types::{DevToolsSessionKey, RendererAgentAttachmentId};+use moli_page_types::{+ DevToolsSessionKey, RendererAgentAttachmentId, RendererDevToolsCommandId,+ RendererInspectorResponseDelivery,+};use serde_json::Value;-use std::sync::atomic::{AtomicU64, Ordering};/// Chromium routes Page DevTools work through separate main-thread and IO-/// session ingress paths. Ordering is guaranteed within one session and one-/// route, while an IO command may overtake main-thread work that has not-/// reached its first dispatch yet.+/// session ingress paths. Main preserves its receiver order independently,+/// while IO commands enter one target-level Inspector task FIFO and may+/// overtake blocked main-thread work.#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]pub enum RendererInspectorCommandRoute {MainThread,Io,}-/// The command owns its `(Page, session, route)` lane until its first access to-/// the frontend V8 Inspector session. Protocol response completion is not part-/// of this lifetime: V8 may complete a response asynchronously, and holding the-/// lane for that response could prevent a later resume command from running.+/// The command owns its receiver dispatch slot until its first access to the+/// target agent. Protocol response completion is not part of this lifetime:+/// V8 may complete a response asynchronously, and holding the slot for that+/// response could prevent a later resume command from running.#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum RendererInspectorFirstDispatchLifecycle {OrderedUntilFirstDispatch,@@ -62,14 +64,12 @@ enum RendererInspectorMainDispatchBoundary {PageOwner,}-static NEXT_RENDERER_INSPECTOR_INGRESS_SEQUENCE: AtomicU64 = AtomicU64::new(1);-#[derive(Clone, Debug, Eq, PartialEq)]pub struct RendererInspectorIngressTicket {attachment: Option<RendererAgentAttachmentId>,session: DevToolsSessionKey,route: RendererInspectorCommandRoute,- sequence: u64,+ command_id: RendererDevToolsCommandId,}impl RendererInspectorIngressTicket {@@ -86,11 +86,7 @@ impl RendererInspectorIngressTicket {.filter(|session_id| !session_id.is_empty()),),route,- sequence: NEXT_RENDERER_INSPECTOR_INGRESS_SEQUENCE- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |sequence| {- sequence.checked_add(1)- })- .expect("renderer Inspector ingress sequence overflow"),+ command_id: RendererDevToolsCommandId::allocate(),}}@@ -106,8 +102,13 @@ impl RendererInspectorIngressTicket {self.route}+ pub fn command_id(&self) -> RendererDevToolsCommandId {+ self.command_id+ }++ /// Transitional raw identity accessor for existing renderer queues.pub fn sequence(&self) -> u64 {- self.sequence+ self.command_id.get()}pub(crate) fn bind_attachment(&mut self, attachment: RendererAgentAttachmentId) {@@ -139,7 +140,7 @@ pub struct RendererInspectorCommandEnvelope {/// Chromium chooses the IO receiver at the `DevToolsSession` boundary, before/// it chooses the renderer agent that will execute the command. Keep that/// ordering structural here as well: V8 Inspector, Performance, and Emulation-/// commands share one `(target, session, IO)` first-dispatch lane.+/// commands share one target-level IO task FIFO.#[doc(hidden)]pub struct RendererDevToolsIoCommandEnvelope {ticket: RendererInspectorIngressTicket,@@ -356,6 +357,7 @@ enum RendererInspectorCommandPayload {Io {raw_json: String,response: Option<RendererRuntimeInspectorResponseSender>,+ response_delivery: RendererInspectorResponseDelivery,},}@@ -423,6 +425,7 @@ impl RendererInspectorCommandEnvelope {ticket: RendererInspectorIngressTicket,raw_json: String,response: Option<RendererRuntimeInspectorResponseSender>,+ response_delivery: RendererInspectorResponseDelivery,) -> Self {assert_eq!(ticket.route(),@@ -435,7 +438,11 @@ impl RendererInspectorCommandEnvelope {first_dispatch: RendererInspectorFirstDispatchLifecycle::OrderedUntilFirstDispatch,pause_effect: RendererInspectorPauseCommandEffect::from_message(message.as_ref()),main_dispatch_boundary: RendererInspectorMainDispatchBoundary::InspectorSession,- payload: RendererInspectorCommandPayload::Io { raw_json, response },+ payload: RendererInspectorCommandPayload::Io {+ raw_json,+ response,+ response_delivery,+ },}}@@ -557,6 +564,16 @@ impl RendererInspectorCommandEnvelope {response.as_ref()}+ pub(crate) fn io_response_delivery(&self) -> RendererInspectorResponseDelivery {+ let RendererInspectorCommandPayload::Io {+ response_delivery, ..+ } = &self.payload+ else {+ panic!("a MainThread Inspector envelope cannot enter IO dispatch");+ };+ *response_delivery+ }+pub(crate) fn take_io_response(&mut self) -> Option<RendererRuntimeInspectorResponseSender> {let RendererInspectorCommandPayload::Io { response, .. } = &mut self.payload else {panic!("a MainThread Inspector envelope cannot enter IO dispatch");diff --git a/moli-renderer-v8/src/devtools/ingress/io.rs b/moli-renderer-v8/src/devtools/ingress/io.rsindex 75aae61f3..d47a5c6ba 100644--- a/moli-renderer-v8/src/devtools/ingress/io.rs+++ b/moli-renderer-v8/src/devtools/ingress/io.rs@@ -1,4 +1,5 @@use std::{+ collections::{BTreeSet, VecDeque},ffi::c_void,sync::{Arc,@@ -12,11 +13,7 @@ use serde_json::json;use crate::{devtools::{- ingress::lane::{- RendererDevToolsIngressCommand, RendererDevToolsLaneEnqueueError,- RendererDevToolsSessionLaneKey, RendererDevToolsSessionLanes,- },- pause::RendererInspectorPauseLoopWake,+ ingress::lane::RendererDevToolsSessionLaneKey, pause::RendererInspectorPauseLoopWake,route::RendererInspectorSessionExecutorRouteId,},runtime::{@@ -47,11 +44,22 @@ pub(crate) enum RendererInspectorIoCommandConsumer {Pause,}+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum RendererRuntimeInspectorIoCommandClaim {+ Dispatched,+ Canceled,+}++type RendererInspectorIoFirstDispatchSender =+ tokio::sync::oneshot::Sender<RendererRuntimeInspectorIoCommandClaim>;+type RendererInspectorIoFirstDispatchReceiver =+ tokio::sync::oneshot::Receiver<RendererRuntimeInspectorIoCommandClaim>;+pub(crate) struct RendererInspectorIoCommand {command_id: u64,pub(crate) agent_token: RendererDevToolsAgentToken,envelope: RendererDevToolsIoCommandEnvelope,- first_dispatch_tx: Option<tokio::sync::oneshot::Sender<RendererRuntimeInspectorIoCommandClaim>>,+ first_dispatch_tx: Option<RendererInspectorIoFirstDispatchSender>,claimed_by: Option<RendererInspectorIoCommandConsumer>,}@@ -87,6 +95,13 @@ impl RendererInspectorIoCommand {.and_then(RendererInspectorCommandEnvelope::io_response)}+ pub(crate) fn response_delivery(&self) -> moli_page_types::RendererInspectorResponseDelivery {+ self.envelope+ .inspector_envelope()+ .expect("only an Inspector IO payload has a response delivery")+ .io_response_delivery()+ }+pub(crate) fn pause_effect(&self) -> RendererInspectorPauseCommandEffect {self.envelope.inspector_envelope()@@ -111,23 +126,10 @@ impl RendererInspectorIoCommand {}}-impl RendererDevToolsIngressCommand for RendererInspectorIoCommand {- fn ingress_command_id(&self) -> u64 {- self.command_id- }-}--#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub enum RendererRuntimeInspectorIoCommandClaim {- Dispatched,- Canceled,-}-pub struct RendererRuntimeInspectorIoCommandRoute {command_id: u64,ticket: RendererInspectorIngressTicket,- first_dispatch_rx:- Option<tokio::sync::oneshot::Receiver<RendererRuntimeInspectorIoCommandClaim>>,+ first_dispatch_rx: Option<RendererInspectorIoFirstDispatchReceiver>,ingress: RendererInspectorIoIngress,}@@ -191,15 +193,41 @@ impl RendererInspectorIoOwnerWake {}struct RendererInspectorIoState {- lanes: RendererDevToolsSessionLanes<RendererInspectorIoCommand>,+ commands: VecDeque<RendererInspectorIoCommand>,+ active_command_id: Option<u64>,+ detached_sessions: BTreeSet<RendererDevToolsSessionLaneKey>,+ closed: bool,owner_wake_tx: Option<tokio::sync::mpsc::UnboundedSender<RendererInspectorIoOwnerWake>>,}+impl RendererInspectorIoState {+ fn has_ready(&self) -> bool {+ !self.closed && self.active_command_id.is_none() && !self.commands.is_empty()+ }++ fn drain_commands(+ &mut self,+ mut should_drain: impl FnMut(&RendererInspectorIoCommand) -> bool,+ ) -> Vec<RendererInspectorIoCommand> {+ let mut retained = VecDeque::with_capacity(self.commands.len());+ let mut drained = Vec::new();+ while let Some(command) = self.commands.pop_front() {+ if should_drain(&command) {+ drained.push(command);+ } else {+ retained.push_back(command);+ }+ }+ self.commands = retained;+ drained+ }+}+pub(crate) struct RendererInspectorIoFirstDispatchGuard {ingress: RendererInspectorIoIngress,- active: Option<(RendererDevToolsSessionLaneKey, u64)>,+ active_command_id: Option<u64>,consumer: RendererInspectorIoCommandConsumer,- first_dispatch_tx: Option<tokio::sync::oneshot::Sender<RendererRuntimeInspectorIoCommandClaim>>,+ first_dispatch_tx: Option<RendererInspectorIoFirstDispatchSender>,}pub(crate) struct RendererInspectorIoPostDispatchWakeGuard {@@ -214,25 +242,25 @@ impl Drop for RendererInspectorIoFirstDispatchGuard {impl RendererInspectorIoFirstDispatchGuard {pub(crate) fn release(&mut self) {- let has_ready = self.release_lane();+ let has_ready = self.release_task();if has_ready {self.ingress.notify_execution_opportunities();}}- /// Commits the first-dispatch lifecycle immediately before entering V8,- /// but defers scheduling another callback until this dispatch returns. A- /// nested pause entered by this dispatch still sees the advanced lane when- /// it first polls the IO ingress.+ /// Releases the receiver slot and publishes first-dispatch immediately+ /// before entering V8, but keeps the next execution wake behind the return+ /// from this dispatch. V8 may enter a nested debugger loop before the call+ /// returns, so the command's ingress lifecycle must already be settled.pub(crate) fn release_for_dispatch(&mut self) -> RendererInspectorIoPostDispatchWakeGuard {- let has_ready = self.release_lane();+ let has_ready = self.release_task();RendererInspectorIoPostDispatchWakeGuard {ingress: has_ready.then(|| self.ingress.clone()),}}- fn release_lane(&mut self) -> bool {- let Some((lane, command_id)) = self.active.take() else {+ fn release_task(&mut self) -> bool {+ let Some(command_id) = self.active_command_id.take() else {return false;};if self.consumer == RendererInspectorIoCommandConsumer::Interrupt {@@ -241,7 +269,7 @@ impl RendererInspectorIoFirstDispatchGuard {.interrupt_armed.store(false, Ordering::Release);}- let has_ready = self.ingress.finish_first_dispatch(lane, command_id);+ let has_ready = self.ingress.finish_first_dispatch(command_id);if let Some(first_dispatch_tx) = self.first_dispatch_tx.take() {let _ = first_dispatch_tx.send(RendererRuntimeInspectorIoCommandClaim::Dispatched);}@@ -269,7 +297,10 @@ impl RendererInspectorIoIngress {Self {shared: Arc::new(RendererInspectorIoShared {state: Mutex::new(RendererInspectorIoState {- lanes: RendererDevToolsSessionLanes::default(),+ commands: VecDeque::new(),+ active_command_id: None,+ detached_sessions: BTreeSet::new(),+ closed: false,owner_wake_tx: None,}),interrupt_armed: AtomicBool::new(false),@@ -313,7 +344,7 @@ impl RendererInspectorIoIngress {let has_ready = {let mut state = self.shared.state.lock();state.owner_wake_tx = Some(owner_wake_tx);- state.lanes.has_ready()+ state.has_ready()};if has_ready {self.notify_execution_opportunities();@@ -330,11 +361,12 @@ impl RendererInspectorIoIngress {RendererInspectorCommandRoute::Io,"only IO DevTools commands may enter RendererInspectorIoIngress");- let ticket = envelope.ticket().clone();- let (first_dispatch_tx, first_dispatch_rx) = tokio::sync::oneshot::channel();+ let lane_key =+ RendererDevToolsSessionLaneKey::new(agent_token, envelope.ticket().session().clone());let mut state = self.shared.state.lock();+ let (first_dispatch_tx, first_dispatch_rx) = tokio::sync::oneshot::channel();+ let ticket = envelope.ticket().clone();let command_id = ticket.sequence();- let lane_key = RendererDevToolsSessionLaneKey::new(agent_token, ticket.session().clone());let command = RendererInspectorIoCommand {command_id,agent_token,@@ -342,18 +374,18 @@ impl RendererInspectorIoIngress {first_dispatch_tx: Some(first_dispatch_tx),claimed_by: None,};- if let Err(rejected) = state.lanes.enqueue(lane_key, command) {- drop(state);- match rejected {- RendererDevToolsLaneEnqueueError::TargetClosed(command) => {- fail_io_command(command, "Inspector IO target is closed");- }- RendererDevToolsLaneEnqueueError::SessionDetached(command) => {- fail_io_command(command, "Inspector IO session was detached");- }- }+ let rejected = if state.closed {+ Some((command, "Inspector IO target is closed"))+ } else if state.detached_sessions.contains(&lane_key) {+ Some((command, "Inspector IO session was detached"))+ } else {+ state.commands.push_back(command);+ None+ };+ drop(state);+ if let Some((command, message)) = rejected {+ fail_io_command(command, message);} else {- drop(state);self.notify_execution_opportunities();}RendererRuntimeInspectorIoCommandRoute {@@ -367,7 +399,7 @@ impl RendererInspectorIoIngress {pub(crate) fn claim_for_owner(&self) -> Option<RendererInspectorIoCommand> {self.shared.owner_wake_armed.store(false, Ordering::Release);let command = self.claim_next(RendererInspectorIoCommandConsumer::Owner);- if command.is_none() && self.shared.state.lock().lanes.has_ready() {+ if command.is_none() && self.shared.state.lock().has_ready() {self.notify_execution_opportunities();}command@@ -377,7 +409,7 @@ impl RendererInspectorIoIngress {let command = self.claim_next(RendererInspectorIoCommandConsumer::Interrupt);if command.is_none() {self.shared.interrupt_armed.store(false, Ordering::Release);- let has_ready = self.shared.state.lock().lanes.has_ready();+ let has_ready = self.shared.state.lock().has_ready();if has_ready {self.request_interrupt();}@@ -402,7 +434,14 @@ impl RendererInspectorIoIngress {consumer: RendererInspectorIoCommandConsumer,) -> Option<RendererInspectorIoCommand> {let mut state = self.shared.state.lock();- let (_, mut command) = state.lanes.claim_next(|_| true)?;+ if !state.has_ready() {+ return None;+ }+ let mut command = state+ .commands+ .pop_front()+ .expect("a ready Inspector task runner must have a command");+ state.active_command_id = Some(command.command_id);command.claimed_by = Some(consumer);Some(command)}@@ -411,24 +450,20 @@ impl RendererInspectorIoIngress {&self,command: &mut RendererInspectorIoCommand,) -> RendererInspectorIoFirstDispatchGuard {- let lane_key = RendererDevToolsSessionLaneKey::new(- command.agent_token,- command.ticket().session().clone(),- );let state = self.shared.state.lock();assert_eq!(command.first_dispatch_lifecycle(),crate::runtime::RendererInspectorFirstDispatchLifecycle::OrderedUntilFirstDispatch,);- state.lanes.assert_active(- &lane_key,- command.command_id,- "a claimed Inspector IO command must own its session lane",+ assert_eq!(+ state.active_command_id,+ Some(command.command_id),+ "a claimed Inspector IO command must own the target task runner",);drop(state);RendererInspectorIoFirstDispatchGuard {ingress: self.clone(),- active: Some((lane_key, command.command_id)),+ active_command_id: Some(command.command_id),consumer: command.claimed_by.expect("a first-dispatch guard requires a claimed IO command"),@@ -436,20 +471,25 @@ impl RendererInspectorIoIngress {}}- fn finish_first_dispatch(- &self,- lane_key: RendererDevToolsSessionLaneKey,- command_id: u64,- ) -> bool {- self.shared.state.lock().lanes.finish_first_dispatch(- lane_key,- command_id,- "only the active Inspector IO command may release its lane",- )+ fn finish_first_dispatch(&self, command_id: u64) -> bool {+ let mut state = self.shared.state.lock();+ assert_eq!(+ state.active_command_id.take(),+ Some(command_id),+ "only the active Inspector IO command may release its target task runner"+ );+ state.has_ready()}pub(crate) fn cancel_queued_command(&self, command_id: u64, message: &str) {- let command = self.shared.state.lock().lanes.cancel_queued(command_id);+ let command = {+ let mut state = self.shared.state.lock();+ state+ .commands+ .iter()+ .position(|command| command.command_id == command_id)+ .and_then(|position| state.commands.remove(position))+ };if let Some(command) = command {fail_io_command(command, message);}@@ -461,14 +501,24 @@ impl RendererInspectorIoIngress {session: &DevToolsSessionKey,) {let lane_key = RendererDevToolsSessionLaneKey::new(agent_token, session.clone());- let commands = self.shared.state.lock().lanes.detach_session(&lane_key);+ let commands = {+ let mut state = self.shared.state.lock();+ state.detached_sessions.insert(lane_key);+ state.drain_commands(|command| {+ command.agent_token == agent_token && command.ticket().session() == session+ })+ };for command in commands {fail_io_command(command, "Inspector IO session was detached");}}pub(crate) fn close(&self, message: &str) {- let commands = { self.shared.state.lock().lanes.close_and_drain() };+ let commands = {+ let mut state = self.shared.state.lock();+ state.closed = true;+ state.commands.drain(..).collect::<Vec<_>>()+ };self.shared.pause_wake.notify_all();for command in commands {fail_io_command(command, message);@@ -476,7 +526,13 @@ impl RendererInspectorIoIngress {}pub(crate) fn cancel_all_queued(&self, message: &str) {- let commands = self.shared.state.lock().lanes.drain_queued();+ let commands = self+ .shared+ .state+ .lock()+ .commands+ .drain(..)+ .collect::<Vec<_>>();for command in commands {fail_io_command(command, message);}@@ -485,7 +541,10 @@ impl RendererInspectorIoIngress {fn notify_execution_opportunities(&self) {let owner_wake = {let state = self.shared.state.lock();- state.owner_wake_tx.clone().zip(self.route_id())+ state+ .has_ready()+ .then(|| state.owner_wake_tx.clone().zip(self.route_id()))+ .flatten()};if let Some((owner_wake_tx, route_id)) = owner_wake&& self@@ -499,8 +558,10 @@ impl RendererInspectorIoIngress {{self.shared.owner_wake_armed.store(false, Ordering::Release);}- self.request_interrupt();- self.shared.pause_wake.notify_one();+ if self.shared.state.lock().has_ready() {+ self.request_interrupt();+ self.shared.pause_wake.notify_one();+ }}fn request_interrupt(&self) {@@ -540,13 +601,13 @@ impl std::fmt::Debug for RendererInspectorIoIngress {formatter.debug_struct("RendererInspectorIoIngress").field("route_id", &self.route_id())- .field("session_lanes", &state.lanes.session_count())- .field("ready_sessions", &state.lanes.ready_count())+ .field("queued_tasks", &state.commands.len())+ .field("active_command_id", &state.active_command_id).field("interrupt_armed",&self.shared.interrupt_armed.load(Ordering::Acquire),)- .field("closed", &state.lanes.is_closed())+ .field("closed", &state.closed).finish()}}@@ -597,6 +658,7 @@ mod tests {),raw_json.to_owned(),None,+ moli_page_types::RendererInspectorResponseDelivery::CommandReply,)),)}@@ -685,36 +747,79 @@ mod tests {}assert!(- ingress.shared.state.lock().lanes.session_count() == 0,- "every stressed first-dispatch lane must retire"+ {+ let state = ingress.shared.state.lock();+ state.commands.is_empty() && state.active_command_id.is_none()+ },+ "every stressed target task must retire");}#[test]- fn one_session_is_fifo_while_another_session_is_independent() {+ fn page_io_uses_one_target_fifo_across_sessions() {let ingress = ingress();let agent = RendererDevToolsAgentToken::allocate();let _a1 = enqueue(&ingress, agent, Some("session-a"), "a1");let _a2 = enqueue(&ingress, agent, Some("session-a"), "a2");let _b1 = enqueue(&ingress, agent, Some("session-b"), "b1");- let mut first = ingress.claim_for_owner().expect("first ready session");+ let mut first = ingress.claim_for_owner().expect("first target task");assert_eq!(first.raw_json(), "a1");+ assert!(+ ingress.claim_for_interrupt().is_none(),+ "only one target task may be active before first dispatch"+ );++ ingress.first_dispatch_guard(&mut first).release();let mut second = ingress.claim_for_interrupt()- .expect("other session must remain independently ready");- assert_eq!(second.raw_json(), "b1");+ .expect("the second target task must follow first dispatch");+ assert_eq!(second.raw_json(), "a2");assert!(ingress.claim_for_pause().is_none());-- ingress.first_dispatch_guard(&mut first).release();ingress.first_dispatch_guard(&mut second).release();- let mut third = ingress.claim_for_pause().expect("a2 after a1 dispatch");- assert_eq!(third.raw_json(), "a2");+ let mut third = ingress+ .claim_for_pause()+ .expect("the third target task must follow second dispatch");+ assert_eq!(third.raw_json(), "b1");ingress.first_dispatch_guard(&mut third).release();}#[tokio::test]- async fn one_io_lane_orders_inspector_performance_and_emulation_first_dispatch() {+ async fn replacement_io_ingress_does_not_wait_for_an_old_first_dispatch_receiver() {+ let agent = RendererDevToolsAgentToken::allocate();+ let first_attachment = ingress();+ let second_attachment = ingress();++ let first = enqueue(&first_attachment, agent, Some("session-a"), "first");+ let second = enqueue(&second_attachment, agent, Some("session-a"), "second");++ let mut first_command = first_attachment+ .claim_for_owner()+ .expect("first attachment command");+ first_attachment+ .first_dispatch_guard(&mut first_command)+ .release();+ let mut second_command = second_attachment+ .claim_for_owner()+ .expect("replacement attachment command");+ second_attachment+ .first_dispatch_guard(&mut second_command)+ .release();++ assert_eq!(+ tokio::time::timeout(+ std::time::Duration::from_secs(1),+ second.wait_for_first_dispatch()+ )+ .await+ .expect("a replacement capability must not wait for the old receiver"),+ Ok(RendererRuntimeInspectorIoCommandClaim::Dispatched)+ );+ drop(first);+ }++ #[tokio::test]+ async fn target_fifo_orders_inspector_performance_and_emulation_first_dispatch() {let ingress = ingress();let agent = RendererDevToolsAgentToken::allocate();let inspector = enqueue(&ingress, agent, Some("session-mixed"), "inspector");@@ -770,6 +875,30 @@ mod tests {);}+ #[tokio::test]+ async fn dropped_io_waiter_cannot_leave_a_completion_hole() {+ let ingress = ingress();+ let agent = RendererDevToolsAgentToken::allocate();+ let abandoned = enqueue(&ingress, agent, Some("session-order"), "abandoned");+ let following = enqueue(&ingress, agent, Some("session-order"), "following");++ drop(abandoned);+ let mut command = ingress+ .claim_for_owner()+ .expect("the following command should remain queued");+ ingress.first_dispatch_guard(&mut command).release();++ assert_eq!(+ tokio::time::timeout(+ std::time::Duration::from_secs(1),+ following.wait_for_first_dispatch()+ )+ .await+ .expect("a dropped waiter must release the next publication"),+ Ok(RendererRuntimeInspectorIoCommandClaim::Dispatched)+ );+ }+#[tokio::test]async fn detach_cancels_all_queued_commands_while_active_first_dispatch_retires_safely() {let ingress = ingress();@@ -803,8 +932,11 @@ mod tests {assert!(ingress.claim_for_pause().is_none());assert!(- ingress.shared.state.lock().lanes.session_count() == 0,- "the detached lane must retire after its active first dispatch releases"+ {+ let state = ingress.shared.state.lock();+ state.commands.is_empty() && state.active_command_id.is_none()+ },+ "the detached session's tasks must retire");}@@ -840,8 +972,11 @@ mod tests {assert!(ingress.claim_for_pause().is_none());assert!(- ingress.shared.state.lock().lanes.session_count() == 0,- "the active lane must retire safely after target close"+ {+ let state = ingress.shared.state.lock();+ state.commands.is_empty() && state.active_command_id.is_none()+ },+ "the active target task must retire safely after target close");let late = enqueue(&ingress, agent, Some("session-late"), "late");diff --git a/moli-renderer-v8/src/devtools/ingress/main.rs b/moli-renderer-v8/src/devtools/ingress/main.rsindex 026837978..f9af35306 100644--- a/moli-renderer-v8/src/devtools/ingress/main.rs+++ b/moli-renderer-v8/src/devtools/ingress/main.rs@@ -407,12 +407,13 @@ impl RendererInspectorMainIngress {RendererInspectorCommandRoute::MainThread,"only MainThread DevTools commands may enter RendererInspectorMainIngress");- let ticket = envelope.ticket().clone();let (claim_tx, claim_rx) = tokio::sync::oneshot::channel();let (owner_reply_tx, owner_reply_rx) = tokio::sync::oneshot::channel();let mut state = self.shared.state.lock();+ let lane_key =+ RendererDevToolsSessionLaneKey::new(agent_token, envelope.ticket().session().clone());+ let ticket = envelope.ticket().clone();let command_id = ticket.sequence();- let lane_key = RendererDevToolsSessionLaneKey::new(agent_token, ticket.session().clone());let command = RendererInspectorMainCommand {command_id,page_token,@@ -943,6 +944,7 @@ mod tests {RendererInspectorIngressTicket::new(None, None, RendererInspectorCommandRoute::Io),r#"{"id":1,"method":"Runtime.terminateExecution"}"#.to_owned(),None,+ moli_page_types::RendererInspectorResponseDelivery::CommandReply,),);}diff --git a/moli-renderer-v8/src/devtools/pause/tests.rs b/moli-renderer-v8/src/devtools/pause/tests.rsindex 9eaf02c0d..c8fe3349a 100644--- a/moli-renderer-v8/src/devtools/pause/tests.rs+++ b/moli-renderer-v8/src/devtools/pause/tests.rs@@ -63,6 +63,7 @@ fn enqueue_command(),raw_json,Some(response),+ moli_page_types::RendererInspectorResponseDelivery::CommandReply,),),)diff --git a/moli-renderer-v8/src/devtools/target.rs b/moli-renderer-v8/src/devtools/target.rsindex ce69cdadb..3a4e736e0 100644--- a/moli-renderer-v8/src/devtools/target.rs+++ b/moli-renderer-v8/src/devtools/target.rs@@ -71,7 +71,7 @@ impl RendererDevToolsTargetHandle {/// Executes Chromium's terminal `Page.crash` IO control boundary.////// Unlike ordinary IO-agent commands, a crash must not wait for or occupy- /// a per-session first-dispatch lane. Seal both command receivers first,+ /// the target Inspector task runner. Seal both command receivers first,/// then interrupt any active JavaScript so the owner can retire the Page.pub(crate) fn crash_from_io(&self) {let _ = self.close("Inspector target crashed through Page.crash");diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rsindex 150ed1e2e..5be860f90 100644--- a/moli-renderer-v8/src/runtime/mod.rs+++ b/moli-renderer-v8/src/runtime/mod.rs@@ -361,9 +361,9 @@ pub use self::page_surface::{RendererTouchPoint, RendererWindowDocumentSource, RuntimeConsoleMessageSnapshot,};pub(crate) use self::page_surface::{- RendererCommandTurnOutputRecorder, RendererInspectorPageCommand,- RendererRuntimeCommandOutputRecorder, RendererRuntimeInspectorResponsePublication,- RendererRuntimeObservableSourceQueue,+ RendererCommandTurnOutputRecorder, RendererDevToolsSessionOutputHost,+ RendererInspectorPageCommand, RendererRuntimeCommandOutputRecorder,+ RendererRuntimeInspectorResponsePublication, RendererRuntimeObservableSourceQueue,};pub(crate) use self::page_vm::PageVm;use self::page_vm::PageVmDropTracker;diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rsindex e97ffe282..8b4c9125a 100644--- a/moli-renderer-v8/src/runtime/page_surface.rs+++ b/moli-renderer-v8/src/runtime/page_surface.rs@@ -1233,6 +1233,20 @@ impl RendererRuntimeInspectorMessageBatch {self.renderer_agent_attachment_id}+ /// Whether this batch contains a concrete Inspector command response.+ ///+ /// The response is identified from the protocol message itself; no+ /// parallel completion marker or inferred scheduler state is involved.+ pub fn has_renderer_protocol_response(&self) -> bool {+ self.messages.iter().any(|message| {+ matches!(+ message,+ RendererRuntimeInspectorMessage::Protocol(message)+ if message.renderer_call_id().is_some()+ )+ })+ }+pub(crate) fn has_resolved_source_identities(&self) -> bool {self.messages.iter()@@ -2678,8 +2692,7 @@ impl RendererRuntimeInspectorAsyncCompletion {pub(crate) struct RendererRuntimeInspectorResponsePublication {call_id: i32,output: RendererRuntimeCommandOutput,- lease_id: u64,- channel: RendererRuntimeInspectorResponseChannel,+ destination: RendererRuntimeInspectorResponseDestination,}impl RendererRuntimeInspectorResponsePublication {@@ -2687,8 +2700,7 @@ impl RendererRuntimeInspectorResponsePublication {self,renderer_output_predecessor: Option<RendererOutputFence>,) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {- self.channel.send(- self.lease_id,+ self.destination.send(RendererRuntimeInspectorAsyncCompletion::from_renderer_response_edge(self.call_id,self.output,@@ -2887,8 +2899,12 @@ impl RendererRuntimeInspectorResponseChannel {Some(RendererRuntimeInspectorResponseSender {call_id,attachment_id,- lease_id,- channel: self.clone(),+ destination: RendererRuntimeInspectorResponseDestination::CommandReply(+ RendererRuntimeInspectorCommandReplyDestination {+ lease_id,+ channel: self.clone(),+ },+ ),publication_boundary: RendererRuntimeInspectorResponsePublicationBoundary::Immediate,})}@@ -2919,6 +2935,109 @@ impl RendererRuntimeInspectorResponseChannel {}}+#[derive(Clone, Debug)]+struct RendererRuntimeInspectorCommandReplyDestination {+ lease_id: u64,+ channel: RendererRuntimeInspectorResponseChannel,+}++impl RendererRuntimeInspectorCommandReplyDestination {+ fn send(+ self,+ completion: RendererRuntimeInspectorAsyncCompletion,+ ) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {+ self.channel.send(self.lease_id, completion)+ }+}++/// Output capability for one concrete renderer attachment and DevTools+/// session.+///+/// Navigation creates another Page journal and attachment identity; closing+/// the old journal structurally prevents an old session response from entering+/// the replacement stream.+#[derive(Clone, Debug)]+pub(crate) struct RendererDevToolsSessionOutputHost {+ agent_token: RendererDevToolsAgentToken,+ session: DevToolsSessionKey,+ attachment_id: RendererAgentAttachmentId,+ output_journal: RendererTurnOutputJournal,+}++impl RendererDevToolsSessionOutputHost {+ pub(crate) fn new(+ agent_token: RendererDevToolsAgentToken,+ session: DevToolsSessionKey,+ attachment_id: RendererAgentAttachmentId,+ output_journal: RendererTurnOutputJournal,+ ) -> Self {+ Self {+ agent_token,+ session,+ attachment_id,+ output_journal,+ }+ }++ fn publish(+ &self,+ completion: RendererRuntimeInspectorAsyncCompletion,+ ) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {+ if completion.renderer_agent_attachment_id() != Some(self.attachment_id) {+ return Err(completion);+ }+ if completion+ .renderer_output_predecessor()+ .is_some_and(|predecessor| {+ predecessor.cursor().stream() != self.output_journal.stream()+ })+ {+ return Err(completion);+ }++ // Keep the completion intact until the exact stream accepts+ // ownership. If the capability already closed, protocol attachment+ // teardown owns terminal completion for the pending frontend call.+ let (_, v8_state_update, messages) = completion.output.clone().into_parts();+ let mut batch = RendererRuntimeInspectorMessageBatch::new(+ self.agent_token,+ self.session.clone(),+ messages,+ );+ batch.v8_state_update = v8_state_update;+ batch.bind_renderer_agent_attachment(self.attachment_id);+ if !batch.has_resolved_source_identities() {+ return Err(completion);+ }+ let record = PendingRendererOutputRecord::observation(+ None,+ RendererProtocolObservation::RuntimeInspector(batch),+ );+ self.output_journal+ .try_publish_records([record])+ .then_some(())+ .ok_or(completion)+ }+}++#[derive(Clone, Debug)]+enum RendererRuntimeInspectorResponseDestination {+ CommandReply(RendererRuntimeInspectorCommandReplyDestination),+ DevToolsSession(RendererDevToolsSessionOutputHost),+}++impl RendererRuntimeInspectorResponseDestination {+ fn send(+ self,+ completion: RendererRuntimeInspectorAsyncCompletion,+ ) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {+ match self {+ Self::CommandReply(destination) => destination.send(completion),+ Self::DevToolsSession(host) => host.publish(completion),+ }+ }+}+#[derive(Clone)]enum RendererRuntimeInspectorResponsePublicationBoundary {Immediate,@@ -2930,8 +3049,7 @@ enum RendererRuntimeInspectorResponsePublicationBoundary {pub struct RendererRuntimeInspectorResponseSender {call_id: i32,attachment_id: Option<RendererAgentAttachmentId>,- lease_id: u64,- channel: RendererRuntimeInspectorResponseChannel,+ destination: RendererRuntimeInspectorResponseDestination,publication_boundary: RendererRuntimeInspectorResponsePublicationBoundary,}@@ -2955,8 +3073,12 @@ impl RendererRuntimeInspectorResponseSender {Self {call_id,attachment_id: None,- lease_id: 1,- channel,+ destination: RendererRuntimeInspectorResponseDestination::CommandReply(+ RendererRuntimeInspectorCommandReplyDestination {+ lease_id: 1,+ channel,+ },+ ),publication_boundary: RendererRuntimeInspectorResponsePublicationBoundary::Immediate,}}@@ -2965,6 +3087,10 @@ impl RendererRuntimeInspectorResponseSender {self.call_id}+ pub(crate) fn renderer_agent_attachment_id(&self) -> Option<RendererAgentAttachmentId> {+ self.attachment_id+ }+pub fn with_renderer_agent_attachment(mut self,attachment_id: RendererAgentAttachmentId,@@ -2991,6 +3117,26 @@ impl RendererRuntimeInspectorResponseSender {self}+ /// Selects the frontend session output capability without changing when+ /// the response is allowed to publish.+ pub(crate) fn route_to_devtools_session_output(+ mut self,+ host: RendererDevToolsSessionOutputHost,+ ) -> Self {+ assert_eq!(+ self.attachment_id,+ Some(host.attachment_id),+ "a DevTools session response host must belong to the command attachment"+ );+ self.destination = match self.destination {+ RendererRuntimeInspectorResponseDestination::CommandReply(_)+ | RendererRuntimeInspectorResponseDestination::DevToolsSession(_) => {+ RendererRuntimeInspectorResponseDestination::DevToolsSession(host)+ }+ };+ self+ }+pub fn send(self, message: Value) -> Result<(), RendererRuntimeInspectorAsyncCompletion> {self.send_output(RendererRuntimeCommandOutput::from_inspector_message(RendererRuntimeInspectorMessage::from_v8_inspector_message(message),@@ -3004,8 +3150,7 @@ impl RendererRuntimeInspectorResponseSender {let Self {call_id,attachment_id,- lease_id,- channel,+ destination,publication_boundary,} = self;if let Some(attachment_id) = attachment_id {@@ -3014,8 +3159,7 @@ impl RendererRuntimeInspectorResponseSender {let publication = RendererRuntimeInspectorResponsePublication {call_id,output,- lease_id,- channel,+ destination,};match publication_boundary {RendererRuntimeInspectorResponsePublicationBoundary::Immediate => {@@ -3164,8 +3308,7 @@ mod renderer_runtime_inspector_response_channel_tests {let RendererRuntimeInspectorResponseSender {call_id,attachment_id,- lease_id,- channel,+ destination,publication_boundary: _,} = sender;let mut output = output(1);@@ -3176,8 +3319,7 @@ mod renderer_runtime_inspector_response_channel_tests {RendererRuntimeInspectorResponsePublication {call_id,output,- lease_id,- channel,+ destination,}.commit(Some(expected_predecessor.clone())).expect("active response lease should complete");@@ -3239,6 +3381,88 @@ mod renderer_runtime_inspector_response_channel_tests {"the response must carry the exact output cursor supplied at the Page owner boundary");}++ #[tokio::test]+ async fn session_output_changes_the_sink_without_bypassing_the_page_owner_boundary() {+ let page_id = PageId::new_for_testing(1);+ let token = RendererPageToken::new_for_testing(page_id);+ let stream = RendererOutputStreamIdentity::new_page_for_protocol_test(page_id);+ let (transport, mut transport_rx) = crate::runtime::renderer_output_transport_channel();+ let journal = RendererTurnOutputJournal::new_with_transport(stream, transport);+ assert!(matches!(+ transport_rx.try_recv(),+ Ok(RendererOutputTransportMessage::StreamControl(+ RendererOutputStreamControl::Opened { stream: opened }+ )) if opened == stream+ ));++ let attachment_id = RendererAgentAttachmentId::allocate();+ let host = RendererDevToolsSessionOutputHost::new(+ RendererDevToolsAgentToken::allocate(),+ DevToolsSessionKey::Attached("SID-session-output".to_owned()),+ attachment_id,+ journal,+ );+ let (owner_wake_tx, mut owner_wake_rx) = tokio::sync::mpsc::unbounded_channel();+ let owner_wake = RendererOwnerWakeSender::new(owner_wake_tx, token);+ let (channel, mut response_rx) = RendererRuntimeInspectorResponseChannel::new();++ channel+ .activate_sender(7, Some(attachment_id))+ .route_to_devtools_session_output(host)+ .defer_publication_to_page_owner(owner_wake)+ .send_output(output(7))+ .expect("Page owner should accept the terminal session response");++ assert_eq!(response_rx.try_recv(), Err(TryRecvError::Empty));+ assert!(+ transport_rx.try_recv().is_err(),+ "selecting session output must not publish before the Page owner boundary"+ );++ let publication = match owner_wake_rx+ .recv()+ .await+ .expect("Page owner response wake")+ {+ RendererOwnerWake::RuntimeInspectorResponsePublication {+ token: actual,+ publication,+ } => {+ assert_eq!(actual, token);+ publication+ }+ other => panic!("expected a Runtime response publication, got {other:?}"),+ };+ publication+ .commit(None)+ .expect("the exact attachment stream should accept the response");++ let RendererOutputTransportMessage::Publication(publication) = transport_rx+ .recv()+ .await+ .expect("session output publication")+ else {+ panic!("expected a session output publication");+ };+ let [record] = publication.records() else {+ panic!("session response should publish exactly one record");+ };+ let RendererOutputItem::Observation(RendererProtocolObservation::RuntimeInspector(batch)) =+ record.item()+ else {+ panic!("session response should use the Runtime Inspector output stream");+ };+ assert_eq!(batch.renderer_agent_attachment_id(), Some(attachment_id));+ assert_eq!(batch.messages.len(), 1);+ let RendererRuntimeInspectorMessage::Protocol(message) = &batch.messages[0] else {+ panic!("session response must remain a protocol message");+ };+ assert_eq!(message.value()["id"], json!(7));+ assert_eq!(response_rx.try_recv(), Err(TryRecvError::Empty));++ channel.cancel();+ }}#[derive(Debug, Clone, PartialEq, Eq)]diff --git a/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs b/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rsindex e8d2aa7ef..e9f3fcaef 100644--- a/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs+++ b/moli-renderer-v8/src/runtime/protocol_output/turn_journal.rs@@ -182,6 +182,41 @@ impl RendererTurnOutputJournal {Some(cursor)}+ /// Atomically appends and publishes one already-resolved producer batch.+ ///+ /// A DevTools session response is a terminal renderer observation, not a+ /// command-side acknowledgement. Admitting it through the same journal as+ /// that session's notifications keeps their producer order without a+ /// second completion sequencer. `false` means the exact attachment stream+ /// was already closed before it could take ownership of the records.+ pub(crate) fn try_publish_records(+ &self,+ records: impl IntoIterator<Item = PendingRendererOutputRecord>,+ ) -> bool {+ let records = records.into_iter().collect::<Vec<_>>();+ assert!(+ !records.is_empty(),+ "renderer output publication must contain at least one record"+ );+ let mut state = self.state.lock();+ if state.closed {+ return false;+ }+ state.records.extend(records);+ let publication = Self::settle_locked(&mut state)+ .expect("newly appended renderer output records must settle");+ if let Some(transport) = state.transport.as_ref() {+ // Admission failure means the protocol owner has retired or its+ // bounded stream is terminal. The journal has nevertheless taken+ // ownership at this exact sequence; falling back to another sink+ // here could duplicate the response.+ let _ = publication.publish_to(transport);+ } else {+ state.deferred_publications.push(publication);+ }+ true+ }+fn settle_locked(state: &mut RendererTurnOutputJournalState,) -> Option<RendererOutputPublication> {diff --git a/moli-renderer-v8/src/script_vm/inspector/outbound.rs b/moli-renderer-v8/src/script_vm/inspector/outbound.rsindex 4cfbb77ed..6669ac91e 100644--- a/moli-renderer-v8/src/script_vm/inspector/outbound.rs+++ b/moli-renderer-v8/src/script_vm/inspector/outbound.rs@@ -3,13 +3,16 @@ use crate::devtools::pause::{RendererInspectorSessionOutboundRoute,};use crate::runtime::{- PendingRendererOutputRecord, RendererCommandTurnOutputRecorder, RendererProtocolObservation,+ PendingRendererOutputRecord, RendererCommandTurnOutputRecorder,+ RendererDevToolsSessionOutputHost, RendererProtocolObservation,RendererRuntimeCommandOutputRecorder, RendererRuntimeInspectorMessage,RendererRuntimeInspectorMessageBatch, RendererRuntimeInspectorResponseSender,RendererTurnOutputJournal,};use anyhow::Result;-use moli_page_types::{DevToolsSessionKey, RendererDevToolsAgentToken};+use moli_page_types::{+ DevToolsSessionKey, RendererDevToolsAgentToken, RendererInspectorResponseDelivery,+};use serde_json::Value;use std::{cell::RefCell,@@ -406,6 +409,38 @@ impl InspectorOutbound {);}+ /// Registers a real frontend command with its explicit terminal response+ /// destination. Internal Classic/BiDi adapter calls intentionally keep+ /// using `register_response_callback`, which always preserves their+ /// private command reply capability.+ pub(in crate::script_vm) fn register_frontend_response_callback(+ &self,+ callback: RendererRuntimeInspectorResponseSender,+ delivery: RendererInspectorResponseDelivery,+ ) {+ let callback = match delivery {+ RendererInspectorResponseDelivery::CommandReply => callback,+ RendererInspectorResponseDelivery::DevToolsSession => {+ let host = self+ .session+ .clone()+ .zip(self.output_journal.clone())+ .zip(callback.renderer_agent_attachment_id())+ .map(|((session, output_journal), attachment_id)| {+ RendererDevToolsSessionOutputHost::new(+ self.agent_token,+ session,+ attachment_id,+ output_journal,+ )+ })+ .expect("frontend session output requires an attachment-scoped Page journal");+ callback.route_to_devtools_session_output(host)+ }+ };+ self.register_response_callback(callback);+ }+pub(in crate::script_vm) fn cancel_response_callback(&self, call_id: i32) {let mut guard = self.response_routing.borrow_mut();guard.pending_response_callbacks.remove(&call_id);diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rsindex ec7f28188..0f1d336ed 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs@@ -381,8 +381,11 @@ impl RendererInspectorSessionExecutorLocal {command.pause_effect(),command.response().map(|response| response.call_id()),);+ let response_delivery = command.response_delivery();if let Some(response) = command.take_response() {- session.outbound.register_response_callback(response);+ session+ .outbound+ .register_frontend_response_callback(response, response_delivery);}let _post_dispatch_wake = first_dispatch.release_for_dispatch();v8_session.dispatch_protocol_message(v8::inspector::StringView::from(diff --git a/moli-renderer-v8/src/worker/inspector_task_runner.rs b/moli-renderer-v8/src/worker/inspector_task_runner.rsindex 1a53aba18..4a2c07959 100644--- a/moli-renderer-v8/src/worker/inspector_task_runner.rs+++ b/moli-renderer-v8/src/worker/inspector_task_runner.rs@@ -9,6 +9,7 @@ use std::{},};+use moli_protocol_cdp::CdpInspectorTaskMode;use parking_lot::{Condvar, Mutex};use serde_json::json;use tokio::sync::{mpsc, oneshot};@@ -74,22 +75,7 @@ unsafe extern "C" fn dispatch_worker_inspector_interrupt(executor.dispatch_interrupt(isolate);}-#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub(crate) enum WorkerInspectorTaskMode {- Interrupt,- DontInterrupt,-}--pub(crate) fn worker_inspector_task_mode(method: &str) -> WorkerInspectorTaskMode {- match method {- "Debugger.evaluateOnCallFrame"- | "Runtime.evaluate"- | "Runtime.callFunctionOn"- | "Runtime.getProperties"- | "Runtime.runScript" => WorkerInspectorTaskMode::DontInterrupt,- _ => WorkerInspectorTaskMode::Interrupt,- }-}+pub(crate) type WorkerInspectorTaskMode = CdpInspectorTaskMode;pub(crate) enum WorkerInspectorTask {DispatchProtocolMessage {@@ -131,13 +117,9 @@ impl WorkerInspectorTask {}}-struct WorkerInspectorTaskEntry {- mode: WorkerInspectorTaskMode,- task: WorkerInspectorTask,-}-struct WorkerInspectorTaskRunnerState {- tasks: VecDeque<WorkerInspectorTaskEntry>,+ interrupting_tasks: VecDeque<WorkerInspectorTask>,+ dont_interrupting_tasks: VecDeque<WorkerInspectorTask>,disposed: bool,isolate_ready: bool,pause_loop_active: bool,@@ -172,7 +154,8 @@ impl WorkerInspectorTaskRunner {Self {shared: Arc::new(WorkerInspectorTaskRunnerShared {state: Mutex::new(WorkerInspectorTaskRunnerState {- tasks: VecDeque::new(),+ interrupting_tasks: VecDeque::new(),+ dont_interrupting_tasks: VecDeque::new(),disposed: false,isolate_ready: false,pause_loop_active: false,@@ -205,7 +188,7 @@ impl WorkerInspectorTaskRunner {value.get("method").and_then(serde_json::Value::as_str)- .map(worker_inspector_task_mode)+ .map(CdpInspectorTaskMode::for_method)}).unwrap_or(WorkerInspectorTaskMode::Interrupt);self.append(@@ -251,9 +234,12 @@ impl WorkerInspectorTaskRunner {task.fail("Worker Inspector task runner is disposed");return false;}- state- .tasks- .push_back(WorkerInspectorTaskEntry { mode, task });+ match mode {+ WorkerInspectorTaskMode::Interrupt => state.interrupting_tasks.push_back(task),+ WorkerInspectorTaskMode::DontInterrupt => {+ state.dont_interrupting_tasks.push_back(task);+ }+ }drop(state);if self@@ -284,8 +270,10 @@ impl WorkerInspectorTaskRunner {pub(crate) fn claim_task(&self, mode: WorkerInspectorTaskMode) -> Option<WorkerInspectorTask> {let mut state = self.shared.state.lock();- let index = state.tasks.iter().position(|entry| entry.mode == mode)?;- state.tasks.remove(index).map(|entry| entry.task)+ match mode {+ WorkerInspectorTaskMode::Interrupt => state.interrupting_tasks.pop_front(),+ WorkerInspectorTaskMode::DontInterrupt => state.dont_interrupting_tasks.pop_front(),+ }}pub(crate) fn interrupt_callback_started(&self) {@@ -295,12 +283,7 @@ impl WorkerInspectorTaskRunner {pub(crate) fn request_interrupt_if_needed(&self) {let should_request = {let state = self.shared.state.lock();- !state.disposed- && state.isolate_ready- && state- .tasks- .iter()- .any(|entry| entry.mode == WorkerInspectorTaskMode::Interrupt)+ !state.disposed && state.isolate_ready && !state.interrupting_tasks.is_empty()};if !should_request|| self@@ -346,8 +329,8 @@ impl WorkerInspectorTaskRunner {if state.disposed || state.quit_pause_loop {return None;}- if let Some(entry) = state.tasks.pop_front() {- return Some(entry.task);+ if let Some(task) = state.interrupting_tasks.pop_front() {+ return Some(task);}self.shared.pause_work.wait(&mut state);}@@ -373,7 +356,7 @@ impl WorkerInspectorTaskRunner {}pub(crate) fn dispose(&self, message: &str) {- let tasks = {+ let (interrupting_tasks, dont_interrupting_tasks) = {let mut state = self.shared.state.lock();if state.disposed {return;@@ -381,14 +364,16 @@ impl WorkerInspectorTaskRunner {state.disposed = true;state.isolate_ready = false;state.quit_pause_loop = true;- state- .tasks- .drain(..)- .map(|entry| entry.task)- .collect::<Vec<_>>()+ (+ state.interrupting_tasks.drain(..).collect::<Vec<_>>(),+ state.dont_interrupting_tasks.drain(..).collect::<Vec<_>>(),+ )};self.shared.pause_work.notify_all();- for task in tasks {+ for task in interrupting_tasks+ .into_iter()+ .chain(dont_interrupting_tasks)+ {task.fail(message);}}@@ -400,7 +385,11 @@ impl std::fmt::Debug for WorkerInspectorTaskRunner {formatter.debug_struct("WorkerInspectorTaskRunner").field("route_id", &self.route_id())- .field("tasks", &state.tasks.len())+ .field("interrupting_tasks", &state.interrupting_tasks.len())+ .field(+ "dont_interrupting_tasks",+ &state.dont_interrupting_tasks.len(),+ ).field("disposed", &state.disposed).field("isolate_ready", &state.isolate_ready).finish()@@ -414,10 +403,7 @@ mod tests {use parking_lot::Mutex;use tokio::sync::{mpsc, oneshot};- use super::{- WorkerInspectorTask, WorkerInspectorTaskMode, WorkerInspectorTaskRunner,- worker_inspector_task_mode,- };+ use super::{WorkerInspectorTask, WorkerInspectorTaskMode, WorkerInspectorTaskRunner};fn runner() -> (WorkerInspectorTaskRunner,@@ -456,7 +442,7 @@ mod tests {"Runtime.runScript",] {assert_eq!(- worker_inspector_task_mode(method),+ WorkerInspectorTaskMode::for_method(method),WorkerInspectorTaskMode::DontInterrupt,"{method} should use Chromium's non-interrupting worker path");@@ -470,7 +456,7 @@ mod tests {"Inspector.disable",] {assert_eq!(- worker_inspector_task_mode(method),+ WorkerInspectorTaskMode::for_method(method),WorkerInspectorTaskMode::Interrupt,"{method} should interrupt a busy worker");@@ -518,31 +504,31 @@ mod tests {}#[test]- fn pause_loop_preserves_fifo_across_task_modes() {+ fn pause_loop_claims_only_interrupting_tasks() {let (runner, _wake_rx) = runner();let _evaluate = append_protocol(&runner, 1, "Runtime.evaluate");let _terminate = append_protocol(&runner, 2, "Runtime.terminateExecution");assert!(runner.begin_pause_loop());- let first = runner+ let interrupt = runner.wait_for_pause_task()- .expect("pause loop should claim the first task");- let second = runner- .wait_for_pause_task()- .expect("pause loop should claim the second task");+ .expect("pause loop should claim the interrupting task");runner.request_quit_pause_loop();assert!(runner.wait_for_pause_task().is_none());runner.finish_pause_loop();assert!(matches!(- first,+ interrupt,WorkerInspectorTask::DispatchProtocolMessage { raw_json, .. }- if raw_json.contains("Runtime.evaluate")+ if raw_json.contains("Runtime.terminateExecution")));+ let ordinary = runner+ .claim_task(WorkerInspectorTaskMode::DontInterrupt)+ .expect("ordinary owner runner must retain DontInterrupt work");assert!(matches!(- second,+ ordinary,WorkerInspectorTask::DispatchProtocolMessage { raw_json, .. }- if raw_json.contains("Runtime.terminateExecution")+ if raw_json.contains("Runtime.evaluate")));}