Skip to content

Automate browser based workflows with AI

Let Task V3 run toggle clicks after an earlier call in the batch fails (#8670)

pedrohsdb480f7eb0ef73
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index ebf358a79..75df88d0e 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -466,6 +466,9 @@ class ToolSpec:
# Exists because `open_verification_link` calls page.goto() while carrying neither flag, so an
# engagement predicate built on those two alone calls a run that navigated "never tried".
engages_page: bool = False
+ # Whether a call's target carries the toggle state observe prints (checked/pressed). Consulted only
+ # to exempt a click from the post-failure submit skip; set by the browser tools on click alone.
+ toggle_probe: Callable[[dict[str, Any]], Awaitable[bool]] | None = None
@property
def touches_page(self) -> bool:
@@ -667,6 +670,7 @@ ACTION_BUDGET_EXTENSION_MAX_FACTOR = 3
# precision is measurable on the canary; change only with the dashboards that read them.
ACTION_BUDGET_EXTENDED_EVENT = "taskv3 loop action budget extended"
ACTION_BUDGET_EXTENSION_REFUSED_EVENT = "taskv3 loop action budget extension refused"
+BATCH_SKIP_TOGGLE_EXEMPT_EVENT = "taskv3 loop batch skip exempted toggle click"
CREDENTIAL_RESUBMIT_REFUSED_EVENT = "taskv3 loop credential resubmit refused"
EXTRACTION_ENTRY_REFUSED_EVENT = "taskv3 loop extraction entry refused"
# Every tool that authors input on the page. Defined here rather than in tools.py because tools.py imports
@@ -1318,6 +1322,25 @@ def _credential_placeholders(args: dict[str, Any]) -> set[str]:
return set(walk(args))
+# Bounds the one probe a would-be-skipped click pays; a probe that overruns keeps the skip.
+TOGGLE_PROBE_TIMEOUT_SECONDS = 2.0
+
+
+async def _is_toggle_click(tool_name: str, spec: ToolSpec | None, args: dict[str, Any]) -> bool:
+ """A click whose target exposes a toggle state chooses an answer rather than submitting. Fails closed."""
+ if tool_name != "click" or spec is None or spec.toggle_probe is None:
+ return False
+ try:
+ is_toggle = await asyncio.wait_for(spec.toggle_probe(args), timeout=TOGGLE_PROBE_TIMEOUT_SECONDS)
+ except Exception:
+ LOG.info("taskv3 toggle probe failed; keeping the batch skip", exc_info=True)
+ return False
+ if is_toggle is True:
+ LOG.info(BATCH_SKIP_TOGGLE_EXEMPT_EVENT, tool=tool_name)
+ return True
+ return False
+
+
def _is_finish(tool_name: str) -> bool:
return tool_name == "finish"
@@ -3373,6 +3396,8 @@ async def run_agent_tool_loop(
# and a verdict written before the failure was seen may be wrong or mis-reasoned.
failed_selectors: set[str] = set()
batch_had_failure = False
+ # A refusal leaves its value in the field, so no click after it -- toggle or not -- may run.
+ batch_had_refusal = False
marks_stale = False
# Loop events minted this batch, emitted only after every progress signal the batch can
# produce has been absorbed (see the end-of-batch emission below).
@@ -3492,6 +3517,7 @@ async def run_agent_tool_loop(
# A refused call did not do what the rest of the batch was planned around, so it marks the
# batch failed: a later click, Enter-shaped submit, or finish in the same batch is skipped.
batch_had_failure = True
+ batch_had_refusal = True
st.messages.append(
{
"role": "tool",
@@ -3521,6 +3547,7 @@ async def run_agent_tool_loop(
# Same reason the extraction refusal marks the batch: a click queued behind this call
# would submit the value still sitting in the field, which is the act being refused.
batch_had_failure = True
+ batch_had_refusal = True
st.messages.append(
{
"role": "tool",
@@ -3537,7 +3564,10 @@ async def run_agent_tool_loop(
}
)
continue
- if batch_had_failure and _may_submit(tool_name, args):
+ toggle_exempted = False
+ if batch_had_failure and not batch_had_refusal and _may_submit(tool_name, args):
+ toggle_exempted = await _is_toggle_click(tool_name, spec, args)
+ if batch_had_failure and _may_submit(tool_name, args) and not toggle_exempted:
st.messages.append(
{
"role": "tool",
@@ -4276,6 +4306,17 @@ async def run_agent_tool_loop(
)
break
+ # A toggle can auto-advance a wizard, leaving the batch's failed field on the step behind it.
+ # Read off the click's own before/after URL comparison, so the check costs nothing extra.
+ if toggle_exempted and result.status == "ok" and result_data.get("page_transitioned") is True:
+ _append_skipped_tool_results(
+ st.messages,
+ tool_calls[idx + 1 :],
+ "an earlier field in this batch failed and was left on the previous step; the page moved "
+ "on — re-observe",
+ )
+ break
+
if result.status == "error":
# A live refusal needs a new model choice, so stop_batch skips pending calls without claiming progress.
poisoned = (
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index a46ba0d98..f80d67f6e 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -6315,6 +6315,34 @@ def _observe_render_clip_spans(text: str) -> tuple[str, list[list[int]]]:
# still lets one control take the digest over.
OBSERVE_SELECTED_OPTIONS_TOTAL_CAP = 600
+# The toggle state observe prints as `checked=`/`pressed=`. Shared with the batch-skip probe, which lets a
+# click on a control carrying one run after an earlier call in its batch failed: a toggle is a choice, not a submit.
+_TOGGLE_STATE_JS = r"""(el) => {
+ const out = {};
+ const role = el.getAttribute('role');
+ if (el.type === 'checkbox' || el.type === 'radio') out.checked = !!el.checked;
+ else if (role === 'checkbox' || role === 'radio' || role === 'switch') {
+ const ck = el.getAttribute('aria-checked');
+ if (ck === 'true' || ck === 'false') out.checked = ck === 'true';
+ }
+ const pressed = el.getAttribute('aria-pressed');
+ if (pressed === 'true' || pressed === 'false') out.pressed = pressed === 'true';
+ return out;
+}"""
+
+_TOGGLE_PROBE_EVALUATE_TIMEOUT_MS = 1000
+# A button with no type attribute is a submit button, so a pressed/checked state does not stop it submitting its form.
+# A reset control clears its form, which is no safer after a failed field.
+_TOGGLE_TARGET_PROBE_JS = (
+ r"""(el) => {
+ if (el.form && (el.type === 'submit' || el.type === 'image' || el.type === 'reset')) return false;
+ const st = ("""
+ + _TOGGLE_STATE_JS
+ + r""")(el);
+ return 'checked' in st || 'pressed' in st;
+}"""
+)
+
# 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.
_OBSERVE_JS_TEMPLATE = (
@@ -6453,6 +6481,9 @@ async () => {
const _labelText = """
+ _LABEL_TEXT_JS
+ r""";
+ const _toggleState = """
+ + _TOGGLE_STATE_JS
+ + r""";
// [role=textbox] is deliberately absent: on a div without contenteditable it names a control that
// cannot be filled, and the ones that can are already matched by [contenteditable=true].
const _WIDGET_ROLES = """
@@ -7387,11 +7418,8 @@ async () => {
const sv = ownCommittedSurface(el);
if (sv) out.value = String(sv).slice(0, _RETAIN_WIDTH);
}
- if (el.type === 'checkbox' || el.type === 'radio') out.checked = !!el.checked;
- else if (role === 'checkbox' || role === 'radio' || role === 'switch') {
- const ck = el.getAttribute('aria-checked');
- if (ck === 'true' || ck === 'false') out.checked = ck === 'true';
- }
+ const toggle = _toggleState(el);
+ if ('checked' in toggle) out.checked = toggle.checked;
const selected = el.getAttribute('aria-selected');
if ((role === 'tab' || role === 'option') && (selected === 'true' || selected === 'false')) out.selected = selected === 'true';
if (role === 'spinbutton' && !secret) {
@@ -7667,8 +7695,8 @@ async () => {
groupTotal += gt.length;
}
}
- const pressed = el.getAttribute('aria-pressed');
- if (pressed === 'true' || pressed === 'false') rec.pressed = pressed === 'true';
+ const toggle = _toggleState(el);
+ if ('pressed' in toggle) rec.pressed = toggle.pressed;
if (minted !== null) minted.rec = rec;
for (const a of anchorRecs) { for (const c of a.ctrls) { if (c.el === el) c.rec = rec; } }
if (hidden) hiddenListed++;
@@ -16030,6 +16058,31 @@ def build_browser_tools(
return wrapped
+ async def _toggle_target(args: dict[str, Any]) -> ToolResult:
+ page, error = await _resolve_page()
+ if error is not None:
+ return error
+ selector = args.get("selector")
+ if not isinstance(selector, str) or not selector:
+ return ToolResult.error("no selector")
+ # Counted by the engine the click acts through, so a selector that would land on the first of
+ # several matches answers "not a toggle" rather than describing an element it may not click.
+ target = page.locator(selector)
+ if await target.count() != 1:
+ return ToolResult.error("not exactly one element")
+ answer = await target.evaluate(_TOGGLE_TARGET_PROBE_JS, timeout=_TOGGLE_PROBE_EVALUATE_TIMEOUT_MS)
+ return ToolResult.ok("", data={"toggle": answer is True})
+
+ # Resolved through click's own address wrappers (mark=N, ref=N, `#id` normalization) on a copy of the
+ # call's arguments, so the probe cannot rewrite the selector the click itself later resolves.
+ _resolve_toggle_target = _with_act_by_mark(
+ _with_ref_resolution("toggle_probe", _with_selector_guard(_toggle_target))
+ )
+
+ async def _click_targets_toggle(args: dict[str, Any]) -> bool:
+ result = await _resolve_toggle_target(dict(args))
+ return result.status == "ok" and result.data is not None and result.data.get("toggle") is True
+
tools = [
_spec(
"observe",
@@ -16260,6 +16313,8 @@ def build_browser_tools(
# args["selector"], so the whole verified click/type path (uniqueness gate, commit-verify)
# runs on the act-by-mark selector unchanged.
_tool_spec.handler = _with_act_by_mark(_tool_spec.handler)
+ if _tool_spec.name == "click":
+ _tool_spec.toggle_probe = _click_targets_toggle
_apply_download_signal(tools, downloads_dir)
return tools
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 552628cf8..b85839941 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -19,7 +19,7 @@ import sys
import time
from datetime import UTC, datetime
from types import SimpleNamespace
-from typing import Any, Collection
+from typing import Any, Awaitable, Callable, Collection
import pytest
from structlog.testing import capture_logs
@@ -168,19 +168,43 @@ class _ScriptedCaller:
def _recording_tool(
- name: str, sink: list[tuple[str, dict[str, Any]]], *, raises: bool = False, billable: bool = False
+ name: str,
+ sink: list[tuple[str, dict[str, Any]]],
+ *,
+ raises: bool = False,
+ billable: bool = False,
+ toggle_probe: Callable[[dict[str, Any]], Awaitable[bool]] | None = None,
+ ok_data: dict[str, Any] | None = None,
) -> ToolSpec:
async def handler(args: dict[str, Any]) -> ToolResult:
sink.append((name, args))
if raises:
raise RuntimeError("boom")
- return ToolResult.ok(f"{name} done")
+ return ToolResult.ok(f"{name} done", data=ok_data)
return ToolSpec(
- name=name, description=name, parameters={"type": "object", "properties": {}}, handler=handler, billable=billable
+ name=name,
+ description=name,
+ parameters={"type": "object", "properties": {}},
+ handler=handler,
+ billable=billable,
+ toggle_probe=toggle_probe,
)
+def _toggle_selectors_probe(
+ toggles: set[str], asked: list[str] | None = None
+) -> Callable[[dict[str, Any]], Awaitable[bool]]:
+ """A click toggle probe answering from a fixed set of selectors that carry a toggle state."""
+
+ async def probe(args: dict[str, Any]) -> bool:
+ if asked is not None:
+ asked.append(args.get("selector"))
+ return args.get("selector") in toggles
+
+ return probe
+
+
def _erroring_tool(
name: str,
sink: list[tuple[str, dict[str, Any]]],
@@ -1523,10 +1547,10 @@ async def test_cross_selector_dependent_call_still_dispatches_and_fails_on_its_o
async def test_click_and_enter_submit_skipped_after_batch_failure_but_other_fields_run(
submit_call: tuple[str, dict[str, Any]],
) -> None:
- # After a page-action failure in the batch, the loop cannot classify a click -- it may be the
- # form's Submit -- so ANY later click is skipped alongside the Enter-shaped submit shapes. Other
- # field-filling tools (select_combobox, type, file_upload) on OTHER selectors are not submit-shaped
- # and still run.
+ # After a page-action failure in the batch, a click on a plain control may be the form's Submit, so
+ # it is skipped alongside the Enter-shaped submit shapes; a click on a control exposing a toggle
+ # state is a choice and runs. Other field-filling tools (select_combobox, type, file_upload) on
+ # OTHER selectors are not submit-shaped and still run.
submit_name, submit_args = submit_call
type_calls: list[tuple[str, dict[str, Any]]] = []
click_calls: list[tuple[str, dict[str, Any]]] = []
@@ -1551,8 +1575,8 @@ async def test_click_and_enter_submit_skipped_after_batch_failure_but_other_fiel
handler=type_handler,
billable=True,
),
- _recording_tool("click", click_calls),
- _recording_tool("press_key", press_calls),
+ _recording_tool("click", click_calls, toggle_probe=_toggle_selectors_probe({"#yes"})),
+ _recording_tool("press_key", press_calls, toggle_probe=_toggle_selectors_probe({"#submit"})),
_recording_tool("select_combobox", combobox_calls),
_recording_tool("file_upload", upload_calls),
make_finish_tool(),
@@ -1561,6 +1585,7 @@ async def test_click_and_enter_submit_skipped_after_batch_failure_but_other_fiel
[
("type", {"selector": "#q"}),
("click", {"selector": "#agree"}),
+ ("click", {"selector": "#yes"}),
(submit_name, submit_args),
("select_combobox", {"selector": "#city"}),
("type", {"selector": "#zip"}),
@@ -1571,7 +1596,8 @@ async def test_click_and_enter_submit_skipped_after_batch_failure_but_other_fiel
outcome, _ = await _run(script, tools, page_probe=probe)
assert outcome.status == "completed"
- assert len(click_calls) == 0 # a click cannot be classified as safe, so it's skipped too
+ # The plain click is skipped; only the toggle click reaches the handler.
+ assert [call_args.get("selector") for _, call_args in click_calls] == ["#yes"]
if submit_name == "press_key":
assert len(press_calls) == 0 # Enter-shaped submit skipped after the batch failure
else:
@@ -1581,13 +1607,158 @@ async def test_click_and_enter_submit_skipped_after_batch_failure_but_other_fiel
assert len(combobox_calls) == 1 # unrelated field, not submit-shaped, still runs
assert any(call_args.get("selector") == "#zip" for _, call_args in type_calls) # unrelated type still runs
assert len(upload_calls) == 1 # unrelated field, not submit-shaped, still runs
- assert outcome.tool_calls == 5 # four dispatched calls plus finish: the two skipped calls cost no budget
+ assert outcome.tool_calls == 6 # five dispatched calls plus finish: the two skipped calls cost no budget
turn1_tool_msgs = [m for m in outcome.messages if m.get("role") == "tool"]
assert any(m.get("name") == "click" and "skipped" in m["content"] for m in turn1_tool_msgs)
assert any(m.get("name") == submit_name and "skipped" in m["content"] for m in turn1_tool_msgs)
+async def _run_batch_after_failure(
+ queued: list[tuple[str, dict[str, Any]]],
+ click_probe: Callable[[dict[str, Any]], Awaitable[bool]] | None,
+ click_data: dict[str, Any] | None = None,
+) -> tuple[Any, list[tuple[str, dict[str, Any]]]]:
+ """One batch: a failing type on #q, then `queued`. Returns the outcome and every dispatched call."""
+ dispatched: list[tuple[str, dict[str, Any]]] = []
+ # Every tool carries the probe, so a test can show that only a click consults it.
+ tools = [
+ _erroring_tool("type", dispatched, billable=True),
+ _recording_tool("click", dispatched, toggle_probe=click_probe, ok_data=click_data),
+ _recording_tool("press_key", dispatched, toggle_probe=click_probe),
+ _recording_tool(CODE_TOOL_NAME, dispatched, toggle_probe=click_probe),
+ _recording_tool("select_combobox", dispatched),
+ make_finish_tool(),
+ ]
+ script = [
+ [("type", {"selector": "#q"}), *queued],
+ [("finish", {"status": "completed", "reason": "done"})],
+ ]
+ outcome, _ = await _run(script, tools)
+ return outcome, [call for call in dispatched if call[0] != "type"]
+
+
+ "selector",
+ ["#no-toggle-pressed", "ref=7", "input[name=agree][value=yes]"],
+ ids=["aria_pressed_button", "observe_ref", "radio"],
+)
+async def test_toggle_click_runs_after_batch_failure(selector: str) -> None:
+ outcome, dispatched = await _run_batch_after_failure(
+ [("click", {"selector": selector})], _toggle_selectors_probe({selector})
+ )
+ assert dispatched == [("click", {"selector": selector})]
+ assert not any("skipped" in m["content"] for m in outcome.messages if m.get("name") == "click")
+
+
+async def test_plain_click_still_skipped_after_batch_failure_when_probe_says_no_toggle() -> None:
+ # A type=button "Next" carries no toggle state: it may advance or submit the form, so it stays skipped.
+ asked: list[str] = []
+ outcome, dispatched = await _run_batch_after_failure(
+ [("click", {"selector": "#next"})], _toggle_selectors_probe(set(), asked)
+ )
+ assert dispatched == []
+ assert asked == ["#next"]
+ assert any("skipped" in m["content"] for m in outcome.messages if m.get("name") == "click")
+
+
+ "call",
+ [(CODE_TOOL_NAME, {"selector": "#yes", "code": "x"}), ("press_key", {"selector": "#yes", "key": "Enter"})],
+ ids=["code_tool", "enter"],
+)
+async def test_non_click_submit_shapes_never_consult_the_toggle_probe(call: tuple[str, dict[str, Any]]) -> None:
+ asked: list[str] = []
+ outcome, dispatched = await _run_batch_after_failure([call], _toggle_selectors_probe({"#yes"}, asked))
+ assert dispatched == []
+ assert asked == []
+ assert any("skipped" in m["content"] for m in outcome.messages if m.get("name") == call[0])
+
+
[email protected]("failure", ["raises", "hangs"])
+async def test_toggle_probe_failure_keeps_the_click_skipped(failure: str, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(loop_module, "TOGGLE_PROBE_TIMEOUT_SECONDS", 0.05)
+ never = asyncio.Event()
+
+ async def probe(args: dict[str, Any]) -> bool:
+ if failure == "raises":
+ raise RuntimeError("page gone")
+ await never.wait()
+ return True
+
+ outcome, dispatched = await _run_batch_after_failure([("click", {"selector": "#yes"})], probe)
+ assert dispatched == []
+ assert any("skipped" in m["content"] for m in outcome.messages if m.get("name") == "click")
+
+
+async def test_toggle_that_advances_the_step_stops_the_rest_of_the_batch() -> None:
+ # A toggle can auto-advance a wizard; the field that failed is then left on the step behind it.
+ outcome, dispatched = await _run_batch_after_failure(
+ [("click", {"selector": "#yes"}), ("select_combobox", {"selector": "#city"})],
+ _toggle_selectors_probe({"#yes"}),
+ click_data={"page_transitioned": True},
+ )
+ assert dispatched == [("click", {"selector": "#yes"})]
+ skipped = [m["content"] for m in outcome.messages if m.get("name") == "select_combobox"]
+ assert len(skipped) == 1 and "left on the previous step" in skipped[0], skipped
+
+
+async def test_toggle_that_stays_on_the_step_lets_the_batch_continue() -> None:
+ outcome, dispatched = await _run_batch_after_failure(
+ [("click", {"selector": "#yes"}), ("select_combobox", {"selector": "#city"})],
+ _toggle_selectors_probe({"#yes"}),
+ click_data={"page_transitioned": False},
+ )
+ assert dispatched == [("click", {"selector": "#yes"}), ("select_combobox", {"selector": "#city"})]
+
+
[email protected]("refusal", ["credential_resubmit", "extraction_entry"])
+async def test_toggle_click_stays_skipped_behind_a_guard_refusal(refusal: str) -> None:
+ # A toggle's own handler can submit the form, and the field a refusal left filled is the value it refused.
+ asked: list[str] = []
+ dispatched: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("type", dispatched),
+ _recording_tool("click", dispatched, toggle_probe=_toggle_selectors_probe({"#yes"}, asked)),
+ make_finish_tool(),
+ ]
+ refused_batch = [("type", {"selector": "ref=8", "text": _PASSWORD}), ("click", {"selector": "#yes"})]
+ script = [
+ *([[("type", {"selector": "ref=1", "text": _PASSWORD})], [("click", {"selector": "#submit"})]] * 2),
+ refused_batch,
+ [("finish", {"status": "failed", "reason": "the site rejected the credential"})],
+ ]
+ if refusal == "extraction_entry":
+ script = [refused_batch, script[-1]]
+ outcome, _ = await _run(script, tools, refuse_input_entry=refusal == "extraction_entry")
+
+ assert ("click", {"selector": "#yes"}) not in dispatched
+ assert asked == []
+ click_results = [m["content"] for m in outcome.messages if m.get("name") == "click"]
+ assert click_results[-1].startswith("skipped"), click_results
+
+
+async def test_toggle_probe_not_consulted_without_a_batch_failure() -> None:
+ asked: list[str] = []
+ dispatched: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _recording_tool("click", dispatched, toggle_probe=_toggle_selectors_probe(set(), asked)),
+ make_finish_tool(),
+ ]
+ script = [[("click", {"selector": "#next"})], [("finish", {"status": "completed", "reason": "done"})]]
+ await _run(script, tools)
+ assert dispatched == [("click", {"selector": "#next"})]
+ assert asked == []
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("data_flag", "error_value", "expected_status"),
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 45ae45dc2..0897ad13c 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -31256,3 +31256,62 @@ async def test_type_append_past_its_deadline_stops_sending_keys(monkeypatch: pyt
assert "stopped after" in r.content, r.content
assert 0 < len(held) < 26, held
assert other == ""
+
+
+@_skip_no_browser
+async def test_click_toggle_probe_matches_the_toggle_state_observe_prints() -> None:
+ # The batch skip lets a click through only when this probe says its target is a toggle, so the probe
+ # must agree with observe's own checked=/pressed= line on every shape except one that submits its form
+ # natively, and a plain type=button that may submit through a script must read as no toggle.
+ async with _content_page(
+ """<button id="yes" type="button" aria-pressed="false">Yes</button>
+ <button id="no" type="button" role="radio" aria-checked="false">No</button>
+ <input id="r1" type="radio" name="g" value="a" aria-label="Radio A">
+ <input id="c1" type="checkbox" name="c" aria-label="Agree box">
+ <div id="sw" role="switch" aria-checked="true" tabindex="0">Notify</div>
+ <button id="next" type="button">Next</button>
+ <button id="send" type="submit">Send</button>
+ <button id="mixed" type="button" aria-pressed="mixed">Mixed</button>
+ <button class="dup" aria-pressed="false">Dup</button><button class="dup" aria-pressed="false">Dup</button>
+ <button id="loose" aria-pressed="false">Loose</button>
+ <form><button id="in-form" aria-pressed="false">In form</button>
+ <input id="img" type="image" aria-pressed="false" alt="Image submit">
+ <button id="reset" type="reset" aria-pressed="false">Reset</button>
+ <input id="reset-input" type="reset" aria-pressed="false" value="Clear">
+ <button id="in-form-button" type="button" aria-pressed="false">In form button</button></form>"""
+ ) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ probe = _tool(tools, "click").toggle_probe
+ assert probe is not None
+ observed = await _tool(tools, "observe").handler({})
+ expected = {
+ "'Yes'": True,
+ "'No'": True,
+ "'Radio A'": True,
+ "'Agree box'": True,
+ "'Notify'": True,
+ "'Next'": False,
+ "'Send'": False,
+ "'Mixed'": False,
+ }
+ lines = observed.content.splitlines()
+ for needle, is_toggle in expected.items():
+ line = next(ln for ln in lines if needle in ln)
+ assert ("checked=" in line or "pressed=" in line) is is_toggle, line
+ args = {"selector": _ref_line(observed.content, needle)}
+ assert await probe(args) is is_toggle, line
+ # Probed on a copy: the click that follows must resolve the ref itself.
+ assert args["selector"].startswith("ref="), args
+ assert await probe({"selector": "#yes"}) is True
+ assert await probe({"selector": "#next"}) is False
+ assert await probe({"selector": ".dup"}) is False
+ assert await probe({"selector": "#gone"}) is False
+ # A button with no type submits its form owner, so pressed= there does not make it safe to click.
+ assert "pressed=" in next(ln for ln in lines if "'In form'" in ln)
+ assert await probe({"selector": "#in-form"}) is False
+ assert await probe({"selector": "#img"}) is False
+ assert await probe({"selector": "#reset"}) is False
+ assert await probe({"selector": "#reset-input"}) is False
+ assert await probe({"selector": "#in-form-button"}) is True
+ assert await probe({"selector": "#loose"}) is True