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): scroll the x axis in scroll-into-view (#521) (#554)
Shubham65b23cac5100
diff --git a/cloakbrowser/human/scroll.py b/cloakbrowser/human/scroll.pyindex 4b15652..1b06797 100644--- a/cloakbrowser/human/scroll.py+++ b/cloakbrowser/human/scroll.py@@ -24,6 +24,10 @@ def _is_in_viewport(bounds: dict, viewport_height: int, cfg: HumanConfig) -> booreturn top_edge >= zone_top and bottom_edge <= zone_bottom+def _is_in_viewport_x(bounds: dict, viewport_width: int) -> bool:+ return bounds["x"] >= 0 and bounds["x"] + bounds["width"] <= viewport_width++def _get_element_box(page: Any, selector: str, timeout: float = 30000) -> Optional[dict]:"""Locate ``selector`` and read geometry only in the isolated world."""world = getattr(page, "_stealth_world", None)@@ -46,14 +50,19 @@ def _get_element_box(page: Any, selector: str, timeout: float = 30000) -> Optionraise StealthEvaluationError(selector)+# In RTL documents Chrome's scrollX runs from 0 down to -range, and the+# viewport takes its direction from <body> when there is one._SCROLL_JS = ("(() => { const e = document.scrollingElement || document.documentElement;"- " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight) }; })()"+ " const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);"+ " const rtl = getComputedStyle(document.body || e).direction === 'rtl';"+ " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight),"+ " x: window.scrollX, minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX }; })()")def _read_scroll_state(page: Any) -> dict:- """Read vertical scroll state only through the isolated world."""+ """Read scroll state only through the isolated world."""world = getattr(page, "_stealth_world", None)if world is None:raise StealthWorldUnavailableError()@@ -66,7 +75,7 @@ def _read_scroll_state(page: Any) -> dict:return state-def _smooth_wheel(raw: RawMouse, delta: int, cfg: HumanConfig) -> None:+def _smooth_wheel(raw: RawMouse, delta: int, cfg: HumanConfig, axis: str = "y") -> None:"""Send one logical scroll as a burst of small wheel events (like real inertia)."""abs_d = abs(delta)sign = 1 if delta > 0 else -1@@ -74,7 +83,11 @@ def _smooth_wheel(raw: RawMouse, delta: int, cfg: HumanConfig) -> None:while sent < abs_d:step_size = rand(20, 40)chunk = min(step_size, abs_d - sent)- raw.wheel(0, round(chunk) * sign)+ step = round(chunk) * sign+ if axis == "x":+ raw.wheel(step, 0)+ else:+ raw.wheel(0, step)sent += chunksleep_ms(rand(8, 20))@@ -115,6 +128,24 @@ def human_scroll_into_view(viewport_height = viewport["height"]viewport_width = viewport["width"]+ box, cursor_x, cursor_y, did_scroll_y = _scroll_y_into_view(+ page, raw, get_box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,+ )+ box, cursor_x, cursor_y, did_scroll_x = _scroll_x_into_view(+ page, raw, get_box, box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,+ )+ return box, cursor_x, cursor_y, did_scroll_y or did_scroll_x+++def _scroll_y_into_view(+ page: Any,+ raw: RawMouse,+ get_box: Callable[[], Optional[dict]],+ viewport_width: int, viewport_height: int,+ cursor_x: float, cursor_y: float,+ cfg: HumanConfig,+) -> Tuple[dict, float, float, bool]:+ """Vertical pass: bring the box into ``scroll_target_zone``."""box = get_box()if box is None:raise RuntimeError("Element not found while scrolling into view")@@ -201,6 +232,50 @@ def human_scroll_into_view(return box, cursor_x, cursor_y, True+def _scroll_x_into_view(+ page: Any,+ raw: RawMouse,+ get_box: Callable[[], Optional[dict]],+ box: dict,+ viewport_width: int, viewport_height: int,+ cursor_x: float, cursor_y: float,+ cfg: HumanConfig,+) -> Tuple[dict, float, float, bool]:+ """Horizontal pass: bring the box inside the viewport width (#521).++ Only containment is checked here, not ``scroll_target_zone``: the zone is+ a vertical reading position, and horizontal overflow is the exception.+ """+ if _is_in_viewport_x(box, viewport_width):+ return box, cursor_x, cursor_y, False++ distance_to_scroll = box["x"] + box["width"] / 2 - viewport_width / 2+ # A box wider than the viewport is never contained; once centred, skip the near-zero wheel.+ if abs(distance_to_scroll) < 1:+ return box, cursor_x, cursor_y, False++ # Page pinned at the boundary in the needed direction: scrolling can't help.+ scroll = _read_scroll_state(page)+ if (scroll["x"] <= scroll["minX"]) if distance_to_scroll < 0 else (scroll["x"] >= scroll["maxX"]):+ return box, cursor_x, cursor_y, False++ scroll_area_x = round(viewport_width * rand(0.3, 0.7))+ scroll_area_y = round(viewport_height * rand(0.3, 0.7))+ human_move(raw, cursor_x, cursor_y, scroll_area_x, scroll_area_y, cfg)+ cursor_x = scroll_area_x+ cursor_y = scroll_area_y+ sleep_ms(rand_range(cfg.scroll_pre_move_delay))++ _smooth_wheel(raw, round(distance_to_scroll), cfg, axis="x")+ sleep_ms(rand_range(cfg.scroll_settle_delay))++ box = get_box()+ if box is None:+ raise RuntimeError("Element lost after scrolling into view")++ return box, cursor_x, cursor_y, True++def scroll_to_element(page: Any,raw: RawMouse,diff --git a/cloakbrowser/human/scroll_async.py b/cloakbrowser/human/scroll_async.pyindex 901ea27..7adbda3 100644--- a/cloakbrowser/human/scroll_async.py+++ b/cloakbrowser/human/scroll_async.py@@ -14,7 +14,7 @@ from typing import Any, Awaitable, Callable, Optional, Tuplefrom .config import HumanConfig, rand, rand_range, rand_int_range, async_sleep_msfrom .mouse_async import AsyncRawMouse, async_human_move-from .scroll import _is_in_viewport, _SCROLL_JS+from .scroll import _is_in_viewport, _is_in_viewport_x, _SCROLL_JSfrom .stealth_dom import (build_box_js, async_eval_parsed, EVALUATION_FAILED, NOT_FOUND, OK, UNSUPPORTED,StealthEvaluationError, StealthWorldUnavailableError,@@ -47,7 +47,7 @@ async def _get_element_box_async(async def _async_read_scroll_state(page: Any) -> dict:- """Read vertical scroll state only through the isolated world."""+ """Read scroll state only through the isolated world."""world = getattr(page, "_stealth_world", None)if world is None:raise StealthWorldUnavailableError()@@ -60,7 +60,9 @@ async def _async_read_scroll_state(page: Any) -> dict:return state-async def _async_smooth_wheel(raw: AsyncRawMouse, delta: int, cfg: HumanConfig) -> None:+async def _async_smooth_wheel(+ raw: AsyncRawMouse, delta: int, cfg: HumanConfig, axis: str = "y",+) -> None:"""Send one logical scroll as a burst of small wheel events (like real inertia)."""abs_d = abs(delta)sign = 1 if delta > 0 else -1@@ -68,7 +70,11 @@ async def _async_smooth_wheel(raw: AsyncRawMouse, delta: int, cfg: HumanConfig)while sent < abs_d:step_size = rand(20, 40)chunk = min(step_size, abs_d - sent)- await raw.wheel(0, round(chunk) * sign)+ step = round(chunk) * sign+ if axis == "x":+ await raw.wheel(step, 0)+ else:+ await raw.wheel(0, step)sent += chunkawait async_sleep_ms(rand(8, 20))@@ -108,6 +114,24 @@ async def async_human_scroll_into_view(viewport_height = viewport["height"]viewport_width = viewport["width"]+ box, cursor_x, cursor_y, did_scroll_y = await _async_scroll_y_into_view(+ page, raw, get_box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,+ )+ box, cursor_x, cursor_y, did_scroll_x = await _async_scroll_x_into_view(+ page, raw, get_box, box, viewport_width, viewport_height, cursor_x, cursor_y, cfg,+ )+ return box, cursor_x, cursor_y, did_scroll_y or did_scroll_x+++async def _async_scroll_y_into_view(+ page: Any,+ raw: AsyncRawMouse,+ get_box: Callable[[], Awaitable[Optional[dict]]],+ viewport_width: int, viewport_height: int,+ cursor_x: float, cursor_y: float,+ cfg: HumanConfig,+) -> Tuple[dict, float, float, bool]:+ """Vertical pass: bring the box into ``scroll_target_zone``."""box = await get_box()if box is None:raise RuntimeError("Element not found while scrolling into view")@@ -194,6 +218,50 @@ async def async_human_scroll_into_view(return box, cursor_x, cursor_y, True+async def _async_scroll_x_into_view(+ page: Any,+ raw: AsyncRawMouse,+ get_box: Callable[[], Awaitable[Optional[dict]]],+ box: dict,+ viewport_width: int, viewport_height: int,+ cursor_x: float, cursor_y: float,+ cfg: HumanConfig,+) -> Tuple[dict, float, float, bool]:+ """Horizontal pass: bring the box inside the viewport width (#521).++ Only containment is checked here, not ``scroll_target_zone``: the zone is+ a vertical reading position, and horizontal overflow is the exception.+ """+ if _is_in_viewport_x(box, viewport_width):+ return box, cursor_x, cursor_y, False++ distance_to_scroll = box["x"] + box["width"] / 2 - viewport_width / 2+ # A box wider than the viewport is never contained; once centred, skip the near-zero wheel.+ if abs(distance_to_scroll) < 1:+ return box, cursor_x, cursor_y, False++ # Page pinned at the boundary in the needed direction: scrolling can't help.+ scroll = await _async_read_scroll_state(page)+ if (scroll["x"] <= scroll["minX"]) if distance_to_scroll < 0 else (scroll["x"] >= scroll["maxX"]):+ return box, cursor_x, cursor_y, False++ scroll_area_x = round(viewport_width * rand(0.3, 0.7))+ scroll_area_y = round(viewport_height * rand(0.3, 0.7))+ await async_human_move(raw, cursor_x, cursor_y, scroll_area_x, scroll_area_y, cfg)+ cursor_x = scroll_area_x+ cursor_y = scroll_area_y+ await async_sleep_ms(rand_range(cfg.scroll_pre_move_delay))++ await _async_smooth_wheel(raw, round(distance_to_scroll), cfg, axis="x")+ await async_sleep_ms(rand_range(cfg.scroll_settle_delay))++ box = await get_box()+ if box is None:+ raise RuntimeError("Element lost after scrolling into view")++ return box, cursor_x, cursor_y, True++async def async_scroll_to_element(page: Any,raw: AsyncRawMouse,diff --git a/dotnet/src/CloakBrowser/Human/HumanScroll.cs b/dotnet/src/CloakBrowser/Human/HumanScroll.csindex fce3b4d..aed5ae9 100644--- a/dotnet/src/CloakBrowser/Human/HumanScroll.cs+++ b/dotnet/src/CloakBrowser/Human/HumanScroll.cs@@ -19,12 +19,14 @@ public interface IRawScrollPageTask<(int Width, int Height)?> GetLiveWindowSizeAsync();/// <summary>- /// Current vertical scroll offset (<c>window.scrollY</c>) and the maximum- /// scrollable offset (<c>scrollHeight - clientHeight</c>). Used to detect when- /// the page is pinned at a boundary and further scrolling can't help. Returns- /// null if the values can't be read.+ /// Current scroll offsets (<c>window.scrollY</c>, <c>window.scrollX</c>) and the+ /// maximum scrollable offsets (<c>scrollHeight - clientHeight</c>,+ /// <c>scrollWidth - clientWidth</c>). X is measured from the leftmost scroll+ /// position, so it runs 0..MaxX in RTL documents too. Used to detect when the+ /// page is pinned at a boundary and further scrolling can't help. Returns null+ /// if the values can't be read./// </summary>- Task<(double Y, double MaxY)?> GetScrollStateAsync();+ Task<(double Y, double MaxY, double X, double MaxX)?> GetScrollStateAsync();}/// <summary>Result of a humanized scroll-into-view operation.</summary>@@ -49,8 +51,13 @@ public static class HumanScrollreturn topEdge >= zoneTop && bottomEdge <= zoneBottom;}+ private static bool IsInViewportX(BoundingBox bounds, int viewportWidth)+ {+ return bounds.X >= 0 && bounds.X + bounds.Width <= viewportWidth;+ }+/// <summary>Send one logical scroll as a burst of small wheel events (like real inertia).</summary>- private static async Task SmoothWheelAsync(IRawMouse raw, int delta, HumanConfig cfg)+ private static async Task SmoothWheelAsync(IRawMouse raw, int delta, HumanConfig cfg, bool horizontal = false){double absD = Math.Abs(delta);int sign = delta > 0 ? 1 : -1;@@ -59,7 +66,11 @@ public static class HumanScroll{double stepSize = HumanRandom.Rand(20, 40);double chunk = Math.Min(stepSize, absD - sent);- await raw.WheelAsync(0, Math.Round(chunk) * sign).ConfigureAwait(false);+ double step = Math.Round(chunk) * sign;+ if (horizontal)+ await raw.WheelAsync(step, 0).ConfigureAwait(false);+ else+ await raw.WheelAsync(0, step).ConfigureAwait(false);sent += chunk;await HumanRandom.SleepMsAsync(HumanRandom.Rand(8, 20)).ConfigureAwait(false);}@@ -109,6 +120,20 @@ public static class HumanScrollint viewportHeight = viewport.Value.Height;int viewportWidth = viewport.Value.Width;+ var yPass = await ScrollYIntoViewAsync(page, raw, getBox, viewportWidth, viewportHeight, cursorX, cursorY, cfg).ConfigureAwait(false);+ var xPass = await ScrollXIntoViewAsync(page, raw, getBox, yPass.Box, viewportWidth, viewportHeight, yPass.CursorX, yPass.CursorY, cfg).ConfigureAwait(false);+ return xPass with { DidScroll = yPass.DidScroll || xPass.DidScroll };+ }++ /// <summary>Vertical pass: bring the box into <c>ScrollTargetZone</c>.</summary>+ private static async Task<ScrollResult> ScrollYIntoViewAsync(+ IRawScrollPage page,+ IRawMouse raw,+ Func<Task<BoundingBox?>> getBox,+ int viewportWidth, int viewportHeight,+ double cursorX, double cursorY,+ HumanConfig cfg)+ {var box = await getBox().ConfigureAwait(false);if (box == null)throw new InvalidOperationException("Element not found while scrolling into view");@@ -211,4 +236,48 @@ public static class HumanScrollreturn new ScrollResult(box.Value, cursorX, cursorY, true);}++ /// <summary>+ /// Horizontal pass: bring the box inside the viewport width (#521). Only+ /// containment is checked here, not <c>ScrollTargetZone</c>: the zone is a+ /// vertical reading position, and horizontal overflow is the exception.+ /// </summary>+ private static async Task<ScrollResult> ScrollXIntoViewAsync(+ IRawScrollPage page,+ IRawMouse raw,+ Func<Task<BoundingBox?>> getBox,+ BoundingBox box,+ int viewportWidth, int viewportHeight,+ double cursorX, double cursorY,+ HumanConfig cfg)+ {+ if (IsInViewportX(box, viewportWidth))+ return new ScrollResult(box, cursorX, cursorY, false);++ double distanceToScroll = box.X + box.Width / 2 - viewportWidth / 2.0;+ // A box wider than the viewport is never contained; once centred, skip the near-zero wheel.+ if (Math.Abs(distanceToScroll) < 1)+ return new ScrollResult(box, cursorX, cursorY, false);++ // Page pinned at the boundary in the needed direction: scrolling can't help.+ var scroll = await page.GetScrollStateAsync().ConfigureAwait(false);+ if (scroll != null && (distanceToScroll < 0 ? scroll.Value.X <= 0 : scroll.Value.X >= scroll.Value.MaxX))+ return new ScrollResult(box, cursorX, cursorY, false);++ double scrollAreaX = Math.Round(viewportWidth * HumanRandom.Rand(0.3, 0.7));+ double scrollAreaY = Math.Round(viewportHeight * HumanRandom.Rand(0.3, 0.7));+ await HumanMouse.HumanMoveAsync(raw, cursorX, cursorY, scrollAreaX, scrollAreaY, cfg).ConfigureAwait(false);+ cursorX = scrollAreaX;+ cursorY = scrollAreaY;+ await HumanRandom.SleepMsAsync(HumanRandom.RandRange(cfg.ScrollPreMoveDelay)).ConfigureAwait(false);++ await SmoothWheelAsync(raw, (int)Math.Round(distanceToScroll), cfg, horizontal: true).ConfigureAwait(false);+ await HumanRandom.SleepMsAsync(HumanRandom.RandRange(cfg.ScrollSettleDelay)).ConfigureAwait(false);++ var finalBox = await getBox().ConfigureAwait(false);+ if (finalBox == null)+ throw new InvalidOperationException("Element lost after scrolling into view");++ return new ScrollResult(finalBox.Value, cursorX, cursorY, true);+ }}diff --git a/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs b/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.csindex b581215..5cdf2a4 100644--- a/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs+++ b/dotnet/src/CloakBrowser/Human/PlaywrightAdapters.cs@@ -108,17 +108,31 @@ internal sealed class PlaywrightScrollPage : IRawScrollPagereturn (resolvedWidth, resolvedHeight);}- public async Task<(double Y, double MaxY)?> GetScrollStateAsync()+ public async Task<(double Y, double MaxY, double X, double MaxX)?> GetScrollStateAsync(){var world = await _getStealthAsync().ConfigureAwait(false);+ // In RTL documents Chrome's scrollX runs from 0 down to -range, and the+ // viewport takes its direction from <body> when there is one.var value = await world.EvaluateAsync("(() => { const e = document.scrollingElement || document.documentElement;" +- " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight) }; })()")+ " const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);" ++ " const rtl = getComputedStyle(document.body || e).direction === 'rtl';" ++ " return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight)," ++ " x: window.scrollX, minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX }; })()").ConfigureAwait(false);+ return ParseScrollState(value);+ }++ /// <summary>Shifts X and MaxX by minX so X runs from 0 at the leftmost position in LTR and RTL alike.</summary>+ internal static (double Y, double MaxY, double X, double MaxX) ParseScrollState(System.Text.Json.JsonElement? value)+ {if (value == null || value.Value.ValueKind != System.Text.Json.JsonValueKind.Object|| !value.Value.TryGetProperty("y", out var y)- || !value.Value.TryGetProperty("maxY", out var maxY))+ || !value.Value.TryGetProperty("maxY", out var maxY)+ || !value.Value.TryGetProperty("x", out var x)+ || !value.Value.TryGetProperty("minX", out var minX)+ || !value.Value.TryGetProperty("maxX", out var maxX))throw new StealthEvaluationError("<scroll-state>");- return (y.GetDouble(), maxY.GetDouble());+ return (y.GetDouble(), maxY.GetDouble(), x.GetDouble() - minX.GetDouble(), maxX.GetDouble() - minX.GetDouble());}}diff --git a/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.cs b/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.csindex 303b4d2..fa01963 100644--- a/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/ScrollFallbackTests.cs@@ -37,16 +37,16 @@ public class ScrollFallbackTestsreturn Task.FromResult(_live);}- public Task<(double Y, double MaxY)?> GetScrollStateAsync() =>- Task.FromResult<(double, double)?>((0, 0));+ public Task<(double Y, double MaxY, double X, double MaxX)?> GetScrollStateAsync() =>+ Task.FromResult<(double, double, double, double)?>((0, 0, 0, 0));}/// <summary>Scroll page with a fixed viewport and configurable scroll position.</summary>private sealed class ViewportPage : IRawScrollPage{private readonly (int, int) _size;- private readonly (double, double)? _scroll;- public ViewportPage((int, int) size, (double, double)? scroll)+ private readonly (double, double, double, double)? _scroll;+ public ViewportPage((int, int) size, (double, double, double, double)? scroll){_size = size;_scroll = scroll;@@ -55,17 +55,18 @@ public class ScrollFallbackTestspublic (int Width, int Height)? ViewportSize => _size;public Task<(int Width, int Height)?> GetLiveWindowSizeAsync() =>Task.FromResult<(int, int)?>(_size);- public Task<(double Y, double MaxY)?> GetScrollStateAsync() =>+ public Task<(double Y, double MaxY, double X, double MaxX)?> GetScrollStateAsync() =>Task.FromResult(_scroll);}private sealed class CountingMouse : IRawMouse{- public int WheelCalls { get; private set; }+ public List<(double Dx, double Dy)> Wheels { get; } = new();+ public int WheelCalls => Wheels.Count;public Task MoveAsync(double x, double y) => Task.CompletedTask;public Task DownAsync() => Task.CompletedTask;public Task UpAsync() => Task.CompletedTask;- public Task WheelAsync(double dx, double dy) { WheelCalls++; return Task.CompletedTask; }+ public Task WheelAsync(double dx, double dy) { Wheels.Add((dx, dy)); return Task.CompletedTask; }}// Zero out the timing ranges so the scroll loop runs instantly in tests.@@ -127,7 +128,7 @@ public class ScrollFallbackTests{// viewport 720 -> zone [144, 576]; element top=50 is above the zone but// fully visible, and the page is pinned at the top (y=0). Must not scroll.- var page = new ViewportPage((1280, 720), scroll: (0, 2000));+ var page = new ViewportPage((1280, 720), scroll: (0, 2000, 0, 0));var mouse = new CountingMouse();Func<Task<BoundingBox?>> getBox = () => Task.FromResult<BoundingBox?>(new BoundingBox(200, 50, 50, 30));@@ -141,7 +142,7 @@ public class ScrollFallbackTestspublic async Task Fully_visible_above_zone_with_room_still_scrolls(){// Same element, but the page is scrolled down (y=500) so it CAN scroll up.- var page = new ViewportPage((1280, 720), scroll: (500, 2000));+ var page = new ViewportPage((1280, 720), scroll: (500, 2000, 0, 0));var mouse = new CountingMouse();Func<Task<BoundingBox?>> getBox = () => Task.FromResult<BoundingBox?>(new BoundingBox(200, 50, 50, 30));@@ -149,4 +150,71 @@ public class ScrollFallbackTestsAssert.True(mouse.WheelCalls > 0);}++ [Fact]+ public async Task Box_past_right_edge_scrolls_x_axis_only()+ {+ // #521: viewport 1000 wide, element spans x 800..1600 on a page that can+ // scroll 600px right. The y axis is already in the zone.+ var page = new ViewportPage((1000, 700), scroll: (0, 0, 0, 600));+ var mouse = new CountingMouse();+ var boxes = new Queue<BoundingBox?>(new BoundingBox?[]+ {+ new BoundingBox(800, 300, 800, 30),+ new BoundingBox(200, 300, 800, 30),+ });+ Func<Task<BoundingBox?>> getBox = () => Task.FromResult(boxes.Dequeue());++ var result = await HumanScroll.HumanScrollIntoViewAsync(page, mouse, getBox, 0, 0, FastConfig());++ Assert.True(result.DidScroll);+ Assert.Equal(200, result.Box.X);+ Assert.NotEmpty(mouse.Wheels);+ Assert.All(mouse.Wheels, w =>+ {+ Assert.True(w.Dx > 0);+ Assert.Equal(0, w.Dy);+ });+ }++ [Fact]+ public async Task Box_past_right_edge_with_page_pinned_right_bails_without_scrolling()+ {+ var page = new ViewportPage((1000, 700), scroll: (0, 0, 600, 600));+ var mouse = new CountingMouse();+ Func<Task<BoundingBox?>> getBox = () => Task.FromResult<BoundingBox?>(new BoundingBox(900, 300, 200, 30));++ var result = await HumanScroll.HumanScrollIntoViewAsync(page, mouse, getBox, 0, 0, FastConfig());++ Assert.False(result.DidScroll);+ Assert.Equal(0, mouse.WheelCalls);+ }++ [Fact]+ public async Task Rtl_page_at_start_scrolls_x_axis_left()+ {+ // RTL page at its start: scrollX 0 with a range of -600..0. The element+ // sits in the left overflow, so the page is not pinned in that direction.+ var scroll = PlaywrightScrollPage.ParseScrollState(System.Text.Json.JsonDocument.Parse(+ """{"y":0,"maxY":0,"x":0,"minX":-600,"maxX":0}""").RootElement);+ var page = new ViewportPage((1000, 700), scroll);+ var mouse = new CountingMouse();+ var boxes = new Queue<BoundingBox?>(new BoundingBox?[]+ {+ new BoundingBox(-600, 300, 200, 30),+ new BoundingBox(400, 300, 200, 30),+ });+ Func<Task<BoundingBox?>> getBox = () => Task.FromResult(boxes.Dequeue());++ var result = await HumanScroll.HumanScrollIntoViewAsync(page, mouse, getBox, 0, 0, FastConfig());++ Assert.True(result.DidScroll);+ Assert.Equal(400, result.Box.X);+ Assert.NotEmpty(mouse.Wheels);+ Assert.All(mouse.Wheels, w =>+ {+ Assert.True(w.Dx < 0);+ Assert.Equal(0, w.Dy);+ });+ }}diff --git a/js/src/human-puppeteer/scroll.ts b/js/src/human-puppeteer/scroll.tsindex 3108be5..6fedc62 100644--- a/js/src/human-puppeteer/scroll.ts+++ b/js/src/human-puppeteer/scroll.ts@@ -32,6 +32,10 @@ function isInViewport(return topEdge >= zoneTop && bottomEdge <= zoneBottom;}+function isInViewportX(bounds: ElementBounds, viewportWidth: number): boolean {+ return bounds.x >= 0 && bounds.x + bounds.width <= viewportWidth;+}+export async function smoothWheel(raw: RawMouse,delta: number,@@ -104,6 +108,19 @@ export async function humanScrollIntoView(}if (!viewport || !viewport.height) throw new Error('Viewport size not available');+ const yPass = await scrollYIntoView(raw, getBox, viewport, cursorX, cursorY, cfg);+ return scrollXIntoView(raw, getBox, yPass.box, viewport, yPass.cursorX, yPass.cursorY, cfg);+}++/** Vertical pass: bring the box into ``scroll_target_zone``. */+async function scrollYIntoView(+ raw: RawMouse,+ getBox: () => Promise<ElementBounds | null>,+ viewport: { width: number; height: number },+ cursorX: number,+ cursorY: number,+ cfg: HumanConfig,+): Promise<{ box: ElementBounds; cursorX: number; cursorY: number }> {let box = await getBox();if (!box) throw new Error('Element not found while scrolling into view');@@ -187,6 +204,46 @@ export async function humanScrollIntoView(return { box, cursorX, cursorY };}+/**+ * Horizontal pass: bring the box inside the viewport width (#521).+ *+ * Only containment is checked here, not ``scroll_target_zone``: the zone is a+ * vertical reading position, and horizontal overflow is the exception.+ */+async function scrollXIntoView(+ raw: RawMouse,+ getBox: () => Promise<ElementBounds | null>,+ box: ElementBounds,+ viewport: { width: number; height: number },+ cursorX: number,+ cursorY: number,+ cfg: HumanConfig,+): Promise<{ box: ElementBounds; cursorX: number; cursorY: number }> {+ if (isInViewportX(box, viewport.width)) {+ return { box, cursorX, cursorY };+ }++ const distanceToScroll = box.x + box.width / 2 - viewport.width / 2;+ // A box wider than the viewport is never contained; once centred, skip the near-zero wheel.+ if (Math.abs(distanceToScroll) < 1) {+ return { box, cursorX, cursorY };+ }++ const scrollAreaX = Math.round(viewport.width * rand(0.3, 0.7));+ const scrollAreaY = Math.round(viewport.height * rand(0.3, 0.7));+ await humanMove(raw, cursorX, cursorY, scrollAreaX, scrollAreaY, cfg);+ cursorX = scrollAreaX;+ cursorY = scrollAreaY;+ await sleep(randRange(cfg.scroll_pre_move_delay));++ await smoothWheel(raw, Math.round(distanceToScroll), cfg, 'x');+ await sleep(randRange(cfg.scroll_settle_delay));++ const finalBox = await getBox();+ if (!finalBox) throw new Error('Element lost after scrolling into view');+ return { box: finalBox, cursorX, cursorY };+}+/*** Selector-based humanized scroll (Puppeteer).*diff --git a/js/src/human/scroll.ts b/js/src/human/scroll.tsindex 37921b5..b4d54ed 100644--- a/js/src/human/scroll.ts+++ b/js/src/human/scroll.ts@@ -39,18 +39,31 @@ function isInViewport(return topEdge >= zoneTop && bottomEdge <= zoneBottom;}+function isInViewportX(bounds: ElementBounds, viewportWidth: number): boolean {+ return bounds.x >= 0 && bounds.x + bounds.width <= viewportWidth;+}++// In RTL documents Chrome's scrollX runs from 0 down to -range, and the+// viewport takes its direction from <body> when there is one.const SCROLL_JS ='(() => { const e = document.scrollingElement || document.documentElement;' +- ' return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight) }; })()';+ ' const rangeX = Math.max(0, e.scrollWidth - e.clientWidth);' ++ " const rtl = getComputedStyle(document.body || e).direction === 'rtl';" ++ ' return { y: window.scrollY, maxY: Math.max(0, e.scrollHeight - e.clientHeight),' ++ ' x: window.scrollX, minX: rtl ? -rangeX : 0, maxX: rtl ? 0 : rangeX }; })()';-async function readScrollState(page: Page): Promise<{ y: number; maxY: number }> {+async function readScrollState(+ page: Page,+): Promise<{ y: number; maxY: number; x: number; minX: number; maxX: number }> {const world = getWorld(page);if (!world) throw new StealthWorldUnavailableError();try {const state = await world.evaluate(SCROLL_JS);if (!state || typeof state !== 'object' ||- typeof state.y !== 'number' || typeof state.maxY !== 'number'+ typeof state.y !== 'number' || typeof state.maxY !== 'number' ||+ typeof state.x !== 'number' || typeof state.minX !== 'number' ||+ typeof state.maxX !== 'number') {throw new StealthEvaluationError('<scroll-state>');}@@ -61,14 +74,24 @@ async function readScrollState(page: Page): Promise<{ y: number; maxY: number }>}}-async function smoothWheel(raw: RawMouse, delta: number, cfg: HumanConfig): Promise<void> {+async function smoothWheel(+ raw: RawMouse,+ delta: number,+ cfg: HumanConfig,+ axis: 'x' | 'y' = 'y',+): Promise<void> {const absD = Math.abs(delta);const sign = delta > 0 ? 1 : -1;let sent = 0;while (sent < absD) {const stepSize = rand(20, 40);const chunk = Math.min(stepSize, absD - sent);- await raw.wheel(0, Math.round(chunk) * sign);+ const d = Math.round(chunk) * sign;+ if (axis === 'x') {+ await raw.wheel(d, 0);+ } else {+ await raw.wheel(0, d);+ }sent += chunk;await sleep(rand(8, 20));}@@ -94,6 +117,23 @@ export async function humanScrollIntoView<T extends ElementBounds>(}if (!viewport || !viewport.height) throw new Error('Viewport size not available');+ const yPass = await scrollYIntoView(page, raw, getBox, viewport, cursorX, cursorY, cfg);+ const xPass = await scrollXIntoView(+ page, raw, getBox, yPass.box, viewport, yPass.cursorX, yPass.cursorY, cfg,+ );+ return { ...xPass, didScroll: yPass.didScroll || xPass.didScroll };+}++/** Vertical pass: bring the box into ``scroll_target_zone``. */+async function scrollYIntoView<T extends ElementBounds>(+ page: Page,+ raw: RawMouse,+ getBox: () => Promise<T | null>,+ viewport: { width: number; height: number },+ cursorX: number,+ cursorY: number,+ cfg: HumanConfig,+): Promise<{ box: T; cursorX: number; cursorY: number; didScroll: boolean }> {let box = await getBox();if (!box) throw new Error('Element not found while scrolling into view');@@ -180,6 +220,53 @@ export async function humanScrollIntoView<T extends ElementBounds>(return { box: finalBox, cursorX, cursorY, didScroll: true };}+/**+ * Horizontal pass: bring the box inside the viewport width (#521).+ *+ * Only containment is checked here, not ``scroll_target_zone``: the zone is a+ * vertical reading position, and horizontal overflow is the exception.+ */+async function scrollXIntoView<T extends ElementBounds>(+ page: Page,+ raw: RawMouse,+ getBox: () => Promise<T | null>,+ box: T,+ viewport: { width: number; height: number },+ cursorX: number,+ cursorY: number,+ cfg: HumanConfig,+): Promise<{ box: T; cursorX: number; cursorY: number; didScroll: boolean }> {+ if (isInViewportX(box, viewport.width)) {+ return { box, cursorX, cursorY, didScroll: false };+ }++ const distanceToScroll = box.x + box.width / 2 - viewport.width / 2;+ // A box wider than the viewport is never contained; once centred, skip the near-zero wheel.+ if (Math.abs(distanceToScroll) < 1) {+ return { box, cursorX, cursorY, didScroll: false };+ }++ // Page pinned at the boundary in the needed direction: scrolling can't help.+ const { x, minX, maxX } = await readScrollState(page);+ if (distanceToScroll < 0 ? x <= minX : x >= maxX) {+ return { box, cursorX, cursorY, didScroll: false };+ }++ const scrollAreaX = Math.round(viewport.width * rand(0.3, 0.7));+ const scrollAreaY = Math.round(viewport.height * rand(0.3, 0.7));+ await humanMove(raw, cursorX, cursorY, scrollAreaX, scrollAreaY, cfg);+ cursorX = scrollAreaX;+ cursorY = scrollAreaY;+ await sleep(randRange(cfg.scroll_pre_move_delay));++ await smoothWheel(raw, Math.round(distanceToScroll), cfg, 'x');+ await sleep(randRange(cfg.scroll_settle_delay));++ const finalBox = await getBox();+ if (!finalBox) throw new Error('Element lost after scrolling into view');+ return { box: finalBox, cursorX, cursorY, didScroll: true };+}+export async function scrollToElement(page: Page,raw: RawMouse,diff --git a/js/tests/humanize.test.ts b/js/tests/humanize.test.tsindex d70a414..30bbbf8 100644--- a/js/tests/humanize.test.ts+++ b/js/tests/humanize.test.ts@@ -1619,7 +1619,7 @@ describe("humanScrollIntoView", () => {const page: any = {viewportSize: () => ({ width: 1280, height: 720 }),evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 2000 })) },+ _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 2000, x: 0, minX: 0, maxX: 0 })) },};const raw = {move: vi.fn(async () => { }), down: vi.fn(async () => { }),@@ -1645,7 +1645,7 @@ describe("humanScrollIntoView", () => {const page: any = {viewportSize: () => ({ width: 1280, height: 720 }),evaluate: vi.fn(),- _stealth: { evaluate: vi.fn(async () => ({ y: 500, maxY: 2000 })) },+ _stealth: { evaluate: vi.fn(async () => ({ y: 500, maxY: 2000, x: 0, minX: 0, maxX: 0 })) },};const raw = {move: vi.fn(async () => { }), down: vi.fn(async () => { }),@@ -1658,6 +1658,96 @@ describe("humanScrollIntoView", () => {expect(raw.wheel).toHaveBeenCalled();expect(page.evaluate).not.toHaveBeenCalled();}, 15000);++ it("scrolls the x axis for an element past the right edge (#521)", async () => {+ const { humanScrollIntoView } = await import("../src/human/scroll.js");+ const cfg = resolveConfig("default", {+ scroll_pre_move_delay: [0, 1], scroll_settle_delay: [0, 1],+ });++ const page: any = {+ viewportSize: () => ({ width: 1000, height: 700 }),+ evaluate: vi.fn(),+ _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 0, minX: 0, maxX: 600 })) },+ };+ const raw = {+ move: vi.fn(async () => { }), down: vi.fn(async () => { }),+ up: vi.fn(async () => { }), wheel: vi.fn(async (_dx: number, _dy: number) => { }),+ };+ const boxes = [+ { x: 800, y: 300, width: 800, height: 30 },+ { x: 200, y: 300, width: 800, height: 30 },+ ];+ let i = 0;+ const getBox = async () => boxes[i++];++ const result = await humanScrollIntoView(page, raw, getBox, 0, 0, cfg);++ expect(result.didScroll).toBe(true);+ expect(result.box.x).toBe(200);+ expect(raw.wheel).toHaveBeenCalled();+ for (const [dx, dy] of raw.wheel.mock.calls) {+ expect(dx).toBeGreaterThan(0);+ expect(dy).toBe(0);+ }+ expect(page.evaluate).not.toHaveBeenCalled();+ }, 15000);++ it("skips the x axis when the page is already scrolled fully right", async () => {+ const { humanScrollIntoView } = await import("../src/human/scroll.js");+ const cfg = resolveConfig("default");++ const page: any = {+ viewportSize: () => ({ width: 1000, height: 700 }),+ evaluate: vi.fn(),+ _stealth: { evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 600, minX: 0, maxX: 600 })) },+ };+ const raw = {+ move: vi.fn(async () => { }), down: vi.fn(async () => { }),+ up: vi.fn(async () => { }), wheel: vi.fn(async () => { }),+ };+ const clippedBox = { x: 900, y: 300, width: 200, height: 30 };++ const result = await humanScrollIntoView(page, raw, async () => clippedBox, 0, 0, cfg);++ expect(result.didScroll).toBe(false);+ expect(raw.wheel).not.toHaveBeenCalled();+ });++ it("scrolls the x axis left on an RTL page at its start", async () => {+ const { humanScrollIntoView } = await import("../src/human/scroll.js");+ const cfg = resolveConfig("default", {+ scroll_pre_move_delay: [0, 1], scroll_settle_delay: [0, 1],+ });++ const page: any = {+ viewportSize: () => ({ width: 1000, height: 700 }),+ evaluate: vi.fn(),+ _stealth: {+ evaluate: vi.fn(async () => ({ y: 0, maxY: 0, x: 0, minX: -600, maxX: 0 })),+ },+ };+ const raw = {+ move: vi.fn(async () => { }), down: vi.fn(async () => { }),+ up: vi.fn(async () => { }), wheel: vi.fn(async (_dx: number, _dy: number) => { }),+ };+ const boxes = [+ { x: -600, y: 300, width: 200, height: 30 },+ { x: 400, y: 300, width: 200, height: 30 },+ ];+ let i = 0;+ const getBox = async () => boxes[i++];++ const result = await humanScrollIntoView(page, raw, getBox, 0, 0, cfg);++ expect(result.didScroll).toBe(true);+ expect(result.box.x).toBe(400);+ expect(raw.wheel).toHaveBeenCalled();+ for (const [dx, dy] of raw.wheel.mock.calls) {+ expect(dx).toBeLessThan(0);+ expect(dy).toBe(0);+ }+ }, 15000);});describe("el.scrollIntoViewIfNeeded humanization", () => {diff --git a/js/tests/stealth.puppeteer.test.ts b/js/tests/stealth.puppeteer.test.tsindex fe71bb8..ae805db 100644--- a/js/tests/stealth.puppeteer.test.ts+++ b/js/tests/stealth.puppeteer.test.ts@@ -954,6 +954,36 @@ describe("Puppeteer: mouse.wheel() smooth scroll", () => {// =========================================================================// mouse.dragAndDrop() — Bézier drag between coordinates// =========================================================================+describe("Puppeteer: humanScrollIntoView x axis (#521)", () => {+ it("scrolls the x axis for an element past the right edge", async () => {+ const { humanScrollIntoView } = await import("../src/human-puppeteer/scroll.js");+ const cfg = resolveConfig("default", {+ scroll_pre_move_delay: [0, 1], scroll_settle_delay: [0, 1],+ });++ const page: any = { viewport: () => ({ width: 1000, height: 700 }) };+ const raw = {+ move: vi.fn(async () => {}), down: vi.fn(async () => {}),+ up: vi.fn(async () => {}), wheel: vi.fn(async (_dx: number, _dy: number) => {}),+ };+ const boxes = [+ { x: 800, y: 300, width: 800, height: 30 },+ { x: 200, y: 300, width: 800, height: 30 },+ ];+ let i = 0;+ const getBox = async () => boxes[i++];++ const result = await humanScrollIntoView(page, raw as any, getBox, 0, 0, cfg);++ expect(result.box.x).toBe(200);+ expect(raw.wheel).toHaveBeenCalled();+ for (const [dx, dy] of raw.wheel.mock.calls) {+ expect(dx).toBeGreaterThan(0);+ expect(dy).toBe(0);+ }+ }, 15000);+});+describe("Puppeteer: mouse.dragAndDrop() humanization", () => {it("mouse.dragAndDrop is patched after patchPage", async () => {const { patchPage } = await import("../src/human-puppeteer/index.js");@@ -2193,6 +2223,32 @@ describeIfSlow("Puppeteer stealth browser: focus() uses click", () => {}, 30000);});+const WIDE_ROW_HTML = `+ <body style="margin:0">+ <div style="display:flex">+ <div style="min-width:800px">left</div>+ <button id="target" style="min-width:800px"+ onclick="this.textContent = 'CLICKED'">right</button>+ </div>+ </body>`;++describeIfSlow("Puppeteer stealth browser: horizontal scroll into view (#521)", () => {+ it("clicks a target past the right edge of a horizontally overflowing page", async () => {+ const { launch } = await import("../src/puppeteer.js");+ const browser = await launch({ humanize: true, headless: true });+ try {+ const page = await browser.newPage();+ await page.setViewport({ width: 1000, height: 700 });+ await page.setContent(WIDE_ROW_HTML);+ await page.click("#target");+ await sleep(500);+ expect(await page.$eval("#target", (el) => el.textContent)).toBe("CLICKED");+ } finally {+ await browser.close();+ }+ }, 60000);+});+describeIfSlow("Puppeteer stealth browser: mouse.wheel smooth scroll", () => {it("mouse.wheel generates multiple small scroll events", async () => {const { launch } = await import("../src/puppeteer.js");diff --git a/js/tests/stealth.test.ts b/js/tests/stealth.test.tsindex fa5b35d..a159533 100644--- a/js/tests/stealth.test.ts+++ b/js/tests/stealth.test.ts@@ -1305,6 +1305,31 @@ describeIfSlow("stealth browser: selector parity and target identity", () => {}, 60000);});+// page.setContent timed out in local runs of this test, so the page is loaded as a data: URL.+const WIDE_ROW_HTML = `+ <body style="margin:0">+ <div style="display:flex">+ <div style="min-width:800px">left</div>+ <button id="target" style="min-width:800px"+ onclick="this.textContent = 'CLICKED'">right</button>+ </div>+ </body>`;++describeIfSlow("stealth browser: horizontal scroll into view (#521)", () => {+ it("clicks a target past the right edge of a horizontally overflowing page", async () => {+ const { launch } = await import("../src/index.js");+ const browser = await launch({ headless: true, humanize: true });+ try {+ const page = await browser.newPage({ viewport: { width: 1000, height: 700 } });+ await page.goto("data:text/html," + encodeURIComponent(WIDE_ROW_HTML));+ await page.click("#target", { timeout: 5000 });+ expect(await page.locator("#target").textContent()).toBe("CLICKED");+ } finally {+ await browser.close();+ }+ }, 60000);+});+describeIfSlow("stealth browser: full form no evaluate leak", () => {it("form with shift symbols has zero evaluate leaks and zero untrusted events", async () => {const { launch } = await import("../src/index.js");diff --git a/tests/test_humanize_unit.py b/tests/test_humanize_unit.pyindex 0387c63..efe533e 100644--- a/tests/test_humanize_unit.py+++ b/tests/test_humanize_unit.py@@ -1083,6 +1083,7 @@ import threadingimport http.serverimport socketserverimport contextlib+from urllib.parse import quote_IFRAME_PARENT = (b"<html><body><h1>parent</h1>"@@ -1230,6 +1231,48 @@ class TestBrowserIframeHumanizeAsync:await browser.close()+# page.set_content timed out in local runs of this test, so the page is loaded as a data: URL.+_WIDE_ROW_HTML = """+<body style="margin:0">+ <div style="display:flex">+ <div style="min-width:800px">left</div>+ <button id="target" style="min-width:800px"+ onclick="this.textContent = 'CLICKED'">right</button>+ </div>+</body>+"""+++class TestBrowserHorizontalScroll:+ """Regression for #521: a target off the right edge of a horizontally+ overflowing page must be scrolled into view on the x axis, not rejected+ as "covered by <none>"."""++ def test_humanized_click_scrolls_x_axis(self):+ from cloakbrowser import launch+ browser = launch(headless=True, humanize=True, geoip=False)+ try:+ page = browser.new_page(viewport={"width": 1000, "height": 700})+ page.goto("data:text/html," + quote(_WIDE_ROW_HTML))+ page.click("#target", timeout=5000)+ assert page.locator("#target").text_content() == "CLICKED"+ finally:+ browser.close()++ @pytest.mark.asyncio+ async def test_async_humanized_click_scrolls_x_axis(self):+ from cloakbrowser import launch_async+ browser = await launch_async(headless=True, humanize=True, geoip=False)+ try:+ page = await browser.new_page(viewport={"width": 1000, "height": 700})+ await page.goto("data:text/html," + quote(_WIDE_ROW_HTML))+ await page.click("#target", timeout=5000)+ assert await page.locator("#target").text_content() == "CLICKED"+ finally:+ await browser.close()++@pytest.mark.slowclass TestBrowserPatching:def test_page_has_original(self):@@ -2286,6 +2329,120 @@ class TestScrollIntoViewIfNeeded:human_scroll_into_view(page, raw, get_box, 0, 0, cfg)assert raw.wheel.called, "Below-fold scroll should produce wheel events"+ def test_human_scroll_into_view_scrolls_x_when_off_right_edge(self):+ """#521: a box past the right edge gets horizontal wheel events only."""+ from cloakbrowser.human.scroll import human_scroll_into_view+ from cloakbrowser.human.config import resolve_config+ from unittest.mock import MagicMock++ cfg = resolve_config("default", {+ "scroll_pre_move_delay": (0, 1),+ "scroll_settle_delay": (0, 1),+ })+ page = MagicMock()+ page.viewport_size = {"width": 1000, "height": 700}+ page._stealth_world.evaluate.return_value = {"y": 0, "maxY": 0, "x": 0, "minX": 0, "maxX": 600}+ raw = MagicMock()+ boxes = iter([+ {"x": 800, "y": 300, "width": 800, "height": 30},+ {"x": 200, "y": 300, "width": 800, "height": 30},+ ])++ box, _, _, did_scroll = human_scroll_into_view(+ page, raw, lambda: next(boxes), 0, 0, cfg,+ )+ assert did_scroll+ assert box["x"] == 200+ wheel_deltas = [c.args for c in raw.wheel.call_args_list]+ assert wheel_deltas, "Off-screen-right element should trigger wheel events"+ assert all(dx > 0 and dy == 0 for dx, dy in wheel_deltas)++ def test_human_scroll_into_view_skips_x_when_pinned_right(self):+ """Page already scrolled fully right: horizontal scrolling can't help."""+ from cloakbrowser.human.scroll import human_scroll_into_view+ from cloakbrowser.human.config import resolve_config+ from unittest.mock import MagicMock++ cfg = resolve_config("default", None)+ page = MagicMock()+ page.viewport_size = {"width": 1000, "height": 700}+ page._stealth_world.evaluate.return_value = {"y": 0, "maxY": 0, "x": 600, "minX": 0, "maxX": 600}+ raw = MagicMock()+ clipped_box = {"x": 900, "y": 300, "width": 200, "height": 30}++ box, _, _, did_scroll = human_scroll_into_view(+ page, raw, lambda: clipped_box, 0, 0, cfg,+ )+ assert not did_scroll+ assert box == clipped_box+ assert not raw.wheel.called++ def test_human_scroll_into_view_scrolls_x_left_on_rtl_page(self):+ """RTL page at its start (scrollX 0, range -600..0): a box in the left+ overflow gets negative horizontal wheel events."""+ from cloakbrowser.human.scroll import human_scroll_into_view+ from cloakbrowser.human.config import resolve_config+ from unittest.mock import MagicMock++ cfg = resolve_config("default", {+ "scroll_pre_move_delay": (0, 1),+ "scroll_settle_delay": (0, 1),+ })+ page = MagicMock()+ page.viewport_size = {"width": 1000, "height": 700}+ page._stealth_world.evaluate.return_value = {+ "y": 0, "maxY": 0, "x": 0, "minX": -600, "maxX": 0,+ }+ raw = MagicMock()+ boxes = iter([+ {"x": -600, "y": 300, "width": 200, "height": 30},+ {"x": 400, "y": 300, "width": 200, "height": 30},+ ])++ box, _, _, did_scroll = human_scroll_into_view(+ page, raw, lambda: next(boxes), 0, 0, cfg,+ )+ assert did_scroll+ assert box["x"] == 400+ wheel_deltas = [c.args for c in raw.wheel.call_args_list]+ assert wheel_deltas, "Off-screen-left element on an RTL page should trigger wheel events"+ assert all(dx < 0 and dy == 0 for dx, dy in wheel_deltas)++ async def test_async_human_scroll_into_view_scrolls_x_left_on_rtl_page(self):+ """Async twin of the RTL case above."""+ from cloakbrowser.human.scroll_async import async_human_scroll_into_view+ from cloakbrowser.human.config import resolve_config+ from unittest.mock import AsyncMock, MagicMock++ cfg = resolve_config("default", {+ "scroll_pre_move_delay": (0, 1),+ "scroll_settle_delay": (0, 1),+ })+ page = MagicMock()+ page.viewport_size = {"width": 1000, "height": 700}+ page._stealth_world.evaluate = AsyncMock(return_value={+ "y": 0, "maxY": 0, "x": 0, "minX": -600, "maxX": 0,+ })+ raw = MagicMock()+ raw.move = AsyncMock()+ raw.wheel = AsyncMock()+ boxes = iter([+ {"x": -600, "y": 300, "width": 200, "height": 30},+ {"x": 400, "y": 300, "width": 200, "height": 30},+ ])++ async def get_box():+ return next(boxes)++ box, _, _, did_scroll = await async_human_scroll_into_view(+ page, raw, get_box, 0, 0, cfg,+ )+ assert did_scroll+ assert box["x"] == 400+ wheel_deltas = [c.args for c in raw.wheel.call_args_list]+ assert wheel_deltas, "Off-screen-left element on an RTL page should trigger wheel events"+ assert all(dx < 0 and dy == 0 for dx, dy in wheel_deltas)+def test_element_handle_scroll_into_view_if_needed_humanized(self):"""el.scroll_into_view_if_needed() routes through human_scroll_into_view."""from cloakbrowser.human import _patch_single_element_handle_sync, _CursorState