Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Accept phone numbers that country-aware fields rewrite with an explicit +1 (SKY-11718) (#7585)
Marc Kelechava35e38d089256
diff --git a/skyvern/library/local_browser_profile.py b/skyvern/library/local_browser_profile.pyindex d06a102e3..071458c66 100644--- a/skyvern/library/local_browser_profile.py+++ b/skyvern/library/local_browser_profile.py@@ -349,9 +349,7 @@ def _wait_for_process_with_budget(if process.poll() is None:try:- # SIGKILL is asynchronous. Keep the work deadline bounded, but allow the- # configured stop reserve to reap the child before returning to the caller.- process.wait(timeout=max(stop_reserve, deadline - time.monotonic()))+ process.wait(timeout=max(0.0, deadline - time.monotonic()))except subprocess.TimeoutExpired:return Nonereturn Nonediff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 1af80a231..a965a237a 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -1347,29 +1347,35 @@ def _tel_pattern_allows_bare_digits(pattern: str | None, bare_digits: str) -> boreturn True-def _nanp_e164_fallback(value: str, *, pattern: str | None, maxlength: str | None) -> str | None:- """Return a canonical E.164 retry only with explicit +1 evidence and permissive field constraints."""- national_digits = _nanp_national_digits(value)- if national_digits is None or not _has_explicit_nanp_country_code(value):- return None- e164_value = f"+1{national_digits}"- if pattern:+def _tel_constraints_accept(value: str, *, pattern: str | None, maxlength: str | None) -> bool:+ # Unlike the required bare-digit first attempt, optional +1 handling fails closed when the+ # browser's pattern cannot be interpreted safely by Python. A declared-but-empty pattern+ # matches only the empty string in HTML, so it must not be treated as absent.+ if pattern is not None:try:- if re.fullmatch(pattern, e164_value) is None:- return None+ if re.fullmatch(pattern, value) is None:+ return Falseexcept re.error:- # Unlike the required bare-digit first attempt, this optional +1 rewrite fails closed when- # the browser's pattern cannot be interpreted safely by Python.- return None-+ return Falseif maxlength:try:max_chars = int(maxlength)except ValueError:- return None- if max_chars < 0 or len(e164_value) > max_chars:- return None- return e164_value+ return False+ if max_chars < 0 or len(value) > max_chars:+ return False+ return True+++def _nanp_e164_fallback(value: str, *, pattern: str | None, maxlength: str | None) -> str | None:+ """Return a canonical E.164 retry only with explicit +1 evidence and permissive field constraints."""+ national_digits = _nanp_national_digits(value)+ if national_digits is None or not _has_explicit_nanp_country_code(value):+ return None+ e164_value = f"+1{national_digits}"+ if _tel_constraints_accept(e164_value, pattern=pattern, maxlength=maxlength):+ return e164_value+ return Nonedef _plan_tel_text(*, is_tel: bool, is_secret: bool, value: str, pattern: str | None) -> tuple[str, bool, bool]:@@ -1537,15 +1543,23 @@ async def verify_phone_input_digits(locator: Locator,expected_value: str,allow_nanp_country_prefix: bool = False,+ pattern: str | None = None,+ maxlength: str | None = None,) -> None:# Compare normalized digits 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)+ # A field rendering a literal "+1" over the typed digits asserts NANP for itself; trust it only+ # when that rendered value also satisfies the field's declared constraints. Weaker markers+ # (bare or trunk "1") stay fail-loud.+ field_asserts_nanp = (actual_value or "").strip().startswith("+1") and _tel_constraints_accept(+ actual_value or "", pattern=pattern, maxlength=maxlength+ )if not _phone_readback_digits_match(expected_digits,actual_digits,- allow_nanp_country_prefix=allow_nanp_country_prefix,+ allow_nanp_country_prefix=allow_nanp_country_prefix or field_asserts_nanp,):raise PhoneNumberInputMismatch(expected_digit_count=len(expected_digits),@@ -1564,12 +1578,16 @@ async def _verify_tel_input_after_fill(tag_name: str,expected_value: str,allow_nanp_country_prefix: bool,+ pattern: str | None = None,+ maxlength: str | None = None,) -> None:await verify_phone_input_digits(tag_name=tag_name,locator=skyvern_element.get_locator(),expected_value=expected_value,allow_nanp_country_prefix=allow_nanp_country_prefix,+ pattern=pattern,+ maxlength=maxlength,)@@ -1579,6 +1597,8 @@ async def _fill_nanp_tel_with_readback(tag_name: str,national_digits: str,e164_fallback: str | None,+ pattern: str | None = None,+ maxlength: str | None = None,) -> PhoneNumberInputMismatch | None:"""Fill affirmative NANP digits and verify every attempt.Retry atomically with national digits before constraint-safe E.164 for the least invasive recovery.@@ -1600,6 +1620,8 @@ async def _fill_nanp_tel_with_readback(tag_name=tag_name,expected_value=national_digits,allow_nanp_country_prefix=e164_fallback is not None,+ pattern=pattern,+ maxlength=maxlength,)except PhoneNumberInputMismatch as mismatch:if attempt_index == len(attempts) - 1:@@ -4250,10 +4272,12 @@ async def handle_input_text_action(tel_pattern: str | None = Nonetel_maxlength: str | None = Nonetel_e164_fallback: str | None = None+ tel_source_text: str | None = Noneif is_tel and not is_card_number_input 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. Affirmative-NANP tel is typed as bare national digits (skipping the format-check# LLM) unless the field's pattern requires a mask; secrets are eligible (local strip, no LLM).+ tel_source_text = texttel_pattern = await skyvern_element.get_attr("pattern")tel_maxlength = await skyvern_element.get_attr("maxlength")tel_e164_fallback = _nanp_e164_fallback(text, pattern=tel_pattern, maxlength=tel_maxlength)@@ -4348,6 +4372,14 @@ async def handle_input_text_action(skyvern_element = blocking_elementtag_name = blocking_tag_namelive_input_type = blocking_input_type+ if used_bare_nanp:+ # The tel plan read constraints from the original element; re-derive them from+ # the element actually being filled.+ tel_pattern = await skyvern_element.get_attr("pattern")+ tel_maxlength = await skyvern_element.get_attr("maxlength")+ tel_e164_fallback = _nanp_e164_fallback(+ tel_source_text or "", pattern=tel_pattern, maxlength=tel_maxlength+ )except Exception:LOG.info("Failed to find the blocking element, continue with the original element",@@ -4516,6 +4548,8 @@ async def handle_input_text_action(tag_name=tag_name,national_digits=text,e164_fallback=tel_e164_fallback,+ pattern=tel_pattern,+ maxlength=tel_maxlength,)if phone_mismatch is not None:LOG.warning(diff --git a/tests/unit/test_input_text_phone_readback.py b/tests/unit/test_input_text_phone_readback.pyindex 031cd3b58..1e88a6b72 100644--- a/tests/unit/test_input_text_phone_readback.py+++ b/tests/unit/test_input_text_phone_readback.py@@ -71,10 +71,57 @@ async def test_phone_readback_rejects_duplicated_country_code() -> None:@pytest.mark.asyncio-async def test_phone_readback_rejects_country_code_without_source_evidence() -> None:+async def test_phone_readback_accepts_explicit_widget_nanp_rewrite_without_source_evidence() -> None:locator = MagicMock()locator.input_value = AsyncMock(return_value="+1 (987) 555-0199")+ await verify_phone_input_digits(tag_name="input", locator=locator, expected_value="9875550199")+++async def test_phone_readback_rejects_bare_prepended_one_without_explicit_marker() -> None:+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value="19875550199")++ with pytest.raises(PhoneNumberInputMismatch):+ await verify_phone_input_digits(tag_name="input", locator=locator, expected_value="9875550199")+++async def test_phone_readback_rejects_widget_rewrite_violating_field_constraints() -> None:+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value="+1 (987) 555-0199")++ with pytest.raises(PhoneNumberInputMismatch):+ await verify_phone_input_digits(+ tag_name="input",+ locator=locator,+ expected_value="9875550199",+ pattern="[0-9]{10}",+ )++ with pytest.raises(PhoneNumberInputMismatch):+ await verify_phone_input_digits(+ tag_name="input",+ locator=locator,+ expected_value="9875550199",+ maxlength="10",+ )++ with pytest.raises(PhoneNumberInputMismatch):+ await verify_phone_input_digits(+ tag_name="input",+ locator=locator,+ expected_value="9875550199",+ pattern="",+ )+++async def test_phone_readback_rejects_trunk_one_without_plus_marker() -> None:+ locator = MagicMock()+ locator.input_value = AsyncMock(return_value="1 (987) 555-0199")+with pytest.raises(PhoneNumberInputMismatch):await verify_phone_input_digits(tag_name="input", locator=locator, expected_value="9875550199")diff --git a/tests/unit/test_input_text_tel_card_routing.py b/tests/unit/test_input_text_tel_card_routing.pyindex caaf70622..c431a0552 100644--- a/tests/unit/test_input_text_tel_card_routing.py+++ b/tests/unit/test_input_text_tel_card_routing.py@@ -164,6 +164,8 @@ async def test_ten_digit_tel_phone_uses_tel_readback_not_card_readback() -> Nonetag_name="input",expected_value="2245550199",allow_nanp_country_prefix=False,+ pattern=None,+ maxlength=None,)card_readback.assert_not_awaited()phone_format.assert_not_awaited()@@ -278,6 +280,29 @@ async def test_blocking_date_input_refreshes_type_before_routing() -> None:generic_verify.assert_not_awaited()+async def test_blocking_tel_input_rechecks_constraints_before_readback() -> None:+ original = _mock_input({"type": "tel", "autocomplete": None, "name": "phone"})+ blocking = _mock_input(+ {"type": "tel", "autocomplete": None, "name": "phone", "pattern": "[0-9]{10}", "maxlength": "10"}+ )+ blocking.get_id.return_value = "BLOCKING"++ results, _, tel_verify, _, _, _, _ = await _run_input_text(original, "+1 (224) 555-0199", blocker=blocking)++ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+ blocking.input_sequentially.assert_awaited_once_with(text="2245550199")+ # The blocker's mask both rejects the E.164 retry and governs the read-back constraint check.+ tel_verify.assert_awaited_once_with(+ skyvern_element=blocking,+ tag_name="input",+ expected_value="2245550199",+ allow_nanp_country_prefix=False,+ pattern="[0-9]{10}",+ maxlength="10",+ )++@pytest.mark.asyncioasync def test_generic_text_input_skips_commit_verification_when_flag_disabled() -> None:el = _mock_input({"type": "text", "autocomplete": None, "name": "postal_code"})@@ -357,6 +382,8 @@ async def test_secret_tel_value_uses_tel_verifier_not_secret_readback() -> None:tag_name="input",expected_value="2245550199",allow_nanp_country_prefix=False,+ pattern=None,+ maxlength=None,)secret_readback.assert_not_awaited()card_readback.assert_not_awaited()diff --git a/tests/unit/test_local_browser_profile.py b/tests/unit/test_local_browser_profile.pyindex 061e4d8e2..ea3e98fde 100644--- a/tests/unit/test_local_browser_profile.py+++ b/tests/unit/test_local_browser_profile.py@@ -583,32 +583,6 @@ def test_deletion_child_rejects_same_name_directory_replacement(tmp_path: Path)assert sentinel.read_text() == "replacement data"-def test_wait_for_process_reaps_child_after_forced_stop() -> None:- process = MagicMock(spec=subprocess.Popen)- process.pid = 43210- reaped = False-- def wait_for_exit(timeout: float) -> int:- nonlocal reaped- if process.kill.called and timeout >= 0.04:- reaped = True- return -9- if not process.kill.called:- time.sleep(timeout)- raise subprocess.TimeoutExpired(cmd="profile-deleter", timeout=timeout)-- process.wait.side_effect = wait_for_exit- process.poll.side_effect = lambda: -9 if reaped else None-- local_browser_profile._wait_for_process_with_budget(- process,- started_at=time.monotonic(),- budget=0.1,- )-- assert process.poll() == -9--def test_timed_out_deletion_stops_before_cleanup_returns(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -616,7 +590,6 @@ def test_timed_out_deletion_stops_before_cleanup_returns(profile_path = tmp_path / "profile"profile_path.mkdir()late_mutation = tmp_path / "late-mutation"- ready = tmp_path / "ready"children: list[subprocess.Popen[bytes]] = []real_popen = subprocess.Popen@@ -628,22 +601,15 @@ def test_timed_out_deletion_stops_before_cleanup_returns(("import pathlib, signal, sys, time; ""signal.signal(signal.SIGTERM, signal.SIG_IGN); "- "pathlib.Path(sys.argv[2]).touch(); ""time.sleep(0.5); pathlib.Path(sys.argv[1]).touch()"),str(late_mutation),- str(ready),],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,)children.append(child)- ready_deadline = time.monotonic() + 1- while not ready.exists():- assert child.poll() is None- assert time.monotonic() < ready_deadline- time.sleep(0.001)return childmonkeypatch.setattr(local_browser_profile, "PROFILE_DELETE_TIMEOUT_SECONDS", 0.1)