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): replay Runtime notifications before enable responses

ldm089863e976cd9
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
index e3fb687f0..6af2ef8a3 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
@@ -139,36 +139,84 @@ async fn enable_runtime_and_expect_default_context(
session_id: Option<&str>,
label: &str,
) -> Vec<serde_json::Value> {
- let mut messages =
+ let messages =
send_cdp_command(socket, command_id, "Runtime.enable", session_id, json!({})).await;
assert_eq!(response_by_id(&messages, command_id)["result"], json!({}));
- if !messages.iter().any(|message| {
- message.get("sessionId").and_then(serde_json::Value::as_str) == session_id
- && message["method"] == json!("Runtime.executionContextCreated")
- && message["params"]["context"]["auxData"]["isDefault"] == json!(true)
- }) {
- messages.extend(
- send_cdp_command(
- socket,
- command_id + 1,
- "Runtime.evaluate",
- session_id,
- json!({ "expression": "void 0" }),
- )
- .await,
- );
- }
+ // V8RuntimeAgentImpl::enable reports existing contexts synchronously;
+ // Blink's DevToolsSession flushes those notifications before the reply.
+ // Waiting for another command would conceal a broken enable boundary.
assert!(
messages.iter().any(|message| {
message.get("sessionId").and_then(serde_json::Value::as_str) == session_id
&& message["method"] == json!("Runtime.executionContextCreated")
&& message["params"]["context"]["auxData"]["isDefault"] == json!(true)
}),
- "{label} did not report the existing default context before the next Runtime response: {messages:#?}"
+ "{label} did not report the existing default context before Runtime.enable replied: {messages:#?}"
);
messages
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cdp_ordering_deferred_reply_allows_its_later_resolver() {
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .expect("connect browser websocket");
+ let context = cdp_create_browser_context(&mut browser, 1).await;
+ let target = cdp_create_attached_target(&mut browser, 2, &context).await;
+ let session = Some(target.session_id.as_str());
+ send_cdp_command_without_wait(
+ &mut browser, 10, "Runtime.evaluate", session,
+ json!({ "expression": "new Promise(resolve => globalThis.finishOrderingProbe = resolve)", "awaitPromise": true, "returnByValue": true }),
+ ).await;
+ let later = send_cdp_command(
+ &mut browser,
+ 11,
+ "Runtime.evaluate",
+ session,
+ json!({ "expression": "typeof finishOrderingProbe", "returnByValue": true }),
+ )
+ .await;
+ assert_eq!(
+ response_by_id(&later, 11)["result"]["result"]["value"],
+ json!("function")
+ );
+ assert!(
+ later.iter().all(|message| message["id"] != json!(10)),
+ "an unresolved Promise must have no terminal reply: {later:#?}"
+ );
+ send_cdp_command_without_wait(
+ &mut browser,
+ 12,
+ "Runtime.evaluate",
+ session,
+ json!({ "expression": "finishOrderingProbe(42); 'resolved'", "returnByValue": true }),
+ )
+ .await;
+ let mut terminal_ids = std::collections::HashSet::new();
+ let completed = recv_until_match(&mut browser, |message| {
+ if let Some(id) = message["id"].as_u64() {
+ assert!(
+ terminal_ids.insert(id),
+ "duplicate terminal reply: {message}"
+ );
+ }
+ terminal_ids.contains(&10) && terminal_ids.contains(&12)
+ })
+ .await;
+ assert_eq!(
+ response_by_id(&completed, 10)["result"]["result"]["value"],
+ json!(42)
+ );
+ assert_eq!(
+ response_by_id(&completed, 12)["result"]["result"]["value"],
+ json!("resolved")
+ );
+ browser.close(None).await.expect("close browser websocket");
+ abort_test_cdp_server(server).await;
+}
+
async fn puppeteer_auto_attach_existing_page(
browser: &mut TestCdpSocket,
command_id: u64,
diff --git a/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs b/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs
index c719c0950..e270cb9f3 100644
--- a/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs
+++ b/moli-protocol/src/domains/runtime/dispatcher/runtime_command_flow.rs
@@ -838,7 +838,10 @@ pub(super) fn complete_pending_runtime_enable_command(
}
let frame_id = conn.runtime_session_owner_frame_id_for_owner(&completed.owner_scope);
- let mut plan = CommandOutputPlan::success();
+ // Runtime.enable reports its existing inventory before acknowledging the
+ // enable. Keep replay and reply in one ordered plan, including worker
+ // adapters that synthesize the replay outside the V8 session sink.
+ let mut plan = CommandOutputPlan::default();
for event in replay.into_events() {
match event {
RuntimeEnableReplayEvent::Context(event) => {
@@ -874,6 +877,7 @@ pub(super) fn complete_pending_runtime_enable_command(
}
}
}
+ plan.push_success();
plan
}
diff --git a/moli-protocol/src/domains/runtime/dispatcher/worker_runtime.rs b/moli-protocol/src/domains/runtime/dispatcher/worker_runtime.rs
index fabeddd86..43a779288 100644
--- a/moli-protocol/src/domains/runtime/dispatcher/worker_runtime.rs
+++ b/moli-protocol/src/domains/runtime/dispatcher/worker_runtime.rs
@@ -1181,7 +1181,10 @@ pub(super) fn shared_worker_runtime_enable_command_output_plan_for_session(
target.mark_runtime_console_emitted(session_id, console_end);
}
- let mut plan = CommandOutputPlan::success();
+ // Runtime.enable reports its existing inventory before acknowledging the
+ // enable. Keep replay and reply in one ordered plan, including worker
+ // adapters that synthesize the replay outside the V8 session sink.
+ let mut plan = CommandOutputPlan::default();
if let Some(execution_context_created) = execution_context_created {
target.record_runtime_contexts_reported_to_frontend(session_id);
push_execution_context_created_background_event(
@@ -1204,6 +1207,7 @@ pub(super) fn shared_worker_runtime_enable_command_output_plan_for_session(
base_timestamp + ((index + 1) as f64 * 0.000_001),
);
}
+ plan.push_success();
plan
}
@@ -1236,7 +1240,10 @@ pub(super) fn service_worker_runtime_enable_command_output_plan_for_session(
target.mark_runtime_exception_emitted(session_id, exception_end);
}
- let mut plan = CommandOutputPlan::success();
+ // Runtime.enable reports its existing inventory before acknowledging the
+ // enable. Keep replay and reply in one ordered plan, including worker
+ // adapters that synthesize the replay outside the V8 session sink.
+ let mut plan = CommandOutputPlan::default();
if let Some(execution_context_created) = execution_context_created {
target.record_runtime_contexts_reported_to_frontend(session_id);
push_execution_context_created_background_event(
@@ -1265,6 +1272,7 @@ pub(super) fn service_worker_runtime_enable_command_output_plan_for_session(
&exception_messages,
exception_start,
);
+ plan.push_success();
plan
}
diff --git a/moli-protocol/src/domains/runtime/tests/service_worker.rs b/moli-protocol/src/domains/runtime/tests/service_worker.rs
index 3311c9b75..9de2d2deb 100644
--- a/moli-protocol/src/domains/runtime/tests/service_worker.rs
+++ b/moli-protocol/src/domains/runtime/tests/service_worker.rs
@@ -271,6 +271,28 @@ async fn runtime_enable_on_service_worker_session_replays_real_worker_context()
}))
.await;
+ let response_index = ctx
+ .sent
+ .iter()
+ .position(|message| message["id"] == json!(82))
+ .expect("enable response");
+ for method in [
+ "Runtime.executionContextCreated",
+ "Runtime.consoleAPICalled",
+ "Runtime.exceptionThrown",
+ ] {
+ let event_index = ctx
+ .sent
+ .iter()
+ .position(|message| message["method"] == json!(method))
+ .expect("buffered Runtime replay");
+ assert!(
+ event_index < response_index,
+ "{method} must precede the enable reply: {:#?}",
+ ctx.sent
+ );
+ }
+
ctx.expect_result(82, json!({}), Some("SID-service-worker"));
let context_event = ctx.take_first_matching("service worker execution context", |message| {
message["method"] == json!("Runtime.executionContextCreated")
diff --git a/moli-protocol/src/domains/runtime/tests/shared_worker.rs b/moli-protocol/src/domains/runtime/tests/shared_worker.rs
index 11bb5b89e..6b0449652 100644
--- a/moli-protocol/src/domains/runtime/tests/shared_worker.rs
+++ b/moli-protocol/src/domains/runtime/tests/shared_worker.rs
@@ -103,6 +103,27 @@ async fn runtime_enable_on_shared_worker_session_replays_real_worker_context() {
}))
.await;
+ let response_index = ctx
+ .sent
+ .iter()
+ .position(|message| message["id"] == json!(72))
+ .expect("enable response");
+ for method in [
+ "Runtime.executionContextCreated",
+ "Runtime.consoleAPICalled",
+ ] {
+ let event_index = ctx
+ .sent
+ .iter()
+ .position(|message| message["method"] == json!(method))
+ .expect("buffered Runtime replay");
+ assert!(
+ event_index < response_index,
+ "{method} must precede the enable reply: {:#?}",
+ ctx.sent
+ );
+ }
+
ctx.expect_result(72, json!({}), Some("SID-shared-worker"));
let context_event = ctx.take_first_matching("shared worker execution context", |message| {
message["method"] == json!("Runtime.executionContextCreated")