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(fetch): invoke wait-script function predicates
ldm0b959a0425387
diff --git a/moli-core/src/runtime/mod.rs b/moli-core/src/runtime/mod.rsindex d1e80f59d..6981bfdc2 100644--- a/moli-core/src/runtime/mod.rs+++ b/moli-core/src/runtime/mod.rs@@ -684,6 +684,9 @@ impl Browser {.await}+ /// Waits until `expression` is truthy. When it evaluates to a function,+ /// the function is invoked without arguments as the predicate on each+ /// polling turn; a returned Promise is awaited.pub async fn wait_for_script_truthy(&self,page: &mut Page,@@ -695,7 +698,8 @@ impl Browser {}/// Waits for a truthy script result using the unspent portion of- /// `deadline`.+ /// `deadline`. Function results are invoked as zero-argument predicates,+ /// and returned Promises are awaited.pub async fn wait_for_script_truthy_with_deadline(&self,page: &mut Page,diff --git a/moli-core/src/runtime/tests.rs b/moli-core/src/runtime/tests.rsindex 4ff4f66c0..aafe1dc1c 100644--- a/moli-core/src/runtime/tests.rs+++ b/moli-core/src/runtime/tests.rs@@ -2778,6 +2778,59 @@ async fn wait_for_script_truthy_awaits_promise_result() -> Result<()> {Ok(())}+#[tokio::test(flavor = "multi_thread")]+async fn wait_for_script_truthy_invokes_function_predicate_each_poll() -> Result<()> {+ let server = FixtureServer::spawn().await?;+ let browser = Browser::new(AppConfig::default())?;++ let mut page = browser+ .fetch_with_wait_until(+ &server.url("/static"),+ RenderedDomWaitUntil::Load,+ Duration::from_secs(5),+ )+ .await?;++ page.evaluate_runtime_expression_async("globalThis.__waitPredicateCalls = 0")+ .await?;+ browser+ .wait_for_script_truthy(+ &mut page,+ "globalThis.__waitPredicateCalls += 1, globalThis.__waitPredicateCalls >= 2",+ Duration::from_secs(2),+ )+ .await?;+ let expression_calls = page+ .evaluate_runtime_expression_async("globalThis.__waitPredicateCalls")+ .await?["value"]+ .as_f64()+ .expect("expression call count should be numeric");+ assert!(+ expression_calls >= 2.0,+ "comma expression changed meaning inside the predicate wrapper: {expression_calls}"+ );++ page.evaluate_runtime_expression_async("globalThis.__waitPredicateCalls = 0")+ .await?;+ browser+ .wait_for_script_truthy(+ &mut page,+ "() => ++globalThis.__waitPredicateCalls >= 2",+ Duration::from_secs(2),+ )+ .await?;++ let calls = page+ .evaluate_runtime_expression_async("globalThis.__waitPredicateCalls")+ .await?["value"]+ .as_f64()+ .expect("predicate call count should be numeric");+ assert!(calls >= 2.0, "function predicate was not polled: {calls}");++ server.shutdown().await;+ Ok(())+}+#[tokio::test(flavor = "multi_thread")]async fn wait_for_script_truthy_wakes_after_async_wasm_compile_tasks() -> Result<()> {let server = FixtureServer::spawn().await?;@@ -2819,7 +2872,8 @@ async fn wait_for_script_truthy_wakes_after_async_wasm_compile_tasks() -> Result}#[tokio::test(flavor = "multi_thread")]-async fn wait_for_script_truthy_times_out_for_false_predicate() -> Result<()> {+async fn wait_for_script_truthy_times_out_for_false_expression_and_function_predicate() -> Result<()>+{let server = FixtureServer::spawn().await?;let browser = Browser::new(AppConfig::default())?;@@ -2831,15 +2885,18 @@ async fn wait_for_script_truthy_times_out_for_false_predicate() -> Result<()> {).await?;- let error = browser- .wait_for_script_truthy(&mut page, "false", Duration::from_millis(150))- .await- .unwrap_err();- assert!(- error- .to_string()- .contains("timed out waiting for script to become truthy")- );+ for predicate in ["false", "() => false", "async () => false"] {+ let error = browser+ .wait_for_script_truthy(&mut page, predicate, Duration::from_millis(150))+ .await+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("timed out waiting for script to become truthy"),+ "unexpected error for `{predicate}`: {error:#}"+ );+ }server.shutdown().await;Ok(())diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rsindex 779deb775..b7d786d7f 100644--- a/moli-renderer-v8/src/runtime/page_dom.rs+++ b/moli-renderer-v8/src/runtime/page_dom.rs@@ -1652,7 +1652,14 @@ impl PageVm {pending_call: Option<PendingRuntimeEvaluateCall>,remaining: std::time::Duration,) -> Result<PageVmScriptTruthyWaitAdvance> {- let evaluation = self.advance_runtime_evaluate(None, expression, pending_call)?;+ // Match the predicate convention used by browser automation APIs: a+ // callable result is the predicate, not a truthy value in its own+ // right. Keeping the invocation inside the evaluated expression also+ // lets Runtime.evaluate await a Promise returned by the predicate.+ // The source is evaluated exactly once per polling turn.+ let predicate_expression = script_truthy_predicate_expression(expression);+ let evaluation =+ self.advance_runtime_evaluate(None, &predicate_expression, pending_call)?;let evaluation = match evaluation {RuntimeEvaluateOutcome::Pending(pending_call) => {return self@@ -4178,6 +4185,10 @@ fn rounded_css_integer(value: f32) -> i32 {value.round().clamp(i32::MIN as f32, i32::MAX as f32) as i32}+fn script_truthy_predicate_expression(expression: &str) -> String {+ format!("((value) => typeof value === 'function' ? value() : value)(\n(\n{expression}\n)\n)")+}+fn evaluation_payload_is_truthy(payload: &Value) -> bool {if payload.get("exception").is_some() {return false;diff --git a/moli/src/cli.rs b/moli/src/cli.rsindex 089ee8538..d6225e8f4 100644--- a/moli/src/cli.rs+++ b/moli/src/cli.rs@@ -85,9 +85,12 @@ pub struct FetchArgs {#[arg(long)]pub wait_selector: Option<String>,+ /// Wait until a JavaScript expression is truthy. A function result is+ /// invoked without arguments as the predicate on each polling turn.#[arg(long)]pub wait_script: Option<String>,+ /// Read the JavaScript wait expression or function predicate from a file.#[arg(long)]pub wait_script_file: Option<String>,diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rsindex a2d5756eb..3a6027370 100644--- a/moli/tests/fetch_cli.rs+++ b/moli/tests/fetch_cli.rs@@ -1947,7 +1947,7 @@ fn cli_readiness_timeout_identifies_response_selector_and_script_phases() -> Reslet runtime = tokio::runtime::Runtime::new()?;let server = runtime.block_on(FixtureServer::spawn())?;let url = server.url("/static");- let cases: [(&[&str], &str); 3] = [+ let cases: [(&[&str], &str); 4] = [(&["--wait-response-url", "/response-that-never-arrives"],"fetch readiness timed out after 350 ms while waiting for a subresource response",@@ -1960,6 +1960,10 @@ fn cli_readiness_timeout_identifies_response_selector_and_script_phases() -> Res&["--wait-script", "globalThis.scriptThatNeverBecomesTruthy"],"fetch readiness timed out after 350 ms while waiting for a script to become truthy",),+ (+ &["--wait-script", "() => false"],+ "fetch readiness timed out after 350 ms while waiting for a script to become truthy",+ ),];for (args, expected_phase) in cases {diff --git a/skills/moli-webfetch/references/fetch-recipes.md b/skills/moli-webfetch/references/fetch-recipes.mdindex bb42b34ae..0c7bef55b 100644--- a/skills/moli-webfetch/references/fetch-recipes.md+++ b/skills/moli-webfetch/references/fetch-recipes.md@@ -41,8 +41,9 @@ a better completion signal:the DOM continuously.- `--wait-selector '<css>'`: wait for a stable content element. Prefer this forclient-rendered lists, articles, and results.-- `--wait-script '<expression>'`: wait for a JavaScript expression to become- truthy.+- `--wait-script '<expression-or-function>'`: wait for a JavaScript expression+ to become truthy. If it evaluates to a function, Moli invokes it without+ arguments on every poll, so `() => window.__ready` is supported.- `--wait-script-file <path>`: use a reusable or multiline condition. It ismutually exclusive with `--wait-script`.- `--wait-response-url <substring>`: wait for an application request whose URL