Skip to content

Automate browser based workflows with AI

Let Task V3 hold and report a set-valued selection (SKY-16270) (#8570)

pedrohsdbd655dbf07271
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index de48ca17e..369268f18 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -487,6 +487,35 @@ def _has_committable_state(state: dict[str, Any] | None) -> bool:
return isinstance(state, dict) and any(state.get(k) is not None for k in _COMMIT_STATE_KEYS)
+def _option_str_list(raw: Any) -> list[str] | None:
+ """The string options of a declared array, or None when the caller declared no usable array.
+
+ An empty string is a real option value -- `<option value="">` is selectable -- so it is kept, and
+ an empty array is a declared request to hold nothing, so it wins over a scalar like any other
+ array. Only an array with nothing usable in it falls through as undeclared.
+ """
+ if not isinstance(raw, list):
+ return None
+ items = [x for x in raw if isinstance(x, str)]
+ return items if items or not raw else None
+
+
+# select_option's readback names the options a control holds, and the page chooses that text. The
+# result is not compacted, so both the count and each option are bounded -- and marked when cut.
+SELECTION_REPORT_MAX_OPTIONS = 20
+SELECTION_REPORT_OPTION_WIDTH = 80
+
+
+def _selection_report(options: list[str]) -> str:
+ shown = [
+ o[:SELECTION_REPORT_OPTION_WIDTH] + "…" if len(o) > SELECTION_REPORT_OPTION_WIDTH else o
+ for o in options[:SELECTION_REPORT_MAX_OPTIONS]
+ ]
+ if len(shown) < len(options):
+ return f"{shown!r} (showing {len(shown)} of {len(options)})"
+ return repr(shown)
+
+
def _classify_commit(
pre: dict[str, Any] | None, post_matches: int, post: dict[str, Any] | None, *, committed_value: bool | None = None
) -> CommitStatus:
@@ -4147,6 +4176,7 @@ _SELECT_VISIBILITY_JS = (
visible: r.width > 0 && r.height > 0 && cs.visibility !== 'hidden',
disabled: !!el.disabled,
proxied: !!_nativeProxy(el),
+ multiple: el.multiple === true,
};
} catch (e) { return { exists: false, visible: false }; }
}"""
@@ -4212,8 +4242,18 @@ _SELECT_READBACK_JS = (
if (!el) return null;
const idx = el.selectedIndex;
const opt = idx >= 0 ? el.options[idx] : null;
+ // el.value and el.selectedIndex both name only the FIRST selected option, so on a
+ // <select multiple> they report a set of many as one. The set is the only honest readout.
+ const picked = Array.from(el.selectedOptions || []);
// Playwright matches label= against option.label (whitespace-collapsed), not raw text.
- return { value: el.value, selectedIndex: idx, selectedLabel: opt ? opt.label : null };
+ return {
+ value: el.value,
+ selectedIndex: idx,
+ selectedLabel: opt ? opt.label : null,
+ multiple: el.multiple === true,
+ selectedLabels: picked.map((o) => o.label),
+ selectedValues: picked.map((o) => o.value),
+ };
} catch (e) { return null; }
}"""
)
@@ -5089,6 +5129,10 @@ OBSERVE_DISPLAY_WIDTHS = {
# call so the longest payload-minted URL fits whole after the widest display window.
OBSERVE_RETAIN_WIDTH_MIN = 2000
OBSERVE_FIELD_DISPLAY_MAX = max(OBSERVE_DISPLAY_WIDTHS.values())
+# Width the whole selected-options list may occupy on one rendered line, repr and all. A set-valued
+# control holds an unbounded number of options and each carries a label, so capping only the count
+# still lets one control take the digest over.
+OBSERVE_SELECTED_OPTIONS_TOTAL_CAP = 600
# Raw DOM perception: collect visible interactive elements with a stable selector each.
# Elements without a natural selector get a data-tv3 marker so later actions can target them.
@@ -6210,7 +6254,21 @@ async () => {
// element line for a selector that does not exist.
if (role && _WIDGET_ROLES.indexOf(String(role)) !== -1) rec.role = String(role);
if (el.tagName === 'SELECT') rec.options = Array.from(el.options).map((o) => o.value + '|' + o.text).slice(0, 60);
- if (secretValue) { if (el.value) rec.value = '(hidden)'; } else if (el.value) rec.value = String(el.value).slice(0, _RETAIN_WIDTH);
+ // el.value on a <select multiple> is the FIRST selected option only: a control holding nine
+ // reads as holding one, so an overwrite and an accumulation look identical. Report the set
+ // instead -- the scalar is a false readout here, not a partial one. Single-select is untouched.
+ const _multiSelect = el.tagName === 'SELECT' && el.multiple === true;
+ if (secretValue) { if (el.value) rec.value = '(hidden)'; }
+ else if (_multiSelect) {
+ const _picked = Array.from(el.selectedOptions || []);
+ // Retained per item at the same width as the scalar branch below: this list rides in the
+ // persistent conversation prefix, so an uncapped label is paid for on every later turn.
+ rec.selectedOptions = _picked.slice(0, 60).map((o) => (o.value + '|' + o.text).slice(0, _RETAIN_WIDTH));
+ // The size actually held, not the size retained. Python renders the truncation marker off
+ // this: a list that lost its tail silently reads as the whole selection.
+ rec.selectedTotal = _picked.length;
+ }
+ else if (el.value) rec.value = String(el.value).slice(0, _RETAIN_WIDTH);
// React-Select-style commit: the widget clears el.value and moves the label into its own surface
// (D3). Only when el.value is empty, so a field still holding its own text is never overridden.
else if (_isAutocomplete(el)) {
@@ -8382,6 +8440,24 @@ def build_browser_tools(
extra += f" placeholder={_field(e['placeholder'], OBSERVE_DISPLAY_WIDTHS['placeholder'])!r}"
if e.get("options"):
extra += f" options={e['options']}"
+ if e.get("selectedOptions") is not None:
+ held = e["selectedOptions"]
+ raw_total = e.get("selectedTotal")
+ total = len(held) if raw_total is None else int(raw_total)
+ shown: list[str] = []
+ for option in held:
+ text = _field(option, OBSERVE_DISPLAY_WIDTHS["value"])
+ # Measured on the RENDERED list, not the raw strings: the line is emitted through
+ # repr, whose quotes and separators add about a third the budget charges for.
+ if len(repr([*shown, text])) > OBSERVE_SELECTED_OPTIONS_TOTAL_CAP:
+ break
+ shown.append(text)
+ extra += f" selected_options={shown}"
+ # A capped selection must say it was capped. Showing 60 of 75 with no marker reads as
+ # the complete set, and the model then reasons about a selection it believes it can
+ # see whole -- the same false-readout failure the set replaced el.value to fix.
+ if len(shown) < total:
+ extra += f" (showing {len(shown)} of {total} selected)"
if e.get("checked") is not None:
extra += f" checked={e['checked']}"
if e.get("selected") is not None:
@@ -11413,6 +11489,8 @@ def build_browser_tools(
selector = args["selector"]
label = args.get("label")
value = args.get("value")
+ label_list = _option_str_list(args.get("labels"))
+ value_list = _option_str_list(args.get("values"))
ambiguous = await _ambiguous_selector_error(page, selector)
if ambiguous is not None:
return ambiguous
@@ -11436,7 +11514,15 @@ def build_browser_tools(
# momentarily fails is never misrouted into typing.
probe_node = str(probe.get("nodeName") or "") if isinstance(probe, dict) and probe.get("exists") else None
if probe_node is not None and probe_node != "select":
- chosen = label if label is not None else value
+ # A custom combobox commits one picked suggestion at a time; it has no set-valued
+ # commit path, so a requested set cannot be honoured in one call here.
+ requested = label_list or value_list
+ if requested is not None and len(requested) > 1:
+ return ToolResult.error(
+ f"{selector} is not a native <select>, so a set of options cannot be committed in "
+ "one call — select one option per call"
+ )
+ chosen = requested[0] if requested else (label if label is not None else value)
if not isinstance(chosen, str) or not chosen:
return ToolResult.error("select_option needs a label or value to choose")
return await _commit_custom_combobox(page, selector, _resolve_text(chosen))
@@ -11445,11 +11531,28 @@ def build_browser_tools(
force = bool(isinstance(probe, dict) and probe.get("exists") and not probe.get("visible"))
if force and not probe.get("proxied"):
return await _unreachable_error(selector)
- if label is not None:
+ # A <select multiple> discards its whole selection on every call, so a set must travel as one
+ # call; the driver takes a list natively.
+ is_multi = bool(isinstance(probe, dict) and probe.get("multiple"))
+ # What the readback is checked against comes off the SAME chain that selects, in the same
+ # order. Derived separately, `values` plus a scalar `label` selected by value and verified by
+ # label, so a call that did exactly what was asked reported `asked for ['Gamma'], it now
+ # holds ['Alpha']` and told the model to re-pass a set it had never asked for.
+ if label_list is not None:
+ by_label, asked = True, label_list
+ await page.select_option(selector, label=label_list, timeout=15000, force=force)
+ elif value_list is not None:
+ by_label, asked = False, value_list
+ await page.select_option(selector, value=value_list, timeout=15000, force=force)
+ elif label is not None:
+ by_label, asked = True, [label]
await page.select_option(selector, label=label, timeout=15000, force=force)
else:
+ by_label, asked = False, ([value] if isinstance(value, str) else [])
await page.select_option(selector, value=value, timeout=15000, force=force)
- if not force:
+ # A set-valued control is read back whether or not it was forced: without it a call that
+ # discarded every prior selection reports the same bare success as one that added to them.
+ if not force and not is_multi:
return ToolResult.ok(f"selected on {selector}")
try:
readback = await page.evaluate(_SELECT_READBACK_JS, await _probe_arg(page, selector))
@@ -11458,13 +11561,35 @@ def build_browser_tools(
value_read: Any = None
post: dict[str, Any] | None = None
committed_value: bool | None = None
+ expected: list[str] = []
+ held: list[str] = []
if isinstance(readback, dict):
value_read = readback.get("value")
- post = {"value": value_read}
- committed_value = readback.get("selectedLabel") == label if label is not None else value_read == value
+ if is_multi:
+ # Compare the SET, never `selectedLabel`/`el.value`: both name only the first selected
+ # option, so they read a nine-option selection and a one-option one identically.
+ expected = asked
+ key = "selectedLabels" if by_label else "selectedValues"
+ held = [x for x in (readback.get(key) or []) if isinstance(x, str)]
+ post = {"value": value_read, "selected": held}
+ # Multiplicity on the HELD side, deduped on the asked side: a page handler that also
+ # selects a duplicate-valued sibling leaves the control holding two options the form
+ # will submit twice, and comparing two sets reports that exact. Asking for the same
+ # option twice is still one request, so the ask is deduped rather than both sides.
+ committed_value = sorted(held) == sorted(set(expected))
+ else:
+ post = {"value": value_read}
+ committed_value = readback.get("selectedLabel") == label if label is not None else value_read == value
matches = await _post_match_count(page, selector)
verdict = _classify_commit(None, matches, post, committed_value=committed_value)
if verdict is CommitStatus.DID_NOT_COMMIT:
+ if is_multi:
+ return ToolResult.error(
+ f"select on {selector} did NOT commit the requested set: asked for "
+ f"{_selection_report(expected)}, it now holds {_selection_report(held)} — one call "
+ "REPLACES the whole selection, so pass every option "
+ "you want held in a single call via `values` or `labels`"
+ )
return ToolResult.error(
f"select on {selector} did NOT commit: native select still reads {value_read!r} — the styled "
"widget may not sync from its hidden control; re-observe and act on the visible proxy instead"
@@ -11479,6 +11604,10 @@ def build_browser_tools(
f"selected on {selector} — {reason}, so the selection could not be verified; re-observe "
"before relying on it"
)
+ if is_multi:
+ return ToolResult.ok(
+ f"selected on {selector} — it now holds {len(held)} option(s): {_selection_report(held)}"
+ )
return ToolResult.ok(f"selected on {selector} (hidden native select, set directly)")
async def press_key(args: dict[str, Any]) -> ToolResult:
@@ -12560,9 +12689,19 @@ def build_browser_tools(
),
_spec(
"select_option",
- "Choose an option in a <select> by value or visible label.",
+ "Choose an option in a <select> by value or visible label. For a control observe reports as "
+ "`select-multiple`, pass ALL the options you want held in ONE call via `values` or `labels` "
+ "-- a second call does not add to the selection, it REPLACES it. The result reports the "
+ "resulting selection set, so you can tell an accumulation from an overwrite.",
_obj(
- {"selector": {"type": "string"}, "value": {"type": "string"}, "label": {"type": "string"}}, ["selector"]
+ {
+ "selector": {"type": "string"},
+ "value": {"type": "string"},
+ "label": {"type": "string"},
+ "values": {"type": "array", "items": {"type": "string"}},
+ "labels": {"type": "array", "items": {"type": "string"}},
+ },
+ ["selector"],
),
select_option,
),
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 5d17ac0fc..6d6a1403e 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -44,6 +44,7 @@ from skyvern.forge.taskv3.tools import (
_OPAQUE_ID_RUN_RE,
_SEMANTIC_COMMIT_STATE_JS,
NAVIGATION_DEAD_END_STATUSES,
+ OBSERVE_SELECTED_OPTIONS_TOTAL_CAP,
PAGE_UNAVAILABLE_ERROR,
BlankWorkingPageGuard,
_annotate_screenshot,
@@ -1473,6 +1474,34 @@ async def test_select_option_diverts_custom_combobox_to_shared_commit(monkeypatc
assert not any(c[0] == "select_option" for c in page.calls) # never hit the native <select> API
+async def test_select_option_refuses_a_set_on_a_custom_combobox(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A custom combobox commits one picked suggestion at a time, so a requested set cannot be
+ # honoured here. It must refuse and name the remedy rather than commit element [0] and report
+ # success -- the whole point of the set-valued path is that a partial commit never reads as done.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(
+ field_type="text",
+ node_name="input",
+ suggestion={"text": "Analytics", "score": 2},
+ committed="Analytics",
+ match_count=1,
+ )
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#dept", "labels": ["Analytics", "Finance"]})
+ assert r.status == "error", r.content
+ assert "not a native <select>" in r.content and "select one option per call" in r.content
+ assert not page.clicked_suggestion # nothing was committed
+ assert not any(c[0] == "select_option" for c in page.calls)
+
+ # One option in the array is still a single commit, not a refusal.
+ r = await _tool(tools, "select_option").handler({"selector": "#dept", "labels": ["Analytics"]})
+ assert r.status == "ok", r.content
+ assert page.clicked_suggestion
+
+
@pytest.mark.asyncio
async def test_select_option_native_select_uses_native_path(monkeypatch: pytest.MonkeyPatch) -> None:
# A real <select> (nodeName == 'select') keeps the native path — dispatch page.select_option, no typing.
@@ -2779,6 +2808,244 @@ async def test_observe_renders_text_digest_and_pressed_state() -> None:
assert "pressed=True" in r.content
+async def test_observe_selection_readout_distinguishes_partial_from_whole() -> None:
+ # A truncated list that reads as the whole set is the same false readout the selection set
+ # replaced el.value to fix: the model reasons about a selection it believes it can see entire.
+ held = [f"v{i:02d}|Option {i:02d}" for i in range(60)]
+ # The cap is on the RENDERED line, so the boundary sits where repr stops fitting -- quotes and
+ # separators, not just the raw strings.
+ fits = 35
+ assert len(repr(held[:fits])) <= OBSERVE_SELECTED_OPTIONS_TOTAL_CAP < len(repr(held[: fits + 1]))
+
+ class _SelectionPage(_FakePage):
+ async def evaluate(self, _js: str) -> str:
+ return json.dumps(
+ {
+ "url": self.url,
+ "title": "Skills",
+ "elements": [
+ {
+ "i": 0,
+ "tag": "select",
+ "type": "select-multiple",
+ "selector": "#whole",
+ "label": "Whole",
+ "selectedOptions": ["a|Alpha", "b|Beta"],
+ "selectedTotal": 2,
+ },
+ {
+ "i": 1,
+ "tag": "select",
+ "type": "select-multiple",
+ "selector": "#partial",
+ "label": "Partial",
+ "selectedOptions": held,
+ "selectedTotal": 75,
+ },
+ ],
+ }
+ )
+
+ tools = build_browser_tools(_fixed_page_provider(_SelectionPage()))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ whole, partial = (ln for ln in r.content.splitlines() if "selected_options=" in ln)
+ # A complete readout names every option held and claims nothing about a cap.
+ assert "selected_options=['a|Alpha', 'b|Beta']" in whole, whole
+ assert "showing" not in whole, whole
+ # A partial one says so, and says how much of the selection it is: both the prefix it shows and
+ # the size actually held, so the two readouts can never be read the same way.
+ assert f"selected_options={held[:fits]} (showing {fits} of 75 selected)" in partial, partial
+ assert 0 < fits < len(held)
+
+
+@_skip_no_browser
+async def test_observe_bounds_each_selected_option_and_reports_the_whole_count() -> None:
+ # The digest rides in the persistent conversation prefix, so a set-valued control holding long
+ # labels is paid for on every later turn. Cap the item like the scalar branch caps el.value --
+ # but keep the true count, which is what makes a capped readout self-disclosing downstream.
+ options = "".join(f'<option value="v{i}" selected>{"L" * 3000}-{i}</option>' for i in range(75))
+ html_doc = f'<!doctype html><html><body><select multiple id="skills" size="4">{options}</select></body></html>'
+ async with _content_page(html_doc) as page:
+ data = await _observe_data(page)
+ sel = next(e for e in data["elements"] if e["tag"] == "select")
+ assert sel["selectedTotal"] == 75
+ assert len(sel["selectedOptions"]) == 60
+ assert max(len(o) for o in sel["selectedOptions"]) <= taskv3_tools.OBSERVE_RETAIN_WIDTH_MIN
+ # el.value would have named exactly one of the 75, which is the readout this replaced.
+ assert "value" not in sel, sel.get("value")
+
+
+_EMPTY_VALUE_SELECT = (
+ "<!doctype html><html><body>"
+ '<select multiple id="s" size="4">'
+ '<option value="">(none specified)</option><option value="x">Ex</option>'
+ '<option value="y">Why</option>'
+ "</select></body></html>"
+)
+
+
+@_skip_no_browser
+async def test_select_option_keeps_an_empty_option_value_in_the_requested_set() -> None:
+ # `<option value="">` is a real selectable value. Dropping it narrowed the request -- and the
+ # expected set the readback verifies against is built from the SAME narrowed list, so the check
+ # agreed with itself and reported committed a set the control never held.
+ async with _content_page(_EMPTY_VALUE_SELECT) as page:
+ handler = _tool(build_browser_tools(_fixed_page_provider(page)), "select_option").handler
+
+ async def _run(args: dict[str, Any]) -> tuple[str, str, list[str]]:
+ await page.set_content(_EMPTY_VALUE_SELECT)
+ r = await handler(args)
+ held = await page.evaluate(
+ "() => Array.from(document.getElementById('s').selectedOptions).map((o) => o.value)"
+ )
+ return r.status, r.content, held
+
+ status, report, held = await _run({"selector": "#s", "values": ["", "x"]})
+ assert (status, held) == ("ok", ["", "x"])
+ assert "holds 2 option(s): ['', 'x']" in report, report
+
+ status, report, held = await _run({"selector": "#s", "values": [""]})
+ assert (status, held) == ("ok", [""])
+ assert "holds 1 option(s): ['']" in report, report
+
+ # A declared-but-empty array asks for no option and must stay distinguishable from an array
+ # that names the empty value -- the two collapsed together before. It is still a DECLARED
+ # array, so it wins over a scalar exactly as a non-empty one does.
+ assert (await _run({"selector": "#s", "values": [], "value": "x"}))[::2] == ("ok", [])
+ assert await _run({"selector": "#s", "values": []}) == (
+ "ok",
+ "selected on #s — it now holds 0 option(s): []",
+ [],
+ )
+
+ # Non-strings are still not options.
+ status, _, held = await _run({"selector": "#s", "values": [None, "x"]})
+ assert (status, held) == ("ok", ["x"])
+
+
+@_skip_no_browser
+async def test_select_option_reports_a_page_added_duplicate_as_uncommitted() -> None:
+ # Two SETS lose multiplicity. A change handler that also selects a duplicate-VALUED sibling
+ # leaves the control holding an option the form submits twice, and a set comparison called that
+ # the requested selection exactly. Only the HELD side carries multiplicity: asking for the same
+ # option twice is still one request, so the ask is deduped rather than both sides.
+ dup_value = (
+ '<select multiple id="s" size="4">'
+ '<option value="x">Alpha</option><option value="x">Beta</option>'
+ '<option value="y">Gamma</option></select>'
+ )
+ dup_label = (
+ '<select multiple id="s" size="4">'
+ '<option value="v1">Alpha</option><option value="v2">Alpha</option>'
+ '<option value="v3">Gamma</option></select>'
+ )
+ unique = (
+ '<select multiple id="s" size="4"><option value="x">Alpha</option><option value="y">Gamma</option></select>'
+ )
+ page_adds_dup = dup_value + (
+ "<script>document.getElementById('s').addEventListener('change', () => {"
+ " const o = document.getElementById('s').options;"
+ " if (o[0].selected) o[1].selected = true; });</script>"
+ )
+
+ async with _content_page("<!doctype html><html><body></body></html>") as page:
+ handler = _tool(build_browser_tools(_fixed_page_provider(page)), "select_option").handler
+
+ async def _run(markup: str, args: dict[str, Any]) -> tuple[str, str, int]:
+ await page.set_content(f"<!doctype html><html><body>{markup}</body></html>")
+ r = await handler(args)
+ n = await page.evaluate("() => document.getElementById('s').selectedOptions.length")
+ return r.status, r.content, n
+
+ # The driver picks ONE option per requested value/label, so a duplicate in the DOM alone
+ # never over-selects -- these are the cases a multiplicity check must NOT start rejecting.
+ assert (await _run(dup_value, {"selector": "#s", "values": ["x"]}))[::2] == ("ok", 1)
+ assert (await _run(dup_label, {"selector": "#s", "labels": ["Alpha"]}))[::2] == ("ok", 1)
+ # The same option asked for twice is one request, not two.
+ assert (await _run(unique, {"selector": "#s", "values": ["x", "x"]}))[::2] == ("ok", 1)
+
+ status, report, n = await _run(page_adds_dup, {"selector": "#s", "values": ["x"]})
+ assert (status, n) == ("error", 2), (status, n, report)
+ assert "did NOT commit the requested set" in report, report
+ assert "it now holds ['x', 'x']" in report, report
+
+
+@_skip_no_browser
+async def test_select_option_verifies_against_the_key_it_selected_by() -> None:
+ # The action chain is labels -> values -> label -> value. Deriving the verification separately let
+ # `values` plus a stray scalar `label` select by value and check by label, so a call that did
+ # exactly what was asked reported `asked for ['Gamma'], it now holds ['Alpha']`.
+ markup = (
+ '<select multiple id="s" size="4"><option value="x">Alpha</option><option value="y">Gamma</option></select>'
+ )
+ async with _content_page(f"<!doctype html><html><body>{markup}</body></html>") as page:
+ handler = _tool(build_browser_tools(_fixed_page_provider(page)), "select_option").handler
+ r = await handler({"selector": "#s", "values": ["x"], "label": "Gamma"})
+ held = await page.evaluate("() => Array.from(document.getElementById('s').selectedOptions).map((o) => o.value)")
+ assert (r.status, held) == ("ok", ["x"]), r.content
+ assert "holds 1 option(s): ['x']" in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_option_bounds_the_selection_it_reports() -> None:
+ # The readback names options the PAGE chose the text of, in a tool result that is never
+ # compacted. Both the count and each option are bounded, and a cut is marked, so a truncated
+ # report cannot be read as the whole selection.
+ long_text = "L" * 500
+ options = "".join(f'<option value="v{i:02d}">{long_text}{i:02d}</option>' for i in range(30))
+ markup = f'<select multiple id="s" size="4">{options}</select>'
+ async with _content_page(f"<!doctype html><html><body>{markup}</body></html>") as page:
+ handler = _tool(build_browser_tools(_fixed_page_provider(page)), "select_option").handler
+ r = await handler({"selector": "#s", "values": [f"v{i:02d}" for i in range(30)]})
+ assert r.status == "ok", r.content[:300]
+ shown = [f"v{i:02d}" for i in range(taskv3_tools.SELECTION_REPORT_MAX_OPTIONS)]
+ assert r.content == (
+ f"selected on #s — it now holds 30 option(s): {shown!r} "
+ f"(showing {taskv3_tools.SELECTION_REPORT_MAX_OPTIONS} of 30)"
+ )
+
+ # Selected by label, each item is the page's own text and is cut at the width, marked.
+ async with _content_page(f"<!doctype html><html><body>{markup}</body></html>") as page:
+ handler = _tool(build_browser_tools(_fixed_page_provider(page)), "select_option").handler
+ r = await handler({"selector": "#s", "labels": [f"{long_text}00", f"{long_text}01"]})
+ width = taskv3_tools.SELECTION_REPORT_OPTION_WIDTH
+ assert r.status == "ok", r.content[:300]
+ assert r.content == f"selected on #s — it now holds 2 option(s): {['L' * width + '…'] * 2!r}"
+ assert long_text not in r.content
+
+
+@_skip_no_browser
+async def test_label_readback_agrees_with_the_driver_across_whitespace_forms() -> None:
+ # `option.label` is stripped and collapsed by the UA, which is the same normalisation Playwright
+ # matches `label=` under -- so asking for the collapsed form commits AND verifies. Read the raw
+ # `textContent` here instead and the verifier starts REJECTING selections that did commit.
+ forms = ["New York", " Boston", "Chicago ", "San\t\nJose"]
+ async with _content_page("<!doctype html><html><body></body></html>") as page:
+ handler = _tool(build_browser_tools(_fixed_page_provider(page)), "select_option").handler
+ for dom_text in forms:
+ asked = " ".join(dom_text.split())
+ await page.set_content(
+ f'<!doctype html><html><body><select multiple id="s" size="2">'
+ f'<option value="v1">{dom_text}</option><option value="v2">Other</option>'
+ "</select></body></html>"
+ )
+ r = await handler({"selector": "#s", "labels": [asked]})
+ held = await page.evaluate(
+ "() => Array.from(document.getElementById('s').selectedOptions).map((o) => o.value)"
+ )
+ assert held == ["v1"], (dom_text, held)
+ assert r.status == "ok", (dom_text, r.content)
+ assert "did NOT commit" not in r.content, (dom_text, r.content)
+
+
@pytest.mark.asyncio
async def test_get_html_falls_back_to_outer_html_for_empty_leaf() -> None:
# inner_html of a void/leaf element ("", e.g. <input>) used to return ok("") — no signal at all.