Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.
Python ai-agentsanti-detectantidetect-browserbot-detectionbrowser-automationcaptcha-bypasschromiumcloudflarecloudflare-bypassfingerprintheadless-browserplaywrightpuppeteerpythonrecaptchaseleniumstealth-browserundetectedweb-scrapingwebscraping
fix(humanize): timeout= bounds every browser call when the page stops answering
CloakHQb1a00eda61ef
diff --git a/cloakbrowser/human/engine.py b/cloakbrowser/human/engine.pyindex c2b205d..2c5fab2 100644--- a/cloakbrowser/human/engine.py+++ b/cloakbrowser/human/engine.py@@ -32,7 +32,7 @@ from . import fieldsfrom .config import HumanConfig, merge_config, rand, rand_int_range, rand_log, rand_rangefrom .keyboard import NEARBY_KEYS, SHIFT_SYMBOLS, _SHIFT_SYMBOL_CODES, _SHIFT_SYMBOL_KEYCODES, key_gap, key_hold, physical_keyfrom .mouse import click_target, plan_move-from .world import HELPERS, StaleElement, Worlds, intersect+from .world import HELPERS, BoundedCalls, StaleElement, Worlds, bounded, intersect_ENTER_FRAME_SPLIT = re.compile(r"\s*>>\s*internal:control=enter-frame\s*>>\s*")@@ -282,8 +282,8 @@ class Human:self.cursor = cursorself.worlds = Worlds(page)self._typeahead_until = 0.0 # monotonic time until which the browser joins typed letters- self.mouse = page.mouse- self.keyboard = page.keyboard+ self.mouse = BoundedCalls(page.mouse)+ self.keyboard = BoundedCalls(page.keyboard)self._platform: Optional[str] = Noneself._handle_ids: Dict[str, Tuple[Any, int, int]] = {}@@ -395,7 +395,7 @@ class Human:return Resolved(frame, cached[2])# An ElementHandle carries no identity our context can read, so find# the element with exactly its border box.- box = await handle.bounding_box()+ box = await bounded(handle.bounding_box())if box is None:if exact:raise RawFallback()@@ -768,12 +768,14 @@ class Human:if trial:return rkeys = [await self._modifier(m) for m in (hold or [])]- for k in keys:- await self.keyboard.down(k)+ held: List[str] = []try:+ for k in keys:+ held.append(k)+ await self.keyboard.down(k)await self.move_to(x, y, cfg)finally:- for k in reversed(keys):+ for k in reversed(held):await self.keyboard.up(k)# The page may replace or remove the target while the cursor# travels; never press on whatever is under it now (even with@@ -794,18 +796,23 @@ class Human:modifiers: Optional[Sequence[str]] = None) -> None:mods = [await self._modifier(m) for m in (modifiers or [])]await sleep_ms(rand_range(cfg.click_aim_delay_input if is_input else cfg.click_aim_delay_button))- for m in mods:- await self.keyboard.down(m)+ held: List[str] = []try:+ for m in mods:+ held.append(m)+ await self.keyboard.down(m)for n in range(1, max(1, int(click_count)) + 1):hold = delay if delay is not None else rand_range(cfg.click_hold_input if is_input else cfg.click_hold_button)- await self.mouse.down(button=button, clickCount=n)- await sleep_ms(hold)- await self.mouse.up(button=button, clickCount=n)+ try:+ await self.mouse.down(button=button, clickCount=n)+ await sleep_ms(hold)+ finally:+ # Never leave the button down, also when the page stopped answering.+ await self.mouse.up(button=button, clickCount=n)if n < click_count:await sleep_ms(delay if delay is not None else rand(60, 140))finally:- for m in reversed(mods):+ for m in reversed(held):await self.keyboard.up(m)# -- public actions -----------------------------------------------------@@ -1074,17 +1081,42 @@ class Human:return r, resr, p = await self.retry(api, target, deadline, plan)- if not p["listbox"]:- await self._select_dropdown(target, r, p["targets"][0] if p["targets"] else None, p, opts, api,- cfg, deadline)- else:- await self._select_listbox(target, r, p, opts, api, cfg, deadline)+ # A pick that navigates (a form submitted on change, here or from an+ # iframe to the top page) leaves nothing to read back, and while that+ # navigation is pending the read may never answer (#619): report what+ # was chosen, as Playwright does.+ navigated = asyncio.get_running_loop().create_future()++ def on_request(req: Any) -> None:+ f = r.frame+ while f is not None and f is not req.frame:+ f = f.parent_frame+ if f is not None and req.is_navigation_request() and not navigated.done():+ navigated.set_result(None)++ self.page.on("request", on_request)try:- state = await self.worlds.call(r.frame, "selectState", r.id)- except StaleElement:- # The pick navigated the page (a form submitted on change): nothing- # left to read back, so report what was chosen, as Playwright does.- return p["values"]+ if not p["listbox"]:+ await self._select_dropdown(target, r, p["targets"][0] if p["targets"] else None, p, opts, api,+ cfg, deadline)+ else:+ await self._select_listbox(target, r, p, opts, api, cfg, deadline)+ read = asyncio.ensure_future(self.worlds.call(r.frame, "selectState", r.id))+ try:+ await asyncio.wait({read, navigated}, return_when=asyncio.FIRST_COMPLETED)+ if not read.done():+ return p["values"]+ try:+ state = read.result()+ except StaleElement:+ # The pick navigated the page (a form submitted on change): nothing+ # left to read back, so report what was chosen, as Playwright does.+ return p["values"]+ finally:+ if not read.done():+ read.cancel()+ finally:+ self.page.remove_listener("request", on_request)if sorted(state["selected"]) != sorted(p["targets"]):raise Error(f"{api}: Error: selection ended as {state['values']} instead of {p['values']}")return state["values"]diff --git a/cloakbrowser/human/patch.py b/cloakbrowser/human/patch.pyindex 9f25f40..fe4f663 100644--- a/cloakbrowser/human/patch.py+++ b/cloakbrowser/human/patch.py@@ -26,8 +26,11 @@ import inspectimport typesfrom typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple+from playwright._impl._errors import TimeoutError+from .config import HumanConfig, randfrom .engine import CursorState, Human, RawFallback, Target+from .world import ACTION, Action, PageStalled_PATCHED = {"sync": False, "async": False}# (class, method name) -> original function@@ -264,6 +267,23 @@ def _handlers(kind: str) -> Dict[str, Handler]:return {**common, "scroll_into_view_if_needed": scroll_into_view_if_needed}+def _in_action(kind: str, name: str, handler: Handler) -> Handler:+ """Run the action with its timeout bounding every browser call it makes, so a+ page that stops answering cannot block past ``timeout=`` (#619)."""+ async def run(h: Human, impl: Any, a: dict) -> Any:+ frame = impl.main_frame if kind == "Page" else impl if kind == "Frame" else impl._frame+ timeout = h.timeout(frame, a.get("timeout"))+ token = ACTION.set(Action(timeout))+ try:+ return await handler(h, impl, a)+ except PageStalled:+ raise TimeoutError(f"{kind}.{name}: Timeout {timeout:.0f}ms exceeded.\n"+ "Call log:\n - waiting for the page to respond") from None+ finally:+ ACTION.reset(token)+ return run++async def _mouse_move(h: Human, impl: Any, a: dict) -> None:await h.mouse_move(a["x"], a["y"], a.get("steps"))@@ -341,7 +361,7 @@ def _install(api: str) -> None:for kind in ("Page", "Frame", "Locator", "ElementHandle"):cls = getattr(g, kind)for name, handler in _handlers(kind).items():- _wrap(kind, cls, name, handler, is_async)+ _wrap(kind, cls, name, _in_action(kind, name, handler), is_async)for kind, table in _INPUT_HANDLERS.items():cls = getattr(g, kind)for name, handler in table.items():diff --git a/cloakbrowser/human/world.py b/cloakbrowser/human/world.pyindex 4a57570..80dbf9b 100644--- a/cloakbrowser/human/world.py+++ b/cloakbrowser/human/world.py@@ -17,8 +17,10 @@ into it through ``SyncBase._sync``.from __future__ import annotationsimport asyncio+import contextvars+import inspectimport json-from typing import Any, Dict, List, Optional, Tuple+from typing import Any, Awaitable, Dict, List, Optional, Tuplefrom playwright._impl._errors import Error@@ -33,6 +35,67 @@ class StealthWorldError(Error):"""An isolated-world evaluation failed (never falls back to the page)."""+class PageStalled(Exception):+ """A browser call got no answer within the action's timeout: the page stopped+ answering, e.g. an onchange running a synchronous XHR (#619). Not a Playwright+ ``Error``, so the engine's ``except Error`` fallbacks let it through; the patch+ layer turns it into Playwright's ``TimeoutError``."""+++class Action:+ """The humanized action in progress: its timeout (ms, 0 = no limit) and+ whether the page stopped answering."""++ __slots__ = ("timeout", "stalled")++ def __init__(self, timeout_ms: float) -> None:+ self.timeout = timeout_ms+ self.stalled = False+++ACTION: "contextvars.ContextVar[Optional[Action]]" = contextvars.ContextVar("cloak_human_action", default=None)+++async def bounded(aw: Awaitable[Any]) -> Any:+ """Await one browser call, bounded by the action's timeout: pauses and typing+ between calls never count, only a call the page does not answer. Once the page+ stopped answering, later calls (key / mouse releases on the way out) are still+ sent, but not waited on, and do not raise again."""+ act = ACTION.get()+ if act is None or not act.timeout:+ return await aw+ task = asyncio.ensure_future(aw)+ try:+ done, _ = await asyncio.wait({task}, timeout=0 if act.stalled else act.timeout / 1000.0)+ finally:+ if not task.done():+ task.cancel()+ if task in done:+ return task.result()+ if act.stalled:+ # The action already failed and is unwinding: this cleanup call was sent;+ # nothing waits for it, and every release in a cleanup loop still goes out.+ return None+ act.stalled = True+ raise PageStalled()+++class BoundedCalls:+ """``obj`` with every coroutine method going through ``bounded``."""++ def __init__(self, obj: Any) -> None:+ self._obj = obj++ def __getattr__(self, name: str) -> Any:+ attr = getattr(self._obj, name)+ if not inspect.iscoroutinefunction(attr):+ return attr++ async def call(*args: Any, **kwargs: Any) -> Any:+ return await bounded(attr(*args, **kwargs))+ return call++# Helper library evaluated after the InjectedScript in every world._HELPERS_JS = r"""(() => {if (globalThis.__cloakH) return true;@@ -366,7 +429,7 @@ class Worlds:async def session(self) -> Any:if self._session is None:- self._session = await self.page.context.new_cdp_session(self.page)+ self._session = BoundedCalls(await bounded(self.page.context.new_cdp_session(self.page)))return self._sessiondef invalidate(self, frame: Any = None) -> None:@@ -396,7 +459,7 @@ class Worlds:async def _locate_child(self, frame: Any, parent: Any) -> _FrameRec:try: # out-of-process iframe: it has its own target/session- own = await self.page.context.new_cdp_session(frame)+ own = BoundedCalls(await bounded(self.page.context.new_cdp_session(frame)))except Error:own = Noneif own is not None:diff --git a/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs b/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.csindex 6c6bc7f..30ca6cf 100644--- a/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs+++ b/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs@@ -9,7 +9,10 @@ internal sealed partial class HumanEngine{private static MouseButton Btn(ActOpts o) => o.Button ?? MouseButton.Left;- public async Task ClickAsync(Target t, ActOpts o, string api, int? clickCount = null)+ public Task ClickAsync(Target t, ActOpts o, string api, int? clickCount = null) =>+ InAction(t, o, api, () => ClickCoreAsync(t, o, api, clickCount));++ private async Task ClickCoreAsync(Target t, ActOpts o, string api, int? clickCount){int count = clickCount ?? o.ClickCount ?? 1;await PointerActionAsync(api, t, o, ClickStates, null, async (r, _, _, cfg) =>@@ -19,7 +22,9 @@ internal sealed partial class HumanEngine}).ConfigureAwait(false);}- public async Task HoverAsync(Target t, ActOpts o, string api)+ public Task HoverAsync(Target t, ActOpts o, string api) => InAction(t, o, api, () => HoverCoreAsync(t, o, api));++ private async Task HoverCoreAsync(Target t, ActOpts o, string api){// Playwright holds the modifiers while the mouse moves onto the target.await PointerActionAsync(api, t, o, HoverStates, false, hold: o.Modifiers).ConfigureAwait(false);@@ -82,7 +87,9 @@ internal sealed partial class HumanEngineawait Sleep(R(20, 60)).ConfigureAwait(false);}- public async Task PressAsync(Target t, string key, ActOpts o, string api)+ public Task PressAsync(Target t, string key, ActOpts o, string api) => InAction(t, o, api, () => PressCoreAsync(t, key, o, api));++ private async Task PressCoreAsync(Target t, string key, ActOpts o, string api){var d = DeadlineFor(t, o);await FocusElementAsync(t, o, api, d, requireFocus: false).ConfigureAwait(false);@@ -90,7 +97,9 @@ internal sealed partial class HumanEngineawait PressKeyAsync(await KeysAsync(key).ConfigureAwait(false), null, o.Delay).ConfigureAwait(false);}- public async Task TypeAsync(Target t, string text, ActOpts o, string api)+ public Task TypeAsync(Target t, string text, ActOpts o, string api) => InAction(t, o, api, () => TypeCoreAsync(t, text, o, api));++ private async Task TypeCoreAsync(Target t, string text, ActOpts o, string api){var cfg = CallCfg(o.HumanConfig);var d = DeadlineFor(t, o);@@ -101,7 +110,9 @@ internal sealed partial class HumanEngineawait TypeTextAsync(text, cfg, r.Frame, await InfoAsync(r).ConfigureAwait(false), o.Delay).ConfigureAwait(false);}- public async Task FillAsync(Target t, string value, ActOpts o, string api)+ public Task FillAsync(Target t, string value, ActOpts o, string api) => InAction(t, o, api, () => FillCoreAsync(t, value, o, api));++ private async Task FillCoreAsync(Target t, string value, ActOpts o, string api){var cfg = CallCfg(o.HumanConfig);var d = DeadlineFor(t, o);@@ -149,7 +160,10 @@ internal sealed partial class HumanEngineif (value.Length > 0) await TypeTextAsync(value, cfg, r.Frame, info, null).ConfigureAwait(false);}- public async Task SetCheckedAsync(Target t, bool want, ActOpts o, string api)+ public Task SetCheckedAsync(Target t, bool want, ActOpts o, string api) =>+ InAction(t, o, api, () => SetCheckedCoreAsync(t, want, o, api));++ private async Task SetCheckedCoreAsync(Target t, bool want, ActOpts o, string api){var d = DeadlineFor(t, o);var r = await WaitForAsync(t, ClickStates, d, api, o.Force).ConfigureAwait(false);@@ -253,7 +267,11 @@ internal sealed partial class HumanEngine/// <summary>Pick options like a person: a dropdown is opened with a click and moved with/// arrow keys + Enter; a list box gets clicks on the options (Ctrl/Cmd to add).</summary>- public async Task<IReadOnlyList<string>> SelectOptionAsync(Target t, IReadOnlyList<object> options,+ public Task<IReadOnlyList<string>> SelectOptionAsync(Target t, IReadOnlyList<object> options,+ IReadOnlyList<IElementHandle> handles, ActOpts o, string api) =>+ InAction(t, o, api, () => SelectOptionCoreAsync(t, options, handles, o, api));++ private async Task<IReadOnlyList<string>> SelectOptionCoreAsync(Target t, IReadOnlyList<object> options,IReadOnlyList<IElementHandle> handles, ActOpts o, string api){var cfg = CallCfg(o.HumanConfig);@@ -270,20 +288,47 @@ internal sealed partial class HumanEngine}).ConfigureAwait(false);var targets = plan.GetProperty("targets").EnumerateArray().Select(x => x.GetInt32()).ToList();var values = plan.GetProperty("values").EnumerateArray().Select(x => x.GetString()!).ToList();- if (!plan.GetProperty("listbox").GetBoolean())- await SelectDropdownAsync(t, r, targets.Count > 0 ? targets[0] : null, plan, o, api, d).ConfigureAwait(false);- else- await SelectListboxAsync(t, r, targets, o, api, cfg, d).ConfigureAwait(false);+ // A pick that navigates (a form submitted on change, here or from an iframe+ // to the top page) leaves nothing to read back, and while that navigation is+ // pending the read may never answer (#619): report what was chosen, as+ // Playwright does.+ var navigated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);+ void OnRequest(object? _, IRequest req)+ {+ var f = r.Frame;+ while (f != null && f != req.Frame) f = f.ParentFrame;+ if (f != null && req.IsNavigationRequest) navigated.TrySetResult();+ }+ _page.Request += OnRequest;JsonElement state;try{- state = (await World.CallAsync(r.Frame, "selectState", r.Id).ConfigureAwait(false))!.Value;+ if (!plan.GetProperty("listbox").GetBoolean())+ await SelectDropdownAsync(t, r, targets.Count > 0 ? targets[0] : null, plan, o, api, d).ConfigureAwait(false);+ else+ await SelectListboxAsync(t, r, targets, o, api, cfg, d).ConfigureAwait(false);+ var read = World.CallAsync(r.Frame, "selectState", r.Id);+ if (await Task.WhenAny(read, navigated.Task).ConfigureAwait(false) != read)+ {+ // Abandoned once the frame navigated.+ _ = read.ContinueWith(x => CloakLog.Debug($"selectState read after navigation: {x.Exception?.GetBaseException().Message}"),+ TaskContinuationOptions.OnlyOnFaulted);+ return values;+ }+ try+ {+ state = (await read.ConfigureAwait(false))!.Value;+ }+ catch (StaleElementException)+ {+ // The pick navigated the page (a form submitted on change): nothing+ // left to read back, so report what was chosen, as Playwright does.+ return values;+ }}- catch (StaleElementException)+ finally{- // The pick navigated the page (a form submitted on change): nothing- // left to read back, so report what was chosen, as Playwright does.- return values;+ _page.Request -= OnRequest;}var selected = state.GetProperty("selected").EnumerateArray().Select(x => x.GetInt32()).OrderBy(x => x).ToList();var got = state.GetProperty("values").EnumerateArray().Select(x => x.GetString()!).ToList();@@ -417,7 +462,10 @@ internal sealed partial class HumanEngine}}- public async Task DragAsync(Target source, Target dest, ActOpts o, string api)+ public Task DragAsync(Target source, Target dest, ActOpts o, string api) =>+ InAction(source, o, api, () => DragCoreAsync(source, dest, o, api));++ private async Task DragCoreAsync(Target source, Target dest, ActOpts o, string api){var sub = new ActOpts { Deadline = DeadlineFor(source, o), Force = o.Force, HumanConfig = o.HumanConfig, Position = o.SourcePosition, Trial = o.Trial };await IdleAsync(CallCfg(o.HumanConfig)).ConfigureAwait(false);@@ -440,7 +488,10 @@ internal sealed partial class HumanEngine/// <summary>Focus without a click (Playwright's focus() is itself programmatic); the/// ElementHandle variant moves the cursor over the element first.</summary>- public async Task FocusAsync(Target t, ActOpts o, string api, bool move = false)+ public Task FocusAsync(Target t, ActOpts o, string api, bool move = false) =>+ InAction(t, o, api, () => FocusCoreAsync(t, o, api, move));++ private async Task FocusCoreAsync(Target t, ActOpts o, string api, bool move){var d = DeadlineFor(t, o);if (move) await HoverAsync(t, new ActOpts { Timeout = o.Timeout, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);@@ -448,7 +499,10 @@ internal sealed partial class HumanEngineawait World.CallAsync(r.Frame, "focus", r.Id).ConfigureAwait(false);}- public async Task ScrollIntoViewIfNeededAsync(Target t, ActOpts o, string api)+ public Task ScrollIntoViewIfNeededAsync(Target t, ActOpts o, string api) =>+ InAction(t, o, api, () => ScrollIntoViewIfNeededCoreAsync(t, o, api));++ private async Task ScrollIntoViewIfNeededCoreAsync(Target t, ActOpts o, string api){var cfg = CallCfg(o.HumanConfig);var d = DeadlineFor(t, o);diff --git a/dotnet/src/CloakBrowser/Human/HumanEngine.cs b/dotnet/src/CloakBrowser/Human/HumanEngine.csindex 3466c78..4e5d19f 100644--- a/dotnet/src/CloakBrowser/Human/HumanEngine.cs+++ b/dotnet/src/CloakBrowser/Human/HumanEngine.cs@@ -150,6 +150,21 @@ internal sealed class PlaywrightRawInput : IRawInputpublic Task InsertTextAsync(string text) => _k.InsertTextAsync(text);}+/// <summary>Raw input whose calls are bounded by the action's timeout.</summary>+internal sealed class BoundedRawInput : IRawInput+{+ private readonly IRawInput _in;+ public BoundedRawInput(IRawInput inner) => _in = inner;+ public Task MoveAsync(double x, double y, int? steps = null) => HumanAction.Bounded(_in.MoveAsync(x, y, steps));+ public Task DownAsync(MouseButton button = MouseButton.Left, int clickCount = 1) => HumanAction.Bounded(_in.DownAsync(button, clickCount));+ public Task UpAsync(MouseButton button = MouseButton.Left, int clickCount = 1) => HumanAction.Bounded(_in.UpAsync(button, clickCount));+ public Task WheelAsync(double dx, double dy) => HumanAction.Bounded(_in.WheelAsync(dx, dy));+ public Task KeyDownAsync(string key) => HumanAction.Bounded(_in.KeyDownAsync(key));+ public Task KeyUpAsync(string key) => HumanAction.Bounded(_in.KeyUpAsync(key));+ public Task KeyPressAsync(string key, float? delay = null) => HumanAction.Bounded(_in.KeyPressAsync(key, delay));+ public Task InsertTextAsync(string text) => HumanAction.Bounded(_in.InsertTextAsync(text));+}+/// <summary>Reads client-side Playwright .NET internals:/// a locator's frame and selector string, and the page's default-timeout settings.</summary>internal static class PlaywrightInternals@@ -225,7 +240,7 @@ internal sealed partial class HumanEngine_page = page;Config = cfg;Cursor = cursor;- _raw = raw ?? new PlaywrightRawInput(page.Mouse, page.Keyboard);+ _raw = new BoundedRawInput(raw ?? new PlaywrightRawInput(page.Mouse, page.Keyboard));World = new HumanWorld(page);}@@ -244,6 +259,28 @@ internal sealed partial class HumanEnginepublic Deadline DeadlineFor(Target t, ActOpts o) =>o.Deadline ?? new Deadline(PlaywrightInternals.Timeout(t.Frame, o.Timeout));+ /// <summary>Run a top-level action with its timeout bounding every browser call it makes,+ /// so a page that stops answering cannot block past the timeout (#619). A call made while+ /// an action is in progress (a sub-action) runs inside that action.</summary>+ private async Task<T> InAction<T>(Target t, ActOpts o, string api, Func<Task<T>> action)+ {+ if (HumanAction.Current != null) return await action().ConfigureAwait(false);+ double timeout = PlaywrightInternals.Timeout(t.Frame, o.Timeout);+ HumanAction.Current = new HumanAction(timeout);+ try+ {+ return await action().ConfigureAwait(false);+ }+ catch (PageStalledException)+ {+ throw new System.TimeoutException($"{api}: Timeout {Math.Round(timeout)}ms exceeded.\n" ++ "Call log:\n - waiting for the page to respond");+ }+ }++ private Task InAction(Target t, ActOpts o, string api, Func<Task> action) =>+ InAction(t, o, api, async () => { await action().ConfigureAwait(false); return true; });+private static PlaywrightException Err(string msg) => new(msg);// -- persona ------------------------------------------------------------@@ -351,7 +388,7 @@ internal sealed partial class HumanEnginereturn new Resolved(frame, cached.Id);// An ElementHandle carries no identity our context can read, so find the element// with exactly its border box.- var box = await handle.BoundingBoxAsync().ConfigureAwait(false);+ var box = await HumanAction.Bounded(handle.BoundingBoxAsync()).ConfigureAwait(false);if (box == null){if (exact) throw new RawFallbackException();@@ -419,7 +456,10 @@ internal sealed partial class HumanEngineawait RetryAsync(api, t, d, () => ResolveHandleAsync(h, exact: true)).ConfigureAwait(false);}- public async Task<string?> ReadAsync(Target t, string op, ActOpts o, string api, params object?[] extra)+ public Task<string?> ReadAsync(Target t, string op, ActOpts o, string api, params object?[] extra) =>+ InAction(t, o, api, () => ReadCoreAsync(t, op, o, api, extra));++ private async Task<string?> ReadCoreAsync(Target t, string op, ActOpts o, string api, object?[] extra){var d = DeadlineFor(t, o);await HandleOrRawAsync(t, d, api).ConfigureAwait(false);@@ -437,7 +477,10 @@ internal sealed partial class HumanEngine////// The event is built by Playwright's own injected helper, evaluated in the/// isolated world instead of the page's world.</summary>- public async Task DispatchAsync(Target t, ActOpts o, string api, string type, object? eventInit = null)+ public Task DispatchAsync(Target t, ActOpts o, string api, string type, object? eventInit = null) =>+ InAction(t, o, api, () => DispatchCoreAsync(t, o, api, type, eventInit));++ private async Task DispatchCoreAsync(Target t, ActOpts o, string api, string type, object? eventInit){if (RawFallbackException.HasHandle(eventInit)) throw new RawFallbackException();var d = DeadlineFor(t, o);@@ -750,14 +793,15 @@ internal sealed partial class HumanEngineif (o.Trial) return r;var keys = new List<string>();foreach (var m in hold ?? Array.Empty<string>()) keys.Add(await ModifierAsync(m).ConfigureAwait(false));- foreach (var k in keys) await _raw.KeyDownAsync(k).ConfigureAwait(false);+ var held = new List<string>();try{+ foreach (var k in keys) { held.Add(k); await _raw.KeyDownAsync(k).ConfigureAwait(false); }await MoveToAsync(x, y, cfg).ConfigureAwait(false);}finally{- for (int i = keys.Count - 1; i >= 0; i--) await _raw.KeyUpAsync(keys[i]).ConfigureAwait(false);+ for (int i = held.Count - 1; i >= 0; i--) await _raw.KeyUpAsync(held[i]).ConfigureAwait(false);}// The page may replace or remove the target while the cursor travels; never// press on whatever is under it now (even with force). Locators re-resolve.@@ -775,22 +819,30 @@ internal sealed partial class HumanEnginevar mods = new List<string>();foreach (var m in modifiers ?? Array.Empty<string>()) mods.Add(await ModifierAsync(m).ConfigureAwait(false));await Sleep(RR(isInput ? cfg.ClickAimDelayInput : cfg.ClickAimDelayButton)).ConfigureAwait(false);- foreach (var m in mods) await _raw.KeyDownAsync(m).ConfigureAwait(false);+ var held = new List<string>();try{+ foreach (var m in mods) { held.Add(m); await _raw.KeyDownAsync(m).ConfigureAwait(false); }int count = Math.Max(1, clickCount);for (int n = 1; n <= count; n++){double hold = delay ?? RR(isInput ? cfg.ClickHoldInput : cfg.ClickHoldButton);- await _raw.DownAsync(button, n).ConfigureAwait(false);- await Sleep(hold).ConfigureAwait(false);- await _raw.UpAsync(button, n).ConfigureAwait(false);+ try+ {+ await _raw.DownAsync(button, n).ConfigureAwait(false);+ await Sleep(hold).ConfigureAwait(false);+ }+ finally+ {+ // Never leave the button down, also when the page stopped answering.+ await _raw.UpAsync(button, n).ConfigureAwait(false);+ }if (n < count) await Sleep(delay ?? R(60, 140)).ConfigureAwait(false);}}finally{- for (int i = mods.Count - 1; i >= 0; i--) await _raw.KeyUpAsync(mods[i]).ConfigureAwait(false);+ for (int i = held.Count - 1; i >= 0; i--) await _raw.KeyUpAsync(held[i]).ConfigureAwait(false);}}}diff --git a/dotnet/src/CloakBrowser/Human/HumanWorld.cs b/dotnet/src/CloakBrowser/Human/HumanWorld.csindex 09036f8..7a90e33 100644--- a/dotnet/src/CloakBrowser/Human/HumanWorld.cs+++ b/dotnet/src/CloakBrowser/Human/HumanWorld.cs@@ -15,6 +15,80 @@ internal sealed class StaleElementException : PlaywrightExceptionpublic StaleElementException() : base("element is not attached to the DOM") { }}+/// <summary>A browser call got no answer within the action's timeout: the page stopped+/// answering, e.g. an onchange running a synchronous XHR (#619). Not a+/// <see cref="PlaywrightException"/>, so the engine's Playwright fallbacks let it through;+/// the engine's entry actions turn it into a <see cref="System.TimeoutException"/>.</summary>+internal sealed class PageStalledException : Exception+{+ public PageStalledException() : base("the page stopped answering") { }+}++/// <summary>The humanized action in progress: its timeout (ms, 0 = no limit) and whether+/// the page stopped answering. Flows with the async calls of the action.</summary>+internal sealed class HumanAction+{+ private static readonly AsyncLocal<HumanAction?> CurrentAction = new();++ public HumanAction(double timeoutMs) => Timeout = timeoutMs;+ public double Timeout { get; }+ public bool Stalled { get; private set; }++ public static HumanAction? Current { get => CurrentAction.Value; set => CurrentAction.Value = value; }++ /// <summary>Await one browser call, bounded by the action's timeout: pauses and typing+ /// between calls never count, only a call the page does not answer. Once the page stopped+ /// answering, later calls (key / mouse releases on the way out) are still sent, but not+ /// waited on, and do not throw again.</summary>+ public static Task Bounded(Task call) => Answered(call);++ public static async Task<T> Bounded<T>(Task<T> call) =>+ await Answered(call).ConfigureAwait(false) ? await call.ConfigureAwait(false) : default!;++ /// <returns>false when the call was sent after a stall and not waited on.</returns>+ private static async Task<bool> Answered(Task call)+ {+ var act = Current;+ // Beyond int.MaxValue ms WaitAsync rejects the TimeSpan: treat it as no limit.+ if (act == null || act.Timeout <= 0 || act.Timeout > int.MaxValue) { await call.ConfigureAwait(false); return true; }+ try+ {+ await call.WaitAsync(TimeSpan.FromMilliseconds(act.Stalled ? 0 : act.Timeout)).ConfigureAwait(false);+ return true;+ }+ catch (System.TimeoutException) when (call.IsCompleted)+ {+ // The answer came the instant the time ran out: its own outcome counts.+ await call.ConfigureAwait(false);+ return true;+ }+ catch (System.TimeoutException) when (!call.IsCompleted)+ {+ // Abandoned: an answer that still comes arrives after the action gave up.+ _ = call.ContinueWith(c => CloakLog.Debug($"browser call failed after the page stalled: {c.Exception?.GetBaseException().Message}"),+ TaskContinuationOptions.OnlyOnFaulted);+ // The action already failed and is unwinding: this cleanup call was sent;+ // nothing waits for it, and every release in a cleanup loop still goes out.+ if (act.Stalled) return false;+ act.Stalled = true;+ throw new PageStalledException();+ }+ }+}++/// <summary>A CDP session whose calls are bounded by the action's timeout.</summary>+internal sealed class BoundedCdpSession : ICDPSession+{+ private readonly ICDPSession _s;+ public BoundedCdpSession(ICDPSession session) => _s = session;+ public event EventHandler<ICDPSession> Close { add => _s.Close += value; remove => _s.Close -= value; }+ public Task DetachAsync() => HumanAction.Bounded(_s.DetachAsync());+ public ICDPSessionEvent Event(string eventName) => _s.Event(eventName);+ public ValueTask DisposeAsync() => _s.DisposeAsync();+ public Task<JsonElement?> SendAsync(string method, Dictionary<string, object>? args = null) =>+ HumanAction.Bounded(_s.SendAsync(method, args));+}+internal readonly record struct Rect(double X, double Y, double Width, double Height){public static Rect Intersect(Rect a, Rect b)@@ -78,7 +152,7 @@ internal sealed class HumanWorldpublic async Task<ICDPSession> SessionAsync(){- _session ??= await _page.Context.NewCDPSessionAsync(_page).ConfigureAwait(false);+ _session ??= new BoundedCdpSession(await HumanAction.Bounded(_page.Context.NewCDPSessionAsync(_page)).ConfigureAwait(false));return _session;}@@ -127,8 +201,8 @@ internal sealed class HumanWorldprivate async Task<FrameRec> LocateChildAsync(IFrame frame, IFrame parent){ICDPSession? own = null;- try { own = await _page.Context.NewCDPSessionAsync(frame).ConfigureAwait(false); } // OOPIF: own target- catch (Exception) { own = null; }+ try { own = new BoundedCdpSession(await HumanAction.Bounded(_page.Context.NewCDPSessionAsync(frame)).ConfigureAwait(false)); } // OOPIF: own target+ catch (Exception e) when (e is not PageStalledException) { own = null; }if (own != null){var t = await own.SendAsync("Page.getFrameTree").ConfigureAwait(false);@@ -275,7 +349,7 @@ internal sealed class HumanWorldprivate static async Task ReleaseAsync(ICDPSession session, string objectId){try { await session.SendAsync("Runtime.releaseObject", new() { ["objectId"] = objectId }).ConfigureAwait(false); }- catch (Exception) { }+ catch (Exception e) when (e is not PageStalledException) { }}/// <summary>Segments of a native date/time editor in visual order, with centres relativediff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.csindex 6b6c003..4516eb5 100644--- a/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs@@ -464,6 +464,117 @@ public class HumanEngineBrowserTests : IClassFixture<EngineFixture>, IAsyncLifetawait p.WaitForURLAsync(new System.Text.RegularExpressions.Regex("city=b"));}+ private const string SyncXhr = "var x = new XMLHttpRequest(); x.open('GET', '/hang', false); x.send();";++ private static Task StallingSelect(IFrame f, string onchange) => f.EvaluateAsync(@"js => {+ const s = document.createElement('select'); s.id = 'stall';+ for (const [l, v] of [['-', ''], ['Alfa', 'a'], ['Bravo', 'b']]) s.add(new Option(l, v));+ s.setAttribute('onchange', js); document.body.prepend(s); }", onchange);++ [BrowserFact]+ public async Task SelectOption_times_out_when_the_page_stops_answering()+ {+ // #619: the timeout holds even when a call to the page never returns.+ var p = await Open();+ await StallingSelect(p.MainFrame, SyncXhr);+ var sw = System.Diagnostics.Stopwatch.StartNew();+ var e = await Assert.ThrowsAsync<TimeoutException>(() => p.SelectOptionAsync("#stall", "b", new() { Timeout = 2000 }))+ .WaitAsync(TimeSpan.FromSeconds(20));+ Assert.Contains("Timeout 2000ms exceeded", e.Message);+ Assert.True(sw.ElapsedMilliseconds < 5000, $"took {sw.ElapsedMilliseconds}ms");+ }++ [BrowserFact]+ public async Task SelectOption_returns_when_its_navigation_never_commits()+ {+ // #619: the pick started a navigation the server never answers; Playwright returns at once.+ var p = await Open();+ await StallingSelect(p.MainFrame, "location.href = '/hang'");+ var sw = System.Diagnostics.Stopwatch.StartNew();+ Assert.Equal(new[] { "b" }, await p.SelectOptionAsync("#stall", "b", new() { Timeout = 5000 }).WaitAsync(TimeSpan.FromSeconds(20)));+ Assert.True(sw.ElapsedMilliseconds < 4500, $"took {sw.ElapsedMilliseconds}ms");+ }++ [BrowserFact]+ public async Task SelectOption_in_a_frame_that_navigates_the_top_page_returns()+ {+ // #619: a pick in an iframe that navigates the top page also counts as a navigation.+ var p = await Open();+ var f = await FrameOf(p);+ await StallingSelect(f, "top.location.href = '/hang'");+ var sw = System.Diagnostics.Stopwatch.StartNew();+ Assert.Equal(new[] { "b" }, await f.SelectOptionAsync("#stall", "b", new() { Timeout = 5000 }).WaitAsync(TimeSpan.FromSeconds(20)));+ Assert.True(sw.ElapsedMilliseconds < 4500, $"took {sw.ElapsedMilliseconds}ms");+ }++ [BrowserFact]+ public async Task A_stall_leaves_no_modifier_key_held()+ {+ // #619: a click with modifiers on a page that stalls still releases every modifier+ // (the page gets the releases once it answers again).+ var p = await Open();+ await p.EvaluateAsync(@"js => { const b = document.createElement('button'); b.id = 'stallbtn';+ b.textContent = 'stall'; b.setAttribute('onclick', js); document.body.prepend(b); }",+ "var x = new XMLHttpRequest(); x.open('GET', '/slow', false); x.send();");+ var e = await Assert.ThrowsAsync<TimeoutException>(() => p.ClickAsync("#stallbtn",+ new() { Modifiers = new[] { KeyboardModifier.Shift, KeyboardModifier.Alt }, Timeout = 1000 })).WaitAsync(TimeSpan.FromSeconds(20));+ Assert.Contains("waiting for the page to respond", e.Message);+ await p.EvaluateAsync("1"); // returns once the page answers again+ await Reset(p);+ await p.ClickAsync("#btn");+ var down = await p.EvaluateAsync<JsonElement>("window.__log.filter(e => e.t === 'mousedown').at(-1)");+ Assert.False(down.GetProperty("shift").GetBoolean());+ Assert.False(down.GetProperty("alt").GetBoolean());+ }++ [BrowserFact]+ public async Task Typing_times_out_when_the_page_stops_answering()+ {+ // #619: a field whose input handler stalls the page times out.+ var p = await Open();+ await p.EvaluateAsync(@"js => { const i = document.createElement('input'); i.id = 'stallin';+ i.setAttribute('oninput', js); document.body.prepend(i); }", SyncXhr);+ var sw = System.Diagnostics.Stopwatch.StartNew();+ var e = await Assert.ThrowsAsync<TimeoutException>(() => p.FillAsync("#stallin", "abcdef", new() { Timeout = 2000 }))+ .WaitAsync(TimeSpan.FromSeconds(20));+ Assert.Contains("waiting for the page to respond", e.Message);+ Assert.True(sw.ElapsedMilliseconds < 5000, $"took {sw.ElapsedMilliseconds}ms");+ }++ [BrowserFact]+ public async Task Human_pauses_do_not_count_against_the_timeout()+ {+ // #619: only a browser call that gets no answer times out, not the deliberate pauses.+ var p = await OpenWith(new() { ["field_switch_delay"] = new[] { 2500.0, 2500.0 } });+ await p.FillAsync("#name", "ab", new() { Timeout = 1000 });+ Assert.Equal("ab", await Value(p, "#name"));+ }++ [BrowserFact]+ public async Task Long_fill_is_not_cut_off_by_the_timeout()+ {+ // #619: typing is slow by design; each key answers in time, so a long fill finishes.+ var p = await OpenWith(new() { ["typing_delay"] = 60.0 });+ var text = new string('x', 40);+ await p.FillAsync("#name", text, new() { Timeout = 1000 });+ Assert.Equal(text, await Value(p, "#name"));+ }++ [BrowserFact]+ public async Task Click_times_out_when_the_page_stops_answering()+ {+ // #619: the timeout holds for every humanized action, not just SelectOption;+ // releasing the held modifiers afterwards does not wait out the timeout again.+ var p = await Open();+ await p.EvaluateAsync(@"js => { const b = document.createElement('button'); b.id = 'stallbtn';+ b.textContent = 'stall'; b.setAttribute('onclick', js); document.body.prepend(b); }", SyncXhr);+ var sw = System.Diagnostics.Stopwatch.StartNew();+ var e = await Assert.ThrowsAsync<TimeoutException>(() => p.ClickAsync("#stallbtn",+ new() { Modifiers = new[] { KeyboardModifier.Shift, KeyboardModifier.Alt }, Timeout = 2000 })).WaitAsync(TimeSpan.FromSeconds(20));+ Assert.Contains("waiting for the page to respond", e.Message);+ Assert.True(sw.ElapsedMilliseconds < 3500, $"took {sw.ElapsedMilliseconds}ms"); // one wait of 2s, not one more per held modifier+ }+// --- frames / handles --------------------------------------------------[BrowserFact]diff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.csindex 98b83f0..9cca501 100644--- a/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.cs+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/SiteServer.cs@@ -275,6 +275,13 @@ public sealed class SiteServer{HttpListenerContext ctx;try { ctx = await listener.GetContextAsync(); } catch { return; }+ if (ctx.Request.Url!.AbsolutePath.StartsWith("/hang")) continue; // a server that never answers+ if (ctx.Request.Url!.AbsolutePath.StartsWith("/slow")) // answers, late+ {+ var late = ctx;+ _ = Task.Delay(3000).ContinueWith(_ => { late.Response.StatusCode = 204; late.Response.Close(); });+ continue;+ }var html = ctx.Request.Url!.AbsolutePath switch{"/" or "/index.html" => IndexHtml,diff --git a/js/src/human/engine.ts b/js/src/human/engine.tsindex 1fce56e..8f47869 100644--- a/js/src/human/engine.ts+++ b/js/src/human/engine.ts@@ -20,7 +20,7 @@ import { type HumanConfig, mergeConfig, rand, randLog, randRange, randIntRange,import { NEARBY_KEYS, keyGap, keyHold, Typist, type TypistKeys } from './keyboard.js';import { clickTarget, planMove } from './mouse.js';import * as fields from './fields.js';-import { HELPERS, StaleElement, Worlds, intersect, type Rect } from './world.js';+import { DEBUG, HELPERS, PageStalled, StaleElement, Worlds, bounded, boundedCalls, intersect, type Rect } from './world.js';const ENTER_FRAME_SPLIT = /\s*>>\s*internal:control=enter-frame\s*>>\s*/;@@ -138,8 +138,11 @@ export class Human {private _platform: string | null = null;private handleIds = new Map<string, [Frame, number, number]>();- constructor(readonly page: Page, public cfg: HumanConfig, public cursor: CursorState, readonly raw: RawInput) {+ readonly raw: RawInput;++ constructor(readonly page: Page, public cfg: HumanConfig, public cursor: CursorState, raw: RawInput) {this.worlds = new Worlds(page);+ this.raw = boundedCalls(raw);}// -- configuration ------------------------------------------------------@@ -162,7 +165,7 @@ export class Human {async platform(): Promise<string> {if (this._platform === null) {try { this._platform = String(await this.worlds.call(this.page.mainFrame(), 'platform')); }- catch { this._platform = ''; }+ catch (e) { if (e instanceof PageStalled) throw e; this._platform = ''; }}return this._platform;}@@ -248,7 +251,7 @@ export class Human {if (!exact && cached && cached[0] === frame && cached[1] === rec.ctx) return new Resolved(frame, cached[2]);// An ElementHandle carries no identity our context can read, so find// the element with exactly its border box.- const box = await handle.boundingBox();+ const box = await bounded(handle.boundingBox());if (!box) {if (exact) throw new RawFallback();// Resolved in an earlier document of this frame and gone now@@ -330,7 +333,7 @@ export class Human {try {return await attempt();} catch (e: any) {- if (e instanceof RawFallback) throw e;+ if (e instanceof RawFallback || e instanceof PageStalled) throw e;if (e instanceof StaleElement) {if (target.handle) throw err(`${api}: Element is not attached to the DOM`);note('element was detached from the DOM, retrying');@@ -599,11 +602,12 @@ export class Human {if (trial) return r;const keys: string[] = [];for (const m of hold ?? []) keys.push(await this.modifier(m));- for (const k of keys) await this.raw.keyDown(k);+ const held: string[] = [];try {+ for (const k of keys) { held.push(k); await this.raw.keyDown(k); }await this.moveTo(x, y, cfg);} finally {- for (const k of [...keys].reverse()) await this.raw.keyUp(k);+ for (const k of held.reverse()) await this.raw.keyUp(k);}// The page may replace or remove the target while the cursor travels;// never press on whatever is under it now (even with force). Locators@@ -621,18 +625,23 @@ export class Human {const mods: string[] = [];for (const m of modifiers ?? []) mods.push(await this.modifier(m));await sleepMs(randRange(isInput ? cfg.click_aim_delay_input : cfg.click_aim_delay_button));- for (const m of mods) await this.raw.keyDown(m);+ const held: string[] = [];try {+ for (const m of mods) { held.push(m); await this.raw.keyDown(m); }const count = Math.max(1, Math.trunc(clickCount));for (let n = 1; n <= count; n++) {const hold = delay ?? randRange(isInput ? cfg.click_hold_input : cfg.click_hold_button);- await this.raw.down({ button, clickCount: n });- await sleepMs(hold);- await this.raw.up({ button, clickCount: n });+ try {+ await this.raw.down({ button, clickCount: n });+ await sleepMs(hold);+ } finally {+ // Never leave the button down, also when the page stopped answering.+ await this.raw.up({ button, clickCount: n });+ }if (n < count) await sleepMs(delay ?? rand(60, 140));}} finally {- for (const m of [...mods].reverse()) await this.raw.keyUp(m);+ for (const m of held.reverse()) await this.raw.keyUp(m);}}@@ -888,16 +897,38 @@ export class Human {if (res.retry) throw new Retry(res.retry);return [rr, res];});- if (!p.listbox) await this.selectDropdown(target, r, p.targets.length ? p.targets[0] : null, p, opts, api, deadline);- else await this.selectListbox(target, r, p, opts, api, cfg, deadline);+ // A pick that navigates (a form submitted on change, here or from an iframe+ // to the top page) leaves nothing to read back, and while that navigation is+ // pending the read may never answer (#619): report what was chosen, as+ // Playwright does.+ const NAVIGATED = Symbol('navigated');+ let onRequest!: (req: any) => void;+ const navigated = new Promise<typeof NAVIGATED>((resolve) => {+ onRequest = (req) => {+ let f: Frame | null = r.frame;+ while (f && f !== req.frame()) f = f.parentFrame();+ if (f && req.isNavigationRequest()) resolve(NAVIGATED);+ };+ });+ this.page.on('request', onRequest);let state;try {- state = await this.worlds.call(r.frame, 'selectState', r.id);- } catch (e) {- // The pick navigated the page (a form submitted on change): nothing- // left to read back, so report what was chosen, as Playwright does.- if (e instanceof StaleElement) return p.values;- throw e;+ if (!p.listbox) await this.selectDropdown(target, r, p.targets.length ? p.targets[0] : null, p, opts, api, deadline);+ else await this.selectListbox(target, r, p, opts, api, cfg, deadline);+ const read = this.worlds.call(r.frame, 'selectState', r.id);+ // Settled below, or abandoned once the frame navigated.+ read.catch((e) => { if (DEBUG) console.debug(`[cloakbrowser] selectState read after navigation: ${e}`); });+ try {+ state = await Promise.race([read, navigated]);+ } catch (e) {+ // The pick navigated the page (a form submitted on change): nothing+ // left to read back, so report what was chosen, as Playwright does.+ if (e instanceof StaleElement) return p.values;+ throw e;+ }+ if (state === NAVIGATED) return p.values;+ } finally {+ this.page.off('request', onRequest);}const sorted = (a: number[]) => JSON.stringify([...a].sort((x, y) => x - y));if (sorted(state.selected) !== sorted(p.targets)) {@@ -1088,7 +1119,7 @@ export class Human {}private async activeValue(frame: Frame): Promise<string | null> {- try { return (await this.worlds.call(frame, 'activeValue'))?.value ?? null; } catch { return null; }+ try { return (await this.worlds.call(frame, 'activeValue'))?.value ?? null; } catch (e) { if (e instanceof PageStalled) throw e; return null; }}/** One key on its own (date editors, type-ahead). */@@ -1123,7 +1154,7 @@ export class Human {async keyboardType(text: string, delay?: number): Promise<void> {const frame = this.page.mainFrame();let info: any = null;- try { info = await this.worlds.call(frame, 'activeValue'); } catch { info = null; }+ try { info = await this.worlds.call(frame, 'activeValue'); } catch (e) { if (e instanceof PageStalled) throw e; info = null; }if (info?.tag === 'iframe') info = null; // focus inside a child frame: value checks impossibleawait this.typeText(text, this.cfg, frame, info?.tag ? info : null, delay);}diff --git a/js/src/human/patch.ts b/js/src/human/patch.tsindex 8aaac51..ced7993 100644--- a/js/src/human/patch.ts+++ b/js/src/human/patch.ts@@ -26,8 +26,10 @@import { createRequire } from 'node:module';import type { Browser, BrowserContext, ElementHandle, Frame, Page } from 'playwright-core';+import { errors } from 'playwright-core';import { type HumanConfig, rand } from './config.js';import { CursorState, Human, RawFallback, Target, type Opts, type RawInput } from './engine.js';+import { ACTION, PageStalled } from './world.js';type Kind = 'Page' | 'Frame' | 'Locator' | 'ElementHandle' | 'Mouse' | 'Keyboard';type Handler = (h: Human, self: any, args: any[]) => Promise<any>;@@ -107,7 +109,7 @@ function target(kind: Kind, self: any, args: any[], o: Opts): { t: Target; rest:* Page / Frame). */const OPT_INDEX: Record<string, number> = {click: 0, dblclick: 0, hover: 0, tap: 0, check: 0, uncheck: 0, focus: 0, clear: 0, scrollIntoViewIfNeeded: 0,- fill: 1, type: 1, pressSequentially: 1, press: 1, setChecked: 1, selectOption: 1, dragTo: 1,+ fill: 1, type: 1, pressSequentially: 1, press: 1, setChecked: 1, selectOption: 1, dragTo: 1, dragAndDrop: 1,inputValue: 0, textContent: 0, innerText: 0, innerHTML: 0, getAttribute: 1, dispatchEvent: 2,};@@ -231,11 +233,31 @@ function wrap(kind: Kind, proto: any, name: string, handler: Handler): void {proto[name] = wrapper;}+/** Run the action with its timeout bounding every browser call it makes, so a+ * page that stops answering cannot block past `timeout` (#619). */+function inAction(kind: Kind, name: string, handler: Handler): Handler {+ const sel = kind === 'Page' || kind === 'Frame' ? 1 : 0;+ return async (h, self, args) => {+ const frame = kind === 'Page' || kind === 'Frame' ? frameOf(kind, self) : self._frame;+ const timeout = h.timeout(frame, args[sel + OPT_INDEX[name]]?.timeout);+ try {+ return await ACTION.run({ timeout, stalled: false }, () => handler(h, self, args));+ } catch (e) {+ if (!(e instanceof PageStalled)) throw e;+ throw new errors.TimeoutError(`${API_NAME[kind]}.${name}: Timeout ${Math.round(timeout)}ms exceeded.\n`+ + 'Call log:\n - waiting for the page to respond');+ }+ };+}+function patchProto(kind: Kind, proto: any): void {if (!proto || proto === Object.prototype || PATCHED.has(proto)) return;PATCHED.add(proto);- const table = kind === 'Mouse' || kind === 'Keyboard' ? INPUT_HANDLERS[kind] : handlers(kind);- for (const [name, handler] of Object.entries(table)) wrap(kind, proto, name, handler);+ if (kind === 'Mouse' || kind === 'Keyboard') {+ for (const [name, handler] of Object.entries(INPUT_HANDLERS[kind])) wrap(kind, proto, name, handler);+ return;+ }+ for (const [name, handler] of Object.entries(handlers(kind))) wrap(kind, proto, name, inAction(kind, name, handler));}/** The unpatched Playwright method `name` of `obj`'s class. */diff --git a/js/src/human/world.ts b/js/src/human/world.tsindex 87cb6ef..7b13bad 100644--- a/js/src/human/world.ts+++ b/js/src/human/world.ts@@ -14,6 +14,7 @@* Port of cloakbrowser/human/world.py.*/+import { AsyncLocalStorage } from 'node:async_hooks';import type { CDPSession, Frame, Page } from 'playwright-core';import { GLOBAL, buildInstallJs, findInjectedLiteral } from './injected.js';import { HELPERS, HELPERS_JS } from './worldHelpers.js';@@ -30,6 +31,63 @@ export class StaleElement extends Error {constructor() { super('element is not attached to the DOM'); this.name = 'StaleElement'; }}+export const DEBUG = /\bcloakbrowser\b/.test(process.env.DEBUG ?? '');++/** A browser call got no answer within the action's timeout: the page stopped+ * answering, e.g. an onchange running a synchronous XHR (#619). Every catch that+ * falls back or retries must rethrow it; the patch layer turns it into+ * Playwright's TimeoutError. */+export class PageStalled extends Error {+ constructor() { super('the page stopped answering'); this.name = 'PageStalled'; }+}++/** The humanized action in progress: its timeout (ms, 0 = no limit) and whether+ * the page stopped answering. */+export interface Action { timeout: number; stalled: boolean; }+export const ACTION = new AsyncLocalStorage<Action>();++/** Await one browser call, bounded by the action's timeout: pauses and typing+ * between calls never count, only a call the page does not answer. Once the page+ * stopped answering, later calls (key / mouse releases on the way out) are still+ * sent, but not waited on, and do not throw again. */+export async function bounded<T>(call: Promise<T>): Promise<T> {+ const act = ACTION.getStore();+ // Beyond setTimeout's range (2^31-1 ms) Node would fire at once: treat it as no limit.+ if (!act || !act.timeout || act.timeout > 2 ** 31 - 1) return call;+ const STALLED = Symbol('stalled');+ let timer: NodeJS.Timeout | undefined;+ try {+ const r = await Promise.race([call, new Promise<typeof STALLED>((res) => {+ timer = setTimeout(res, act.stalled ? 0 : act.timeout, STALLED);+ timer.unref(); // a pending bound never keeps Node alive on its own+ })]);+ if (r !== STALLED) return r as T;+ } finally {+ clearTimeout(timer);+ }+ // Abandoned: an answer that still comes arrives after the action gave up.+ call.catch((e) => { if (DEBUG) console.debug(`[cloakbrowser] browser call failed after the page stalled: ${e}`); });+ // The action already failed and is unwinding: this cleanup call was sent;+ // nothing waits for it, and every release in a cleanup loop still goes out.+ if (act.stalled) return undefined as T;+ act.stalled = true;+ throw new PageStalled();+}++/** `obj` with every method that returns a promise going through `bounded`. */+export function boundedCalls<T extends object>(obj: T): T {+ return new Proxy(obj, {+ get(target, key, receiver) {+ const v = Reflect.get(target, key, receiver);+ if (typeof v !== 'function') return v;+ return (...args: any[]) => {+ const r = v.apply(target, args);+ return r instanceof Promise ? bounded(r) : r;+ };+ },+ });+}+export interface Rect { x: number; y: number; width: number; height: number; }const STALE_MARKERS = [@@ -81,7 +139,7 @@ export function matchChild(frame: Frame, parent: Frame, kids: any[]): string | n}async function release(session: CDPSession, objectId: string): Promise<void> {- try { await session.send('Runtime.releaseObject', { objectId }); } catch { /* gone */ }+ try { await session.send('Runtime.releaseObject', { objectId }); } catch (e) { if (e instanceof PageStalled) throw e; /* gone */ }}/** Isolated worlds for all frames of one Playwright page. */@@ -105,7 +163,7 @@ export class Worlds {async session(): Promise<CDPSession> {if (this._session) return this._session;- if (!this._sessionP) this._sessionP = this.page.context().newCDPSession(this.page);+ if (!this._sessionP) this._sessionP = bounded(this.page.context().newCDPSession(this.page)).then(boundedCalls);try {this._session = await this._sessionP;} finally {@@ -146,8 +204,8 @@ export class Worlds {private async locateChild(frame: Frame, parent: Frame): Promise<FrameRec> {let own: CDPSession | null = null;try { // out-of-process iframe: it has its own target/session- own = await this.page.context().newCDPSession(frame);- } catch { own = null; }+ own = boundedCalls(await bounded(this.page.context().newCDPSession(frame)));+ } catch (e) { if (e instanceof PageStalled) throw e; own = null; }if (own) {const tree: any = await own.send('Page.getFrameTree');return { session: own, cdpId: tree.frameTree.frame.id, ctx: null };@@ -163,7 +221,7 @@ export class Worlds {async frameForCdpId(parent: Frame, cdpId: string): Promise<Frame | null> {for (const child of parent.childFrames()) {- try { if ((await this.locate(child)).cdpId === cdpId) return child; } catch { /* skip */ }+ try { if ((await this.locate(child)).cdpId === cdpId) return child; } catch (e) { if (e instanceof PageStalled) throw e; /* skip */ }}return null;}diff --git a/js/tests/humanize.test.ts b/js/tests/humanize.test.tsindex 517050d..cec907b 100644--- a/js/tests/humanize.test.ts+++ b/js/tests/humanize.test.ts@@ -619,3 +619,11 @@ describe("matchChild", () => {});});++describe("bounded browser calls (#619)", () => {+ it("a timeout beyond setTimeout's range means no limit, not an instant stall", async () => {+ const { ACTION, bounded } = await import("../src/human/world.js");+ const call = new Promise((r) => setTimeout(() => r("ok"), 50));+ expect(await ACTION.run({ timeout: 1e10, stalled: false }, () => bounded(call))).toBe("ok");+ });+});diff --git a/js/tests/humanizeEngine.test.ts b/js/tests/humanizeEngine.test.tsindex 89d3253..4a8ee00 100644--- a/js/tests/humanizeEngine.test.ts+++ b/js/tests/humanizeEngine.test.ts@@ -538,6 +538,91 @@ describe.skipIf(!process.env.CLOAKBROWSER_BINARY_PATH)('humanize engine (real brawait p.waitForURL('**city=b');});+ const SYNC_XHR = "var x = new XMLHttpRequest(); x.open('GET', '/hang', false); x.send();";+ const stallingSelect = (p: Page | Frame, onchange: string) => p.evaluate((js) => {+ const s = document.createElement('select'); s.id = 'stall';+ for (const [l, v] of [['-', ''], ['Alfa', 'a'], ['Bravo', 'b']]) s.add(new Option(l, v));+ s.setAttribute('onchange', js); document.body.prepend(s);+ }, onchange);++ it('selectOption times out when the page stops answering (#619)', async () => {+ const p = await open();+ await stallingSelect(p, SYNC_XHR);+ const started = Date.now();+ await expect(p.selectOption('#stall', 'b', { timeout: 2000 })).rejects.toThrow(/Timeout 2000ms exceeded/);+ expect(Date.now() - started).toBeLessThan(5000);+ });++ it('selectOption returns when its navigation never commits (#619)', async () => {+ const p = await open();+ await stallingSelect(p, "location.href = '/hang'");+ const started = Date.now();+ expect(await p.selectOption('#stall', 'b', { timeout: 5000 })).toEqual(['b']);+ expect(Date.now() - started).toBeLessThan(4500); // returned, did not wait out the timeout+ });++ it('selectOption in an iframe that navigates the top page returns (#619)', async () => {+ const p = await open();+ const f = await frame(p);+ await stallingSelect(f, "top.location.href = '/hang'");+ const started = Date.now();+ expect(await f.selectOption('#stall', 'b', { timeout: 5000 })).toEqual(['b']);+ expect(Date.now() - started).toBeLessThan(4500);+ });++ it('click times out when the page stops answering, without waiting again to release modifiers (#619)', async () => {+ const p = await open();+ await p.evaluate((js) => {+ const b = document.createElement('button'); b.id = 'stallbtn'; b.textContent = 'stall';+ b.setAttribute('onclick', js); document.body.prepend(b);+ }, SYNC_XHR);+ const started = Date.now();+ await expect(p.click('#stallbtn', { modifiers: ['Shift', 'Alt'], timeout: 2000 })).rejects.toThrow(/waiting for the page to respond/);+ expect(Date.now() - started).toBeLessThan(3500); // one wait of 2s, not one more per held modifier+ });++ it('a stall leaves no modifier key held (#619)', async () => {+ // A click with modifiers on a page that stalls still releases every modifier+ // (the page gets the releases once it answers again).+ const p = await open();+ await p.evaluate((js) => {+ const b = document.createElement('button'); b.id = 'stallbtn'; b.textContent = 'stall';+ b.setAttribute('onclick', js); document.body.prepend(b);+ }, "var x = new XMLHttpRequest(); x.open('GET', '/slow', false); x.send();");+ await expect(p.click('#stallbtn', { modifiers: ['Shift', 'Alt'], timeout: 1000 })).rejects.toThrow(/waiting for the page to respond/);+ await p.evaluate('1'); // returns once the page answers again+ await reset(p);+ await p.click('#btn');+ const down = (await events(p, 'mousedown')).at(-1);+ expect([down.shift, down.alt]).toEqual([false, false]);+ });++ it('typing times out when the page stops answering (#619)', async () => {+ const p = await open();+ await p.evaluate((js) => {+ const i = document.createElement('input'); i.id = 'stallin';+ i.setAttribute('oninput', js); document.body.prepend(i);+ }, SYNC_XHR);+ const started = Date.now();+ await expect(p.fill('#stallin', 'abcdef', { timeout: 2000 })).rejects.toThrow(/waiting for the page to respond/);+ expect(Date.now() - started).toBeLessThan(5000);+ });++ it('human pauses do not count against the timeout (#619)', async () => {+ // Only a browser call that gets no answer times out, not the deliberate pauses.+ const p = await open();+ await p.fill('#name', 'ab', { timeout: 1000, human_config: { field_switch_delay: [2500, 2500] } } as any);+ expect(await value(p, '#name')).toBe('ab');+ });++ it('a long fill is not cut off by the timeout (#619)', async () => {+ // Typing is slow by design; each key answers in time, so a long fill finishes.+ const p = await open();+ const text = 'x'.repeat(40);+ await p.fill('#name', text, { timeout: 1000, human_config: { typing_delay: 60 } } as any);+ expect(await value(p, '#name')).toBe(text);+ });+// --- frames and handles ---------------------------------------------------it('frame actions', async () => {diff --git a/js/tests/humanizeHarness.ts b/js/tests/humanizeHarness.tsindex 8c54c5a..d3fd792 100644--- a/js/tests/humanizeHarness.ts+++ b/js/tests/humanizeHarness.ts@@ -277,13 +277,18 @@ const PAGES: Record<string, string> = { '/index.html': INDEX_HTML, '/frame.html'export async function startServer(): Promise<{ url: string; close: () => Promise<void> }> {const srv = http.createServer((req, res) => {+ if ((req.url ?? '').startsWith('/hang')) return; // a server that never answers+ if ((req.url ?? '').startsWith('/slow')) { setTimeout(() => { res.writeHead(204); res.end(); }, 3000); return; } // answers, lateconst body = PAGES[(req.url ?? '/').split('?')[0]];res.writeHead(body ? 200 : 404, { 'content-type': 'text/html; charset=utf-8' });res.end(body ?? '');});await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r));const { port } = srv.address() as AddressInfo;- return { url: `http://127.0.0.1:${port}/`, close: () => new Promise((r) => srv.close(() => r())) };+ return {+ url: `http://127.0.0.1:${port}/`,+ close: () => new Promise((r) => { srv.closeAllConnections(); srv.close(() => r()); }),+ };}/** Recorded input events, optionally filtered by type. */diff --git a/tests/test_humanize_engine.py b/tests/test_humanize_engine.pyindex 9727bfe..add3fa7 100644--- a/tests/test_humanize_engine.py+++ b/tests/test_humanize_engine.py@@ -274,6 +274,14 @@ _PAGES = {"/index.html": INDEX_HTML, "/frame.html": FRAME_HTML}class _Handler(http.server.BaseHTTPRequestHandler):def do_GET(self) -> None: # noqa: N802+ if self.path.startswith("/hang"):+ time.sleep(30) # a server that never answers+ return+ if self.path.startswith("/slow"):+ time.sleep(3) # answers, late+ self.send_response(204)+ self.end_headers()+ returnbody = _PAGES.get(self.path.split("?")[0])self.send_response(200 if body else 404)self.send_header("content-type", "text/html; charset=utf-8")@@ -861,6 +869,105 @@ def test_select_option_that_navigates_the_page(page):page.wait_for_url("**city=b")+SYNC_XHR = "var x = new XMLHttpRequest(); x.open('GET', '/hang', false); x.send();"+++def _stalling_select(target, onchange):+ target.evaluate("""js => { const s = document.createElement('select'); s.id = 'stall';+ for (const [l, v] of [['-', ''], ['Alfa', 'a'], ['Bravo', 'b']]) s.add(new Option(l, v));+ s.setAttribute('onchange', js); document.body.prepend(s); }""", onchange)+++def test_select_option_times_out_when_the_page_stops_answering(page):+ """#619: timeout= holds even when a call to the page never returns."""+ _stalling_select(page, SYNC_XHR)+ started = time.monotonic()+ with pytest.raises(TimeoutError, match="Timeout 2000ms exceeded"):+ page.select_option("#stall", "b", timeout=2000)+ assert time.monotonic() - started < 5+++def test_select_option_returns_when_its_navigation_never_commits(page):+ """#619: the pick started a navigation the server never answers; Playwright returns at once."""+ _stalling_select(page, "location.href = '/hang'")+ started = time.monotonic()+ assert page.select_option("#stall", "b", timeout=5000) == ["b"]+ assert time.monotonic() - started < 4.5 # returned, did not wait out the timeout+++def test_select_option_in_a_frame_that_navigates_the_top_page(page):+ """#619: a pick in an iframe that navigates the top page also counts as a navigation."""+ f = frame(page)+ _stalling_select(f, "top.location.href = '/hang'")+ started = time.monotonic()+ assert f.select_option("#stall", "b", timeout=5000) == ["b"]+ assert time.monotonic() - started < 4.5+++def test_click_times_out_when_the_page_stops_answering(page):+ """#619: the timeout holds for every humanized action, not just select_option;+ releasing the held modifiers afterwards does not wait out the timeout again."""+ page.evaluate("""js => { const b = document.createElement('button'); b.id = 'stallbtn';+ b.textContent = 'stall'; b.setAttribute('onclick', js); document.body.prepend(b); }""", SYNC_XHR)+ started = time.monotonic()+ with pytest.raises(TimeoutError, match="waiting for the page to respond"):+ page.click("#stallbtn", modifiers=["Shift", "Alt"], timeout=2000)+ assert time.monotonic() - started < 3.5 # one wait of 2s, not one more per held modifier+++def test_a_stall_leaves_no_modifier_key_held(page):+ """#619: a click with modifiers on a page that stalls still releases every+ modifier (the page gets the releases once it answers again)."""+ page.evaluate("""js => { const b = document.createElement('button'); b.id = 'stallbtn';+ b.textContent = 'stall'; b.setAttribute('onclick', js); document.body.prepend(b); }""",+ "var x = new XMLHttpRequest(); x.open('GET', '/slow', false); x.send();")+ with pytest.raises(TimeoutError, match="waiting for the page to respond"):+ page.click("#stallbtn", modifiers=["Shift", "Alt"], timeout=1000)+ page.evaluate("1") # returns once the page answers again+ reset(page)+ page.click("#btn")+ down = events(page, "mousedown")[-1]+ assert not down["shift"] and not down["alt"], down+++def test_typing_times_out_when_the_page_stops_answering(page):+ """#619: a field whose input handler stalls the page times out."""+ page.evaluate("""js => { const i = document.createElement('input'); i.id = 'stallin';+ i.setAttribute('oninput', js); document.body.prepend(i); }""", SYNC_XHR)+ started = time.monotonic()+ with pytest.raises(TimeoutError, match="waiting for the page to respond"):+ page.fill("#stallin", "abcdef", timeout=2000)+ assert time.monotonic() - started < 5+++def test_human_pauses_do_not_count_against_the_timeout(page):+ """#619: only a browser call that gets no answer times out, not the deliberate pauses."""+ page.fill("#name", "ab", timeout=1000, human_config={"field_switch_delay": (2500, 2500)})+ assert value(page, "#name") == "ab"+++def test_long_fill_is_not_cut_off_by_the_timeout(page):+ """#619: typing is slow by design; each key answers in time, so a long fill finishes."""+ text = "x" * 40+ page.fill("#name", text, timeout=1000, human_config={"typing_delay": 60})+ assert value(page, "#name") == text+++def test_bounded_calls_keep_the_idle_between_actions(page, monkeypatch):+ """#619: bounding browser calls must not mark a top-level action as nested (nested calls skip the idle)."""+ from cloakbrowser.human.engine import Human+ calls = []+ orig = Human.idle++ async def spy(self, cfg):+ calls.append(cfg)+ await orig(self, cfg)++ monkeypatch.setattr(Human, "idle", spy)+ page.click("#btn")+ assert calls++# --- frames and handles ------------------------------------------------------def test_frame_actions(page):diff --git a/tests/test_humanize_unit.py b/tests/test_humanize_unit.pyindex 3ea511b..07489a3 100644--- a/tests/test_humanize_unit.py+++ b/tests/test_humanize_unit.py@@ -1159,3 +1159,51 @@ def test_match_child_same_url_siblings_keep_attach_order_after_rename():{"id": "B", "name": "renamed", "url": "http://site.test/w.html"}]assert _match_child(a, parent, kids) == "A"assert _match_child(b, parent, kids) == "B"+++# --- #619: each browser call is bounded by the action's timeout ----------------++def test_bounded_call_times_out_and_marks_the_action_stalled():+ from cloakbrowser.human.world import ACTION, Action, PageStalled, bounded++ async def main():+ ACTION.set(Action(50))+ with pytest.raises(PageStalled):+ await bounded(asyncio.sleep(5))+ return ACTION.get().stalled++ assert asyncio.run(main()) is True+++def test_bounded_call_after_a_stall_is_sent_but_not_waited_on():+ """Once the page stopped answering, a release (key / mouse up) still goes out+ to the browser, but the action neither waits for its answer nor raises again,+ so every release of a cleanup loop goes out."""+ from cloakbrowser.human.world import ACTION, Action, bounded+ started = []++ async def call():+ started.append(True)+ await asyncio.sleep(5)++ async def main():+ act = Action(60000)+ act.stalled = True+ ACTION.set(act)+ t = time.monotonic()+ for _ in range(2):+ assert await bounded(call()) is None+ return time.monotonic() - t++ assert asyncio.run(main()) < 1 and len(started) == 2+++def test_bounded_call_has_no_limit_outside_an_action_or_with_timeout_zero():+ from cloakbrowser.human.world import ACTION, Action, bounded++ async def main():+ assert await bounded(asyncio.sleep(0.1, "out")) == "out"+ ACTION.set(Action(0))+ assert await bounded(asyncio.sleep(0.1, "zero")) == "zero"++ asyncio.run(main())