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): preserve navigation failure context at protocol boundaries

ldm03ae44b515075
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index 995ab9c34..ef009261a 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -499,7 +499,9 @@ impl CommandDispatchContext {
}
pub(crate) use moli_protocol_cdp::{DEFAULT_LOADER_ID, monotonic_timestamp_seconds};
-pub use navigation_error::NavigationNetworkError;
+pub(crate) use navigation_error::{
+ NavigationNetworkError, NavigationNetworkErrorKind, NavigationRequestBlocked,
+};
pub(crate) use output::NavigationBackgroundEvent;
pub use output::{
BackgroundCommandResponsePayload, BackgroundEventSender, BackgroundProtocolEvent,
diff --git a/moli-protocol/src/conn/navigation_error.rs b/moli-protocol/src/conn/navigation_error.rs
index 4ce96c751..6f7889366 100644
--- a/moli-protocol/src/conn/navigation_error.rs
+++ b/moli-protocol/src/conn/navigation_error.rs
@@ -2,23 +2,56 @@ use std::{error::Error, fmt};
use url::Url;
-/// A failed navigation request, captured where the network policy is enforced.
+/// Network policy failures produced by the navigation request loaders.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum NavigationNetworkErrorKind {
+ InternetDisconnected,
+}
+
+impl NavigationNetworkErrorKind {
+ pub(crate) fn error_text(self) -> &'static str {
+ match self {
+ Self::InternetDisconnected => "net::ERR_INTERNET_DISCONNECTED",
+ }
+ }
+}
+
+/// A navigation request rejected by emulated offline network policy.
+///
+/// Transport failures retain `moli_fetch::NetworkFetchFailureContext` and use
+/// their existing handling paths; this cause currently represents offline
+/// enforcement only.
///
/// This is an error cause rather than display context, so callers can recover
/// its request identity through `anyhow::Error::downcast_ref` after adding
/// diagnostic context along the navigation pipeline.
#[derive(Debug)]
-pub struct NavigationNetworkError {
- pub error_text: String,
- pub unreachable_url: Url,
- pub request_method: String,
- pub request_headers: Vec<(String, String)>,
+pub(crate) struct NavigationNetworkError {
+ pub(crate) kind: NavigationNetworkErrorKind,
+ pub(crate) unreachable_url: Url,
+ pub(crate) request_method: String,
+ pub(crate) request_headers: Vec<(String, String)>,
}
impl fmt::Display for NavigationNetworkError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
- formatter.write_str(&self.error_text)
+ formatter.write_str(self.kind.error_text())
}
}
impl Error for NavigationNetworkError {}
+
+/// A navigation request rejected by `Network.setBlockedURLs`.
+///
+/// The protocol boundary preserves its canonical error text independently of
+/// diagnostic context on other navigation failures.
+#[derive(Debug)]
+pub(crate) struct NavigationRequestBlocked;
+
+impl fmt::Display for NavigationRequestBlocked {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("net::ERR_BLOCKED_BY_CLIENT")
+ }
+}
+
+impl Error for NavigationRequestBlocked {}
diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rs
index 61039a4d0..999cf11c8 100644
--- a/moli-protocol/src/conn/runtime_load.rs
+++ b/moli-protocol/src/conn/runtime_load.rs
@@ -29,9 +29,7 @@ use crate::domains::network::{
MainDocumentBodyProgressSource,
};
-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(
@@ -898,7 +896,7 @@ impl BackgroundNavigationLoadJob {
.with_context(|| format!("failed to parse request url `{}`", self.raw_url))?;
tracing::debug!(
url = %self.raw_url,
- network_error_text = NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT,
+ network_error_text = NavigationNetworkErrorKind::InternetDisconnected.error_text(),
"main document blocked by emulated offline conditions"
);
return prepare_network_error_page_navigation_with_engine_async(
@@ -908,7 +906,7 @@ impl BackgroundNavigationLoadJob {
requested_url,
self.method,
self.request_headers,
- NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned(),
+ NavigationNetworkErrorKind::InternetDisconnected.error_text().to_owned(),
RendererReplyBoundary::DocumentCommit,
)
.await;
@@ -2345,7 +2343,7 @@ impl CdpConnection {
network_error.unreachable_url.clone(),
network_error.request_method.clone(),
network_error.request_headers.clone(),
- network_error.error_text.clone(),
+ network_error.kind.error_text().to_owned(),
RendererReplyBoundary::Stage,
)
.await
@@ -3952,7 +3950,7 @@ fn validate_navigation_network_request(
let requested_url = Url::parse(raw_url)
.with_context(|| format!("failed to parse request url `{raw_url}`"))?;
return Err(NavigationNetworkError {
- error_text: NET_ERR_INTERNET_DISCONNECTED_ERROR_TEXT.to_owned(),
+ kind: NavigationNetworkErrorKind::InternetDisconnected,
unreachable_url: requested_url,
request_method: method.to_owned(),
request_headers: request_headers.to_vec(),
@@ -3971,7 +3969,7 @@ fn ensure_url_not_blocked_for_load_inputs(
.iter()
.any(|pattern| url_pattern_matches(pattern, raw_url))
{
- Err(anyhow::anyhow!(BLOCKED_BY_CLIENT_ERROR_TEXT))
+ Err(NavigationRequestBlocked.into())
} else {
Ok(())
}
diff --git a/moli-protocol/src/conn/tests/navigation_error.rs b/moli-protocol/src/conn/tests/navigation_error.rs
index 631422463..4ead270f3 100644
--- a/moli-protocol/src/conn/tests/navigation_error.rs
+++ b/moli-protocol/src/conn/tests/navigation_error.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::conn::{
- CommandOwnerScope, NavigationLoadOutcome, NavigationNetworkError, NavigationRequestLoadPolicy,
+ CommandOwnerScope, NavigationLoadOutcome, NavigationNetworkError, NavigationNetworkErrorKind,
+ NavigationRequestLoadPolicy,
};
use moli_core::page::{SubresourceAuthCredentials, SubresourceAuthScheme, SubresourceAuthTarget};
@@ -196,7 +197,11 @@ async fn offline_navigation_loaders_preserve_typed_error_causes_through_context(
let network_error = error
.downcast_ref::<NavigationNetworkError>()
.expect("navigation request identity must survive diagnostic context");
- assert_eq!(network_error.error_text, OFFLINE_ERROR_TEXT);
+ assert_eq!(
+ network_error.kind,
+ NavigationNetworkErrorKind::InternetDisconnected
+ );
+ assert_eq!(network_error.to_string(), OFFLINE_ERROR_TEXT);
assert_eq!(network_error.unreachable_url, navigation.requested_url);
assert_eq!(network_error.request_method, *method);
assert_eq!(network_error.request_headers, *headers);
@@ -210,10 +215,10 @@ async fn offline_navigation_loaders_preserve_typed_error_causes_through_context(
#[tokio::test(flavor = "multi_thread")]
async fn navigation_error_document_uses_typed_failure_request_after_context() {
let (mut ctx, navigation) = navigation_fixture();
- let unreachable_url = Url::parse("https://redirect.example/unreachable").unwrap();
- let request_headers = vec![("x-request".to_owned(), "failed-hop".to_owned())];
+ let unreachable_url = Url::parse("https://overridden.example/unreachable").unwrap();
+ let request_headers = vec![("x-request".to_owned(), "overridden-request".to_owned())];
let error = anyhow::Error::new(NavigationNetworkError {
- error_text: OFFLINE_ERROR_TEXT.to_owned(),
+ kind: NavigationNetworkErrorKind::InternetDisconnected,
unreachable_url: unreachable_url.clone(),
request_method: "POST".to_owned(),
request_headers: request_headers.clone(),
diff --git a/moli-protocol/src/domains/activity/main_document.rs b/moli-protocol/src/domains/activity/main_document.rs
index e3eb32a65..cf81a7d54 100644
--- a/moli-protocol/src/domains/activity/main_document.rs
+++ b/moli-protocol/src/domains/activity/main_document.rs
@@ -1144,30 +1144,97 @@ mod tests {
);
}
- #[test]
- fn failed_cdp_navigation_returns_error_text_result_after_network_terminal() {
+ fn failed_navigation_messages(navigation: anyhow::Result<NavigationLoadOutcome>) -> Vec<Value> {
+ let mut conn = CdpConnection::new();
+ let mut browser_context = BrowserContext::new("BID-1".to_owned());
+ browser_context.set_active_target_id("TID-page");
+ browser_context.attach_active_session("SID-page");
+ browser_context
+ .active_page_target_mut()
+ .runtime_slot
+ .enable_primary_network_events();
+ conn.install_browser_context_fixture_for_test(browser_context);
+
+ let state = navigation_state();
+ let MaterializedNavigationLoadOutcome::Failed(failure) =
+ materialize_navigation_load_result(&mut conn, &state, navigation)
+ else {
+ panic!("expected failed navigation progress");
+ };
let mut output = CommandOutputBuffer::default();
MainDocumentFailedNavigationActivity::new(
- navigation_state(),
- empty_main_document_progress_gate_for_test(),
- FailedNavigationResponseMode::CdpErrorTextResult,
+ state,
+ failure.progress_gate,
+ failure.response_mode,
)
- .emit_navigation_error_into_buffer(&mut output, "net::ERR_CONNECTION_RESET");
+ .emit_navigation_error_into_buffer(&mut output, &failure.error_text);
let mut messages = Vec::new();
output
.into_plan()
.emit_into(&mut messages, Some(77), Some("SID-nav"));
+ messages
+ }
- assert_eq!(messages.len(), 1);
- assert_eq!(messages[0]["id"], json!(77));
- assert_eq!(messages[0]["result"]["frameId"], json!("FRAME-1"));
- assert_eq!(messages[0]["result"]["loaderId"], json!("LID-1"));
+ fn assert_failed_navigation_terminal(messages: &[Value], error_text: &str) {
+ assert_eq!(messages.len(), 2);
+ assert_eq!(messages[0]["method"], json!("Network.loadingFailed"));
+ assert_eq!(messages[0]["sessionId"], json!("SID-page"));
+ assert_eq!(messages[0]["params"]["requestId"], json!("REQ-1"));
+ assert_eq!(messages[0]["params"]["errorText"], json!(error_text));
+ assert_eq!(messages[1]["id"], json!(77));
+ assert_eq!(messages[1]["sessionId"], json!("SID-nav"));
+ }
+
+ #[test]
+ fn failed_navigation_protocol_error_preserves_context_chain() {
+ let error = anyhow::Error::new(std::io::Error::new(
+ std::io::ErrorKind::ConnectionReset,
+ "connection reset by peer",
+ ))
+ .context("failed to read page body from stream")
+ .context("failed to load document")
+ .context("failed to continue intercepted navigation");
+ let messages = failed_navigation_messages(Err(error));
+ let expected = "failed to continue intercepted navigation: failed to load document: failed to read page body from stream: connection reset by peer";
+
+ assert_eq!(messages[1]["error"]["code"], json!(-32000));
+ assert_eq!(messages[1]["error"]["message"], json!(expected));
+ assert!(messages[1].get("result").is_none());
+ assert_failed_navigation_terminal(&messages, expected);
+ }
+
+ #[test]
+ fn failed_navigation_protocol_error_does_not_classify_network_display_text() {
+ for error_text in [
+ "net::ERR_INTERNET_DISCONNECTED",
+ "net::ERR_BLOCKED_BY_CLIENT",
+ ] {
+ let error = anyhow::anyhow!(error_text).context("failed to load document");
+ let messages = failed_navigation_messages(Err(error));
+ let expected = format!("failed to load document: {error_text}");
+
+ assert_eq!(messages[1]["error"]["code"], json!(-32000));
+ assert_eq!(messages[1]["error"]["message"], json!(expected));
+ assert!(messages[1].get("result").is_none());
+ assert_failed_navigation_terminal(&messages, &expected);
+ }
+ }
+
+ #[test]
+ fn failed_cdp_navigation_returns_error_text_result_after_network_terminal() {
+ let messages = failed_navigation_messages(Ok(NavigationLoadOutcome::NetworkFailure(
+ "net::ERR_CONNECTION_RESET".to_owned(),
+ )));
+
+ assert_failed_navigation_terminal(&messages, "net::ERR_CONNECTION_RESET");
+ assert_eq!(messages[1]["result"]["frameId"], json!("FRAME-1"));
+ assert_eq!(messages[1]["result"]["loaderId"], json!("LID-1"));
assert_eq!(
- messages[0]["result"]["errorText"],
+ messages[1]["result"]["errorText"],
json!("net::ERR_CONNECTION_RESET")
);
- assert_eq!(messages[0]["result"]["isDownload"], json!(false));
- assert!(messages[0].get("error").is_none());
+ assert_eq!(messages[1]["result"]["isDownload"], json!(false));
+ assert!(messages[1].get("error").is_none());
}
#[test]
diff --git a/moli-protocol/src/domains/fetch/tests/navigation_auth.rs b/moli-protocol/src/domains/fetch/tests/navigation_auth.rs
index e40b3b109..a740b27b9 100644
--- a/moli-protocol/src/domains/fetch/tests/navigation_auth.rs
+++ b/moli-protocol/src/domains/fetch/tests/navigation_auth.rs
@@ -550,21 +550,19 @@ async fn continue_with_non_basic_auth_and_intercept_response_fails_explicitly_wi
.await;
ctx.expect_result(72_203, json!({}), Some("SID-1"));
+ let expected_error = concat!(
+ "failed to continue intercepted navigation: ",
+ "Fetch response-stage interception after Negotiate authentication is not supported for navigation without buffering"
+ );
let failed = ctx.take_one();
assert_eq!(failed["method"], "Network.loadingFailed");
assert_eq!(failed["params"]["requestId"], LOADER_ID);
- assert_eq!(
- failed["params"]["errorText"],
- "Fetch response-stage interception after Negotiate authentication is not supported for navigation without buffering"
- );
+ assert_eq!(failed["params"]["errorText"], expected_error);
let navigate_error = ctx.take_one();
assert_eq!(navigate_error["id"], 72_201);
assert_eq!(navigate_error["error"]["code"], -32000);
- assert_eq!(
- navigate_error["error"]["message"],
- "Fetch response-stage interception after Negotiate authentication is not supported for navigation without buffering"
- );
+ assert_eq!(navigate_error["error"]["message"], expected_error);
assert_eq!(
request_count.load(Ordering::SeqCst),
1,
diff --git a/moli-protocol/src/domains/fetch/tests/navigation_control.rs b/moli-protocol/src/domains/fetch/tests/navigation_control.rs
index 3d935a67a..0abbf70ab 100644
--- a/moli-protocol/src/domains/fetch/tests/navigation_control.rs
+++ b/moli-protocol/src/domains/fetch/tests/navigation_control.rs
@@ -302,6 +302,76 @@ async fn fail_request_blocked_by_client_maps_main_document_navigation_to_net_err
ctx.expect_error(304, -32000, "net::ERR_BLOCKED_BY_CLIENT");
}
+#[tokio::test]
+async fn request_paused_then_continue_request_preserves_blocked_url_error_text() {
+ let mut ctx = TestContext::new();
+ ctx.conn
+ .install_browser_context_fixture_for_test(attached_browser_context());
+ ctx.process_async(json!({
+ "id": 16640,
+ "method": "Network.enable",
+ "sessionId": "SID-1"
+ }))
+ .await;
+ ctx.expect_result(16640, json!({}), Some("SID-1"));
+ ctx.process_async(json!({
+ "id": 16641,
+ "method": "Fetch.enable",
+ "sessionId": "SID-1"
+ }))
+ .await;
+ ctx.expect_result(16641, json!({}), Some("SID-1"));
+ ctx.process_async(json!({
+ "id": 16642,
+ "method": "Page.navigate",
+ "sessionId": "SID-1",
+ "params": { "url": "http://example.test/blocked/document" }
+ }))
+ .await;
+ let paused = take_main_document_request_pause(&mut ctx).await;
+ let network_id = paused["params"]["networkId"].clone();
+ assert!(network_id.is_string());
+
+ ctx.process_async(json!({
+ "id": 16643,
+ "method": "Network.setBlockedURLs",
+ "sessionId": "SID-1",
+ "params": { "urls": ["http://example.test/blocked/*"] }
+ }))
+ .await;
+ ctx.expect_result(16643, json!({}), Some("SID-1"));
+ ctx.process_async(json!({
+ "id": 16644,
+ "method": "Fetch.continueRequest",
+ "sessionId": "SID-1",
+ "params": { "requestId": paused["params"]["requestId"] }
+ }))
+ .await;
+ ctx.expect_result(16644, json!({}), Some("SID-1"));
+
+ wait_until_message(
+ &mut ctx,
+ Some("SID-1"),
+ "continued blocked navigation result",
+ |message| message["id"] == json!(16642),
+ )
+ .await;
+ let response = take_response_by_id(&mut ctx, 16642);
+ assert_eq!(response["sessionId"], "SID-1");
+ assert_eq!(response["error"]["code"], -32000);
+ assert_eq!(response["error"]["message"], "net::ERR_BLOCKED_BY_CLIENT");
+ let failed = ctx
+ .sent
+ .iter()
+ .find(|message| {
+ message["method"] == json!("Network.loadingFailed")
+ && message["sessionId"] == json!("SID-1")
+ && message["params"]["requestId"] == network_id
+ })
+ .expect("continued blocked document must emit loadingFailed");
+ assert_eq!(failed["params"]["errorText"], "net::ERR_BLOCKED_BY_CLIENT");
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn request_paused_then_continue_request_commits_offline_error_document() {
assert_continued_offline_navigation_commits_error_document(false).await;
diff --git a/moli-protocol/src/domains/network/main_document_progress/mod.rs b/moli-protocol/src/domains/network/main_document_progress/mod.rs
index 0b194101f..ae2887b2a 100644
--- a/moli-protocol/src/domains/network/main_document_progress/mod.rs
+++ b/moli-protocol/src/domains/network/main_document_progress/mod.rs
@@ -19,7 +19,7 @@ use url::Url;
use crate::conn::{
BackgroundEventSender, BackgroundProtocolEvent, CapturedBody, CdpConnection,
CompletedDownloadBodyArtifact, DownloadNavigation, LoadedNavigation, NavigationDispatchState,
- NavigationLoadOutcome, ResponseCommitReady, TargetRuntimeSlot,
+ NavigationLoadOutcome, NavigationRequestBlocked, ResponseCommitReady, TargetRuntimeSlot,
};
#[cfg(test)]
@@ -374,10 +374,14 @@ pub(crate) fn materialize_navigation_load_result(
session_id = state.owner.session_id(),
"navigation load failed"
);
+ let error_text = match error.downcast_ref::<NavigationRequestBlocked>() {
+ Some(blocked) => blocked.to_string(),
+ None => format!("{error:#}"),
+ };
MaterializedNavigationLoadOutcome::Failed(materialize_failed_navigation_progress(
conn,
state,
- error.root_cause().to_string(),
+ error_text,
FailedNavigationDocumentPolicy::InvalidateCommittedDocument,
FailedNavigationResponseMode::ProtocolError,
))