Skip to content

Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.

fix(humanize): select_option types ahead instead of walking every row (#580, #581) (#582)

lilos117b60229b28
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82496ae..c9eb4de 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,10 @@ Changes are tagged: **[wrapper]** for Python/JS wrapper, **[binary]** for Chromi
---
+## [Unreleased]
+
+- **[wrapper]** Humanized `select_option()` on a dropdown now types the first letters of the option, like a person does on a long list, plus a few arrow keys when that is shorter, instead of pressing an arrow key once per row. A pick on a 200-option list takes about 1.5-2s instead of up to 30s, and `timeout=` now bounds it (#581). The keys typed land on the same option wherever the open popup's highlight starts, so a popup that opens under the mouse pointer no longer picks the wrong option on headed Linux (#580). On a macOS host the shortest unique prefix of the label is typed instead of the whole label. Python, JavaScript Playwright, and .NET.
+
## [0.6.0] — 2026-10-08
- **[wrapper]** The first-launch Pro banner now names the current Pro major (v154) instead of v152. Python, JavaScript, and .NET.
diff --git a/cloakbrowser/human/engine.py b/cloakbrowser/human/engine.py
index f888b18..48b4ff7 100644
--- a/cloakbrowser/human/engine.py
+++ b/cloakbrowser/human/engine.py
@@ -121,6 +121,7 @@ class Human:
self.cfg = cfg
self.cursor = cursor
self.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._platform: Optional[str] = None
@@ -873,40 +874,54 @@ class Human:
await self.click(target, {"_deadline": deadline, "force": opts.get("force"),
"human_config": opts.get("human_config")}, api=api)
await sleep_ms(rand(200, 450)) # popup opens; eyes find the option
- if sys.platform == "darwin":
- # macOS shows a native popup that ignores arrow keys sent as page
- # input; type-ahead on the option's label still selects it.
- for ch in p["labels"][0]:
- if ch.isascii():
- await self._type_char(ch, cfg)
- else: # no US-layout key: send the character itself, like a native layout does
- session = await self.worlds.session()
- await session.send("Input.dispatchKeyEvent",
- {"type": "keyDown", "key": ch, "text": ch, "unmodifiedText": ch})
- await sleep_ms(rand_range(cfg.key_hold))
- await session.send("Input.dispatchKeyEvent", {"type": "keyUp", "key": ch})
- await sleep_ms(rand(60, 140)) # type-ahead resets after ~1s of silence
- await self.keyboard.press("Enter")
- await sleep_ms(rand(80, 160))
- return
- nav = p["navigable"]
- cur = state["current"]
- for _ in range(len(nav) + 1):
- if cur == index:
- break
- step = 1 if index > cur else -1
- nxt = cur + step
- while 0 <= nxt < len(nav) and not nav[nxt]:
- nxt += step
- if not (0 <= nxt < len(nav)):
- break
- await self.keyboard.press("ArrowDown" if step > 0 else "ArrowUp")
- await sleep_ms(rand(70, 180))
- cur = nxt
+ mac = sys.platform == "darwin" # a macOS host's native popup ignores arrow keys
+ plan = await self.worlds.call(r.frame, "typeAheadPlan", r.id, index, 0 if mac else 3)
+ if plan is None:
+ raise Error(f"{api}: Error: no option of this dropdown can be reached")
+ if plan.get("home"):
+ # No name prefix is unique (duplicate labels): Home, then walk; on
+ # macOS type the whole label instead.
+ keys = list(plan["label"]) if mac else ["Home"] + [
+ "ArrowDown" if plan["arrows"] > 0 else "ArrowUp"] * abs(plan["arrows"])
+ else:
+ keys = list(plan["typed"]) + ["ArrowDown" if plan["arrows"] > 0 else "ArrowUp"] * abs(plan["arrows"])
+ # The browser joins letters typed within ~1s into one search: let an
+ # earlier select_option's search lapse before starting a new one.
+ if keys and len(keys[0]) == 1:
+ wait = self._typeahead_until - time.monotonic()
+ if wait > 0:
+ await sleep_ms(wait * 1000)
+ typed = False
+ for k in keys:
+ if deadline.expired():
+ await self.keyboard.press("Escape")
+ raise TimeoutError(f"{api}: Timeout {deadline.timeout:.0f}ms exceeded.\n"
+ f"Call log:\n - choosing an option of {target.description}")
+ if len(k) == 1:
+ await self._typeahead_char(k, cfg)
+ typed = True
+ self._typeahead_until = time.monotonic() + 1.1
+ await sleep_ms(rand(60, 160))
+ else:
+ await self.keyboard.press(k)
+ await sleep_ms(rand(90, 200))
await sleep_ms(rand(100, 250))
await self.keyboard.press("Enter")
+ if typed:
+ self._typeahead_until = time.monotonic() + 1.1
await sleep_ms(rand(80, 160))
+ async def _typeahead_char(self, ch: str, cfg: HumanConfig) -> None:
+ """One type-ahead letter. Letters go lowercase (a person doesn't hold Shift
+ to search a list); a character without a US-layout key is sent as itself."""
+ if ch.isascii():
+ await self._type_char(ch, cfg)
+ return
+ session = await self.worlds.session()
+ await session.send("Input.dispatchKeyEvent", {"type": "keyDown", "key": ch, "text": ch, "unmodifiedText": ch})
+ await sleep_ms(rand_range(cfg.key_hold))
+ await session.send("Input.dispatchKeyEvent", {"type": "keyUp", "key": ch})
+
async def _select_listbox(self, target: Target, r: Resolved, p: dict, opts: dict, api: str,
cfg: HumanConfig, deadline: _Deadline) -> None:
state = await self.worlds.call(r.frame, "selectState", r.id)
diff --git a/cloakbrowser/human/world.py b/cloakbrowser/human/world.py
index 08721c4..2d5608a 100644
--- a/cloakbrowser/human/world.py
+++ b/cloakbrowser/human/world.py
@@ -237,6 +237,45 @@ const H = {
values: targets.map(i => opts[i].value), labels: targets.map(i => norm(opts[i].label)) };
},
optionId(id, index) { const sel = I.retarget(get(id), 'follow-label') || get(id); return put(sel.options[index]); },
+ // How to reach option 'target' of an open dropdown by typing, like a person:
+ // the shortest prefix whose type-ahead result does not depend on which row is
+ // highlighted (it can't be read while the popup is open), then a few arrows.
+ // Mirrors Blink's TypeAhead (case/accent-insensitive prefix match over enabled
+ // options, leading whitespace ignored; a repeated first letter cycles instead).
+ typeAheadPlan(id, target, maxArrows) {
+ const sel = I.retarget(get(id), 'follow-label') || get(id);
+ const opts = [...sel.options];
+ const fold = (s) => s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
+ const enabled = (o) => !o.disabled && !(o.parentElement && o.parentElement.nodeName === 'OPTGROUP' && o.parentElement.disabled);
+ const nav = opts.map(o => enabled(o) && !o.hidden && getComputedStyle(o).display !== 'none');
+ const keys = opts.map(o => enabled(o) ? fold(o.label.replace(/\s+/g, ' ').trim()) : '');
+ if (!nav[target]) return null;
+ // Signed arrow presses from row a to the target (disabled/hidden rows are skipped).
+ const arrows = (a) => { let n = 0; const d = target > a ? 1 : -1;
+ for (let i = a; i !== target; i += d) if (nav[i + d]) n += d; return n; };
+ const unique = (s) => { let hit = -1;
+ for (let i = 0; i < keys.length; i++) if (keys[i].startsWith(s)) { if (hit >= 0) return -1; hit = i; }
+ return hit; };
+ let best = null;
+ const order = [target].concat(opts.map((_, i) => i).filter(i => i !== target));
+ for (const a of order) {
+ if (!keys[a] || !nav[a]) continue;
+ const n = arrows(a);
+ if (Math.abs(n) > maxArrows) continue;
+ for (let k = 1; k <= keys[a].length; k++) {
+ const cost = k + Math.abs(n) + (a === target ? 0 : 1); // prefer the option's own name
+ if (best && cost >= best.cost) break;
+ const s = keys[a].slice(0, k);
+ // A run of one letter ('aa', 'aaa') cycles from the highlighted row instead.
+ if (/^(.)\1+$/.test(s) || s.endsWith(' ')) continue;
+ if (unique(s) === a) { best = { cost, typed: s, arrows: n }; break; }
+ }
+ }
+ if (best) return { typed: best.typed, arrows: best.arrows };
+ // No name prefix is unique (e.g. duplicate labels): Home, then walk with arrows.
+ const first = nav.indexOf(true);
+ return first < 0 ? null : { typed: '', home: true, arrows: first === target ? 0 : arrows(first), label: keys[target] };
+ },
selectState(id) {
const sel = I.retarget(get(id), 'follow-label') || get(id);
return { current: sel.selectedIndex, selected: [...sel.options].map((o, i) => o.selected ? i : -1).filter(i => i >= 0),
diff --git a/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs b/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs
index aa5ddcb..562fe5f 100644
--- a/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs
+++ b/dotnet/src/CloakBrowser/Human/HumanEngine.Actions.cs
@@ -294,48 +294,80 @@ internal sealed partial class HumanEngine
}
await ClickAsync(t, new ActOpts { Deadline = d, Force = o.Force, HumanConfig = o.HumanConfig }, api).ConfigureAwait(false);
await Sleep(R(200, 450)).ConfigureAwait(false); // popup opens; eyes find the option
- if (OperatingSystem.IsMacOS())
+ var cfg = CallCfg(o.HumanConfig);
+ bool mac = OperatingSystem.IsMacOS(); // a macOS host's native popup ignores arrow keys
+ var ta = await World.CallAsync(r.Frame, "typeAheadPlan", r.Id, index.Value, mac ? 0 : 3).ConfigureAwait(false);
+ if (ta is not { ValueKind: JsonValueKind.Object } p) throw Err($"{api}: Error: no option of this dropdown can be reached");
+ int n = p.GetProperty("arrows").GetInt32();
+ var walk = Enumerable.Repeat(n > 0 ? "ArrowDown" : "ArrowUp", Math.Abs(n));
+ var keys = new List<string>();
+ if (p.TryGetProperty("home", out var home) && home.GetBoolean())
{
- // macOS shows a native popup that ignores arrow keys sent as page
- // input; type-ahead on the option's label still selects it.
- var cfg = CallCfg(o.HumanConfig);
- foreach (var ch in plan.GetProperty("labels")[0].GetString()!)
- {
- if (ch < 128)
- {
- await TypeCharAsync(ch, cfg).ConfigureAwait(false);
- }
- else // no US-layout key: send the character itself, like a native layout does
- {
- var session = await World.SessionAsync().ConfigureAwait(false);
- await session.SendAsync("Input.dispatchKeyEvent", new()
- {
- ["type"] = "keyDown", ["key"] = ch.ToString(), ["text"] = ch.ToString(), ["unmodifiedText"] = ch.ToString(),
- }).ConfigureAwait(false);
- await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);
- await session.SendAsync("Input.dispatchKeyEvent", new() { ["type"] = "keyUp", ["key"] = ch.ToString() }).ConfigureAwait(false);
- }
- await Sleep(R(60, 140)).ConfigureAwait(false); // type-ahead resets after ~1s of silence
- }
- await _raw.KeyPressAsync("Enter").ConfigureAwait(false);
- await Sleep(R(80, 160)).ConfigureAwait(false);
- return;
+ // No name prefix is unique (duplicate labels): Home, then walk; on macOS type the whole label.
+ if (mac) keys.AddRange(p.GetProperty("label").GetString()!.Select(c => c.ToString()));
+ else { keys.Add("Home"); keys.AddRange(walk); }
}
- var nav = plan.GetProperty("navigable").EnumerateArray().Select(x => x.GetBoolean()).ToList();
- for (int k = 0; k <= nav.Count && cur != index; k++)
+ else
+ {
+ keys.AddRange(p.GetProperty("typed").GetString()!.Select(c => c.ToString()));
+ keys.AddRange(walk);
+ }
+ // The browser joins letters typed within ~1s into one search: let an earlier
+ // SelectOption's search lapse before starting a new one.
+ if (keys.Count > 0 && keys[0].Length == 1)
{
- int step = index > cur ? 1 : -1, nxt = cur + step;
- while (nxt >= 0 && nxt < nav.Count && !nav[nxt]) nxt += step;
- if (nxt < 0 || nxt >= nav.Count) break;
- await _raw.KeyPressAsync(step > 0 ? "ArrowDown" : "ArrowUp").ConfigureAwait(false);
- await Sleep(R(70, 180)).ConfigureAwait(false);
- cur = nxt;
+ double wait = (_typeAheadUntil - DateTime.UtcNow).TotalMilliseconds;
+ if (wait > 0) await Sleep(wait).ConfigureAwait(false);
+ }
+ bool typed = false;
+ foreach (var k in keys)
+ {
+ if (d.Expired)
+ {
+ await _raw.KeyPressAsync("Escape").ConfigureAwait(false);
+ throw new System.TimeoutException($"{api}: Timeout {Math.Round(d.Timeout)}ms exceeded.\n"
+ + $"Call log:\n - choosing an option of {t.Description}");
+ }
+ if (k.Length == 1)
+ {
+ await TypeAheadCharAsync(k[0], cfg).ConfigureAwait(false);
+ typed = true;
+ _typeAheadUntil = DateTime.UtcNow.AddMilliseconds(1100);
+ await Sleep(R(60, 160)).ConfigureAwait(false);
+ }
+ else
+ {
+ await _raw.KeyPressAsync(k).ConfigureAwait(false);
+ await Sleep(R(90, 200)).ConfigureAwait(false);
+ }
}
await Sleep(R(100, 250)).ConfigureAwait(false);
await _raw.KeyPressAsync("Enter").ConfigureAwait(false);
+ if (typed) _typeAheadUntil = DateTime.UtcNow.AddMilliseconds(1100);
await Sleep(R(80, 160)).ConfigureAwait(false);
}
+ /// <summary>When the browser stops joining typed letters into one type-ahead search.</summary>
+ private DateTime _typeAheadUntil = DateTime.MinValue;
+
+ /// <summary>One type-ahead letter (lowercase: a person doesn't hold Shift to search a list);
+ /// a character without a US-layout key is sent as itself.</summary>
+ private async Task TypeAheadCharAsync(char ch, HumanConfig cfg)
+ {
+ if (ch < 128)
+ {
+ await TypeCharAsync(ch, cfg).ConfigureAwait(false);
+ return;
+ }
+ var session = await World.SessionAsync().ConfigureAwait(false);
+ await session.SendAsync("Input.dispatchKeyEvent", new()
+ {
+ ["type"] = "keyDown", ["key"] = ch.ToString(), ["text"] = ch.ToString(), ["unmodifiedText"] = ch.ToString(),
+ }).ConfigureAwait(false);
+ await Sleep(RR(cfg.KeyHold)).ConfigureAwait(false);
+ await session.SendAsync("Input.dispatchKeyEvent", new() { ["type"] = "keyUp", ["key"] = ch.ToString() }).ConfigureAwait(false);
+ }
+
private async Task SelectListboxAsync(Target t, Resolved r, List<int> want, ActOpts o, string api, HumanConfig cfg, Deadline d)
{
var state = (await World.CallAsync(r.Frame, "selectState", r.Id).ConfigureAwait(false))!.Value;
diff --git a/dotnet/src/CloakBrowser/Human/WorldHelpers.cs b/dotnet/src/CloakBrowser/Human/WorldHelpers.cs
index 9e30dff..45d1a9f 100644
--- a/dotnet/src/CloakBrowser/Human/WorldHelpers.cs
+++ b/dotnet/src/CloakBrowser/Human/WorldHelpers.cs
@@ -214,6 +214,45 @@ const H = {
values: targets.map(i => opts[i].value), labels: targets.map(i => norm(opts[i].label)) };
},
optionId(id, index) { const sel = I.retarget(get(id), 'follow-label') || get(id); return put(sel.options[index]); },
+ // How to reach option 'target' of an open dropdown by typing, like a person:
+ // the shortest prefix whose type-ahead result does not depend on which row is
+ // highlighted (it can't be read while the popup is open), then a few arrows.
+ // Mirrors Blink's TypeAhead (case/accent-insensitive prefix match over enabled
+ // options, leading whitespace ignored; a repeated first letter cycles instead).
+ typeAheadPlan(id, target, maxArrows) {
+ const sel = I.retarget(get(id), 'follow-label') || get(id);
+ const opts = [...sel.options];
+ const fold = (s) => s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
+ const enabled = (o) => !o.disabled && !(o.parentElement && o.parentElement.nodeName === 'OPTGROUP' && o.parentElement.disabled);
+ const nav = opts.map(o => enabled(o) && !o.hidden && getComputedStyle(o).display !== 'none');
+ const keys = opts.map(o => enabled(o) ? fold(o.label.replace(/\s+/g, ' ').trim()) : '');
+ if (!nav[target]) return null;
+ // Signed arrow presses from row a to the target (disabled/hidden rows are skipped).
+ const arrows = (a) => { let n = 0; const d = target > a ? 1 : -1;
+ for (let i = a; i !== target; i += d) if (nav[i + d]) n += d; return n; };
+ const unique = (s) => { let hit = -1;
+ for (let i = 0; i < keys.length; i++) if (keys[i].startsWith(s)) { if (hit >= 0) return -1; hit = i; }
+ return hit; };
+ let best = null;
+ const order = [target].concat(opts.map((_, i) => i).filter(i => i !== target));
+ for (const a of order) {
+ if (!keys[a] || !nav[a]) continue;
+ const n = arrows(a);
+ if (Math.abs(n) > maxArrows) continue;
+ for (let k = 1; k <= keys[a].length; k++) {
+ const cost = k + Math.abs(n) + (a === target ? 0 : 1); // prefer the option's own name
+ if (best && cost >= best.cost) break;
+ const s = keys[a].slice(0, k);
+ // A run of one letter ('aa', 'aaa') cycles from the highlighted row instead.
+ if (/^(.)\1+$/.test(s) || s.endsWith(' ')) continue;
+ if (unique(s) === a) { best = { cost, typed: s, arrows: n }; break; }
+ }
+ }
+ if (best) return { typed: best.typed, arrows: best.arrows };
+ // No name prefix is unique (e.g. duplicate labels): Home, then walk with arrows.
+ const first = nav.indexOf(true);
+ return first < 0 ? null : { typed: '', home: true, arrows: first === target ? 0 : arrows(first), label: keys[target] };
+ },
selectState(id) {
const sel = I.retarget(get(id), 'follow-label') || get(id);
return { current: sel.selectedIndex, selected: [...sel.options].map((o, i) => o.selected ? i : -1).filter(i => i >= 0),
diff --git a/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs b/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs
index 46cbd84..e1c8494 100644
--- a/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/HumanEngine/HumanEngineBrowserTests.cs
@@ -347,6 +347,25 @@ public class HumanEngineBrowserTests : IClassFixture<EngineFixture>, IAsyncLifet
Assert.Equal(new[] { "b" }, await p.SelectOptionAsync("#sel", new SelectOptionValue { Index = 1 }));
}
+ [BrowserFact]
+ public async Task SelectOption_on_a_long_dropdown_types_ahead()
+ {
+ // #581: no walk over every row, and the timeout bounds it.
+ var p = await Open();
+ await p.EvaluateAsync(@"() => { const s = document.createElement('select'); s.id = 'long';
+ for (let i = 0; i < 205; i++) s.add(new Option('Country ' + String(i).padStart(3, '0'), 'v' + i));
+ window.__sel = []; for (const t of ['input', 'change']) s.addEventListener(t, () => __sel.push(t));
+ document.body.append(s); }");
+ await Reset(p);
+ Assert.Equal(new[] { "v150" }, await p.SelectOptionAsync("#long", "v150"));
+ var keys = (await Events(p, "keydown")).Select(e => e.GetProperty("key").GetString()).ToList();
+ Assert.DoesNotContain("ArrowDown", keys);
+ Assert.True(keys.Count <= 13, string.Join(",", keys));
+ Assert.Equal("[\"input\",\"change\"]", await p.EvaluateAsync<string>("JSON.stringify(__sel)"));
+ await p.EvaluateAsync("document.querySelector('#long').selectedIndex = 0");
+ await Assert.ThrowsAsync<TimeoutException>(() => p.SelectOptionAsync("#long", "v200", new() { Timeout = 200 }));
+ }
+
// --- frames / handles --------------------------------------------------
[BrowserFact]
diff --git a/js/src/human/engine.ts b/js/src/human/engine.ts
index 2af6a86..098e70c 100644
--- a/js/src/human/engine.ts
+++ b/js/src/human/engine.ts
@@ -119,6 +119,8 @@ const isUpper = (ch: string) => /^[A-Z]$/.test(ch);
export class Human {
readonly worlds: Worlds;
+ /** Date.now() until which the browser joins typed letters into one type-ahead search. */
+ private typeAheadUntil = 0;
private _platform: string | null = null;
private handleIds = new Map<string, [Frame, number, number]>();
@@ -830,42 +832,56 @@ export class Human {
}
await this.click(target, { _deadline: deadline, force: opts.force, human_config: opts.human_config }, api);
await sleepMs(rand(200, 450)); // popup opens; eyes find the option
- if (process.platform === 'darwin') {
- // macOS shows a native popup that ignores arrow keys sent as page
- // input; type-ahead on the option's label still selects it.
- const cfg = this.callCfg(opts.human_config);
- for (const ch of p.labels[0] as string) {
- if (ch.charCodeAt(0) < 128) {
- await this.typeChar(ch, cfg);
- } else { // no US-layout key: send the character itself, like a native layout does
- const session: CDPSession = await this.worlds.session();
- await session.send('Input.dispatchKeyEvent', { type: 'keyDown', key: ch, text: ch, unmodifiedText: ch });
- await sleepMs(randRange(cfg.key_hold));
- await session.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
- }
- await sleepMs(rand(60, 140)); // type-ahead resets after ~1s of silence
- }
- await this.raw.keyPress('Enter');
- await sleepMs(rand(80, 160));
- return;
+ const cfg = this.callCfg(opts.human_config);
+ const mac = process.platform === 'darwin'; // a macOS host's native popup ignores arrow keys
+ const plan = await this.worlds.call(r.frame, 'typeAheadPlan', r.id, index, mac ? 0 : 3);
+ if (!plan) throw err(`${api}: Error: no option of this dropdown can be reached`);
+ const arrows = (n: number) => Array<string>(Math.abs(n)).fill(n > 0 ? 'ArrowDown' : 'ArrowUp');
+ // No name prefix is unique (duplicate labels): Home, then walk; on macOS type the whole label.
+ const keys: string[] = plan.home ? (mac ? [...plan.label] : ['Home', ...arrows(plan.arrows)])
+ : [...plan.typed, ...arrows(plan.arrows)];
+ // The browser joins letters typed within ~1s into one search: let an earlier
+ // selectOption's search lapse before starting a new one.
+ if (keys.length && keys[0].length === 1) {
+ const wait = this.typeAheadUntil - Date.now();
+ if (wait > 0) await sleepMs(wait);
}
- const nav: boolean[] = p.navigable;
- let cur: number = state.current;
- for (let k = 0; k <= nav.length; k++) {
- if (cur === index) break;
- const step = index > cur ? 1 : -1;
- let nxt = cur + step;
- while (nxt >= 0 && nxt < nav.length && !nav[nxt]) nxt += step;
- if (!(nxt >= 0 && nxt < nav.length)) break;
- await this.raw.keyPress(step > 0 ? 'ArrowDown' : 'ArrowUp');
- await sleepMs(rand(70, 180));
- cur = nxt;
+ let typed = false;
+ for (const k of keys) {
+ if (deadline.expired()) {
+ await this.raw.keyPress('Escape');
+ throw new errors.TimeoutError(`${api}: Timeout ${Math.round(deadline.timeout)}ms exceeded.\n`
+ + `Call log:\n - choosing an option of ${target.description}`);
+ }
+ if (k.length === 1) {
+ await this.typeAheadChar(k, cfg);
+ typed = true;
+ this.typeAheadUntil = Date.now() + 1100;
+ await sleepMs(rand(60, 160));
+ } else {
+ await this.raw.keyPress(k);
+ await sleepMs(rand(90, 200));
+ }
}
await sleepMs(rand(100, 250));
await this.raw.keyPress('Enter');
+ if (typed) this.typeAheadUntil = Date.now() + 1100;
await sleepMs(rand(80, 160));
}
+ /** One type-ahead letter (lowercase: a person doesn't hold Shift to search a
+ * list); a character without a US-layout key is sent as itself. */
+ private async typeAheadChar(ch: string, cfg: HumanConfig): Promise<void> {
+ if (ch.charCodeAt(0) < 128) {
+ await this.typeChar(ch, cfg);
+ return;
+ }
+ const session: CDPSession = await this.worlds.session();
+ await session.send('Input.dispatchKeyEvent', { type: 'keyDown', key: ch, text: ch, unmodifiedText: ch });
+ await sleepMs(randRange(cfg.key_hold));
+ await session.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
+ }
+
private async selectListbox(target: Target, r: Resolved, p: any, opts: Opts, api: string, cfg: HumanConfig,
deadline: Deadline): Promise<void> {
const state = await this.worlds.call(r.frame, 'selectState', r.id);
diff --git a/js/src/human/worldHelpers.ts b/js/src/human/worldHelpers.ts
index 653826c..246565f 100644
--- a/js/src/human/worldHelpers.ts
+++ b/js/src/human/worldHelpers.ts
@@ -210,6 +210,45 @@ const H = {
values: targets.map(i => opts[i].value), labels: targets.map(i => norm(opts[i].label)) };
},
optionId(id, index) { const sel = I.retarget(get(id), 'follow-label') || get(id); return put(sel.options[index]); },
+ // How to reach option 'target' of an open dropdown by typing, like a person:
+ // the shortest prefix whose type-ahead result does not depend on which row is
+ // highlighted (it can't be read while the popup is open), then a few arrows.
+ // Mirrors Blink's TypeAhead (case/accent-insensitive prefix match over enabled
+ // options, leading whitespace ignored; a repeated first letter cycles instead).
+ typeAheadPlan(id, target, maxArrows) {
+ const sel = I.retarget(get(id), 'follow-label') || get(id);
+ const opts = [...sel.options];
+ const fold = (s) => s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
+ const enabled = (o) => !o.disabled && !(o.parentElement && o.parentElement.nodeName === 'OPTGROUP' && o.parentElement.disabled);
+ const nav = opts.map(o => enabled(o) && !o.hidden && getComputedStyle(o).display !== 'none');
+ const keys = opts.map(o => enabled(o) ? fold(o.label.replace(/\s+/g, ' ').trim()) : '');
+ if (!nav[target]) return null;
+ // Signed arrow presses from row a to the target (disabled/hidden rows are skipped).
+ const arrows = (a) => { let n = 0; const d = target > a ? 1 : -1;
+ for (let i = a; i !== target; i += d) if (nav[i + d]) n += d; return n; };
+ const unique = (s) => { let hit = -1;
+ for (let i = 0; i < keys.length; i++) if (keys[i].startsWith(s)) { if (hit >= 0) return -1; hit = i; }
+ return hit; };
+ let best = null;
+ const order = [target].concat(opts.map((_, i) => i).filter(i => i !== target));
+ for (const a of order) {
+ if (!keys[a] || !nav[a]) continue;
+ const n = arrows(a);
+ if (Math.abs(n) > maxArrows) continue;
+ for (let k = 1; k <= keys[a].length; k++) {
+ const cost = k + Math.abs(n) + (a === target ? 0 : 1); // prefer the option's own name
+ if (best && cost >= best.cost) break;
+ const s = keys[a].slice(0, k);
+ // A run of one letter ('aa', 'aaa') cycles from the highlighted row instead.
+ if (/^(.)\1+$/.test(s) || s.endsWith(' ')) continue;
+ if (unique(s) === a) { best = { cost, typed: s, arrows: n }; break; }
+ }
+ }
+ if (best) return { typed: best.typed, arrows: best.arrows };
+ // No name prefix is unique (e.g. duplicate labels): Home, then walk with arrows.
+ const first = nav.indexOf(true);
+ return first < 0 ? null : { typed: '', home: true, arrows: first === target ? 0 : arrows(first), label: keys[target] };
+ },
selectState(id) {
const sel = I.retarget(get(id), 'follow-label') || get(id);
return { current: sel.selectedIndex, selected: [...sel.options].map((o, i) => o.selected ? i : -1).filter(i => i >= 0),
diff --git a/js/tests/humanizeEngine.test.ts b/js/tests/humanizeEngine.test.ts
index 5dfeb06..30b70c4 100644
--- a/js/tests/humanizeEngine.test.ts
+++ b/js/tests/humanizeEngine.test.ts
@@ -335,6 +335,26 @@ describe.skipIf(!process.env.CLOAKBROWSER_BINARY_PATH)('humanize engine (real br
expect(await p.selectOption('#sel', { index: 1 })).toEqual(['b']);
});
+ it('selectOption on a long dropdown types ahead instead of walking every row (#581)', async () => {
+ const p = await open();
+ await p.evaluate(() => {
+ const s = document.createElement('select'); s.id = 'long';
+ for (let i = 0; i < 205; i++) s.add(new Option('Country ' + String(i).padStart(3, '0'), 'v' + i));
+ (window as any).__sel = [];
+ for (const t of ['input', 'change']) s.addEventListener(t, () => (window as any).__sel.push(t));
+ document.body.append(s);
+ });
+ await reset(p);
+ expect(await p.selectOption('#long', 'v150')).toEqual(['v150']);
+ const keys = (await events(p, 'keydown')).map((e) => e.key);
+ expect(keys).not.toContain('ArrowDown');
+ expect(keys.length).toBeLessThanOrEqual(13);
+ expect(await p.evaluate(() => (window as any).__sel)).toEqual(['input', 'change']);
+ await p.evaluate(() => { (document.querySelector('#long') as HTMLSelectElement).selectedIndex = 0; });
+ const e = await p.selectOption('#long', 'v200', { timeout: 200 }).catch((x) => x);
+ expect(e).toBeInstanceOf(errors.TimeoutError);
+ });
+
// --- frames and handles ---------------------------------------------------
it('frame actions', async () => {
diff --git a/tests/test_humanize_engine.py b/tests/test_humanize_engine.py
index e2922a0..e7d61b5 100644
--- a/tests/test_humanize_engine.py
+++ b/tests/test_humanize_engine.py
@@ -597,6 +597,87 @@ def test_check_uncheck_and_select(page):
assert page.select_option("#sel", index=1) == ["b"]
+COUNTRIES = ["Afghanistan", "Albania", "Chad", "Chile", "China", "Dominica", "Dominican Republic",
+ "Guinea", "Guinea-Bissau", "Niger", "Nigeria", "\u00c5land Islands", "Aaland", "United Arab Emirates",
+ "United Kingdom", "United States", "United States Minor Outlying Islands", "Zimbabwe"]
+
+
+def _blink_typeahead(labels, enabled, start, typed):
+ """Blink's TypeAhead::HandleEvent (kMatchPrefix | kCycleFirstChar) for one search."""
+ import unicodedata
+
+ def fold(t):
+ return "".join(c for c in unicodedata.normalize("NFD", t) if not unicodedata.combining(c)).lower()
+ keys = [fold(l.lstrip()) if ok else "" for l, ok in zip(labels, enabled)]
+ buf = rep = ""
+ sel = start
+ for ch in fold(typed):
+ buf += ch
+ if ch == rep:
+ prefix, off = ch, 1
+ else:
+ prefix = buf
+ off = 0 if len(buf) > 1 else 1
+ rep = "" if len(buf) > 1 else ch
+ i = (max(sel, 0) + off) % len(keys)
+ for _ in keys:
+ if keys[i] and keys[i].startswith(prefix):
+ sel = i
+ break
+ i = (i + 1) % len(keys)
+ return sel
+
+
+def test_type_ahead_plan_lands_on_the_option_from_any_highlighted_row(page):
+ """The plan must not depend on which row the open popup highlights (#580): it
+ can sit under the OS pointer, and the page cannot read it."""
+ page.evaluate("""(labels) => { const s = document.createElement('select'); s.id = 'ta';
+ for (const l of labels) s.add(new Option(l));
+ s.options[1].disabled = true; document.body.append(s); }""", COUNTRIES)
+ enabled = [i != 1 for i in range(len(COUNTRIES))]
+ human = page._impl_obj._cloak_human
+ frame = page.main_frame._impl_obj
+
+ async def plans():
+ from cloakbrowser.human.engine import Target, _Deadline
+ r = await human.resolve(Target(frame, "#ta"), _Deadline(5000))
+ return [await human.worlds.call(frame, "typeAheadPlan", r.id, t, 3) for t in range(len(COUNTRIES))]
+ for target, plan in enumerate(page._sync(plans())):
+ if target == 1:
+ assert plan is None # disabled: not reachable
+ continue
+ assert plan and not plan.get("home"), (COUNTRIES[target], plan)
+ for start in range(len(COUNTRIES)):
+ row = _blink_typeahead(COUNTRIES, enabled, start, plan["typed"])
+ step = 1 if plan["arrows"] > 0 else -1
+ for _ in range(abs(plan["arrows"])):
+ row += step
+ while not enabled[row]:
+ row += step
+ assert row == target, (COUNTRIES[target], plan, COUNTRIES[start])
+ got = {COUNTRIES[t]: p for t, p in enumerate(page._sync(plans()))}
+ assert got["Chile"] == {"typed": "chil", "arrows": 0} # its own name, not "cha" + 1 arrow
+ assert got["\u00c5land Islands"]["typed"] == "al" # the browser folds accents: plain "al" finds it
+ assert got["Aaland"]["typed"] == "aal" # "aa" would cycle through the a's instead
+ assert all(abs(p["arrows"]) <= 3 for p in got.values() if p)
+
+
+def test_select_option_on_a_long_dropdown_types_ahead(page):
+ """#581: no walk over every row, and the timeout bounds it."""
+ page.evaluate("""() => { const s = document.createElement('select'); s.id = 'long';
+ for (let i = 0; i < 205; i++) s.add(new Option('Country ' + String(i).padStart(3, '0'), 'v' + i));
+ window.__sel = []; for (const t of ['input', 'change']) s.addEventListener(t, () => __sel.push(t));
+ document.body.append(s); }""")
+ reset(page)
+ assert page.select_option("#long", "v150") == ["v150"]
+ keys = [e["key"] for e in events(page, "keydown")]
+ assert "ArrowDown" not in keys and len(keys) <= 13, keys
+ assert page.evaluate("__sel") == ["input", "change"]
+ page.evaluate("document.querySelector('#long').selectedIndex = 0")
+ with pytest.raises(TimeoutError):
+ page.select_option("#long", "v200", timeout=200)
+
+
# --- frames and handles ------------------------------------------------------
def test_frame_actions(page):