Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(cdp): settle navigation terminations in session owner

ldm01ea452f139a1
diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rs
index fcc2e237f..a6a8b33e1 100644
--- a/moli-protocol/src/conn/runtime_eval.rs
+++ b/moli-protocol/src/conn/runtime_eval.rs
@@ -23,7 +23,7 @@ use moli_core::{
use crate::conn::state::{
DevToolsSessionState, PreparedRendererCallTermination, SessionRendererCallReplay,
- devtools_sessions_have_pending_inspector_awaits,
+ SessionRendererCallTermination, devtools_sessions_have_pending_inspector_awaits,
drain_pending_inspector_awaits_for_devtools_sessions,
};
use crate::domains::command_output::protocol_message_background_event;
@@ -4836,7 +4836,7 @@ impl CdpConnection {
) {
Ok(route) => route,
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -4848,7 +4848,7 @@ impl CdpConnection {
}
};
if route.renderer_agent_attachment_id != new_attachment_id {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -4891,7 +4891,7 @@ impl CdpConnection {
)
| Ok(moli_core::page::CompletedDevToolsIoCommandDispatch::Dispatched) => {}
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -4931,7 +4931,7 @@ impl CdpConnection {
)
| Ok(moli_core::page::CompletedDevToolsIoCommandDispatch::Dispatched) => {}
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -4954,7 +4954,7 @@ impl CdpConnection {
) {
Ok(raw_json) => raw_json,
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -4970,7 +4970,7 @@ impl CdpConnection {
{
Ok(page) => page,
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -5028,7 +5028,7 @@ impl CdpConnection {
),
},
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -5042,7 +5042,7 @@ impl CdpConnection {
let completed = match pending.wait().await {
Ok(completed) => completed,
Err(error) => {
- self.settle_renderer_replay_error(
+ self.settle_renderer_replacement_error(
&mut events,
frontend_session_id.as_deref(),
response_delivery,
@@ -5080,7 +5080,7 @@ impl CdpConnection {
{
Ok(output) => output,
Err(error) => {
- send_renderer_replay_error(
+ send_renderer_replacement_error(
&response_sender,
correlation,
&format!("runtime inspector replay dispatch failed: {error}"),
@@ -5095,7 +5095,7 @@ impl CdpConnection {
events.extend(command.take_protocol_events());
events.extend(command.take_post_response_events());
let Some(output) = completion.into_runtime_inspector_output() else {
- send_renderer_replay_error(
+ send_renderer_replacement_error(
&response_sender,
correlation,
"runtime inspector replay completed with a non-Runtime renderer reply",
@@ -5121,7 +5121,7 @@ impl CdpConnection {
Ok(events)
}
- fn settle_renderer_replay_error(
+ fn settle_renderer_replacement_error(
&mut self,
events: &mut Vec<BackgroundProtocolEvent>,
frontend_session_id: Option<&str>,
@@ -5131,10 +5131,25 @@ impl CdpConnection {
message: &str,
) {
if response_delivery == RendererInspectorResponseDelivery::CommandReply {
- send_renderer_replay_error(response_sender, correlation, message);
+ send_renderer_replacement_error(response_sender, correlation, message);
return;
}
+ self.settle_devtools_session_renderer_error(
+ events,
+ frontend_session_id,
+ correlation,
+ message,
+ );
+ }
+
+ fn settle_devtools_session_renderer_error(
+ &mut self,
+ events: &mut Vec<BackgroundProtocolEvent>,
+ frontend_session_id: Option<&str>,
+ correlation: RendererCommandCorrelation,
+ message: &str,
+ ) {
let Some(resolved) = self
.take_frontend_command_for_renderer_if_attachment_matches_for_session_owner(
frontend_session_id,
@@ -5160,19 +5175,27 @@ impl CdpConnection {
pub(crate) fn terminate_prepared_renderer_calls_after_navigation(
&mut self,
- terminations: Vec<PreparedRendererCallTermination>,
+ terminations: Vec<SessionRendererCallTermination>,
reason: &str,
- ) {
+ ) -> Vec<BackgroundProtocolEvent> {
+ let mut events = Vec::new();
for termination in terminations {
- let correlation = termination.correlation();
- let _ = termination.into_response_sender().send(json!({
- "id": correlation.renderer_call_id().get(),
- "error": {
- "code": -32000,
- "message": reason,
- },
- }));
+ let (frontend_session_id, termination) = termination.into_parts();
+ match termination {
+ PreparedRendererCallTermination::CommandReply {
+ correlation,
+ response_sender,
+ } => send_renderer_replacement_error(&response_sender, correlation, reason),
+ PreparedRendererCallTermination::DevToolsSession { correlation } => self
+ .settle_devtools_session_renderer_error(
+ &mut events,
+ frontend_session_id.as_deref(),
+ correlation,
+ reason,
+ ),
+ }
}
+ events
}
#[cfg(test)]
@@ -5993,7 +6016,7 @@ impl CdpConnection {
}
}
-fn send_renderer_replay_error(
+fn send_renderer_replacement_error(
response_sender: &RendererRuntimeInspectorResponseSender,
correlation: RendererCommandCorrelation,
message: &str,
@@ -6384,6 +6407,24 @@ mod tests {
.unwrap()
}
+ fn devtools_session_renderer_command_descriptor_for_test(
+ command_id: u64,
+ ) -> RendererCommandDescriptor {
+ let frontend_payload = json!({
+ "id": command_id,
+ "method": "Runtime.evaluate",
+ "params": { "expression": command_id.to_string() },
+ })
+ .to_string();
+ let frontend =
+ ParsedCdpCommand::parse_str(&frontend_payload).expect("frontend command should parse");
+ RendererCommandDescriptor::from_frontend_policy(
+ frontend.json().to_owned(),
+ frontend.renderer_policy(),
+ RendererInspectorResponseDelivery::DevToolsSession,
+ )
+ }
+
fn register_devtools_session_response_for_test(
conn: &mut CdpConnection,
session_id: &str,
@@ -6414,6 +6455,263 @@ mod tests {
correlation
}
+ #[test]
+ fn navigation_termination_consumes_a_devtools_session_frontend_call() {
+ let mut conn = CdpConnection::default();
+ let mut browser_context = BrowserContext::new("BID-navigation-termination".to_owned());
+ browser_context.set_active_target_id("TID-navigation-termination".to_owned());
+ browser_context.attach_active_session("SID-navigation-termination".to_owned());
+ conn.browser_context = Some(browser_context);
+
+ let old_attachment = RendererAgentAttachmentId::allocate();
+ let terminal_attachment = RendererAgentAttachmentId::allocate();
+ let prepared = conn
+ .try_register_renderer_call_for_session_owner(
+ Some("SID-navigation-termination"),
+ 69,
+ Some(old_attachment),
+ devtools_session_renderer_command_descriptor_for_test(69),
+ )
+ .expect("frontend response correlation should register");
+ let (old_correlation, old_sender, response_receiver) = prepared.into_parts();
+ assert!(response_receiver.is_none());
+
+ let replacements = {
+ let browser_context = conn
+ .browser_context
+ .as_mut()
+ .expect("test browser context should remain loaded");
+ crate::conn::state::prepare_renderer_call_replacements_for_devtools_sessions(
+ Some("SID-navigation-termination"),
+ &mut browser_context.devtools_session_state,
+ &mut browser_context.auxiliary_devtools_session_states,
+ old_attachment,
+ terminal_attachment,
+ )
+ .expect("navigation replacement should prepare")
+ };
+ let (replacement_attachment, terminations, replays) = replacements.into_parts();
+ assert_eq!(replacement_attachment, terminal_attachment);
+ assert_eq!(terminations.len(), 1);
+ assert!(replays.is_empty());
+ assert!(
+ old_sender
+ .send(json!({
+ "id": old_correlation.renderer_call_id().get(),
+ "result": {},
+ }))
+ .is_err(),
+ "navigation termination must invalidate the old renderer lease"
+ );
+ assert_eq!(
+ conn.renderer_call_for_frontend_for_session_owner(
+ Some("SID-navigation-termination"),
+ 69,
+ ),
+ Some(old_correlation),
+ "direct session termination must retain the original correlation until settlement"
+ );
+
+ let termination_events = conn.terminate_prepared_renderer_calls_after_navigation(
+ terminations,
+ "Inspected target navigated or closed",
+ );
+ assert_eq!(termination_events.len(), 1);
+ let response = termination_events[0]
+ .protocol_message()
+ .expect("DevToolsSession termination should emit a frontend response");
+ assert_eq!(response["id"], json!(69));
+ assert_eq!(response["sessionId"], json!("SID-navigation-termination"));
+ assert_eq!(response["error"]["code"], json!(-32000));
+ assert_eq!(
+ response["error"]["message"],
+ json!("Inspected target navigated or closed")
+ );
+
+ assert!(
+ conn.renderer_runtime_command_cause_for_frontend(
+ Some("SID-navigation-termination"),
+ 69,
+ )
+ .is_none(),
+ "navigation termination must consume the frontend correlation"
+ );
+ }
+
+ #[test]
+ fn navigation_termination_isolated_same_frontend_id_by_devtools_session() {
+ let mut conn = CdpConnection::default();
+ let mut browser_context = BrowserContext::new("BID-navigation-sessions".to_owned());
+ browser_context.set_active_target_id("TID-navigation-sessions".to_owned());
+ browser_context.attach_active_session("SID-navigation-primary".to_owned());
+ assert!(browser_context.assign_auxiliary_session_to_target(
+ "TID-navigation-sessions",
+ "SID-navigation-auxiliary".to_owned(),
+ ));
+ conn.browser_context = Some(browser_context);
+
+ let old_attachment = RendererAgentAttachmentId::allocate();
+ let terminal_attachment = RendererAgentAttachmentId::allocate();
+ let primary = conn
+ .try_register_renderer_call_for_session_owner(
+ Some("SID-navigation-primary"),
+ 71,
+ Some(old_attachment),
+ devtools_session_renderer_command_descriptor_for_test(71),
+ )
+ .expect("primary frontend response correlation should register");
+ let auxiliary = conn
+ .try_register_renderer_call_for_session_owner(
+ Some("SID-navigation-auxiliary"),
+ 71,
+ Some(old_attachment),
+ devtools_session_renderer_command_descriptor_for_test(71),
+ )
+ .expect("auxiliary frontend response correlation should register");
+ let (primary_correlation, primary_sender, primary_receiver) = primary.into_parts();
+ let (auxiliary_correlation, auxiliary_sender, auxiliary_receiver) = auxiliary.into_parts();
+ assert!(primary_receiver.is_none());
+ assert!(auxiliary_receiver.is_none());
+
+ let replacements = {
+ let browser_context = conn
+ .browser_context
+ .as_mut()
+ .expect("test browser context should remain loaded");
+ crate::conn::state::prepare_renderer_call_replacements_for_devtools_sessions(
+ Some("SID-navigation-primary"),
+ &mut browser_context.devtools_session_state,
+ &mut browser_context.auxiliary_devtools_session_states,
+ old_attachment,
+ terminal_attachment,
+ )
+ .expect("navigation replacement should prepare for every session")
+ };
+ let (_, terminations, replays) = replacements.into_parts();
+ assert_eq!(terminations.len(), 2);
+ assert!(replays.is_empty());
+ for (correlation, sender) in [
+ (primary_correlation, primary_sender),
+ (auxiliary_correlation, auxiliary_sender),
+ ] {
+ assert!(
+ sender
+ .send(json!({
+ "id": correlation.renderer_call_id().get(),
+ "result": {},
+ }))
+ .is_err(),
+ "navigation replacement must invalidate every old session lease"
+ );
+ }
+ assert_eq!(
+ conn.renderer_call_for_frontend_for_session_owner(Some("SID-navigation-primary"), 71,),
+ Some(primary_correlation)
+ );
+ assert_eq!(
+ conn.renderer_call_for_frontend_for_session_owner(
+ Some("SID-navigation-auxiliary"),
+ 71,
+ ),
+ Some(auxiliary_correlation)
+ );
+
+ let termination_events = conn.terminate_prepared_renderer_calls_after_navigation(
+ terminations,
+ "Inspected target navigated or closed",
+ );
+ assert_eq!(termination_events.len(), 2);
+ let session_ids = termination_events
+ .iter()
+ .map(|event| {
+ let response = event
+ .protocol_message()
+ .expect("each session termination should emit a frontend response");
+ assert_eq!(response["id"], json!(71));
+ assert_eq!(response["error"]["code"], json!(-32000));
+ response["sessionId"]
+ .as_str()
+ .expect("attached sessions must retain sessionId")
+ .to_owned()
+ })
+ .collect::<std::collections::BTreeSet<_>>();
+ assert_eq!(
+ session_ids,
+ std::collections::BTreeSet::from([
+ "SID-navigation-primary".to_owned(),
+ "SID-navigation-auxiliary".to_owned(),
+ ])
+ );
+ assert!(
+ conn.renderer_runtime_command_cause_for_frontend(Some("SID-navigation-primary"), 71,)
+ .is_none()
+ );
+ assert!(
+ conn.renderer_runtime_command_cause_for_frontend(Some("SID-navigation-auxiliary"), 71,)
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn navigation_termination_preserves_sessionless_page_response_shape() {
+ let mut conn = CdpConnection::default();
+ let mut browser_context = BrowserContext::new("BID-navigation-sessionless".to_owned());
+ browser_context.set_active_target_id("TID-navigation-sessionless".to_owned());
+ conn.browser_context = Some(browser_context);
+
+ let old_attachment = RendererAgentAttachmentId::allocate();
+ let terminal_attachment = RendererAgentAttachmentId::allocate();
+ let prepared = conn
+ .try_register_renderer_call_for_session_owner(
+ None,
+ 72,
+ Some(old_attachment),
+ devtools_session_renderer_command_descriptor_for_test(72),
+ )
+ .expect("sessionless frontend response correlation should register");
+ let (old_correlation, old_sender, response_receiver) = prepared.into_parts();
+ assert!(response_receiver.is_none());
+
+ let replacements = {
+ let browser_context = conn
+ .browser_context
+ .as_mut()
+ .expect("test browser context should remain loaded");
+ crate::conn::state::prepare_renderer_call_replacements_for_devtools_sessions(
+ None,
+ &mut browser_context.devtools_session_state,
+ &mut browser_context.auxiliary_devtools_session_states,
+ old_attachment,
+ terminal_attachment,
+ )
+ .expect("sessionless navigation replacement should prepare")
+ };
+ let (_, terminations, replays) = replacements.into_parts();
+ assert_eq!(terminations.len(), 1);
+ assert!(replays.is_empty());
+ drop(old_sender);
+ assert_eq!(
+ conn.renderer_call_for_frontend_for_session_owner(None, 72),
+ Some(old_correlation)
+ );
+
+ let termination_events = conn.terminate_prepared_renderer_calls_after_navigation(
+ terminations,
+ "Inspected target navigated or closed",
+ );
+ assert_eq!(termination_events.len(), 1);
+ let response = termination_events[0]
+ .protocol_message()
+ .expect("sessionless termination should emit a frontend response");
+ assert_eq!(response["id"], json!(72));
+ assert!(response.get("sessionId").is_none());
+ assert_eq!(response["error"]["code"], json!(-32000));
+ assert!(
+ conn.renderer_runtime_command_cause_for_frontend(None, 72)
+ .is_none()
+ );
+ }
+
#[test]
fn devtools_session_output_wrong_attachment_does_not_consume_live_correlation() {
let mut conn = CdpConnection::default();
diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rs
index e4b93157e..2206c0e71 100644
--- a/moli-protocol/src/conn/state/devtools_session.rs
+++ b/moli-protocol/src/conn/state/devtools_session.rs
@@ -55,17 +55,23 @@ pub(crate) struct SessionRendererCallReplay {
replay: PreparedRendererCallReplay,
}
+#[derive(Debug)]
+pub(crate) struct SessionRendererCallTermination {
+ frontend_session_id: Option<String>,
+ termination: PreparedRendererCallTermination,
+}
+
#[derive(Debug, Default)]
pub(crate) struct PreparedRendererCallReplacements {
new_attachment_id: Option<moli_page_types::RendererAgentAttachmentId>,
- terminations: Vec<PreparedRendererCallTermination>,
+ terminations: Vec<SessionRendererCallTermination>,
replays: Vec<SessionRendererCallReplay>,
}
impl PreparedRendererCallReplacements {
fn new(
new_attachment_id: moli_page_types::RendererAgentAttachmentId,
- terminations: Vec<PreparedRendererCallTermination>,
+ terminations: Vec<SessionRendererCallTermination>,
replays: Vec<SessionRendererCallReplay>,
) -> Self {
Self {
@@ -83,7 +89,7 @@ impl PreparedRendererCallReplacements {
self,
) -> (
moli_page_types::RendererAgentAttachmentId,
- Vec<PreparedRendererCallTermination>,
+ Vec<SessionRendererCallTermination>,
Vec<SessionRendererCallReplay>,
) {
(
@@ -95,6 +101,12 @@ impl PreparedRendererCallReplacements {
}
}
+impl SessionRendererCallTermination {
+ pub(crate) fn into_parts(self) -> (Option<String>, PreparedRendererCallTermination) {
+ (self.frontend_session_id, self.termination)
+ }
+}
+
impl SessionRendererCallReplay {
pub(crate) fn frontend_session_id(&self) -> Option<&str> {
self.frontend_session_id.as_deref()
@@ -606,14 +618,19 @@ pub(crate) fn prepare_renderer_call_replays_for_devtools_sessions(
}
pub(crate) fn prepare_renderer_call_terminations_for_devtools_sessions(
+ primary_session_id: Option<&str>,
primary: &mut DevToolsSessionState,
auxiliary: &mut HashMap<String, DevToolsSessionState>,
old_attachment_id: moli_page_types::RendererAgentAttachmentId,
terminal_attachment_id: moli_page_types::RendererAgentAttachmentId,
-) -> Result<Vec<PreparedRendererCallTermination>, RendererCallIdExhausted> {
+) -> Result<Vec<SessionRendererCallTermination>, RendererCallIdExhausted> {
let mut terminations = primary
.prepare_renderer_call_terminations(old_attachment_id, terminal_attachment_id)?
.into_iter()
+ .map(|termination| SessionRendererCallTermination {
+ frontend_session_id: primary_session_id.map(str::to_owned),
+ termination,
+ })
.collect::<Vec<_>>();
let mut auxiliary_session_ids = auxiliary.keys().cloned().collect::<Vec<_>>();
auxiliary_session_ids.sort();
@@ -622,7 +639,13 @@ pub(crate) fn prepare_renderer_call_terminations_for_devtools_sessions(
.get_mut(&session_id)
.expect("selected auxiliary session must remain registered");
terminations.extend(
- state.prepare_renderer_call_terminations(old_attachment_id, terminal_attachment_id)?,
+ state
+ .prepare_renderer_call_terminations(old_attachment_id, terminal_attachment_id)?
+ .into_iter()
+ .map(|termination| SessionRendererCallTermination {
+ frontend_session_id: Some(session_id.clone()),
+ termination,
+ }),
);
}
Ok(terminations)
@@ -636,6 +659,7 @@ pub(crate) fn prepare_renderer_call_replacements_for_devtools_sessions(
new_attachment_id: moli_page_types::RendererAgentAttachmentId,
) -> Result<PreparedRendererCallReplacements, RendererCallIdExhausted> {
let terminations = prepare_renderer_call_terminations_for_devtools_sessions(
+ primary_session_id,
primary,
auxiliary,
old_attachment_id,
diff --git a/moli-protocol/src/conn/state/mod.rs b/moli-protocol/src/conn/state/mod.rs
index f69d671bb..018774b0d 100644
--- a/moli-protocol/src/conn/state/mod.rs
+++ b/moli-protocol/src/conn/state/mod.rs
@@ -48,7 +48,7 @@ pub(crate) use dedicated_worker_target::{
};
pub(crate) use devtools_session::{
DevToolsConsoleOutputSessionState, DevToolsLogViolationThreshold, DevToolsSessionState,
- PreparedRendererCallReplacements, SessionRendererCallReplay,
+ PreparedRendererCallReplacements, SessionRendererCallReplay, SessionRendererCallTermination,
devtools_sessions_have_pending_inspector_awaits,
devtools_sessions_pending_inspector_await_count,
drain_pending_inspector_awaits_for_devtools_sessions,
diff --git a/moli-protocol/src/conn/state/pending_renderer_command.rs b/moli-protocol/src/conn/state/pending_renderer_command.rs
index b060af3d8..d30e3d7ab 100644
--- a/moli-protocol/src/conn/state/pending_renderer_command.rs
+++ b/moli-protocol/src/conn/state/pending_renderer_command.rs
@@ -236,18 +236,29 @@ pub(crate) struct PreparedRendererCallReplay {
}
#[derive(Debug)]
-pub(crate) struct PreparedRendererCallTermination {
- correlation: RendererCommandCorrelation,
- response_sender: RendererRuntimeInspectorResponseSender,
+pub(crate) enum PreparedRendererCallTermination {
+ /// Internal adapters await a private receiver, so navigation rotates the
+ /// lease to a synthetic terminal completion owned by the replacement.
+ CommandReply {
+ correlation: RendererCommandCorrelation,
+ response_sender: RendererRuntimeInspectorResponseSender,
+ },
+ /// Frontend calls remain owned by their protocol session. Navigation only
+ /// revokes the retired renderer lease; the session consumes this original
+ /// correlation when it emits the terminal response directly.
+ DevToolsSession {
+ correlation: RendererCommandCorrelation,
+ },
}
impl PreparedRendererCallTermination {
+ #[cfg(test)]
pub(crate) const fn correlation(&self) -> RendererCommandCorrelation {
- self.correlation
- }
-
- pub(crate) fn into_response_sender(self) -> RendererRuntimeInspectorResponseSender {
- self.response_sender
+ match self {
+ Self::CommandReply { correlation, .. } | Self::DevToolsSession { correlation } => {
+ *correlation
+ }
+ }
}
}
@@ -463,6 +474,33 @@ impl<T> PendingRendererCommandRegistry<T> {
let mut terminations = Vec::with_capacity(frontend_command_ids.len());
for frontend_command_id in frontend_command_ids {
+ let response_delivery = self
+ .renderer_calls_by_frontend
+ .get(&frontend_command_id)
+ .expect("selected terminal command must remain registered")
+ .descriptor
+ .response_delivery();
+ match response_delivery {
+ RendererInspectorResponseDelivery::DevToolsSession => {
+ let call = self
+ .renderer_calls_by_frontend
+ .get(&frontend_command_id)
+ .expect("selected terminal command must remain registered");
+ if !call.response_channel.try_revoke_active_lease() {
+ continue;
+ }
+ terminations.push(PreparedRendererCallTermination::DevToolsSession {
+ correlation: RendererCommandCorrelation {
+ frontend_command_id,
+ renderer_call_id: call.renderer_call_id,
+ dispatched_attachment_id: call.dispatched_attachment_id,
+ },
+ });
+ continue;
+ }
+ RendererInspectorResponseDelivery::CommandReply => {}
+ }
+
let renderer_call_id = self.allocate_renderer_call_id()?;
let response_sender = {
let call = self
@@ -491,7 +529,7 @@ impl<T> PendingRendererCommandRegistry<T> {
call.renderer_call_id = renderer_call_id;
call.dispatched_attachment_id = Some(terminal_attachment_id);
- terminations.push(PreparedRendererCallTermination {
+ terminations.push(PreparedRendererCallTermination::CommandReply {
correlation: RendererCommandCorrelation {
frontend_command_id,
renderer_call_id,
@@ -1118,7 +1156,7 @@ mod tests {
}
#[tokio::test]
- async fn termination_rotates_attachment_and_invalidates_old_response_lease() {
+ async fn command_reply_termination_rotates_attachment_and_invalidates_old_response_lease() {
let frontend_id = FrontendCommandId::new(42);
let old_attachment = RendererAgentAttachmentId::allocate();
let new_attachment = RendererAgentAttachmentId::allocate();
@@ -1163,8 +1201,15 @@ mod tests {
"replacement must invalidate an old renderer callback before Page teardown"
);
- termination
- .into_response_sender()
+ let PreparedRendererCallTermination::CommandReply {
+ correlation,
+ response_sender,
+ } = termination
+ else {
+ panic!("a synthesized command must use CommandReply termination")
+ };
+ assert_eq!(correlation, terminal_correlation);
+ response_sender
.send(serde_json::json!({
"id": terminal_correlation.renderer_call_id().get(),
"error": {
@@ -1198,6 +1243,67 @@ mod tests {
);
}
+ #[test]
+ fn devtools_session_termination_revokes_without_renderer_identity_rotation() {
+ let frontend_id = FrontendCommandId::new(43);
+ let old_attachment = RendererAgentAttachmentId::allocate();
+ let new_attachment = RendererAgentAttachmentId::allocate();
+ let frontend = ParsedCdpCommand::parse_str(
+ r#"{"id":43,"method":"Runtime.evaluate","params":{"expression":"43"}}"#,
+ )
+ .expect("frontend command must parse at ingress");
+ let mut registry = PendingRendererCommandRegistry::<()>::default();
+ let prepared = registry
+ .try_register_renderer_call(
+ frontend_id,
+ Some(old_attachment),
+ RendererCommandDescriptor::from_frontend_policy(
+ frontend.json().to_owned(),
+ frontend.renderer_policy(),
+ RendererInspectorResponseDelivery::DevToolsSession,
+ ),
+ )
+ .unwrap();
+ let (old_correlation, old_sender, response_receiver) = prepared.into_parts();
+ assert!(response_receiver.is_none());
+ registry.next_renderer_call_id = None;
+
+ let mut terminations = registry
+ .prepare_terminations_from_attachment(old_attachment, new_attachment)
+ .expect("session termination must not allocate a renderer call id");
+
+ assert_eq!(terminations.len(), 1);
+ let termination = terminations.pop().unwrap();
+ assert_eq!(termination.correlation(), old_correlation);
+ assert!(matches!(
+ termination,
+ PreparedRendererCallTermination::DevToolsSession {
+ correlation
+ } if correlation == old_correlation
+ ));
+ assert_eq!(
+ registry.renderer_call_for_frontend(frontend_id),
+ Some(old_correlation),
+ "the session owner consumes the original correlation when it emits the error"
+ );
+ assert!(
+ old_sender
+ .send(serde_json::json!({
+ "id": old_correlation.renderer_call_id().get(),
+ "result": {},
+ }))
+ .is_err(),
+ "preparing the direct session error must revoke the old renderer lease"
+ );
+ assert_eq!(
+ registry.take_frontend_command_for_renderer_if_attachment_matches(
+ old_correlation.renderer_call_id(),
+ Some(old_attachment),
+ ),
+ Some(old_correlation)
+ );
+ }
+
#[tokio::test]
async fn terminal_drain_completes_receivers_and_removes_all_correlations() {
let first_id = FrontendCommandId::new(51);
diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rs
index aa0f507a8..21e48a4d0 100644
--- a/moli-protocol/src/domains/page/navigation.rs
+++ b/moli-protocol/src/domains/page/navigation.rs
@@ -3523,10 +3523,11 @@ pub(crate) async fn complete_materialized_navigation_into_buffer_async(
}
if let Some(renderer_call_replacements) = renderer_call_replacements {
let (new_attachment_id, terminations, replays) = renderer_call_replacements.into_parts();
- conn.terminate_prepared_renderer_calls_after_navigation(
+ let termination_events = conn.terminate_prepared_renderer_calls_after_navigation(
terminations,
"Inspected target navigated or closed",
);
+ out.extend_background_events_after_messages(termination_events);
match conn
.replay_prepared_renderer_calls_after_navigation_async(replays, new_attachment_id)
.await
diff --git a/moli-protocol/src/domains/runtime/tests/evaluate.rs b/moli-protocol/src/domains/runtime/tests/evaluate.rs
index 75ca1fcb5..0c94b7e4b 100644
--- a/moli-protocol/src/domains/runtime/tests/evaluate.rs
+++ b/moli-protocol/src/domains/runtime/tests/evaluate.rs
@@ -8024,10 +8024,17 @@ fn runtime_evaluate_await_promise_pending_is_terminated_once_by_navigation_repla
ctx.sent
);
assert_eq!(responses[0]["error"]["code"], json!(-32000));
+ assert_eq!(responses[0]["sessionId"], json!("SID-1"));
assert_eq!(
responses[0]["error"]["message"],
json!("Inspected target navigated or closed")
);
+ assert!(
+ ctx.conn
+ .renderer_runtime_command_cause_for_frontend(Some("SID-1"), 9_012)
+ .is_none(),
+ "terminal replacement response must consume the renderer correlation"
+ );
assert!(
!ctx.conn.has_pending_inspector_awaits(),
"terminal replacement response must consume the pending command owner"
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index b087f73f8..107c1193e 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -3102,6 +3102,20 @@ impl RendererRuntimeInspectorResponseChannel {
})
}
+ /// Revokes the current renderer sender without settling the frontend call.
+ ///
+ /// Attachment replacement uses this to prevent the retired renderer from
+ /// publishing while the protocol session still owns terminal completion.
+ /// A response that already claimed the channel wins and returns `false`.
+ pub fn try_revoke_active_lease(&self) -> bool {
+ let mut state = self.state.lock();
+ if !state.open || state.active_lease_id.is_none() {
+ return false;
+ }
+ state.active_lease_id = None;
+ true
+ }
+
pub fn cancel(&self) {
let mut state = self.state.lock();
state.open = false;
@@ -3634,6 +3648,33 @@ mod renderer_runtime_inspector_response_channel_tests {
assert!(rx.await.is_err());
}
+ #[tokio::test]
+ async fn revoking_session_lease_leaves_terminal_settlement_to_protocol_owner() {
+ let attachment = RendererAgentAttachmentId::allocate();
+ let (channel, receiver) = RendererRuntimeInspectorResponseChannel::new_for_delivery(
+ moli_page_types::RendererInspectorResponseDelivery::DevToolsSession,
+ );
+ assert!(receiver.is_none());
+ let sender = channel.activate_sender(1, Some(attachment));
+ let mut settlement_rx = sender
+ .take_session_response_settlement_receiver()
+ .expect("the frontend call should retain a settlement waiter");
+
+ assert!(channel.try_revoke_active_lease());
+ assert!(
+ !channel.try_revoke_active_lease(),
+ "one attachment replacement must revoke the lease only once"
+ );
+ assert!(sender.send_output(output(1)).is_err());
+ assert!(
+ matches!(settlement_rx.try_recv(), Err(TryRecvError::Empty)),
+ "lease revocation must not settle the frontend call before its protocol error",
+ );
+
+ channel.cancel();
+ assert!(settlement_rx.await.is_err());
+ }
+
#[tokio::test]
async fn completed_response_lease_cannot_be_rotated() {
let (channel, rx) = RendererRuntimeInspectorResponseChannel::new();
@@ -3642,6 +3683,10 @@ mod renderer_runtime_inspector_response_channel_tests {
.send_output(output(1))
.expect("active response lease should complete");
+ assert!(
+ !channel.try_revoke_active_lease(),
+ "attachment replacement must not revoke a response that already won"
+ );
assert!(channel.try_activate_sender(2, None).is_none());
assert_eq!(rx.await.unwrap().call_id, 1);
}