Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Log a structured outcome event for every custom-select opportunity (observation-only) (#7490)
Marc Kelechava63411e2adf42
diff --git a/skyvern/core/script_generations/fuzzy_matcher.py b/skyvern/core/script_generations/fuzzy_matcher.pyindex 63286f4d4..9a2a2462b 100644--- a/skyvern/core/script_generations/fuzzy_matcher.py+++ b/skyvern/core/script_generations/fuzzy_matcher.py@@ -7,6 +7,7 @@ form-filling pipeline into a single, configurable implementation.from __future__ import annotationsimport re+from typing import Literalimport structlog@@ -99,26 +100,31 @@ def match_option(candidate: str, options: list[str], *, min_substring_len: int =return None-def match_option_exact_or_stem(candidate: str, options: list[str], *, min_stem_len: int = 3) -> int | None:- """Find an exact or singular/plural stem option match.+def match_option_exact_or_stem_with_tier(+ candidate: str,+ options: list[str],+ *,+ min_stem_len: int = 3,+) -> tuple[int | None, Literal["exact", "stem"] | None]:+ """Find an exact or singular/plural stem option match and its tier.- This deliberately excludes substring and word-overlap matches. Returning- None is the safe fallback signal for option matches that need the LLM path.+ This deliberately excludes substring and word-overlap matches. A+ ``(None, None)`` result is the safe fallback signal for the LLM path."""if not candidate or not options:- return None+ return None, Nonecandidate_norm = _normalize(candidate)exact_matches = [i for i, opt in enumerate(options) if _normalize(opt) == candidate_norm]if len(exact_matches) == 1:- return exact_matches[0]+ return exact_matches[0], "exact"if len(exact_matches) > 1:- return None+ return None, None# Simple trailing-s stripping is intentionally precision-first; min_stem_len keeps non-linguistic stems safe.candidate_stem = candidate_norm.rstrip("s")if len(candidate_stem) < min_stem_len:- return None+ return None, Nonestem_matches = [i@@ -126,6 +132,11 @@ def match_option_exact_or_stem(candidate: str, options: list[str], *, min_stem_lif len(opt_stem := _normalize(opt).rstrip("s")) >= min_stem_len and opt_stem == candidate_stem]if len(stem_matches) == 1:- return stem_matches[0]+ return stem_matches[0], "stem"- return None+ return None, None+++def match_option_exact_or_stem(candidate: str, options: list[str], *, min_stem_len: int = 3) -> int | None:+ """Find an exact or singular/plural stem option match."""+ return match_option_exact_or_stem_with_tier(candidate, options, min_stem_len=min_stem_len)[0]diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 79d445786..df2df3898 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -7,7 +7,7 @@ from collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezone-from typing import TYPE_CHECKING, Any, Dict, List+from typing import TYPE_CHECKING, Any, Dict, List, Literalimport aiohttpimport httpx@@ -18,7 +18,7 @@ from playwright.async_api import Frame, Pagefrom skyvern.config import settingsfrom skyvern.constants import CUSTOMER_STORAGE_UPLOAD_MAX_BYTES, SKYVERN_ID_ATTR-from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_stem+from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_stem_with_tierfrom skyvern.exceptions import (AzureConfigurationError,DisabledBlockExecutionError,@@ -125,6 +125,7 @@ class FieldOptionResolution:matched_value: str | Noneconfidence: floatfallback_to_llm: bool+ matched_tier: Literal["exact", "stem"] | None = None@dataclass@@ -1906,7 +1907,7 @@ class AgentFunction:resolvable. A ``None`` match or ``fallback_to_llm=True`` means thecaller must defer to the LLM path."""- matched_index = match_option_exact_or_stem(target_value, option_labels)+ matched_index, matched_tier = match_option_exact_or_stem_with_tier(target_value, option_labels)if matched_index is None:return FieldOptionResolution(matched_index=None,@@ -1914,6 +1915,7 @@ class AgentFunction:matched_value=None,confidence=0.0,fallback_to_llm=True,+ matched_tier=None,)matched_value = option_values[matched_index] if matched_index < len(option_values) else None@@ -1923,6 +1925,7 @@ class AgentFunction:matched_value=matched_value,confidence=1.0,fallback_to_llm=False,+ matched_tier=matched_tier,)async def fill_custom_widget(diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex e90a5edd4..d6a9ef219 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -9,8 +9,9 @@ import urllib.parseimport uuidfrom collections import dequefrom datetime import datetime, timedelta, timezone+from enum import StrEnumfrom pathlib import Path-from typing import Any, Awaitable, Callable, List, TypedDict+from typing import Any, Awaitable, Callable, List, NamedTuple, TypedDictimport structlogfrom cachetools import TTLCache@@ -176,6 +177,31 @@ COLLAPSE_XP_ASSIGNMENT_FLAG = "COLLAPSE_XP_ASSIGNMENT"# Cross-process re-resolution is deterministic under stable flag config._COLLAPSE_XP_ASSIGNMENT_MEMO: TTLCache[str, bool] = TTLCache(maxsize=100_000, ttl=86_400)++class _CollapseGateResult(NamedTuple):+ family_enabled: bool+ assigned: bool | None+ gate_error: bool+++class CustomSelectFamilyOutcome(StrEnum):+ llm_fallback_gate_error = "llm_fallback_gate_error"+ llm_fallback_eval_error = "llm_fallback_eval_error"+ llm_fallback_family_off = "llm_fallback_family_off"+ llm_fallback_control = "llm_fallback_control"+ llm_fallback_no_match = "llm_fallback_no_match"+ llm_fallback_match_unactionable = "llm_fallback_match_unactionable"+ llm_fallback_pre_click_error = "llm_fallback_pre_click_error"+ llm_fallback_reset_verified = "llm_fallback_reset_verified"+ llm_fallback_post_click_unverified = "llm_fallback_post_click_unverified"+ success_precommit = "success_precommit"+ success_verified = "success_verified"+ terminal_post_click_exception = "terminal_post_click_exception"+ terminal_unverified_reset = "terminal_unverified_reset"+ terminal_unverified_click = "terminal_unverified_click"+ terminal_unverified_toggle = "terminal_unverified_toggle"++DOWNLOAD_EVENT_ACTIVE_DIR_GRACE_SECONDS = 60DOWNLOAD_DUPLICATE_STEM_SUFFIX_RE = re.compile(r"(?:\s+\(\d{1,3}\)|_\d{1,3})$")SELECT_SHADOW_MATCH_APOSTROPHE_RE = re.compile(r"['`‘’]")@@ -1214,31 +1240,39 @@ async def _resolve_collapse_xp_assignment(return assignment-async def _is_collapse_fanout_enabled(task: Task, family_flag: str, log_label: str) -> bool:+async def _resolve_collapse_gate(task: Task, family_flag: str, log_label: str) -> _CollapseGateResult:organization_id = task.organization_idif not organization_id:- return False+ return _CollapseGateResult(False, None, False)experimentation_provider = getattr(app, "EXPERIMENTATION_PROVIDER", None)if not experimentation_provider:- return False+ return _CollapseGateResult(False, None, False)try:- family_enabled = await experimentation_provider.is_feature_enabled_cached(- family_flag,- organization_id,- properties={"organization_id": organization_id},+ family_enabled = bool(+ await experimentation_provider.is_feature_enabled_cached(+ family_flag,+ organization_id,+ properties={"organization_id": organization_id},+ ))if not family_enabled:- return False+ return _CollapseGateResult(False, None, False)# PostHog hashes per flag key, so this umbrella is the only randomization source.# Family flags are kill switches and must never use percentage rollouts.- return await _resolve_collapse_xp_assignment(experimentation_provider, task, organization_id)+ assigned = await _resolve_collapse_xp_assignment(experimentation_provider, task, organization_id)+ return _CollapseGateResult(True, assigned, False)except Exception:LOG.warning(f"Failed to evaluate {log_label} flag; defaulting to disabled",organization_id=organization_id,exc_info=True,)- return False+ return _CollapseGateResult(False, None, True)+++async def _is_collapse_fanout_enabled(task: Task, family_flag: str, log_label: str) -> bool:+ gate = await _resolve_collapse_gate(task, family_flag, log_label)+ return gate.family_enabled and bool(gate.assigned)async def _is_collapse_select_fanout_enabled(task: Task) -> bool:@@ -2894,6 +2928,7 @@ async def handle_sequential_click_for_dropdown(scraped_page=scraped_page,step=step,task=task,+ entry_action_type="click",scraped_page_after_open=scraped_page_after_open,new_interactable_element_ids=new_interactable_element_ids,)@@ -3244,7 +3279,14 @@ async def handle_input_text_action(action=action,)action.set_has_mini_agent()- return await handle_select_option_action(select_action, page, scraped_page, task, step)+ return await handle_select_option_action(+ select_action,+ page,+ scraped_page,+ task,+ step,+ entry_action_type="input_text_converted",+ )select_action = SelectOptionAction(reasoning=action.reasoning,@@ -3353,6 +3395,7 @@ async def handle_input_text_action(step=step,task=task,target_value=text,+ entry_action_type="input_text",)if select_result is not None:@@ -3703,6 +3746,7 @@ async def handle_input_text_action(task=task,force_select=True,target_value=text,+ entry_action_type="input_text",)if select_result and select_result.action_result and select_result.action_result.success:auto_complete_hacky_flag = False@@ -3741,6 +3785,7 @@ async def handle_input_text_action(task=task,force_select=True,target_value=text,+ entry_action_type="input_text",)if select_result and select_result.action_result and select_result.action_result.success:auto_complete_hacky_flag = False@@ -4040,6 +4085,7 @@ async def handle_select_option_action(scraped_page: ScrapedPage,task: Task,step: Step,+ entry_action_type: str = "select_option",) -> list[ActionResult]:dom = DomUtil(scraped_page, page)skyvern_element = await dom.get_skyvern_element_by_id(action.element_id)@@ -4286,6 +4332,7 @@ async def handle_select_option_action(scraped_page=scraped_page,task=task,step=step,+ entry_action_type=entry_action_type,))return results@@ -4304,6 +4351,7 @@ async def handle_select_option_action(task=task,force_select=True,target_value=action.option.label or action.option.value or "",+ entry_action_type=entry_action_type,)# force_select won't return None resultassert result is not None@@ -6228,6 +6276,7 @@ async def sequentially_select_from_dropdown(force_select: bool = False,target_value: str = "",continue_until_close: bool = False,+ entry_action_type: str = "select_option",) -> CustomSingleSelectResult | None:"""TODO: support to return all values retrieved from the sequentially select@@ -6247,6 +6296,7 @@ async def sequentially_select_from_dropdown(values: list[str | None] = []select_history: list[CustomSingleSelectResult] = []single_select_result: CustomSingleSelectResult | None = None+ selection_group_id = str(uuid.uuid4())check_filter_funcs: list[CheckFilterOutElementIDFunc] = [check_existed_but_not_option_element_in_dom_factory(dom)]for i in range(max_depth):@@ -6263,6 +6313,8 @@ async def sequentially_select_from_dropdown(select_history=select_history,force_select=force_select,target_value=target_value,+ entry_action_type=entry_action_type,+ selection_group_id=selection_group_id,)assert single_select_result is not Noneselect_history.append(single_select_result)@@ -6899,31 +6951,95 @@ async def _select_deterministic_custom_option(get_skyvern_element: Callable[[str], Awaitable[SkyvernElement]],get_readback_scope_element: Callable[[], Awaitable[SkyvernElement | None]] | None = None,task: Task,+ step: Step | None = None,+ entry_action_type: str = "select_option",+ selection_group_id: str | None = None,+ select_depth: int = 0,) -> tuple[ActionResult, str | None] | None:+ started_at = time.monotonic()+ selection_group_id = selection_group_id or str(uuid.uuid4())+ option_count: int | None = None+ eligible = False+ match_tier: str | None = None+ attempted = False+ click_attempted = False++ def emit(outcome: CustomSelectFamilyOutcome) -> None:+ try:+ LOG.info(+ "custom_select_family_outcome",+ family="custom_select",+ workflow_run_id=task.workflow_run_id,+ task_id=task.task_id,+ organization_id=task.organization_id,+ step_id=getattr(step, "step_id", None),+ entry_action_type=entry_action_type,+ selection_group_id=selection_group_id,+ select_depth=select_depth,+ family_gate_enabled=gate.family_enabled,+ assigned=gate.assigned,+ gate_error=gate.gate_error,+ encountered=True,+ eligible=eligible,+ match_tier=match_tier,+ option_count=option_count,+ attempted=attempted,+ click_attempted=click_attempted,+ verified_success=outcome+ in {CustomSelectFamilyOutcome.success_precommit, CustomSelectFamilyOutcome.success_verified},+ outcome=outcome.value,+ llm_fallback_requested=outcome.value.startswith("llm_fallback_"),+ duration_ms=int((time.monotonic() - started_at) * 1000),+ )+ except Exception:+ LOG.debug("custom_select_family_outcome failed", exc_info=True)+if not target_value:return Noneif isinstance(field_context, dict) and field_context.get("is_date_related") is True:return None- if not await _is_collapse_custom_select_fanout_enabled(task):++ gate = await _resolve_collapse_gate(+ task,+ COLLAPSE_CUSTOM_SELECT_FANOUT_FLAG,+ "collapse-custom-select-fanout",+ )+ if gate.gate_error:+ emit(CustomSelectFamilyOutcome.llm_fallback_gate_error)return None- option_candidates = get_option_candidates()- if not option_candidates:+ try:+ option_candidates = get_option_candidates()+ if not option_candidates:+ return None+ option_labels = [str(candidate.get("label") or "") for candidate in option_candidates]+ option_values = [candidate.get("value") for candidate in option_candidates]+ resolution = await app.AGENT_FUNCTION.resolve_field_option(+ target_value=target_value,+ option_labels=option_labels,+ option_values=option_values,+ field_context=field_context,+ url=task.url,+ organization_id=task.organization_id,+ )+ except Exception:+ emit(CustomSelectFamilyOutcome.llm_fallback_eval_error)return None- option_labels = [str(candidate.get("label") or "") for candidate in option_candidates]- option_values = [candidate.get("value") for candidate in option_candidates]- resolution = await app.AGENT_FUNCTION.resolve_field_option(- target_value=target_value,- option_labels=option_labels,- option_values=option_values,- field_context=field_context,- url=task.url,- organization_id=task.organization_id,- )+ option_count = len(option_candidates)+ eligible = not resolution.fallback_to_llm and resolution.matched_index is not None+ match_tier = getattr(resolution, "matched_tier", None)+ if not gate.family_enabled:+ emit(CustomSelectFamilyOutcome.llm_fallback_family_off)+ return None+ if gate.assigned is False:+ emit(CustomSelectFamilyOutcome.llm_fallback_control)+ return Noneif resolution.fallback_to_llm or resolution.matched_index is None:+ emit(CustomSelectFamilyOutcome.llm_fallback_no_match)return Noneif resolution.matched_index >= len(option_candidates):+ emit(CustomSelectFamilyOutcome.llm_fallback_match_unactionable)return Nonematched_candidate = option_candidates[resolution.matched_index]@@ -6933,6 +7049,7 @@ async def _select_deterministic_custom_option(# that are not necessarily present on the resolved element itself.matched_option_is_choice_input = matched_candidate["is_choice_input"]if not element_id:+ emit(CustomSelectFamilyOutcome.llm_fallback_match_unactionable)return Nonereadback_scope_element: SkyvernElement | None = None@@ -6940,8 +7057,10 @@ async def _select_deterministic_custom_option(try:selected_element = await get_skyvern_element(element_id)if await selected_element.get_attr("role") == "listbox":+ emit(CustomSelectFamilyOutcome.llm_fallback_match_unactionable)return None+ attempted = Truematched_state = await _read_custom_select_matched_state(selected_element)live_role = str((matched_state or {}).get("role") or "").lower()live_toggle_shaped = (@@ -6962,6 +7081,7 @@ async def _select_deterministic_custom_option(expected_label = _normalize_select_shadow_text(matched_label)if expected_label:if _custom_select_matched_state_confirms_pre_click(matched_state, expected_label):+ emit(CustomSelectFamilyOutcome.success_precommit)return ActionSuccess(), matched_labelif await _custom_select_scope_confirms_committed(readback_scope_element=readback_scope_element,@@ -6971,9 +7091,11 @@ async def _select_deterministic_custom_option(expected_label=expected_label,allow_aria_selected_option_tokens=False,):+ emit(CustomSelectFamilyOutcome.success_precommit)return ActionSuccess(), matched_labelawait selected_element.scroll_into_view()+ click_attempted = Trueawait selected_element.click(page=page)verified = await _verify_custom_select_option_with_settle(matched_element=selected_element,@@ -6983,6 +7105,7 @@ async def _select_deterministic_custom_option(matched_label=matched_label,)if verified:+ emit(CustomSelectFamilyOutcome.success_verified)return ActionSuccess(), matched_labelexcept Exception:LOG.info(@@ -6992,18 +7115,28 @@ async def _select_deterministic_custom_option(matched_label=matched_label,exc_info=True,)+ emit(+ CustomSelectFamilyOutcome.llm_fallback_post_click_unverified+ if click_attempted+ else CustomSelectFamilyOutcome.llm_fallback_pre_click_error+ )return Noneif anchor_is_combobox_input:# Text-input comboboxes can be safely reset, so an unconfirmed read-back routes to the LLM# mini-agent (which clears/reopens the field) instead of hard-failing the whole action.- await _reset_custom_select_combobox_input(readback_scope_element, page)+ reset_verified = await _reset_custom_select_combobox_input(readback_scope_element, page)LOG.info("Deterministic custom-select read-back inconclusive on combobox input; routing to LLM fallback",target_value=target_value,matched_element_id=element_id,matched_label=matched_label,)+ emit(+ CustomSelectFamilyOutcome.llm_fallback_reset_verified+ if reset_verified+ else CustomSelectFamilyOutcome.llm_fallback_post_click_unverified+ )return Noneif not matched_option_is_choice_input:@@ -7015,6 +7148,7 @@ async def _select_deterministic_custom_option(matched_element_id=element_id,matched_label=matched_label,)+ emit(CustomSelectFamilyOutcome.llm_fallback_post_click_unverified)return NoneLOG.info(@@ -7030,21 +7164,24 @@ async def _select_deterministic_custom_option())action_failure.skip_remaining_actions = True+ emit(CustomSelectFamilyOutcome.terminal_unverified_toggle)return action_failure, matched_label-async def _reset_custom_select_combobox_input(element: SkyvernElement | None, page: Page) -> None:+async def _reset_custom_select_combobox_input(element: SkyvernElement | None, page: Page) -> bool:if element is None:- return+ return Falsetry:locator = element.get_locator()await locator.fill("")await element.click(page=page)+ return await get_input_value(element.get_tag_name(), locator) == ""except Exception:LOG.info("Failed to reset custom-select combobox input before LLM fallback",exc_info=True,)+ return Falsedef _no_match_exception_for_dropdown(@@ -7097,6 +7234,7 @@ async def select_from_emerging_elements(scraped_page: ScrapedPage,step: Step,task: Task,+ entry_action_type: str = "select_option",scraped_page_after_open: ScrapedPage | None = None,new_interactable_element_ids: list[str] | None = None,) -> ActionResult:@@ -7105,6 +7243,7 @@ async def select_from_emerging_elements(Currently mainly used for the dropdown menu selection."""+ selection_group_id = str(uuid.uuid4())# TODO: support to handle the case when options are loaded by scrollscraped_page_after_open = scraped_page_after_open or await scraped_page.generate_scraped_page_without_screenshots()new_element_ids = set(scraped_page_after_open.id_to_css_dict.keys()) - set(scraped_page.id_to_css_dict.keys())@@ -7172,6 +7311,10 @@ async def select_from_emerging_elements(get_skyvern_element=dom_after_open.get_skyvern_element_by_id,get_readback_scope_element=get_readback_scope_element,task=task,+ step=step,+ entry_action_type=entry_action_type,+ selection_group_id=selection_group_id,+ select_depth=0,)if deterministic_result is not None:action_result, _matched_label = deterministic_result@@ -7280,6 +7423,8 @@ async def select_from_dropdown(select_history: list[CustomSingleSelectResult] | None = None,force_select: bool = False,target_value: str = "",+ entry_action_type: str = "select_option",+ selection_group_id: str | None = None,) -> CustomSingleSelectResult:"""force_select: is used to choose an element to click even there's no dropdown menu;@@ -7337,6 +7482,10 @@ async def select_from_dropdown(get_skyvern_element=lambda element_id: SkyvernElement.create_from_incremental(incremental_scraped, element_id),get_readback_scope_element=_readback_scope_element_provider(skyvern_element),task=task,+ step=step,+ entry_action_type=entry_action_type,+ selection_group_id=selection_group_id or str(uuid.uuid4()),+ select_depth=len(select_history),)if deterministic_result is not None:action_result, matched_label = deterministic_resultdiff --git a/tests/unit/test_collapse_fanout_gates.py b/tests/unit/test_collapse_fanout_gates.pyindex 9073b338b..acf7e95db 100644--- a/tests/unit/test_collapse_fanout_gates.py+++ b/tests/unit/test_collapse_fanout_gates.py@@ -9,6 +9,7 @@ from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.webeye.actions import handlerUMBRELLA_FLAG = "COLLAPSE_XP_ASSIGNMENT"+CUSTOM_FLAG = handler.COLLAPSE_CUSTOM_SELECT_FANOUT_FLAGclass CaptureLogger:@@ -68,6 +69,38 @@ def _umbrella_calls(provider: FakeExperimentationProvider) -> list[tuple[str, streturn [call for call in provider.calls if call[1] == UMBRELLA_FLAG]+async def test_resolve_collapse_gate_family_off_skips_assignment_and_reports_null(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ provider = FakeExperimentationProvider({CUSTOM_FLAG: False})+ _set_provider(monkeypatch, provider)+ gate = await handler._resolve_collapse_gate(_task(), CUSTOM_FLAG, "custom-select")+ assert gate == handler._CollapseGateResult(family_enabled=False, assigned=None, gate_error=False)+ assert _umbrella_calls(provider) == []+++ ("results", "raises_for", "expected"),+ [+ ({CUSTOM_FLAG: True, UMBRELLA_FLAG: False}, set(), handler._CollapseGateResult(True, False, False)),+ ({CUSTOM_FLAG: True}, {CUSTOM_FLAG}, handler._CollapseGateResult(False, None, True)),+ ],+)+async def test_resolve_collapse_gate_separates_control_family_off_and_gate_error(+ monkeypatch: pytest.MonkeyPatch,+ results: dict[str, bool],+ raises_for: set[str],+ expected: handler._CollapseGateResult,+) -> None:+ handler._COLLAPSE_XP_ASSIGNMENT_MEMO.clear()+ provider = FakeExperimentationProvider(results, raises_for=raises_for)+ _set_provider(monkeypatch, provider)+ actual = await handler._resolve_collapse_gate(_task(), CUSTOM_FLAG, "custom-select")+ assert actual == expected++@pytest.mark.asyncioasync def test_collapse_family_off_skips_umbrella(monkeypatch: pytest.MonkeyPatch) -> None:provider = FakeExperimentationProvider({handler.COLLAPSE_SELECT_FANOUT_FLAG: False})diff --git a/tests/unit/test_fuzzy_matcher_exact_or_stem.py b/tests/unit/test_fuzzy_matcher_exact_or_stem.pyindex ea4731ed2..b12f38890 100644--- a/tests/unit/test_fuzzy_matcher_exact_or_stem.py+++ b/tests/unit/test_fuzzy_matcher_exact_or_stem.py@@ -2,7 +2,10 @@ from __future__ import annotationsimport pytest-from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_stem+from skyvern.core.script_generations.fuzzy_matcher import (+ match_option_exact_or_stem,+ match_option_exact_or_stem_with_tier,+)@pytest.mark.parametrize(@@ -33,3 +36,9 @@ def test_returns_index_on_exact_or_clean_stem(candidate: str, options: list[str])def test_returns_none_when_not_safely_resolvable(candidate: str, options: list[str]) -> None:assert match_option_exact_or_stem(candidate, options) is None+++def test_match_option_exact_or_stem_with_tier() -> None:+ assert match_option_exact_or_stem_with_tier("Alpha", ["Other", "alpha"]) == (1, "exact")+ assert match_option_exact_or_stem_with_tier("Years", ["Year", "Month"]) == (0, "stem")+ assert match_option_exact_or_stem_with_tier("County", ["County", "county"]) == (None, None)diff --git a/tests/unit/test_input_text_combobox_commit.py b/tests/unit/test_input_text_combobox_commit.pyindex 15d6a0c97..a927b8592 100644--- a/tests/unit/test_input_text_combobox_commit.py+++ b/tests/unit/test_input_text_combobox_commit.py@@ -226,6 +226,7 @@ async def test_invalid_combobox_commits_and_suppresses_tab() -> None:select_mock.assert_awaited_once()assert select_mock.await_args.kwargs["force_select"] is Trueassert select_mock.await_args.kwargs["target_value"] == _TARGET+ assert select_mock.await_args.kwargs["entry_action_type"] == "input_text"assert "Tab" not in _pressed_keys(el)assert not results[0].skip_remaining_actionsdiff --git a/tests/unit/test_select_shadow_match.py b/tests/unit/test_select_shadow_match.pyindex 87d9e06ba..2024df225 100644--- a/tests/unit/test_select_shadow_match.py+++ b/tests/unit/test_select_shadow_match.py@@ -8,7 +8,7 @@ import structlog.testingfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.webeye.actions import handler-from skyvern.webeye.actions.actions import InputOrSelectContext, SelectOption, SelectOptionAction+from skyvern.webeye.actions.actions import ClickAction, InputOrSelectContext, SelectOption, SelectOptionAction_SHADOW_OPTION = {"id": "matched-id",@@ -565,3 +565,392 @@ async def test_dropdown_select_call_path_forwards_committed_value_to_shadow_matcassert len(events) == 1assert events[0]["prompt_name"] == "custom-select/dropdown"assert events[0]["match_agrees_with_llm"] is True+++_OUTCOME_TASK = SimpleNamespace(+ workflow_run_id="wr",+ task_id="task",+ organization_id="org",+ url="https://test",+ navigation_goal="goal",+ navigation_payload={},+ llm_key=None,+)+++async def _run_outcome_case(+ monkeypatch: pytest.MonkeyPatch,+ case: str,+ *,+ family_enabled: bool = True,+ assigned: bool = False,+ entry_action_type: str = "select_option",+ selection_group_id: str = "group-1",+ select_depth: int = 0,+) -> tuple[object, dict[str, object], SimpleNamespace, AsyncMock]:+ handler._COLLAPSE_XP_ASSIGNMENT_MEMO.clear()+ family = (+ AsyncMock(side_effect=RuntimeError("gate")) if case == "gate_error" else AsyncMock(return_value=family_enabled)+ )+ provider = SimpleNamespace(+ is_feature_enabled_cached=family,+ resolve_feature_enabled_unrecorded=AsyncMock(return_value=assigned),+ )+ resolution = SimpleNamespace(+ fallback_to_llm=case == "no_match",+ matched_index=None if case == "no_match" else 2 if case == "bad_index" else 0,+ matched_label="Choice",+ matched_tier=None if case == "no_match" else "exact",+ )+ resolver = AsyncMock(side_effect=RuntimeError("matcher") if case == "matcher_error" else None)+ resolver.return_value = resolution+ selected = SimpleNamespace(+ get_attr=AsyncMock(return_value="listbox" if case == "listbox" else None),+ scroll_into_view=AsyncMock(),+ click=AsyncMock(side_effect=RuntimeError("after dispatch") if case == "post_click" else None),+ )+ monkeypatch.setattr(handler.app, "EXPERIMENTATION_PROVIDER", provider)+ monkeypatch.setattr(handler.app, "AGENT_FUNCTION", SimpleNamespace(resolve_field_option=resolver))+ monkeypatch.setattr(+ handler,+ "_read_custom_select_matched_state",+ AsyncMock(side_effect=RuntimeError("before click") if case == "pre_click" else None, return_value=None),+ )+ monkeypatch.setattr(handler, "_resolve_custom_select_readback_scope_element", AsyncMock(return_value=MagicMock()))+ monkeypatch.setattr(handler, "_anchor_is_combobox_input", AsyncMock(return_value=case.startswith("reset")))+ monkeypatch.setattr(+ handler, "_custom_select_matched_state_confirms_pre_click", Mock(return_value=case == "precommit")+ )+ monkeypatch.setattr(handler, "_custom_select_scope_confirms_committed", AsyncMock(return_value=False))+ monkeypatch.setattr(handler, "_verify_custom_select_option_with_settle", AsyncMock(return_value=case == "verified"))+ monkeypatch.setattr(handler, "_reset_custom_select_combobox_input", AsyncMock(return_value=case == "reset_ok"))+ candidates = (+ Mock(side_effect=RuntimeError("walker"))+ if case == "walker_error"+ else Mock(+ return_value=[+ {+ "label": "Choice",+ "element_id": None if case == "no_element_id" else "choice-1",+ "value": "choice",+ "is_choice_input": case == "toggle",+ }+ ]+ )+ )+ with structlog.testing.capture_logs() as logs:+ result = await handler._select_deterministic_custom_option(+ target_value="Choice",+ get_option_candidates=candidates,+ field_context={},+ page=MagicMock(),+ get_skyvern_element=AsyncMock(return_value=selected),+ task=_OUTCOME_TASK,+ step=SimpleNamespace(step_id="step"),+ entry_action_type=entry_action_type,+ selection_group_id=selection_group_id,+ select_depth=select_depth,+ )+ events = [log for log in logs if log.get("event") == "custom_select_family_outcome"]+ assert len(events) == 1+ return result, events[0], provider, resolver++[email protected]("entry_action_type", ["select_option", "input_text", "input_text_converted"])+async def test_outcome_event_emitted_once_per_opportunity(+ monkeypatch: pytest.MonkeyPatch, entry_action_type: str+) -> None:+ _, event, _, _ = await _run_outcome_case(monkeypatch, "control", entry_action_type=entry_action_type)+ assert event["outcome"] == "llm_fallback_control"+ assert event["entry_action_type"] == entry_action_type+++async def test_click_route_without_target_emits_nothing_and_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:+ gate = AsyncMock()+ monkeypatch.setattr(handler, "_resolve_collapse_gate", gate)++ with structlog.testing.capture_logs() as logs:+ result = await handler._select_deterministic_custom_option(+ target_value=None,+ get_option_candidates=Mock(),+ field_context={},+ page=MagicMock(),+ get_skyvern_element=AsyncMock(),+ task=_OUTCOME_TASK,+ entry_action_type="click",+ )++ assert result is None+ assert [log for log in logs if log.get("event") == "custom_select_family_outcome"] == []+ gate.assert_not_awaited()+++async def test_click_ingress_routes_no_target_and_emits_nothing(monkeypatch: pytest.MonkeyPatch) -> None:+ select_from_emerging_elements = AsyncMock(return_value=MagicMock())+ monkeypatch.setattr(handler, "select_from_emerging_elements", select_from_emerging_elements)+ monkeypatch.setattr(handler, "_build_after_click_verify_prompt", AsyncMock(return_value="prompt"))+ monkeypatch.setattr(+ handler,+ "resolve_check_user_goal_handler",+ AsyncMock(+ return_value=AsyncMock(+ return_value={"thoughts": "continue", "user_goal_achieved": False, "should_terminate": False}+ )+ ),+ )+ monkeypatch.setattr(handler, "locate_dropdown_menu", AsyncMock(return_value=MagicMock()))+ monkeypatch.setattr(+ handler,+ "_get_input_or_select_context",+ AsyncMock(return_value=InputOrSelectContext(field="Field", is_required=True, is_date_related=False)),+ )+ monkeypatch.setattr(+ handler,+ "DomUtil",+ Mock(+ return_value=SimpleNamespace(+ get_skyvern_element_by_id=AsyncMock(+ return_value=SimpleNamespace(is_interactable=Mock(return_value=True))+ )+ )+ ),+ )++ scraped_page_after_open = SimpleNamespace(id_to_css_dict={"choice-id": "[data-id=choice-id]"})+ scraped_page = SimpleNamespace(+ url="https://test",+ id_to_css_dict={},+ generate_scraped_page_without_screenshots=AsyncMock(return_value=scraped_page_after_open),+ )+ incremental_scraped = SimpleNamespace(+ get_incremental_elements_num=AsyncMock(return_value=1),+ get_incremental_element_tree=AsyncMock(return_value=[_SHADOW_OPTION]),+ )++ with structlog.testing.capture_logs() as logs:+ await handler.handle_sequential_click_for_dropdown(+ action=ClickAction(element_id="field-id", reasoning="click", intention="choose"),+ action_history=[],+ anchor_element=MagicMock(get_id=Mock(return_value="field-id")),+ dom=MagicMock(),+ page=SimpleNamespace(url="https://test"),+ skyvern_frame=SimpleNamespace(safe_wait_for_animation_end=AsyncMock()),+ scraped_page=scraped_page,+ incremental_scraped=incremental_scraped,+ task=_OUTCOME_TASK,+ step=SimpleNamespace(step_id="step"),+ )++ options = select_from_emerging_elements.await_args.kwargs["options"]+ assert options.target_value is None+ assert [log for log in logs if log.get("event") == "custom_select_family_outcome"] == []+++async def test_outcome_event_once_per_dropdown_level_with_group_id(monkeypatch: pytest.MonkeyPatch) -> None:+ handler._COLLAPSE_XP_ASSIGNMENT_MEMO.clear()+ monkeypatch.setattr(+ handler.app,+ "EXPERIMENTATION_PROVIDER",+ SimpleNamespace(+ is_feature_enabled_cached=AsyncMock(return_value=True),+ resolve_feature_enabled_unrecorded=AsyncMock(return_value=False),+ ),+ )+ monkeypatch.setattr(+ handler.app,+ "AGENT_FUNCTION",+ SimpleNamespace(+ resolve_field_option=AsyncMock(+ return_value=SimpleNamespace(+ fallback_to_llm=False,+ matched_index=0,+ matched_label="Choice",+ matched_tier="exact",+ )+ )+ ),+ )+ monkeypatch.setattr(+ handler.app,+ "CUSTOM_SELECT_AGENT_LLM_API_HANDLER",+ AsyncMock(return_value={"id": "matched-id", "value": "Choice", "action_type": "input_text"}),+ )+ monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))+ monkeypatch.setattr(handler, "get_input_value", AsyncMock(return_value=""))+ monkeypatch.setattr(+ handler, "get_actual_value_of_parameter_if_secret_with_task", Mock(side_effect=lambda _, value: value)+ )++ dropdown = MagicMock(+ get_element_handler=AsyncMock(return_value=MagicMock()),+ get_locator=Mock(return_value=MagicMock(count=AsyncMock(return_value=1))),+ )+ input_element = MagicMock(+ get_tag_name=Mock(return_value="input"),+ get_locator=Mock(return_value=MagicMock()),+ scroll_into_view=AsyncMock(),+ is_readonly=AsyncMock(return_value=False),+ input_clear=AsyncMock(),+ input_sequentially=AsyncMock(),+ )+ skyvern_frame = MagicMock(+ safe_wait_for_animation_end=AsyncMock(),+ get_element_scrollable=AsyncMock(return_value=False),+ get_element_visible=AsyncMock(return_value=True),+ )+ incremental_scraped = MagicMock(get_incremental_element_tree=AsyncMock(return_value=[_SHADOW_OPTION]))+ incremental_scraped.build_element_tree.return_value = "<div>Choice</div>"+ monkeypatch.setattr(handler, "try_to_find_potential_scrollable_element", AsyncMock(return_value=dropdown))+ monkeypatch.setattr(handler.SkyvernElement, "create_from_incremental", AsyncMock(return_value=input_element))++ action = SelectOptionAction(+ element_id="field-id",+ option=SelectOption(label="Choice"),+ input_or_select_context=InputOrSelectContext(field="Field"),+ )+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ with structlog.testing.capture_logs() as logs:+ await handler.sequentially_select_from_dropdown(+ action=action,+ input_or_select_context=InputOrSelectContext(field="Field"),+ page=MagicMock(),+ dom=MagicMock(),+ skyvern_element=MagicMock(),+ skyvern_frame=skyvern_frame,+ incremental_scraped=incremental_scraped,+ step=SimpleNamespace(step_id="step"),+ task=_OUTCOME_TASK,+ dropdown_menu_element=dropdown,+ force_select=True,+ target_value="Choice",+ )++ events = [log for log in logs if log.get("event") == "custom_select_family_outcome"]+ assert len(events) == 3+ assert [event["outcome"] for event in events] == ["llm_fallback_control"] * 3+ assert events[0]["selection_group_id"]+ assert len({event["selection_group_id"] for event in events}) == 1+ assert [event["select_depth"] for event in events] == [0, 1, 2]+++async def test_outcome_event_family_off_emits_without_assignment_resolution(monkeypatch: pytest.MonkeyPatch) -> None:+ _, event, provider, resolver = await _run_outcome_case(monkeypatch, "family_off", family_enabled=False)+ assert event["outcome"] == "llm_fallback_family_off"+ assert (event["assigned"], event["eligible"], event["match_tier"]) == (None, True, "exact")+ provider.resolve_feature_enabled_unrecorded.assert_not_awaited()+ resolver.assert_awaited_once()+++async def test_outcome_event_key_allowlist_and_enum(monkeypatch: pytest.MonkeyPatch) -> None:+ _, event, _, _ = await _run_outcome_case(monkeypatch, "control")+ expected_keys = set(+ "event log_level family workflow_run_id task_id organization_id step_id entry_action_type selection_group_id "+ "select_depth family_gate_enabled assigned gate_error encountered eligible match_tier option_count attempted "+ "click_attempted verified_success outcome llm_fallback_requested duration_ms".split()+ )+ expected_outcomes = set(+ "llm_fallback_gate_error llm_fallback_eval_error llm_fallback_family_off llm_fallback_control "+ "llm_fallback_no_match llm_fallback_match_unactionable llm_fallback_pre_click_error "+ "llm_fallback_reset_verified llm_fallback_post_click_unverified success_precommit success_verified "+ "terminal_post_click_exception terminal_unverified_reset terminal_unverified_click "+ "terminal_unverified_toggle".split()+ )+ assert event["outcome"] == "llm_fallback_control"+ assert set(event) == expected_keys+ assert {outcome.value for outcome in handler.CustomSelectFamilyOutcome} == expected_outcomes+++async def test_outcome_event_gate_error_fields(monkeypatch: pytest.MonkeyPatch) -> None:+ _, event, _, _ = await _run_outcome_case(monkeypatch, "gate_error")+ assert event["outcome"] == "llm_fallback_gate_error"+ assert (event["option_count"], event["eligible"], event["match_tier"]) == (None, False, None)+++ ("case", "family_enabled", "assigned"),+ [+ (case, family, assigned)+ for case in ("walker_error", "matcher_error")+ for family, assigned in ((False, False), (True, False), (True, True))+ ],+)+async def test_outcome_event_eval_error_emits_on_all_arms(+ monkeypatch: pytest.MonkeyPatch, case: str, family_enabled: bool, assigned: bool+) -> None:+ result, event, _, _ = await _run_outcome_case(monkeypatch, case, family_enabled=family_enabled, assigned=assigned)+ assert result is None+ assert event["outcome"] == "llm_fallback_eval_error"+++ ("case", "outcome", "attempted"),+ [+ ("no_match", "llm_fallback_no_match", False),+ ("bad_index", "llm_fallback_match_unactionable", False),+ ("no_element_id", "llm_fallback_match_unactionable", False),+ ("listbox", "llm_fallback_match_unactionable", False),+ ("pre_click", "llm_fallback_pre_click_error", True),+ ("precommit", "success_precommit", True),+ ("verified", "success_verified", True),+ ("nonchoice", "llm_fallback_post_click_unverified", True),+ ("toggle", "terminal_unverified_toggle", True),+ ],+)+async def test_outcome_event_exact_for_each_treatment_exit(+ monkeypatch: pytest.MonkeyPatch, case: str, outcome: str, attempted: bool+) -> None:+ _, event, _, _ = await _run_outcome_case(monkeypatch, case, assigned=True)+ assert event["outcome"] == outcome+ assert event["attempted"] is attempted+++async def test_click_attempted_true_when_click_dispatches_then_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ result, event, _, _ = await _run_outcome_case(monkeypatch, "post_click", assigned=True)+ assert result is None+ assert event["outcome"] == "llm_fallback_post_click_unverified"+ assert event["click_attempted"] is True+++ ("case", "outcome"),+ [("reset_ok", "llm_fallback_reset_verified"), ("reset_failed", "llm_fallback_post_click_unverified")],+)+async def test_reset_outcome_recorded_without_behavior_change(+ monkeypatch: pytest.MonkeyPatch, case: str, outcome: str+) -> None:+ result, event, _, _ = await _run_outcome_case(monkeypatch, case, assigned=True)+ assert result is None+ assert event["outcome"] == outcome+++async def test_converted_route_reports_input_text_converted(monkeypatch: pytest.MonkeyPatch) -> None:+ element = MagicMock(is_disabled=AsyncMock(return_value=False), get_selectable=AsyncMock(return_value=True))+ element.get_tag_name.return_value, element.get_id.return_value = "input", "field"+ monkeypatch.setattr(+ handler, "DomUtil", Mock(return_value=MagicMock(get_skyvern_element_by_id=AsyncMock(return_value=element)))+ )+ monkeypatch.setattr(handler.SkyvernFrame, "create_instance", AsyncMock(return_value=MagicMock()))+ monkeypatch.setattr(handler, "IncrementalScrapePage", MagicMock())+ monkeypatch.setattr(handler, "get_input_value", AsyncMock(return_value=""))+ select = AsyncMock(return_value=[handler.ActionSuccess()])+ monkeypatch.setattr(handler, "handle_select_option_action", select)+ await handler.handle_input_text_action(+ handler.InputTextAction(element_id="field", text="Choice"),+ MagicMock(),+ SimpleNamespace(id_to_element_dict={"field": {"tagName": "input"}}),+ SimpleNamespace(workflow_run_id=None),+ MagicMock(),+ )+ assert select.await_args.kwargs["entry_action_type"] == "input_text_converted"