Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(webdriver): stop sync alert during page load from hanging the session
LeandroPG195a50f45b8575
diff --git a/moli-protocol-server/src/cdp_scheduler.rs b/moli-protocol-server/src/cdp_scheduler.rsindex 721274ee4..ee31eb7b5 100644--- a/moli-protocol-server/src/cdp_scheduler.rs+++ b/moli-protocol-server/src/cdp_scheduler.rs@@ -1398,7 +1398,12 @@ impl CdpScheduler {// A pre-commit navigation can legitimately have no renderer key yet// (for example while an auth challenge owns the response). Its// background command response remains the completion authority.- if !observed_download && !observed_lifecycle_protocol_event {+ // An open JavaScript dialog holds the renderer until a command answers+ // it, so the lifecycle cannot reach this milestone yet (#809).+ if !observed_download+ && !observed_lifecycle_protocol_event+ && !self.has_pending_javascript_dialog()+ {if let Some(key) = document_lifecycle_wait_key.as_ref() {let wait_state = self.conn@@ -1477,6 +1482,7 @@ impl CdpScheduler {.conn.devtools_document_lifecycle_wait_state(context, key)== moli_protocol::DevToolsDocumentLifecycleWaitState::Pending+ && !self.has_pending_javascript_dialog(){let Some(input) = receivers.recv_interleaved_input().await else {return Err(RendererOutputTransportFailure::new(@@ -1782,6 +1788,11 @@ impl CdpScheduler {if !self.has_deferred_main_document_load_completion_for_devtools_context(context) {return Ok(out);}+ // The deferred load cannot complete while a dialog blocks the renderer;+ // the next command answers the dialog instead (#809).+ if self.has_pending_javascript_dialog() {+ return Ok(out);+ }let Some(input) = receivers.recv_interleaved_input().await else {return Err(RendererOutputTransportFailure::new(out,diff --git a/moli-protocol-server/src/protocol_server/tests/classic/extracted/navigation.rs b/moli-protocol-server/src/protocol_server/tests/classic/extracted/navigation.rsindex 2570f14f0..191aa0a47 100644--- a/moli-protocol-server/src/protocol_server/tests/classic/extracted/navigation.rs+++ b/moli-protocol-server/src/protocol_server/tests/classic/extracted/navigation.rs@@ -1970,3 +1970,214 @@ async fn webdriver_classic_click_mousedown_navigation_does_not_activate_successoassert_eq!(observed, json!({"value":[1,"target",true]}));classic_request_json(app, Method::DELETE, &format!("/session/{session_id}")).await;}++const CLASSIC_SYNC_ALERT_TEXT: &str = "sync-during-load";+const CLASSIC_SYNC_ALERT_DEADLINE: Duration = Duration::from_secs(5);++async fn spawn_classic_sync_alert_fixture_server()+-> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind classic sync alert fixture server");+ let addr = listener+ .local_addr()+ .expect("classic sync alert fixture addr");+ let server = tokio::spawn(async move {+ let app = Router::new()+ .route(+ "/sync-alert",+ get(|| async {+ (+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],+ "<!doctype html><html><head><title>Sync Alert</title></head><body>\+ <script>alert(\"sync-during-load\");</script><p>after</p></body></html>",+ )+ }),+ )+ .route(+ "/control",+ get(|| async {+ (+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],+ "<!doctype html><html><head><title>Control</title></head>\+ <body><p>control</p></body></html>",+ )+ }),+ );+ axum::serve(listener, app)+ .await+ .expect("classic sync alert fixture server should serve");+ });+ (addr, server)+}++async fn classic_sync_alert_request(+ app: &Router,+ method: Method,+ path: &str,+ body: Option<serde_json::Value>,+) -> (StatusCode, serde_json::Value) {+ let request = async {+ match body {+ Some(body) => {+ classic_request_status_and_json_with_body(app.clone(), method.clone(), path, body)+ .await+ }+ None => classic_request_status_and_json(app.clone(), method.clone(), path).await,+ }+ };+ timeout(CLASSIC_SYNC_ALERT_DEADLINE, request)+ .await+ .unwrap_or_else(|_| {+ panic!(+ "{method} {path} did not respond within {CLASSIC_SYNC_ALERT_DEADLINE:?}: \+ a synchronous alert during page load must not deadlock the classic session (#809)"+ )+ })+}++async fn classic_sync_alert_session(app: &Router, capabilities: serde_json::Value) -> String {+ let (status, created) = classic_sync_alert_request(+ app,+ Method::POST,+ "/session",+ Some(json!({ "capabilities": { "alwaysMatch": capabilities } })),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "create session: {created:?}");+ created["value"]["sessionId"]+ .as_str()+ .expect("classic session id")+ .to_owned()+}++async fn classic_sync_alert_navigate(app: &Router, session_id: &str, url: &str) {+ let (status, navigated) = classic_sync_alert_request(+ app,+ Method::POST,+ &format!("/session/{session_id}/url"),+ Some(json!({ "url": url })),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "navigate to {url}: {navigated:?}");+ assert_eq!(navigated, json!({ "value": null }));+}++async fn classic_sync_alert_open_text(app: &Router, session_id: &str) {+ let (status, alert) = classic_sync_alert_request(+ app,+ Method::GET,+ &format!("/session/{session_id}/alert/text"),+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "alert text: {alert:?}");+ assert_eq!(alert, json!({ "value": CLASSIC_SYNC_ALERT_TEXT }));+}++async fn classic_sync_alert_delete(app: &Router, session_id: &str) {+ let (status, deleted) =+ classic_sync_alert_request(app, Method::DELETE, &format!("/session/{session_id}"), None)+ .await;+ assert_eq!(status, StatusCode::OK, "delete session: {deleted:?}");+}++#[tokio::test]+async fn webdriver_classic_sync_alert_during_load_does_not_deadlock_session() {+ let app = build_router(test_state());+ let (fixture_addr, fixture_server) = spawn_classic_sync_alert_fixture_server().await;+ let url = format!("http://{fixture_addr}/sync-alert");++ let session_id = classic_sync_alert_session(&app, json!({})).await;+ classic_sync_alert_navigate(&app, &session_id, &url).await;+ classic_sync_alert_open_text(&app, &session_id).await;++ let title_path = format!("/session/{session_id}/title");+ let (status, blocked) = classic_sync_alert_request(&app, Method::GET, &title_path, None).await;+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{blocked:?}");+ assert_eq!(blocked["value"]["error"], json!("unexpected alert open"));+ assert_eq!(+ blocked["value"]["data"],+ json!({ "text": CLASSIC_SYNC_ALERT_TEXT })+ );+ let (status, no_alert) = classic_sync_alert_request(+ &app,+ Method::GET,+ &format!("/session/{session_id}/alert/text"),+ None,+ )+ .await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{no_alert:?}");+ assert_eq!(no_alert["value"]["error"], json!("no such alert"));++ let (status, title) = classic_sync_alert_request(&app, Method::GET, &title_path, None).await;+ assert_eq!(status, StatusCode::OK, "{title:?}");+ assert_eq!(title, json!({ "value": "Sync Alert" }));+ let (status, parsed_after_alert) = classic_sync_alert_request(+ &app,+ Method::POST,+ &format!("/session/{session_id}/execute/sync"),+ Some(json!({+ "script": "return document.body.textContent.includes('after');",+ "args": []+ })),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{parsed_after_alert:?}");+ assert_eq!(parsed_after_alert, json!({ "value": true }));++ let accepting_session_id =+ classic_sync_alert_session(&app, json!({ "unhandledPromptBehavior": "accept" })).await;+ classic_sync_alert_navigate(&app, &accepting_session_id, &url).await;+ let (status, accepted_title) = classic_sync_alert_request(+ &app,+ Method::GET,+ &format!("/session/{accepting_session_id}/title"),+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{accepted_title:?}");+ assert_eq!(accepted_title, json!({ "value": "Sync Alert" }));++ classic_sync_alert_delete(&app, &session_id).await;+ classic_sync_alert_delete(&app, &accepting_session_id).await;+ fixture_server.abort();+}++#[tokio::test]+async fn webdriver_classic_sync_alert_during_eager_load_does_not_deadlock_session() {+ let app = build_router(test_state());+ let (fixture_addr, fixture_server) = spawn_classic_sync_alert_fixture_server().await;++ let session_id = classic_sync_alert_session(&app, json!({ "pageLoadStrategy": "eager" })).await;+ classic_sync_alert_navigate(+ &app,+ &session_id,+ &format!("http://{fixture_addr}/sync-alert"),+ )+ .await;+ classic_sync_alert_open_text(&app, &session_id).await;++ classic_sync_alert_delete(&app, &session_id).await;+ fixture_server.abort();+}++#[tokio::test]+async fn webdriver_classic_sync_alert_control_page_without_alert_responds_in_time() {+ let app = build_router(test_state());+ let (fixture_addr, fixture_server) = spawn_classic_sync_alert_fixture_server().await;++ let session_id = classic_sync_alert_session(&app, json!({})).await;+ classic_sync_alert_navigate(&app, &session_id, &format!("http://{fixture_addr}/control")).await;+ let (status, title) = classic_sync_alert_request(+ &app,+ Method::GET,+ &format!("/session/{session_id}/title"),+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{title:?}");+ assert_eq!(title, json!({ "value": "Control" }));+ classic_sync_alert_delete(&app, &session_id).await;+ fixture_server.abort();+}