Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep the country calling code in an international phone field, and stop reporting a wrong one as entered (SKY-18890) (#9042)
Aaron Perezc8190461410b
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex 71526ba10..60fa6d8ad 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -317,12 +317,38 @@ class InvalidOpenAIResponseFormat(SkyvernException):class PhoneNumberInputMismatch(SkyvernException):- def __init__(self, *, expected_digit_count: int, actual_digit_count: int):+ def __init__(self, *, expected_digit_count: int, actual_digit_count: int, message: str | None = None):self.expected_digit_count = expected_digit_countself.actual_digit_count = actual_digit_countsuper().__init__(- "Phone input read-back mismatch: "- f"expected {expected_digit_count} digits, found {actual_digit_count} digits."+ message+ or (+ "Phone input read-back mismatch: "+ f"expected {expected_digit_count} digits, found {actual_digit_count} digits."+ )+ )+++class PhoneNumberInputCountryCodeMismatch(PhoneNumberInputMismatch):+ def __init__(self, *, expected_digit_count: int, actual_digit_count: int):+ message = (+ (+ f"Phone input reads its value as an international number but holds {actual_digit_count} digits "+ f"instead of the {expected_digit_count} entered, so its country calling code is gone and the "+ "number now reads as another country. Enter the whole number, country calling code included, "+ "into this field."+ )+ if actual_digit_count != expected_digit_count+ else (+ f"Phone input put a '+' in front of the {actual_digit_count} digits entered, so their leading "+ "digits now read as a country calling code. Enter the number together with its country calling "+ "code from the task data; do not guess one."+ )+ )+ super().__init__(+ expected_digit_count=expected_digit_count,+ actual_digit_count=actual_digit_count,+ message=message,)diff --git a/skyvern/forge/prompts/skyvern/check-phone-number-format.j2 b/skyvern/forge/prompts/skyvern/check-phone-number-format.j2index f3e841357..c06ac1379 100644--- a/skyvern/forge/prompts/skyvern/check-phone-number-format.j2+++ b/skyvern/forge/prompts/skyvern/check-phone-number-format.j2@@ -4,9 +4,10 @@ You need to help checking two goals:There are several checkpoints to verify the format of the phone number:- Whether there are form validation errors near the phone input field (e.g., <mat-error>, inline error text). If present, the error message takes priority over the formatting signals below.-- Whether the country code is already present near the phone number field (as a dropdown, input, or displayed text). If so, do NOT include the country code in the recommended number.+- Whether the phone number field itself takes the international number: its value or placeholder starts with "+". Such a field holds the country calling code, and a country picker next to it only displays the country the typed digits belong to. KEEP the country calling code in the recommended number, even when that picker exists. NEVER remove a country calling code the current value already has, and never move those digits into the picker: the field would then read the first national digits as a country calling code and put the number under the wrong country.+- Whether the country code is already present in a SEPARATE field (a dropdown, input, or displayed text) that holds it instead of the phone number field. If so, do NOT include the country code in the recommended number.- Whether the phone number should add hyphen.-- Whether the phone number should add country code. Only add if there is NO separate country code element on the page.+- Whether the phone number should add country code. Add it if the phone number field takes the international number, or if there is NO separate country code element on the page. Take it from the user details; do not guess one.- Whether the phone number should add space between the country code and the area code.MAKE SURE YOU OUTPUT VALID JSON. No text before or after JSON, no trailing commas, no comments (//), no unnecessary quotes, etc.@@ -18,7 +19,7 @@ Reply in JSON format with the following keys:"thought": str, // Think step by step. Describe your thought about how you come up with the phone_number_format. Use information you see on the site to explain."phone_number_format": str, // Think step by step. The format of the phone number required on the page according to HTML elements. Null if is_phone_number_input is False."is_current_format_correct": bool, // True if the current phone number format is matching the required format. Null if is_phone_number_input is False.-"recommended_phone_number": str, // If is_current_format_correct is True or is_phone_number_input is False, return null. Otherwise, return the recommended phone number with the correct format. Exclude country code if handled by a separate element.+"recommended_phone_number": str, // If is_current_format_correct is True or is_phone_number_input is False, return null. Otherwise, return the recommended phone number with the correct format. Exclude the country code only when a separate element holds it; keep it when this field takes the international number.}Context/Intentiondiff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 3702e4d91..d4dad37ec 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -97,6 +97,7 @@ from skyvern.exceptions import (OptionIndexOutOfBound,PhoneNumberInputBrowserInteractionFailed,PhoneNumberInputBrowserValidityMismatch,+ PhoneNumberInputCountryCodeMismatch,PhoneNumberInputMismatch,ScreenshotTargetClosed,SecretInputMismatch,@@ -2785,6 +2786,7 @@ async def check_phone_number_format(scraped_page: ScrapedPage,task: Task,step: Step,+ field_current_value: str | None = None,) -> str:# check the phone number formatLOG.info(@@ -2810,22 +2812,37 @@ async def check_phone_number_format()check_phone_number_format_response = CheckPhoneNumberFormatResponse.model_validate(json_response)+ recommended_phone_number = check_phone_number_format_response.recommended_phone_numberif (not check_phone_number_format_response.is_phone_number_inputor check_phone_number_format_response.is_current_format_correct- or not check_phone_number_format_response.recommended_phone_number+ or not recommended_phone_number):return value+ # A country picker next to an international field selects the same dial code the field holds, so+ # dropping the dial code here leaves the picker to infer a country from the national digits.+ if _recommendation_drops_dial_code(value, recommended_phone_number) and _tel_field_carries_dial_code(+ field_value=field_current_value,+ placeholder=await skyvern_element.get_attr("placeholder"),+ autocomplete=await skyvern_element.get_attr("autocomplete"),+ ):+ LOG.info(+ "Keeping the country calling code of an international phone input, ignoring the recommended number",+ element_id=skyvern_element.get_id(),+ source_digit_count=len(_phone_digits(value)),+ recommended_digit_count=len(_phone_digits(recommended_phone_number)),+ )+ return value+LOG.info("The current phone number format is incorrect, using the recommended phone number",element_id=skyvern_element.get_id(),source_digit_count=len(_phone_digits(value)),- recommended_digit_count=len(_phone_digits(check_phone_number_format_response.recommended_phone_number)),- digit_count_changed=len(_phone_digits(value))- != len(_phone_digits(check_phone_number_format_response.recommended_phone_number)),+ recommended_digit_count=len(_phone_digits(recommended_phone_number)),+ digit_count_changed=len(_phone_digits(value)) != len(_phone_digits(recommended_phone_number)),)- return check_phone_number_format_response.recommended_phone_number+ return recommended_phone_numberdef _phone_digits(value: str | None) -> str:@@ -2862,6 +2879,92 @@ def _has_explicit_nanp_country_code(value: str | None) -> bool:return re.match(r"\+1|1[ \-.(]", (value or "").strip()) is not None+_DIAL_CODE_PREFIX_RE = re.compile(r"^\s*\+\s*\d")+# Shorter digit strings are more likely an extension or a local number than an international number+# whose leading digits a widget could read as a country calling code.+_MIN_INTERNATIONAL_PHONE_DIGITS = 8+_NATIONAL_ONLY_AUTOCOMPLETE_TOKENS = frozenset({"tel-national", "tel-local", "tel-area-code", "tel-extension"})+++def _has_explicit_dial_code(value: str | None) -> bool:+ return _DIAL_CODE_PREFIX_RE.match(value or "") is not None+++def _is_international_phone_form(value: str | None) -> bool:+ # A leading "+" makes the digits that follow a country calling code plus the number. Unlike+ # _has_explicit_dial_code this accepts a bare "+", which is a field's own international form+ # before any digits are in it.+ return (value or "").lstrip().startswith("+")+++def _tel_field_carries_dial_code(*, field_value: str | None, placeholder: str | None, autocomplete: str | None) -> bool:+ """Whether this field takes the international number, so a paired country picker only mirrors it."""+ autocomplete_tokens = (autocomplete or "").lower().split()+ if _NATIONAL_ONLY_AUTOCOMPLETE_TOKENS.intersection(autocomplete_tokens):+ return False+ # A placeholder needs a dial code in it to be about phone format at all ("+ Add phone" is not); an+ # example number in a national box can still read as one, which keeps a code the site may not want+ # over dropping one it does. A value of bare "+" is what such a field holds before anything is typed.+ return (+ "tel" in autocomplete_tokens+ or _has_explicit_dial_code(placeholder)+ or _is_international_phone_form(field_value)+ )+++def _recommendation_drops_dial_code(value: str, recommended: str) -> bool:+ if not _has_explicit_dial_code(value) or _is_international_phone_form(recommended):+ return False+ value_digits = _phone_digits(value)+ recommended_digits = _phone_digits(recommended)+ return (+ bool(recommended_digits)+ and len(recommended_digits) < len(value_digits)+ and (+ value_digits.endswith(recommended_digits)+ or (+ recommended_digits.startswith("0")+ and len(recommended_digits) > 1+ and value_digits.endswith(recommended_digits[1:])+ )+ )+ )+++def _tel_country_code_mismatch(+ *, expected_value: str, actual_value: str | None, dial_code_withheld: bool = False+) -> PhoneNumberInputCountryCodeMismatch | None:+ """A field rendering its value in international form while reading digits of the number itself as the+ country calling code. ``dial_code_withheld`` says the digits typed are a number whose own calling code+ was taken off, which is the only evidence that a "+" in front of them is the wrong country: digits+ that were never written with a "+" can equally be an international number given without one.+ """+ if not _is_international_phone_form(actual_value):+ return None+ expected_digits = _phone_digits(expected_value)+ actual_digits = _phone_digits(actual_value)+ if not actual_digits:+ return None+ if _has_explicit_dial_code(expected_value):+ # A national trunk zero promoted to a false calling code also hides the lost dial code.+ actual_without_trunk_prefix = (+ actual_digits[1:] if actual_digits.startswith("0") and len(actual_digits) > 1 else actual_digits+ )+ if not (+ len(actual_digits) < len(expected_digits)+ and (expected_digits.endswith(actual_digits) or expected_digits.endswith(actual_without_trunk_prefix))+ ):+ return None+ elif not dial_code_withheld or actual_digits != expected_digits:+ return None+ elif len(actual_digits) < _MIN_INTERNATIONAL_PHONE_DIGITS:+ return None+ return PhoneNumberInputCountryCodeMismatch(+ expected_digit_count=len(expected_digits),+ actual_digit_count=len(actual_digits),+ )++def _nanp_national_digits(value: str | None) -> str | None:text = (value or "").strip()if re.search(r"[A-Za-z]", text):@@ -3108,6 +3211,7 @@ async def verify_phone_input_digits(locator: Locator,expected_value: str,allow_nanp_country_prefix: bool = False,+ dial_code_withheld: bool = False,pattern: str | None = None,maxlength: str | None = None,engine_selection: BrowserEngineSelection | None = None,@@ -3131,6 +3235,11 @@ async def verify_phone_input_digits(expected_digit_count=len(expected_digits),actual_digit_count=len(actual_digits),)+ country_code_mismatch = _tel_country_code_mismatch(+ expected_value=expected_value, actual_value=actual_value, dial_code_withheld=dial_code_withheld+ )+ if country_code_mismatch is not None:+ raise country_code_mismatchLOG.info("Phone input read-back verified",expected_digit_count=len(expected_digits),@@ -3145,6 +3254,7 @@ async def _verify_tel_input_after_fill(tag_name: str,expected_value: str,allow_nanp_country_prefix: bool,+ dial_code_withheld: bool = False,pattern: str | None = None,maxlength: str | None = None,engine_selection: BrowserEngineSelection | None = None,@@ -3154,6 +3264,7 @@ async def _verify_tel_input_after_fill(locator=skyvern_element.get_locator(),expected_value=expected_value,allow_nanp_country_prefix=allow_nanp_country_prefix,+ dial_code_withheld=dial_code_withheld,pattern=pattern,maxlength=maxlength,engine_selection=engine_selection,@@ -3208,7 +3319,10 @@ async def _fill_nanp_tel_with_readback(skyvern_element=skyvern_element,tag_name=tag_name,expected_value=national_digits,+ # An E.164 retry exists only for a number written with its own "+1", so typing the+ # national digits is both what permits a rendered "+1" and what withheld that code.allow_nanp_country_prefix=e164_fallback is not None,+ dial_code_withheld=e164_fallback is not None,pattern=pattern,maxlength=maxlength,engine_selection=engine_selection,@@ -3255,7 +3369,14 @@ async def _fill_nanp_tel_with_readback(return None-async def _log_tel_fallback_fill_digit_counts(+class TelFallbackReadback(NamedTuple):+ expected_digit_count: int+ actual_digit_count: int | None+ country_code_mismatch: PhoneNumberInputCountryCodeMismatch | None = None+ digits_match: bool = False+++async def _read_back_tel_fallback_fill(*,skyvern_element: SkyvernElement,tag_name: str,@@ -3263,9 +3384,10 @@ async def _log_tel_fallback_fill_digit_counts(task_id: str | None,step_id: str | None,engine_selection: BrowserEngineSelection | None = None,-) -> tuple[int, int | None]:- # Observability only: the LLM-fallback tel fill has no raising read-back, so a digit drop there is- # otherwise invisible. Count-only (values may be secrets) and never fails the action.+) -> TelFallbackReadback:+ # The LLM-fallback tel fill has no raising read-back, so a digit drop there is otherwise invisible.+ # Counts are logged for every fill (values may be secrets); only a wrong international reading of+ # the number is reported back as a failure.expected_digit_count = len(_phone_digits(expected_value))try:actual_value = await get_input_value(@@ -3274,6 +3396,28 @@ async def _log_tel_fallback_fill_digit_counts(engine_selection=engine_selection,)actual_digit_count = len(_phone_digits(actual_value))+ expected_digits = _phone_digits(expected_value)+ actual_digits = _phone_digits(actual_value)+ field_asserts_nanp = (+ len(expected_digits) == 10+ and actual_digits == f"1{expected_digits}"+ and (actual_value or "").strip().startswith("+1")+ and _tel_constraints_accept(+ actual_value or "",+ pattern=await skyvern_element.get_attr("pattern"),+ maxlength=await skyvern_element.get_attr("maxlength"),+ )+ )+ # `(0)` explicitly marks an optional national trunk prefix; all other digits must match.+ optional_trunk_digits = _phone_digits(re.sub(r"\(\s*0\s*\)", "", expected_value))+ digits_match = (+ _phone_readback_digits_match(+ expected_digits,+ actual_digits,+ allow_nanp_country_prefix=field_asserts_nanp,+ )+ or actual_digits == optional_trunk_digits+ )LOG.info("Tel fallback fill digit counts",expected_digit_count=expected_digit_count,@@ -3283,7 +3427,17 @@ async def _log_tel_fallback_fill_digit_counts(task_id=task_id,step_id=step_id,)- return expected_digit_count, actual_digit_count+ country_code_mismatch = _tel_country_code_mismatch(expected_value=expected_value, actual_value=actual_value)+ if country_code_mismatch is not None:+ LOG.warning(+ "Phone input country calling code mismatch",+ element_id=skyvern_element.get_id(),+ expected_digit_count=expected_digit_count,+ actual_digit_count=actual_digit_count,+ task_id=task_id,+ step_id=step_id,+ )+ return TelFallbackReadback(expected_digit_count, actual_digit_count, country_code_mismatch, digits_match)except Exception as exc:LOG.warning("Failed to read back tel fallback fill",@@ -3291,7 +3445,39 @@ async def _log_tel_fallback_fill_digit_counts(step_id=step_id,error_type=type(exc).__name__,)- return expected_digit_count, None+ return TelFallbackReadback(expected_digit_count, None, digits_match=False)+++async def _tel_fill_recovers_with_source_number(+ *,+ skyvern_element: SkyvernElement,+ tag_name: str,+ source_value: str,+ task_id: str | None,+ step_id: str | None,+ engine_selection: BrowserEngineSelection | None = None,+) -> bool:+ """Re-enter the number as the task gave it, once a recommended format left the field under another+ country calling code. The field renders a "+", so it takes the number whole."""+ try:+ await skyvern_element.input_clear()+ await skyvern_element.input_fill(text=source_value)+ except Exception as exc:+ LOG.warning(+ "Failed to re-enter the phone number with its country calling code",+ element_id=skyvern_element.get_id(),+ error_type=type(exc).__name__,+ )+ return False+ readback = await _read_back_tel_fallback_fill(+ skyvern_element=skyvern_element,+ tag_name=tag_name,+ expected_value=source_value,+ task_id=task_id,+ step_id=step_id,+ engine_selection=engine_selection,+ )+ return readback.digits_match and readback.country_code_mismatch is None_CARD_NUMBER_MIN_DIGITS = 13@@ -9741,6 +9927,7 @@ async def _handle_input_text_action(scraped_page=scraped_page,task=task,step=step,+ field_current_value=current_text,)except Exception as exc:LOG.warning(@@ -9808,6 +9995,7 @@ async def _handle_input_text_action(scraped_page=scraped_page,task=task,step=step,+ field_current_value=current_text,)except Exception as exc:LOG.warning(@@ -9828,7 +10016,7 @@ async def _handle_input_text_action(return [ActionFailure(PhoneNumberInputBrowserInteractionFailed())]raiseif tel_outcome is not None and is_tel:- expected_digit_count, actual_digit_count = await _log_tel_fallback_fill_digit_counts(+ readback = await _read_back_tel_fallback_fill(skyvern_element=skyvern_element,tag_name=tag_name,expected_value=tel_source_text or text,@@ -9837,8 +10025,23 @@ async def _handle_input_text_action(engine_selection=engine_selection,)tel_outcome.attempt_count = max(tel_outcome.attempt_count, 1)- tel_outcome.actual_digit_count = actual_digit_count+ tel_outcome.actual_digit_count = readback.actual_digit_counttel_outcome.browser_valid = await _probe_tel_browser_validity(skyvern_element.get_locator())+ if readback.country_code_mismatch is not None:+ # The recommended format is what lost the calling code, so the number as given is a+ # retry the field has not seen yet.+ if tel_source_text is None or _phone_digits(tel_source_text) == _phone_digits(text):+ return [ActionFailure(readback.country_code_mismatch)]+ if not await _tel_fill_recovers_with_source_number(+ skyvern_element=skyvern_element,+ tag_name=tag_name,+ source_value=tel_source_text,+ task_id=task.task_id,+ step_id=step.step_id,+ engine_selection=engine_selection,+ ):+ return [ActionFailure(readback.country_code_mismatch)]+ tel_outcome.attempt_count += 1return [ActionSuccess()]# `Locator.clear()` on a spin button could cause the cursor moving away, and never be back@@ -9984,6 +10187,7 @@ async def _handle_input_text_action(scraped_page=scraped_page,task=task,step=step,+ field_current_value=current_text,)except Exception as exc:LOG.warning(@@ -10237,7 +10441,7 @@ async def _handle_input_text_action(if isinstance(truncation_failure, ActionFailure):return [truncation_failure]if tel_outcome is not None and is_tel and not verify_tel_input_after_fill:- expected_digit_count, actual_digit_count = await _log_tel_fallback_fill_digit_counts(+ readback = await _read_back_tel_fallback_fill(skyvern_element=skyvern_element,tag_name=tag_name,expected_value=tel_source_text or text,@@ -10246,8 +10450,21 @@ async def _handle_input_text_action(engine_selection=engine_selection,)tel_outcome.attempt_count = max(tel_outcome.attempt_count, 1)- tel_outcome.actual_digit_count = actual_digit_count+ tel_outcome.actual_digit_count = readback.actual_digit_counttel_outcome.browser_valid = await _probe_tel_browser_validity(skyvern_element.get_locator())+ if readback.country_code_mismatch is not None:+ if tel_source_text is None or _phone_digits(tel_source_text) == _phone_digits(text):+ return [ActionFailure(readback.country_code_mismatch)]+ if not await _tel_fill_recovers_with_source_number(+ skyvern_element=skyvern_element,+ tag_name=tag_name,+ source_value=tel_source_text,+ task_id=task.task_id,+ step_id=step.step_id,+ engine_selection=engine_selection,+ ):+ return [ActionFailure(readback.country_code_mismatch)]+ tel_outcome.attempt_count += 1incremental_cleanup = clean_and_remove_element_tree_factory(task=task,diff --git a/tests/unit/test_input_text_phone_readback.py b/tests/unit/test_input_text_phone_readback.pyindex 7278d9e45..e48059c0b 100644--- a/tests/unit/test_input_text_phone_readback.py+++ b/tests/unit/test_input_text_phone_readback.py@@ -1,5 +1,6 @@from __future__ import annotations+from datetime import UTC, datetimefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -9,20 +10,35 @@ from skyvern.exceptions import (InvalidElementForTextInput,PhoneNumberInputBrowserInteractionFailed,PhoneNumberInputBrowserValidityMismatch,+ PhoneNumberInputCountryCodeMismatch,PhoneNumberInputMismatch,)-from skyvern.webeye.actions.actions import TelInputOutcome, TelInputStrategy+from skyvern.forge.sdk.models import StepStatus+from skyvern.webeye.actions.actions import InputTextAction, TelInputOutcome, TelInputStrategyfrom skyvern.webeye.actions.handler import (_fill_nanp_tel_with_readback,_input_target_log_fields,- _log_tel_fallback_fill_digit_counts,+ _read_back_tel_fallback_fill,+ _recommendation_drops_dial_code,+ _tel_fill_recovers_with_source_number,+ check_phone_number_format,verify_phone_input_digits,)from skyvern.webeye.browser_engine import BrowserEngineMetadata, BrowserEngineSelection+from tests.unit.helpers import make_organization, make_step, make_taskNANP_DIGITS = "2245550199"NANP_E164 = f"+1{NANP_DIGITS}"_NOT_INPUTELEMENT_ERROR = "Node is not an HTMLInputElement, HTMLTextAreaElement or HTMLSelectElement"+_NOW = datetime.now(UTC)+_ORG = make_organization(_NOW)+_TASK = make_task(+ _NOW,+ _ORG,+ navigation_payload={"phone": NANP_E164},+ navigation_goal="Fill out the job application form",+)+_STEP = make_step(_NOW, _TASK, step_id="stp-1", status=StepStatus.created, order=0, output=None)class _EngineError(Exception):@@ -104,7 +120,7 @@ async def test_tel_fallback_readback_sanitizes_exception() -> None:locator.input_value = AsyncMock(side_effect=RuntimeError(NANP_DIGITS))with patch("skyvern.webeye.actions.handler.LOG.warning") as warning_log:- counts = await _log_tel_fallback_fill_digit_counts(+ readback = await _read_back_tel_fallback_fill(skyvern_element=_make_element(locator),tag_name="input",expected_value=NANP_DIGITS,@@ -112,7 +128,7 @@ async def test_tel_fallback_readback_sanitizes_exception() -> None:step_id="stp_1",)- assert counts == (10, None)+ assert readback == (10, None, None, False)assert warning_log.call_args.kwargs == {"task_id": "tsk_1","step_id": "stp_1",@@ -270,7 +286,7 @@ async def test_tel_fill_and_fallback_log_thread_engine_selection() -> None:)is None)- await _log_tel_fallback_fill_digit_counts(+ await _read_back_tel_fallback_fill(skyvern_element=element,tag_name="input",expected_value=NANP_DIGITS,@@ -402,7 +418,7 @@ async def test_tel_fallback_digit_count_log_never_raises_on_mismatch() -> None:locator = MagicMock()locator.input_value = AsyncMock(return_value="(224) 555-019")- await _log_tel_fallback_fill_digit_counts(+ readback = await _read_back_tel_fallback_fill(skyvern_element=_make_element(locator),tag_name="input",expected_value="(224) 555-0199",@@ -410,16 +426,209 @@ async def test_tel_fallback_digit_count_log_never_raises_on_mismatch() -> None:step_id="stp_1",)+ assert readback.country_code_mismatch is None+@pytest.mark.asyncioasync def test_tel_fallback_digit_count_log_swallows_read_errors() -> None:locator = MagicMock()locator.input_value = AsyncMock(side_effect=RuntimeError("element detached"))- await _log_tel_fallback_fill_digit_counts(+ await _read_back_tel_fallback_fill(skyvern_element=_make_element(locator),tag_name="input",expected_value="2245550199",task_id="tsk_1",step_id="stp_1",)+++ ("expected_value", "readback", "country_code_mismatch"),+ [+ # SKY-18890: the dial code came off the front, leaving the national digits behind the "+".+ (f"+1 {NANP_DIGITS}", f"+{NANP_DIGITS}", True),+ # The widget treated a UK national trunk prefix as the calling code.+ ("+44 7911 123456", "+07911 123456", True),+ # A "+" in front of the digits given, with nothing saying they are national: a number given+ # as an international one without its "+" reads exactly the same way.+ (NANP_DIGITS, f"+{NANP_DIGITS}", False),+ ("447911123456", "+447911123456", False),+ # The widget moved the dial code into its picker and kept the national digits.+ ("+1 (224) 555-0199", "(224) 555-0199", False),+ # The field regrouped the whole international number it was given.+ ("+1 (224) 555-0199", "+1 224-555-0199", False),+ # The field resolved the national digits to an international number of its own.+ (NANP_DIGITS, NANP_E164, False),+ # Shortenings that keep the number: a normalized trunk zero and a trimmed extension.+ ("+44 (0) 7911 123456", "+447911123456", False),+ (f"{NANP_E164} x12", NANP_E164, False),+ # Too few digits to be read as a country calling code plus a number.+ ("5550199", "+5550199", False),+ # An empty field is not a country the number landed under.+ (NANP_E164, "+", False),+ ],+)+async def test_tel_fallback_readback_reports_a_wrong_international_reading(+ expected_value: str, readback: str, country_code_mismatch: bool+) -> None:+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value=readback)+ element = _make_element(locator)+ element.get_attr = AsyncMock(return_value=None)++ result = await _read_back_tel_fallback_fill(+ skyvern_element=element,+ tag_name="input",+ expected_value=expected_value,+ task_id="tsk_1",+ step_id="stp_1",+ )++ assert isinstance(result.country_code_mismatch, PhoneNumberInputCountryCodeMismatch) is country_code_mismatch+++async def test_nanp_fill_recovers_plus_prefixed_national_digits_with_e164() -> None:+ # The ladder types national digits, which an international field reads as a country calling code+ # plus a number. The digits match, so only the withheld "+1" says the country is wrong; the E.164+ # attempt puts it back.+ element = _make_fill_element([f"+{NANP_DIGITS}", f"+{NANP_DIGITS}", NANP_E164])++ mismatch = await _fill_nanp_tel_with_readback(+ skyvern_element=element,+ tag_name="input",+ national_digits=NANP_DIGITS,+ e164_fallback=NANP_E164,+ )++ assert mismatch is None+ assert [call.kwargs["text"] for call in element.input_fill.await_args_list] == [NANP_DIGITS, NANP_E164]+++ ("source_value", "retry_readback", "recovered"),+ [+ (NANP_E164, NANP_E164, True),+ # The field keeps reading its own leading digits as the calling code, so nothing recovered it.+ (NANP_E164, f"+{NANP_DIGITS}", False),+ # A truncated or substituted retry is not a successful recovery.+ (NANP_E164, f"+1{NANP_DIGITS[:-1]}", False),+ (NANP_E164, f"+1{NANP_DIGITS[:-1]}8", False),+ # Explicitly marked optional trunk zero and a constraint-valid NANP +1 rewrite are allowed.+ ("+44 (0) 7911 123456", "+447911123456", True),+ (NANP_DIGITS, NANP_E164, True),+ ],+)+async def test_tel_fill_recovery_re_enters_the_number_as_given(+ source_value: str, retry_readback: str, recovered: bool+) -> None:+ element = _make_fill_element([retry_readback])+ element.get_attr = AsyncMock(return_value=None)++ assert (+ await _tel_fill_recovers_with_source_number(+ skyvern_element=element,+ tag_name="input",+ source_value=source_value,+ task_id="tsk_1",+ step_id="stp_1",+ )+ is recovered+ )+ element.input_clear.assert_awaited_once()+ element.input_fill.assert_awaited_once_with(text=source_value)+++async def test_tel_fill_recovery_fails_when_source_readback_is_unavailable() -> None:+ element = _make_fill_element([])++ assert not await _tel_fill_recovers_with_source_number(+ skyvern_element=element,+ tag_name="input",+ source_value=NANP_E164,+ task_id="tsk_1",+ step_id="stp_1",+ )+++def test_recommendation_drops_dial_code_with_national_trunk_prefix() -> None:+ assert _recommendation_drops_dial_code("+44 7911 123456", "07911 123456")+++async def test_phone_readback_keeps_plus_prefixed_digits_without_withheld_evidence() -> None:+ # Same read-back, no withheld country calling code: the digits given may themselves be an+ # international number, so the entry is not called wrong.+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value=f"+{NANP_DIGITS}")++ await verify_phone_input_digits(tag_name="input", locator=locator, expected_value=NANP_DIGITS)+++def _format_check_element(placeholder: str | None, autocomplete: str | None) -> MagicMock:+ element = _make_element(MagicMock())+ element.get_attr = AsyncMock(+ side_effect=lambda name, **_: {"placeholder": placeholder, "autocomplete": autocomplete}[name]+ )+ return element+++ ("field_current_value", "placeholder", "autocomplete", "expected_text"),+ [+ # SKY-18890: an international field whose own box holds the dial code keeps it, whether the box+ # shows the picker's dial code or an earlier attempt at the number.+ ("+48", None, None, NANP_E164),+ ("+48 605 550 199", None, None, NANP_E164),+ ("", "+1 (201) 555-0123", None, NANP_E164),+ ("", None, "tel", NANP_E164),+ # A national-number box next to a country-code element still drops the dial code.+ ("", "(201) 555-0123", None, NANP_DIGITS),+ ("(201) 555-0123", None, None, NANP_DIGITS),+ ("+48", None, "tel-national", NANP_DIGITS),+ # A placeholder whose "+" is prose, not a dial code.+ ("", "+ Add phone", None, NANP_DIGITS),+ ],+)+async def test_phone_format_check_keeps_the_dial_code_of_an_international_field(+ field_current_value: str, placeholder: str | None, autocomplete: str | None, expected_text: str+) -> None:+ element = _format_check_element(placeholder, autocomplete)+ llm_response = {+ "page_info": "a phone field with a country picker",+ "is_phone_number_input": True,+ "thought": "a country picker exists, so the country code is handled elsewhere",+ "phone_number_format": "national digits only",+ "is_current_format_correct": False,+ "recommended_phone_number": NANP_DIGITS,+ }++ with (+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch(+ "skyvern.webeye.actions.handler.get_org_aware_secondary_llm_api_handler",+ new=MagicMock(return_value=AsyncMock(return_value=llm_response)),+ ),+ ):+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)+ scraped_page = MagicMock()+ scraped_page.generate_scraped_page_without_screenshots = AsyncMock(return_value=MagicMock())++ text = await check_phone_number_format(+ value=NANP_E164,+ action=InputTextAction(element_id="elem-phone", text=NANP_E164),+ skyvern_element=element,+ scraped_page=scraped_page,+ task=_TASK,+ step=_STEP,+ field_current_value=field_current_value,+ )++ assert text == expected_textdiff --git a/tests/unit/test_input_text_tel_card_routing.py b/tests/unit/test_input_text_tel_card_routing.pyindex 6b072f622..85625c061 100644--- a/tests/unit/test_input_text_tel_card_routing.py+++ b/tests/unit/test_input_text_tel_card_routing.py@@ -520,6 +520,7 @@ async def test_ten_digit_tel_phone_uses_tel_readback_not_card_readback() -> Nonetag_name="input",expected_value="2245550199",allow_nanp_country_prefix=False,+ dial_code_withheld=False,pattern=None,maxlength=None,engine_selection=None,@@ -617,6 +618,7 @@ async def test_blocking_tel_input_rechecks_constraints_before_readback() -> Nonetag_name="input",expected_value="2245550199",allow_nanp_country_prefix=False,+ dial_code_withheld=False,pattern="[0-9]{10}",maxlength="10",engine_selection=None,@@ -641,6 +643,7 @@ async def test_secret_tel_value_uses_tel_verifier_not_secret_readback() -> None:tag_name="input",expected_value="2245550199",allow_nanp_country_prefix=False,+ dial_code_withheld=False,pattern=None,maxlength=None,engine_selection=None,