Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11315 fix tel digit-drop by typing bare NANP digits (#6826)
Shuchang Zhengf86799234d6c
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex 9d7591da4..2b6360fed 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -161,6 +161,16 @@ class InvalidOpenAIResponseFormat(SkyvernException):super().__init__(f"Invalid response format: {message}")+class PhoneNumberInputMismatch(SkyvernException):+ def __init__(self, *, expected_digit_count: int, actual_digit_count: int):+ self.expected_digit_count = expected_digit_count+ self.actual_digit_count = actual_digit_count+ super().__init__(+ "Phone input read-back mismatch: "+ f"expected {expected_digit_count} digits, found {actual_digit_count} digits."+ )++class ConditionalBranchEvaluationError(SkyvernException):"""A conditional block could not resolve which branch to take."""diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex bf7010cdb..c3b8c388e 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -59,6 +59,7 @@ from skyvern.exceptions import (NoIncrementalElementFoundForCustomSelection,NoSuitableAutoCompleteOption,OptionIndexOutOfBound,+ PhoneNumberInputMismatch,)from skyvern.experimentation.wait_utils import get_or_create_wait_config, get_wait_timefrom skyvern.forge import app@@ -153,6 +154,8 @@ LOG = structlog.get_logger()UPLOAD_PENDING_FOLLOWUP_MESSAGE = "Upload is not complete yet. Continue the upload flow."+FIX_TEL_INPUT_DIGIT_DROP_FLAG = "FIX_TEL_INPUT_DIGIT_DROP"+DOWNLOAD_EVENT_ACTIVE_DIR_GRACE_SECONDS = 60DOWNLOAD_DUPLICATE_STEM_SUFFIX_RE = re.compile(r"(?:\s+\(\d{1,3}\)|_\d{1,3})$")@@ -547,6 +550,88 @@ async def check_phone_number_format(return check_phone_number_format_response.recommended_phone_number+def _phone_digits(value: str | None) -> str:+ return re.sub(r"\D", "", value or "")+++def _is_plain_nanp_number(value: str | None) -> bool:+ # A 10-digit North American number with no '+'/country-code/extension markers. There is no+ # international handling, so a value carrying a '+' or letters (an extension) is excluded.+ text = value or ""+ if "+" in text or re.search(r"[A-Za-z]", text):+ return False+ return len(_phone_digits(text)) == 10+++def _tel_pattern_allows_bare_digits(pattern: str | None, bare_digits: str) -> bool:+ # An HTML `pattern` is an implicitly-anchored constraint on the field's value. If the bare national+ # digits do not satisfy it, the field requires a specific mask (e.g. "(ddd) ddd-dddd") and bare+ # digits would fail validation, so they must not be used. A missing or unparseable pattern is+ # treated as permissive.+ if not pattern:+ return True+ try:+ return re.fullmatch(pattern, bare_digits) is not None+ except re.error:+ return True+++def _plan_tel_text(*, is_tel: bool, is_secret: bool, value: str, pattern: str | None) -> tuple[str, bool, bool]:+ # Decide how to fill a tel field. Returns (text_to_type, used_bare_nanp, run_format_check).+ # A separator-formatted value is long enough to fill()-split into a half-open "(ddd" that a+ # self-formatting field collapses, dropping a digit; bare national digits avoid that. Stripping is a+ # local transform, so it is applied to secret values too. The format-check LLM is reserved for+ # non-secret values that the bare-digit path does not handle.+ if is_tel and _is_plain_nanp_number(value) and _tel_pattern_allows_bare_digits(pattern, _phone_digits(value)):+ return _phone_digits(value), True, False+ return value, False, is_tel and not is_secret+++async def _is_tel_digit_fix_enabled(task: Task) -> bool:+ organization_id = task.organization_id+ if not organization_id:+ return False+ experimentation_provider = getattr(app, "EXPERIMENTATION_PROVIDER", None)+ if not experimentation_provider:+ return False+ try:+ # Bucket by org (not per-run) for a stable, monitorable ramp and clean rollback.+ return bool(+ await experimentation_provider.is_feature_enabled_cached(+ FIX_TEL_INPUT_DIGIT_DROP_FLAG,+ organization_id,+ properties={"organization_id": organization_id},+ )+ )+ except Exception:+ LOG.warning(+ "Failed to evaluate tel-digit-fix flag; defaulting to disabled",+ organization_id=organization_id,+ exc_info=True,+ )+ return False+++async def verify_phone_input_digits(*, tag_name: str, locator: Locator, expected_value: str) -> None:+ # Compare digit counts only — never the raw value, which may be a secret.+ actual_value = await get_input_value(tag_name=tag_name, locator=locator)+ expected_digits = _phone_digits(expected_value)+ actual_digits = _phone_digits(actual_value)+ if expected_digits != actual_digits:+ raise PhoneNumberInputMismatch(+ expected_digit_count=len(expected_digits),+ actual_digit_count=len(actual_digits),+ )+++async def _verify_tel_input_after_fill(*, skyvern_element: SkyvernElement, tag_name: str, expected_value: str) -> None:+ await verify_phone_input_digits(+ tag_name=tag_name,+ locator=skyvern_element.get_locator(),+ expected_value=expected_value,+ )++async def check_date_format(value: str,action: actions.InputTextAction,@@ -2076,8 +2161,20 @@ async def handle_input_text_action()return [ActionFailure(InputToReadonlyElement(element_id=skyvern_element.get_id()))]- # check the phone number format when type=tel and the text is not a secret value- if not is_secret_value and await skyvern_element.get_attr("type") == "tel":+ is_tel = await skyvern_element.get_attr("type") == "tel"+ is_plain_nanp_tel = False+ run_phone_format_check = False+ if is_tel and await _is_tel_digit_fix_enabled(task):+ # SKY-11315 fix, behind FIX_TEL_INPUT_DIGIT_DROP. Flag-off keeps the original behavior below+ # byte-for-byte. Plain-NANP tel is typed as bare digits (skipping the format-check LLM) unless+ # the field's pattern requires a mask; secrets are eligible (local strip, no LLM).+ tel_pattern = await skyvern_element.get_attr("pattern")+ text, is_plain_nanp_tel, run_phone_format_check = _plan_tel_text(+ is_tel=True, is_secret=is_secret_value, value=text, pattern=tel_pattern+ )+ elif is_tel and not is_secret_value:+ run_phone_format_check = True+ if run_phone_format_check:try:action.set_has_mini_agent()text = await check_phone_number_format(@@ -2219,10 +2316,40 @@ async def handle_input_text_action(auto_complete_hacky_flag = Falsereturn [result]+ # Only the bare-digit NANP fill is read back to verify; other tel shapes are left unverified.+ verify_tel_input_after_fill = is_plain_nanp_tel+await incremental_scraped.start_listen_dom_increment(await skyvern_element.get_element_handler())try:await skyvern_element.input_sequentially(text=text)+ if verify_tel_input_after_fill:+ # Read the typed digits back; on mismatch, clear and retype once. A second mismatch+ # fails the action here rather than letting it surface as a silent wrong fill.+ try:+ await _verify_tel_input_after_fill(+ skyvern_element=skyvern_element,+ tag_name=tag_name,+ expected_value=text,+ )+ except PhoneNumberInputMismatch:+ await skyvern_element.input_clear()+ await skyvern_element.input_sequentially(text=text)+ try:+ await _verify_tel_input_after_fill(+ skyvern_element=skyvern_element,+ tag_name=tag_name,+ expected_value=text,+ )+ except PhoneNumberInputMismatch as mismatch:+ LOG.warning(+ "Phone input read-back mismatch after retry",+ action=action,+ element_id=skyvern_element.get_id(),+ expected_digit_count=mismatch.expected_digit_count,+ actual_digit_count=mismatch.actual_digit_count,+ )+ return [ActionFailure(mismatch)]incremental_element = await incremental_scraped.get_incremental_element_tree(clean_and_remove_element_tree_factory(diff --git a/tests/unit/test_input_text_phone_readback.py b/tests/unit/test_input_text_phone_readback.pynew file mode 100644index 000000000..94e0f51a4--- /dev/null+++ b/tests/unit/test_input_text_phone_readback.py@@ -0,0 +1,29 @@+from __future__ import annotations++from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.exceptions import PhoneNumberInputMismatch+from skyvern.webeye.actions.handler import verify_phone_input_digits+++async def test_phone_readback_accepts_matching_ten_digits() -> None:+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value="(224) 555-0199")++ # Matching digit counts must not raise.+ await verify_phone_input_digits(tag_name="input", locator=locator, expected_value="224-555-0199")+++async def test_phone_readback_mismatch_raises() -> None:+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value="(224) 555-019")++ with pytest.raises(PhoneNumberInputMismatch) as exc:+ await verify_phone_input_digits(tag_name="input", locator=locator, expected_value="224-555-0199")++ assert exc.value.expected_digit_count == 10+ assert exc.value.actual_digit_count == 9diff --git a/tests/unit/test_tel_input_bare_digits.py b/tests/unit/test_tel_input_bare_digits.pynew file mode 100644index 000000000..f0aa674d8--- /dev/null+++ b/tests/unit/test_tel_input_bare_digits.py@@ -0,0 +1,136 @@+from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.webeye.actions import handler_utils+from skyvern.webeye.actions.handler import _is_plain_nanp_number, _is_tel_digit_fix_enabled, _plan_tel_text+from tests.unit.helpers import make_organization, make_task+++ "value,expected",+ [+ ("224-555-0199", True),+ ("(224) 555-0199", True),+ ("2245550199", True),+ (" 224 555 0199 ", True),+ ("+44 20 7946 0958", False), # international: leave to the format-check LLM+ ("+1 224-555-0199", False), # explicit country code+ ("224-555-0199 x123", False), # extension marker+ ("1-224-555-0199", False), # 11 digits (leading country code)+ ("224-555-019", False), # 9 digits+ ("", False),+ ],+)+def test_is_plain_nanp_number(value: str, expected: bool) -> None:+ assert _is_plain_nanp_number(value) is expected+++def test_plan_tel_text_strips_secret_resolved_formatted_nanp() -> None:+ # A secret that resolves to a formatted 10-digit NANP number is typed as bare digits and is never+ # sent to the format-check LLM.+ text, used_bare, run_format_check = _plan_tel_text(+ is_tel=True, is_secret=True, value="(224) 555-0199", pattern=None+ )+ assert text == "2245550199"+ assert used_bare is True+ assert run_format_check is False+++def test_plan_tel_text_self_formatting_field_uses_bare_digits() -> None:+ # A permissive pattern that accepts bare digits keeps the bare-digit fast path.+ text, used_bare, run_format_check = _plan_tel_text(+ is_tel=True, is_secret=False, value="(224) 555-0199", pattern=r"[+0-9().\- ]{7,20}"+ )+ assert text == "2245550199"+ assert used_bare is True+ assert run_format_check is False+++def test_plan_tel_text_masked_field_keeps_format_check() -> None:+ # A field whose pattern requires a specific mask (bare digits don't match) is not stripped; the+ # non-secret format-check path still runs.+ text, used_bare, run_format_check = _plan_tel_text(+ is_tel=True, is_secret=False, value="(224) 555-0199", pattern=r"\(\d{3}\) \d{3}-\d{4}"+ )+ assert text == "(224) 555-0199"+ assert used_bare is False+ assert run_format_check is True+++def test_plan_tel_text_masked_secret_skips_llm() -> None:+ # A masked field carrying a secret: not stripped, and the LLM is never called for secrets.+ assert _plan_tel_text(is_tel=True, is_secret=True, value="(224) 555-0199", pattern=r"\(\d{3}\) \d{3}-\d{4}") == (+ "(224) 555-0199",+ False,+ False,+ )+++def test_plan_tel_text_non_tel_passthrough() -> None:+ assert _plan_tel_text(is_tel=False, is_secret=False, value="(224) 555-0199", pattern=None) == (+ "(224) 555-0199",+ False,+ False,+ )+++async def test_input_sequentially_does_not_fill_split_ten_digits(monkeypatch: pytest.MonkeyPatch) -> None:+ """Bare 10-digit values are typed in one pass — no fill()-split that an auto-formatting tel field+ would mangle into a dropped digit."""+ typed: list[str] = []+ monkeypatch.setattr(+ handler_utils.EventStrategyFactory,+ "type_text",+ AsyncMock(side_effect=lambda page, locator, text: typed.append(text)),+ )+ locator = MagicMock()+ locator.fill = AsyncMock()+ locator.page = MagicMock()++ await handler_utils.input_sequentially(locator, "2245550199")++ locator.fill.assert_not_called()+ assert typed == ["2245550199"]+++async def test_input_sequentially_fill_splits_separator_formatted_value(monkeypatch: pytest.MonkeyPatch) -> None:+ """A 14-char separator-formatted value gets fill()-split into the half-open '(224', which a live+ AsYouType formatter collapses — the failure mode the bare-digit path avoids."""+ typed: list[str] = []+ monkeypatch.setattr(+ handler_utils.EventStrategyFactory,+ "type_text",+ AsyncMock(side_effect=lambda page, locator, text: typed.append(text)),+ )+ locator = MagicMock()+ locator.fill = AsyncMock()+ locator.page = MagicMock()++ await handler_utils.input_sequentially(locator, "(224) 555-0199")++ locator.fill.assert_awaited_once()+ assert locator.fill.await_args.args[0] == "(224"+ assert typed == [") 555-0199"]+++async def test_is_tel_digit_fix_enabled_uses_org_keyed_rollout(monkeypatch: pytest.MonkeyPatch) -> None:+ now = datetime.now(UTC)+ organization = make_organization(now)+ task = make_task(now, organization)+ provider = SimpleNamespace(is_feature_enabled_cached=AsyncMock(return_value=True))+ monkeypatch.setattr("skyvern.webeye.actions.handler.app.EXPERIMENTATION_PROVIDER", provider)++ assert await _is_tel_digit_fix_enabled(task) is True+ provider.is_feature_enabled_cached.assert_awaited_once_with(+ "FIX_TEL_INPUT_DIGIT_DROP",+ organization.organization_id,+ properties={"organization_id": organization.organization_id},+ )