Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
report offline navigations as network failures, not -32000
BibekPathak8032606abf23
diff --git a/moli-protocol-server/src/protocol_server/tests/websocket.rs b/moli-protocol-server/src/protocol_server/tests/websocket.rsindex 0b6ce3b63..1d6a9e256 100644--- a/moli-protocol-server/src/protocol_server/tests/websocket.rs+++ b/moli-protocol-server/src/protocol_server/tests/websocket.rs@@ -2045,19 +2045,14 @@ async fn websocket_cdp_raw_client_runtime_evaluate_immediately_after_page_naviga}#[tokio::test]-async fn websocket_cdp_offline_emulation_loopback_navigation_proceeds_and_evaluates() {+async fn websocket_cdp_offline_emulation_navigation_fails_like_network_error() {async fn page() -> impl IntoResponse {([(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],"<!doctype html><html><body><div id='probe'>online</div></body></html>",)}- async fn probe() -> &'static str {- "pong"- }- let fixture_app = Router::new()- .route("/", get(page))- .route("/probe", get(probe));+ let fixture_app = Router::new().route("/", get(page));let fixture_listener = TcpListener::bind("127.0.0.1:0").await.expect("bind fixture listener");@@ -2073,257 +2068,137 @@ async fn websocket_cdp_offline_emulation_loopback_navigation_proceeds_and_evalua.await.expect("connect to cdp websocket");- socket- .send(WsMessage::Text(- json!({ "id": 1_u64, "method": "Target.createBrowserContext" })- .to_string()- .into(),- ))- .await- .expect("send createBrowserContext");- let create_browser_context = recv_until_id(&mut socket, 1).await;- let browser_context_id = create_browser_context- .iter()- .find(|message| message["id"] == json!(1_u64))- .and_then(|message| message["result"]["browserContextId"].as_str())- .expect("browserContextId")- .to_owned();-- socket- .send(WsMessage::Text(- json!({- "id": 2_u64,- "method": "Target.createTarget",- "params": { "browserContextId": browser_context_id, "url": "about:blank" }- })- .to_string()- .into(),- ))- .await- .expect("send createTarget");- let create_target = recv_until_id(&mut socket, 2).await;- let target_id = create_target- .iter()- .find(|message| message["id"] == json!(2_u64))- .and_then(|message| message["result"]["targetId"].as_str())- .expect("targetId")- .to_owned();+ let browser_context_id = cdp_create_browser_context(&mut socket, 1).await;+ let session = cdp_create_attached_target(&mut socket, 2, &browser_context_id).await;- socket- .send(WsMessage::Text(- json!({- "id": 3_u64,- "method": "Target.attachToTarget",- "params": { "targetId": target_id, "flatten": true }- })- .to_string()- .into(),- ))- .await- .expect("send attachToTarget");- let attach = recv_until_id(&mut socket, 3).await;- let session_id = attach- .iter()- .find(|message| message["id"] == json!(3_u64))- .and_then(|message| message["result"]["sessionId"].as_str())- .expect("sessionId")- .to_owned();+ let network_enable = send_cdp_command(+ &mut socket,+ 4,+ "Network.enable",+ Some(&session.session_id),+ json!({}),+ )+ .await;+ assert!(+ network_enable+ .iter()+ .any(|message| message["id"] == json!(4_u64) && message.get("error").is_none()),+ "Network.enable should succeed: {network_enable:?}"+ );- // Reproduce the offline scenario from the bug report: enable offline- // emulation, then navigate to a loopback fixture. Chromium does not- // hard-block loopback navigations under offline emulation, so the- // navigation must proceed and the committed page must stay usable.- socket- .send(WsMessage::Text(- json!({- "id": 4_u64,- "method": "Network.emulateNetworkConditions",- "sessionId": session_id,- "params": {- "offline": true,- "latency": 0,- "downloadThroughput": -1,- "uploadThroughput": -1- }- })- .to_string()- .into(),- ))- .await- .expect("send emulateNetworkConditions");- let emulate = recv_until_id(&mut socket, 4).await;- let emulate_response = emulate- .iter()- .find(|message| message["id"] == json!(4_u64))- .expect("emulateNetworkConditions response");+ // Turn offline emulation on. Chromium blocks loopback too, so the+ // navigation must fail as a network error rather than succeed.+ let emulate = send_cdp_command(+ &mut socket,+ 5,+ "Network.emulateNetworkConditions",+ Some(&session.session_id),+ json!({+ "offline": true,+ "latency": 0,+ "downloadThroughput": -1,+ "uploadThroughput": -1+ }),+ )+ .await;assert!(- emulate_response.get("error").is_none(),- "offline emulation should be accepted; got {emulate_response}"+ emulate+ .iter()+ .any(|message| message["id"] == json!(5_u64) && message.get("error").is_none()),+ "offline emulation should be accepted: {emulate:?}");- socket- .send(WsMessage::Text(- json!({- "id": 5_u64,- "method": "Page.navigate",- "sessionId": session_id,- "params": { "url": fixture_url }- })- .to_string()- .into(),- ))- .await- .expect("send Page.navigate");- let navigate = recv_until_id(&mut socket, 5).await;+ let navigate = send_cdp_command(+ &mut socket,+ 6,+ "Page.navigate",+ Some(&session.session_id),+ json!({ "url": fixture_url }),+ )+ .await;let navigate_response = navigate.iter()- .find(|message| message["id"] == json!(5_u64))+ .find(|message| message["id"] == json!(6_u64)).expect("Page.navigate response");assert!(navigate_response.get("error").is_none(),- "loopback navigation must proceed under offline emulation; got {navigate_response}"+ "an offline navigation must not be a -32000 protocol error; got {navigate_response:#?}");assert!(navigate_response["result"]["frameId"].is_string(),- "Page.navigate must resolve with a frameId; got {navigate_response}"+ "Page.navigate must still resolve with a frameId; got {navigate_response:#?}");-- socket- .send(WsMessage::Text(- json!({- "id": 6_u64,- "method": "Runtime.evaluate",- "sessionId": session_id,- "params": { "expression": "1 + 1", "returnByValue": true }- })- .to_string()- .into(),- ))- .await- .expect("send Runtime.evaluate");- let evaluate = recv_until_id(&mut socket, 6).await;- let evaluate_response = evaluate- .iter()- .find(|message| message["id"] == json!(6_u64))- .expect("Runtime.evaluate response");assert!(- evaluate_response.get("error").is_none(),- "Runtime.evaluate must not error after loopback navigation; got {evaluate_response}"- );- assert_eq!(- evaluate_response["result"]["result"]["value"],- json!(2),- "Runtime.evaluate must observe the committed loopback document"+ navigate.iter().any(|message| {+ message["sessionId"].as_str() == Some(session.session_id.as_str())+ && message["method"] == json!("Network.loadingFailed")+ && message["params"]["errorText"] == json!("net::ERR_INTERNET_DISCONNECTED")+ }),+ "offline navigation must emit Network.loadingFailed with net::ERR_INTERNET_DISCONNECTED: {navigate:#?}");+ if let Some(error_text) = navigate_response["result"]["errorText"].as_str() {+ assert_eq!(+ error_text, "net::ERR_INTERNET_DISCONNECTED",+ "Page.navigate errorText must match the network error"+ );+ }- // The loopback document keeps navigator.onLine true, matching the known- // Chromium quirk where offline emulation leaves loopback pages online.- socket- .send(WsMessage::Text(- json!({- "id": 7_u64,- "method": "Runtime.evaluate",- "sessionId": session_id,- "params": { "expression": "navigator.onLine", "returnByValue": true }- })- .to_string()- .into(),- ))- .await- .expect("send navigator.onLine evaluate");- let on_line = recv_until_id(&mut socket, 7).await;- let on_line_response = on_line- .iter()- .find(|message| message["id"] == json!(7_u64))- .expect("navigator.onLine response");- assert_eq!(- on_line_response["result"]["result"]["value"],- json!(true),- "navigator.onLine should stay true on a loopback page; got {on_line_response}"- );+ // The committed error Document keeps the target responsive.+ let value =+ cdp_runtime_evaluate_string(&mut socket, &session.session_id, 7, "String(1 + 1)").await;+ assert_eq!(value, "2");- // Subresource fetches to the loopback fixture also succeed while offline- // emulation stays active, because the committed document is online.- socket- .send(WsMessage::Text(- json!({- "id": 8_u64,- "method": "Runtime.evaluate",- "sessionId": session_id,- "params": {- "expression": "fetch('/probe').then((r) => r.text()).catch(() => 'offline')",- "awaitPromise": true,- "returnByValue": true- }- })- .to_string()- .into(),- ))- .await- .expect("send loopback fetch evaluate");- let fetched = recv_until_id(&mut socket, 8).await;- let fetch_response = fetched- .iter()- .find(|message| message["id"] == json!(8_u64))- .expect("loopback fetch response");- assert_eq!(- fetch_response["result"]["result"]["value"],- json!("pong"),- "loopback subresource fetch must succeed while offline; got {fetch_response}"+ // Restoring offline:false lets the same loopback navigation succeed.+ let restore = send_cdp_command(+ &mut socket,+ 8,+ "Network.emulateNetworkConditions",+ Some(&session.session_id),+ json!({+ "offline": false,+ "latency": 0,+ "downloadThroughput": -1,+ "uploadThroughput": -1+ }),+ )+ .await;+ assert!(+ restore+ .iter()+ .any(|message| message["id"] == json!(8_u64) && message.get("error").is_none()),+ "offline:false should be accepted: {restore:?}");- // Restoring offline:false is accepted and the target stays responsive.- socket- .send(WsMessage::Text(- json!({- "id": 9_u64,- "method": "Network.emulateNetworkConditions",- "sessionId": session_id,- "params": {- "offline": false,- "latency": 0,- "downloadThroughput": -1,- "uploadThroughput": -1- }- })- .to_string()- .into(),- ))- .await- .expect("send offline restore");- let restore = recv_until_id(&mut socket, 9).await;- let restore_response = restore+ let reloaded = send_cdp_command(+ &mut socket,+ 9,+ "Page.navigate",+ Some(&session.session_id),+ json!({ "url": fixture_url }),+ )+ .await;+ let reloaded_response = reloaded.iter().find(|message| message["id"] == json!(9_u64))- .expect("offline restore response");+ .expect("recovered Page.navigate response");assert!(- restore_response.get("error").is_none(),- "offline:false must be accepted; got {restore_response}"+ reloaded_response.get("error").is_none(),+ "navigation after offline:false must succeed; got {reloaded_response:#?}");-- socket- .send(WsMessage::Text(- json!({- "id": 10_u64,- "method": "Runtime.evaluate",- "sessionId": session_id,- "params": { "expression": "1 + 1", "returnByValue": true }- })- .to_string()- .into(),- ))- .await- .expect("send post-restore evaluate");- let restored = recv_until_id(&mut socket, 10).await;- let restored_response = restored- .iter()- .find(|message| message["id"] == json!(10_u64))- .expect("post-restore evaluate response");- assert_eq!(- restored_response["result"]["result"]["value"],- json!(2),- "target must remain responsive after restoring offline; got {restored_response}"+ assert!(+ reloaded_response["result"]+ .get("errorText")+ .is_none_or(|value| value.is_null()),+ "a recovered navigation must not report an errorText; got {reloaded_response:#?}");+ let body = cdp_runtime_evaluate_string(+ &mut socket,+ &session.session_id,+ 10,+ "document.querySelector('#probe')?.textContent ?? ''",+ )+ .await;+ assert_eq!(body, "online");let _ = socket.close(None).await;abort_test_cdp_server(protocol_server).await;diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rsindex fe02e2c1a..fd0a67fb8 100644--- a/moli-protocol/src/conn/runtime_load.rs+++ b/moli-protocol/src/conn/runtime_load.rs@@ -30,6 +30,7 @@ use crate::domains::network::{const BLOCKED_BY_CLIENT_ERROR_TEXT: &str = "net::ERR_BLOCKED_BY_CLIENT";const HTTP_RESPONSE_CODE_FAILURE_ERROR_TEXT: &str = "net::ERR_HTTP_RESPONSE_CODE_FAILURE";+const NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT: &str = "net::ERR_INTERNET_DISCONNECTED";const CAPTURED_RAW_REPLAY_CHUNK_SIZE: usize = 64 * 1024;fn apply_navigation_request_load_policy(@@ -858,11 +859,31 @@ impl BackgroundNavigationLoadJob {}ensure_url_not_blocked_for_load_inputs(&self.load_inputs, &self.raw_url)?;- if network_offline_blocks_url(self.load_inputs.network_offline, &self.raw_url) {- return Err("Network emulation offline".to_owned());- }if self.load_inputs.network_offline {- self.load_inputs.network_offline = false;+ // Emulated offline is a network failure, not a protocol error.+ // Report it like any other transport failure: commit a+ // browser-owned error page so Page.navigate resolves with an+ // `errorText` and the target stays responsive (Chromium+ // reports net::ERR_INTERNET_DISCONNECTED here).+ let requested_url = Url::parse(&self.raw_url).map_err(|error| {+ format!("failed to parse request url `{}`: {error}", self.raw_url)+ })?;+ tracing::debug!(+ url = %self.raw_url,+ network_error_text = NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT,+ "main document blocked by emulated offline conditions"+ );+ return prepare_network_error_page_navigation_with_engine_async(+ &mut engine,+ self.page_reservation,+ &self.load_inputs,+ requested_url,+ self.method,+ self.request_headers,+ NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned(),+ RendererReplyBoundary::DocumentCommit,+ )+ .await;}let requested_url = Url::parse(&self.raw_url).map_err(|error| {@@ -1565,7 +1586,7 @@ impl CdpConnection {document_activity: load_inputs.document_activity,browser_resource_runtime,navigator_identity,- network_offline: load_inputs.network_offline && !url_is_loopback(final_url),+ network_offline: load_inputs.network_offline,bypass_service_worker: load_inputs.bypass_service_worker,cache_disabled: load_inputs.cache_disabled,blocked_url_patterns: load_inputs.blocked_url_patterns,@@ -2283,7 +2304,7 @@ impl CdpConnection {async fn load_navigation_request_via_runtime_with_network_events_and_load_inputs_async(&mut self,owner: &CommandOwnerScope,- mut load_inputs: TargetNavigationLoadInputs,+ load_inputs: TargetNavigationLoadInputs,method: &str,raw_url: &str,body: Option<Vec<u8>>,@@ -2354,11 +2375,8 @@ impl CdpConnection {}ensure_url_not_blocked_for_load_inputs(&load_inputs, raw_url)?;- if network_offline_blocks_url(load_inputs.network_offline, raw_url) {- return Err("Network emulation offline".to_owned());- }if load_inputs.network_offline {- load_inputs.network_offline = false;+ return Err(NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned());}let requested_url = Url::parse(raw_url)@@ -2971,8 +2989,8 @@ impl CdpConnection {) -> Result<NetworkFetchResult<NavigationResponse>, String> {let load_inputs = self.navigation_load_inputs_for_session_owner(None);ensure_url_not_blocked_for_load_inputs(&load_inputs, raw_url)?;- if network_offline_blocks_url(load_inputs.network_offline, raw_url) {- return Err("Network emulation offline".to_owned());+ if load_inputs.network_offline {+ return Err(NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned());}let resource_storage = load_inputs.resource_storage_handles();let engine = self@@ -3011,8 +3029,8 @@ impl CdpConnection {request_load_policy,);ensure_url_not_blocked_for_load_inputs(&load_inputs, raw_url)?;- if network_offline_blocks_url(load_inputs.network_offline, raw_url) {- return Err("Network emulation offline".to_owned());+ if load_inputs.network_offline {+ return Err(NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned());}let mut request = Request::new_browser_bytes(@@ -3103,8 +3121,8 @@ impl CdpConnection {auth: Option<SubresourceAuthCredentials>,) -> Result<NetworkFetchResult<StreamingRawResponse>, String> {ensure_url_not_blocked_for_load_inputs(load_inputs, raw_url)?;- if network_offline_blocks_url(load_inputs.network_offline, raw_url) {- return Err("Network emulation offline".to_owned());+ if load_inputs.network_offline {+ return Err(NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned());}let mut request = Request::new_browser_bytes(@@ -3903,33 +3921,6 @@ fn ensure_url_not_blocked_for_load_inputs(}}-/// Chromium does not hard-block loopback navigations under emulated offline-/// conditions (`Network.emulateNetworkConditions {offline:true}`); requests-/// to `localhost`/`*.localhost` and loopback IPs keep working while the page-/// is otherwise offline. Match that quirk so loopback navigations proceed.-fn url_is_loopback(url: &Url) -> bool {- match url.host() {- Some(url::Host::Ipv4(ip)) => ip.is_loopback(),- Some(url::Host::Ipv6(ip)) => ip.is_loopback(),- Some(url::Host::Domain(domain)) => {- let domain = domain.trim_end_matches('.');- let domain = domain.to_ascii_lowercase();- domain == "localhost" || domain.ends_with(".localhost")- }- None => false,- }-}--/// Resolves whether the emulated network-offline policy should block a-/// navigation to `raw_url`. Loopback destinations are exempt so that a-/// navigation to a local fixture proceeds like Chromium.-fn network_offline_blocks_url(network_offline: bool, raw_url: &str) -> bool {- network_offline- && Url::parse(raw_url)- .map(|url| !url_is_loopback(&url))- .unwrap_or(true)-}-#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum NavigationLoadInputOverrideMode {FreshlyBuiltPage,@@ -3973,10 +3964,9 @@ mod tests {use super::{BackgroundNavigationEarlyResult, decode_data_url_body, decode_data_url_response,decode_text_html_data_url, decoded_data_url_navigation_response,- inline_html_navigation_source, network_offline_blocks_url, url_is_loopback,+ inline_html_navigation_source,};use serde_json::json;- use url::Url;#[test]fn decode_text_html_data_url_uses_data_url_processor() {@@ -4099,70 +4089,4 @@ mod tests {}));}-- #[test]- fn url_is_loopback_accepts_local_hosts_and_loopback_addresses() {- for url in [- "http://localhost/",- "http://localhost:8765/page.html",- "http://LOCALHOST/",- "http://localhost./",- "http://app.localhost/page",- "http://127.0.0.1/",- "http://127.0.0.1:8765/page.html",- "http://127.0.0.2/",- "http://[::1]/",- "http://[::1]:8765/page.html",- ] {- let parsed = Url::parse(url).expect(url);- assert!(- url_is_loopback(&parsed),- "expected `{url}` to be treated as loopback"- );- }- }-- #[test]- fn url_is_loopback_rejects_remote_hosts_and_schemeless_urls() {- for url in [- "http://example.test/",- "http://example.test:8765/offline",- "https://example.com/",- "http://8.8.8.8/",- "http://192.168.1.10/",- "http://localhost.evil.example/",- "about:blank",- "data:text/html,hello",- ] {- let parsed = Url::parse(url).expect(url);- assert!(- !url_is_loopback(&parsed),- "expected `{url}` not to be treated as loopback"- );- }- }-- #[test]- fn network_offline_blocks_url_exempts_loopback_destinations_only() {- assert!(network_offline_blocks_url(true, "http://example.test/"));- assert!(network_offline_blocks_url(- true,- "http://example.test/offline"- ));- assert!(network_offline_blocks_url(true, "http://8.8.8.8/"));- assert!(!network_offline_blocks_url(- true,- "http://127.0.0.1:8765/page.html"- ));- assert!(!network_offline_blocks_url(- true,- "http://localhost/page.html"- ));- assert!(!network_offline_blocks_url(true, "http://[::1]/"));- assert!(!network_offline_blocks_url(false, "http://example.test/"));- assert!(!network_offline_blocks_url(- false,- "http://127.0.0.1:8765/page.html"- ));- }}diff --git a/moli-protocol/src/domains/fetch/tests/navigation_control.rs b/moli-protocol/src/domains/fetch/tests/navigation_control.rsindex 8bfedeef0..9227b47d1 100644--- a/moli-protocol/src/domains/fetch/tests/navigation_control.rs+++ b/moli-protocol/src/domains/fetch/tests/navigation_control.rs@@ -363,8 +363,11 @@ async fn request_paused_then_continue_request_fails_when_network_offline() {let failed = ctx.take_one();assert_eq!(failed["method"], "Network.loadingFailed");assert_eq!(failed["sessionId"], "SID-1");- assert_eq!(failed["params"]["errorText"], "Network emulation offline");- ctx.expect_error(16632, -32000, "Network emulation offline");+ assert_eq!(+ failed["params"]["errorText"],+ "net::ERR_INTERNET_DISCONNECTED"+ );+ ctx.expect_error(16632, -32000, "net::ERR_INTERNET_DISCONNECTED");}#[tokio::test(flavor = "multi_thread")]diff --git a/moli-protocol/src/domains/network/tests/blocked_urls.rs b/moli-protocol/src/domains/network/tests/blocked_urls.rsindex 27fb8e82d..0566e5f59 100644--- a/moli-protocol/src/domains/network/tests/blocked_urls.rs+++ b/moli-protocol/src/domains/network/tests/blocked_urls.rs@@ -1319,7 +1319,7 @@ async fn emulate_network_conditions_updates_browser_context_state() {assert!(bc.active_page_target().network_policy.network_offline());}#[tokio::test(flavor = "multi_thread")]-async fn emulate_network_conditions_offline_navigation_fails_before_completion_events() {+async fn emulate_network_conditions_offline_navigation_commits_error_document() {let mut ctx = TestContext::new();let mut bc = BrowserContext::new("BID-1".into());bc.set_active_target_id("TID-1");@@ -1328,6 +1328,7 @@ async fn emulate_network_conditions_offline_navigation_fails_before_completion_e.runtime_slot.enable_primary_network_events();ctx.conn.install_browser_context_fixture_for_test(bc);+ ctx.enable_page_events_for_test(Some("SID-1"));ctx.process_async(json!({"id": 31,@@ -1349,16 +1350,93 @@ async fn emulate_network_conditions_offline_navigation_fails_before_completion_e"params": { "url": "http://example.test/offline" }})).await;+ wait_until_messages(+ &mut ctx,+ Some("SID-1"),+ "offline error Document load",+ |messages| {+ messages+ .iter()+ .any(|message| message["method"] == json!("Page.loadEventFired"))+ },+ )+ .await;- consume_main_document_navigation_start(&mut ctx);- let request = ctx.take_one();- assert_eq!(request["method"], "Network.requestWillBeSent");- let failed = ctx.take_one();- assert_eq!(failed["method"], "Network.loadingFailed");- assert_eq!(failed["sessionId"], "SID-1");- assert_eq!(failed["params"]["errorText"], "Network emulation offline");- ctx.expect_error(32, -32000, "Network emulation offline");- assert!(ctx.sent.is_empty());+ let messages = ctx.take_all();+ let request_index = messages+ .iter()+ .position(|message| {+ message["method"] == json!("Network.requestWillBeSent")+ && message["sessionId"] == json!("SID-1")+ })+ .unwrap_or_else(|| panic!("missing document request: {messages:?}"));+ let request = &messages[request_index];+ assert_eq!(request["params"]["frameId"], "TID-1");+ let request_id = request["params"]["requestId"]+ .as_str()+ .expect("request id")+ .to_owned();++ let failed_index = messages+ .iter()+ .position(|message| {+ message["method"] == json!("Network.loadingFailed")+ && message["sessionId"] == json!("SID-1")+ && message["params"]["requestId"] == json!(request_id)+ })+ .unwrap_or_else(|| panic!("missing document loadingFailed: {messages:?}"));+ let failed = &messages[failed_index];+ assert_eq!(failed["params"]["requestId"], request_id);+ assert_eq!(failed["params"]["type"], "Document");+ assert_eq!(failed["params"]["canceled"], false);+ assert_eq!(+ failed["params"]["errorText"],+ "net::ERR_INTERNET_DISCONNECTED"+ );+ assert!(+ request_index < failed_index,+ "requestWillBeSent must precede loadingFailed: {messages:?}"+ );++ let response = messages+ .iter()+ .find(|message| message["id"] == json!(32))+ .expect("Page.navigate response");+ assert!(+ response.get("error").is_none(),+ "offline navigation must not return a protocol error; got {response}"+ );+ assert_eq!(response["result"]["frameId"], "TID-1");+ assert!(response["result"]["loaderId"].is_string());+ assert_eq!(response["result"]["isDownload"], false);+ assert_eq!(+ response["result"]["errorText"],+ "net::ERR_INTERNET_DISCONNECTED"+ );++ let frame_index = messages+ .iter()+ .position(|message| {+ message["method"] == json!("Page.frameNavigated")+ && message["sessionId"] == json!("SID-1")+ })+ .unwrap_or_else(|| panic!("missing error Document frame commit: {messages:?}"));+ assert!(+ failed_index < frame_index,+ "loadingFailed must precede the error Document frame commit: {messages:?}"+ );+ let finished_index = messages+ .iter()+ .position(|message| {+ message["method"] == json!("Network.loadingFinished")+ && message["sessionId"] == json!("SID-1")+ && message["params"]["requestId"] == json!(request_id)+ })+ .unwrap_or_else(|| panic!("missing error Document loadingFinished: {messages:?}"));+ assert!(+ frame_index < finished_index,+ "frame commit must precede error Document loadingFinished: {messages:?}"+ );}#[tokio::test(flavor = "multi_thread")]async fn emulate_network_conditions_offline_runtime_fetch_emits_loading_failed() {diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rsindex 71b2361d5..18586eb89 100644--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs@@ -1669,9 +1669,13 @@ async fn same_context_background_session_can_stage_its_own_network_conditions_be.await;consume_main_document_navigation_start(&mut ctx);let activated_navigation = take_response_by_id(&mut ctx, 10419456);+ assert!(+ activated_navigation.get("error").is_none(),+ "offline navigation must not return a protocol error; got {activated_navigation}"+ );assert_eq!(- activated_navigation["error"]["message"],- json!("Network emulation offline")+ activated_navigation["result"]["errorText"],+ json!("net::ERR_INTERNET_DISCONNECTED"));}diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs b/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rsindex d860a9738..efaf1ea06 100644--- a/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs+++ b/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs@@ -357,9 +357,13 @@ async fn same_context_targets_restore_their_own_network_conditions_after_session.await;consume_main_document_navigation_start(&mut ctx);let second_error = take_response_by_id(&mut ctx, 104169273);+ assert!(+ second_error.get("error").is_none(),+ "offline navigation must not return a protocol error; got {second_error}"+ );assert_eq!(- second_error["error"]["message"],- json!("Network emulation offline")+ second_error["result"]["errorText"],+ json!("net::ERR_INTERNET_DISCONNECTED"));{