Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Put back date segments a write moved, and never report a corrupted date as ok (#8786)
pedrohsdbeb6c5d0253d1
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex caf17e5b1..1df0ba6ff 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -77,6 +77,9 @@ ToolErrorClass = Literal["not_editable",# `type`: the page replaced the typed text with a non-empty value of its own; left in place."value_changed_by_page",+ # `type`: another segment of the same date moved and could not be put back, or could not be read back.+ "date_sibling_moved",+ "date_sibling_unverified",# `type`: the field does not hold the typed text afterwards -- an append that is partial or unchanged, or a# one-character-per-box code field whose boxes did not all keep their character."text_not_held",diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.pyindex 42e21fcea..20f079aa2 100644--- a/skyvern/forge/taskv3/tools.py+++ b/skyvern/forge/taskv3/tools.py@@ -13,6 +13,7 @@ alongside `make_finish_tool()`.from __future__ import annotationsimport asyncio+import calendarimport contextlibimport dataclassesimport functools@@ -88,6 +89,7 @@ from skyvern.forge.taskv3.run_arms import (run_arm_enabled,)from skyvern.forge.taskv3.target_label import TARGET_KIND_TOKENS, TARGET_NAME_CAP+from skyvern.utils.contained_effects import contained_effectfrom skyvern.webeye.actions.key_names import normalize_key_chordfrom skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_errorfrom skyvern.webeye.browser_state import BLANK_PAGE_URLS@@ -5950,6 +5952,32 @@ _COLLATERAL_IS_DATE_SEGMENT_JS = (}""")+_DATE_SEGMENT_FOCUS_JS = r"""(el) => {+ let a = document.activeElement;+ while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement;+ const group = el.closest('[data-tv3-dateseg="group"]');+ return a === el || (!!a && !!group && group.contains(a) && !a.hasAttribute('data-tv3-dateseg'));+}"""++# Per tagged date segment: [its first digit run as a number, or null when empty; the value a failed restore recorded+# on it, or 'none'], or null when the segment is gone. `arg.set[label]` records a value, and 'drop' removes the record.+_DATE_SEGMENT_STATE_JS = (+ r"""(arg) => {+ const _q = """+ + _ROOT_QUERY_JS+ + r""";+ const K = Symbol.for('tv3-date-restore');+ return arg.labels.map((l) => {+ const e = _q.find('[data-tv3-dateseg="' + l + '"]');+ if (!e) return null;+ if (arg.set[l] === 'drop') delete e[K];+ else if (l in arg.set) e[K] = arg.set[l];+ const m = (String(e.value ?? '') + '|' + String(e.textContent ?? '')).match(/\d+/);+ return [m ? Number(m[0]) : null, K in e ? e[K] : 'none'];+ });+}"""+)+# Every text-holding field our keystrokes could reach if the widget routes them somewhere other than# the element we focused, tagged so each one can be read back by the same handle afterwards. Scoped to# the target's own form -- or its own root when it has none, which keeps a field inside a component@@ -6188,8 +6216,8 @@ _DATE_SEGMENT_GROUP_JS = (const da = String(el.getAttribute('aria-disabled') || '').trim().toLowerCase();return ro !== 'true' && da !== 'true';};- _q.all('[data-tv3-dateseg]').forEach((e) => e.removeAttribute('data-tv3-dateseg'));const target = _q.find(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);+ _q.all('[data-tv3-dateseg]').forEach((e) => e.removeAttribute('data-tv3-dateseg'));if (!target || !isSpinbutton(target)) return { ok: false, reason: 'not_spinbutton', targetLabel: null };const targetLabel = norm(target) || null;if (LABELS.indexOf(targetLabel) === -1) return { ok: false, reason: 'target_not_date_segment', targetLabel };@@ -15766,10 +15794,11 @@ def build_browser_tools(return Nonereturn {"month": f"{month:02d}", "day": f"{day:02d}", "year": year_s}- async def _date_segment_group(page: Any, selector: str) -> dict[str, Any]:+ async def _date_segment_group(page: Any, selector: str, *, tag_partial: bool = False) -> dict[str, Any]:try:probe = await page.evaluate(- _DATE_SEGMENT_GROUP_JS, {**await _probe_arg(page, selector), "aim": _date_segment_aim_on()}+ _DATE_SEGMENT_GROUP_JS,+ {**await _probe_arg(page, selector), "aim": tag_partial or _date_segment_aim_on()},)except Exception:return {"ok": False, "reason": None, "targetLabel": None}@@ -15782,6 +15811,171 @@ def build_browser_tools(return ""return str(raw) if isinstance(raw, str) else ""+ async def _date_segment_state(+ page: Any, labels: Sequence[str], record: dict[str, Any] | None = None+ ) -> dict[str, list[Any]] | None:+ # Compared by integer, so a widget re-padding "3" as "03" is not a move; an empty segment is None, never 0.+ try:+ raw = await page.evaluate(_DATE_SEGMENT_STATE_JS, {"labels": list(labels), "set": record or {}})+ except Exception:+ return None+ ok = isinstance(raw, list) and len(raw) == len(labels) and all(isinstance(r, list) for r in raw)+ return dict(zip(labels, raw, strict=False)) if ok else None++ async def _date_siblings_begin(page: Any, target: str, order: list[str]) -> dict[str, int | None] | None:+ # Each other segment's reference is the value a failed restore recorded on it, so a retried write is judged+ # against the date before the first corruption; else what it holds now. The target's record is dropped.+ siblings = [label for label in order if label != target]+ if not siblings:+ return {}+ state = await _date_segment_state(page, [target, *siblings], {target: "drop"})+ if state is None:+ return None+ return {label: held if rec == "none" else rec for label, (held, rec) in state.items() if label != target}++ async def _commit_with_tab(page: Any, selector: str) -> ToolResult | None:+ # A trusted Tab, never blur(): a segment widget commits what it assembled only when focus really leaves.+ try:+ planted = await page.evaluate("() => { window.__tv3_doc = 1; return true; }") is True+ except Exception:+ planted = False+ try:+ await input_dispatch.press(_current_page(), None, "Tab")+ await page.wait_for_load_state("domcontentloaded", timeout=1000)+ except Exception:+ pass+ try:+ if planted and await page.evaluate("() => window.__tv3_doc === 1"):+ return None+ except Exception:+ pass+ # Leaving the field submitted or navigated, or the check could not run: the selector may match something+ # else now, so nothing is read back.+ return ToolResult.error(+ f"typed into {selector}, then the page navigated, or could not be checked, when focus "+ "left the field -- the field may not hold the text. Re-observe before doing anything else.",+ data={"navigated": True, "page_state_changed": True},+ )++ async def _settled_date_read(page: Any, selector: str, label: str, labels: list[str]) -> dict[str, Any] | None:+ # Re-tagged through the written segment's own tag (the caller's selector only if that element is gone), since+ # a widget may re-render on a commit; then two equal reads 0.15s apart within 0.6s. None: a segment is gone.+ if not (await _date_segment_group(page, f'[data-tv3-dateseg="{label}"]', tag_partial=True)).get("ok"):+ await _date_segment_group(page, selector, tag_partial=True)+ last: dict[str, Any] | None = None+ deadline = time.monotonic() + 0.6+ while True:+ state = await _date_segment_state(page, labels)+ now = None if state is None else {other: held for other, (held, _) in state.items()}+ if (now is not None and now == last) or time.monotonic() >= deadline:+ return now+ last = now+ await asyncio.sleep(0.15)++ async def _settle_date_group(+ page: Any, selector: str, digits: str, group: dict[str, Any] | None+ ) -> tuple[ToolResult | None, dict[str, Any] | None, int]:+ # (error, settled values, segments the page set) after a write into the group's `label` segment. The keys land+ # in earlier segments and a segment written alone is clean, so the group is re-read before each restore and the+ # latest wrong segment is put back and committed with a Tab -- the day only once the month is right, since the+ # page clamps the day against the month it holds. A segment that cannot be read stops the loop.+ if group is None:+ return None, None, 0+ label, ref = group["label"], group["ref"]+ stats = {"date_siblings_moved_after_tab": 0, "date_siblings_filled_after_tab": 0}+ try:+ unverified = ToolResult.error(+ f"typed into {selector}, but the segments of the same date could not be read back afterwards, so the "+ "date is NOT confirmed. Re-observe the date before relying on it.",+ error_class="date_sibling_unverified",+ )+ if ref is None:+ return unverified, None, 0+ labels = [*ref, label]+ want: dict[str, int | None] = {**ref, label: int(digits)}+ # Recorded while the segments are still tagged, so an exit that cannot read them leaves the retry a+ # reference; the confirmed path below drops the records again.+ await _date_segment_state(page, list(ref), {o: want[o] for o in ref if want[o] is not None})+ now = await _settled_date_read(page, selector, label, labels)+ clamped = 0+ emptied: set[str] = set()+ restored: dict[str, tuple[Any, Any]] = {}+ for _ in range(2 * len(ref)):+ # A month outside 1-12 (a day/month flip into a lenient input) is never a date this can confirm.+ if now is None or not 1 <= (now.get("month") or 1) <= 12:+ return unverified, None, 0+ # Judged against the month and year the page holds, and only once both are the ones wanted.+ month, year, day = now.get("month"), now.get("year") or 2000, ref.get("day") or 0+ settled = month == want.get("month") and now.get("year") == want.get("year", now.get("year"))+ if not clamped and settled and month and day > (last := calendar.monthrange(year, month)[1]):+ # Only the month's last day is a clamp; anything else leaves the date invalid or incomplete.+ if now.get("day") != last:+ return (+ ToolResult.error(+ f"typed into {selector}, but the day of the same date is not valid for that month. The "+ "date is NOT correct: re-type the day on its own.",+ error_class="date_sibling_moved",+ ),+ now,+ 0,+ )+ want["day"], clamped = last, 1+ # A segment emptied once and filled again by the widget holds its default, and keeps it.+ wrong = [o for o in reversed(ref) if now[o] != want[o] and not (want[o] is None and o in emptied)]+ if not wrong:+ break+ other = "month" if wrong[0] == "day" and "month" in wrong else wrong[0]+ restored[other] = (restored[other][0] if other in restored else now[other], want[other])+ locator = page.locator(f'[data-tv3-dateseg="{other}"]').first+ await _aim_date_segment(page, f'[data-tv3-dateseg="{other}"]', locator)+ # The caret goes to the end, since a clear deletes only what precedes it. Focus is checked before the+ # clear, so a refusal never leaves the segment wiped.+ with contextlib.suppress(Exception):+ await locator.evaluate(_CARET_TO_END_JS, timeout=2000)+ if not await _segment_focused(locator):+ return unverified, None, 0+ await _clear_date_segment(page, f'[data-tv3-dateseg="{other}"]', locator)+ cleared = ((await _date_segment_state(page, [other])) or {}).get(other, (1, None))[0] is None+ if want[other] is not None:+ with contextlib.suppress(Exception):+ await input_dispatch.type_keys(_current_page(), None, str(want[other]).zfill(2), delay=40)+ stats["date_siblings_moved_after_tab"] += 1+ emptied |= {other} if want[other] is None and cleared else set()+ if (navigated := await _commit_with_tab(page, selector)) is not None:+ return navigated, None, 0+ before, now = now, await _settled_date_read(page, selector, label, labels)+ # An emptied segment that this restore of another segment changed was moved again, not defaulted.+ emptied -= {o for o in emptied if o != other and now and before and now[o] != before[o]}+ if now is None:+ return unverified, None, 0+ # A value that reappears after a restore to empty is the widget's default, and becomes the reference.+ noted = clamped + sum(ref[o] is None and now[o] is not None for o in ref)+ stats["date_siblings_filled_after_tab"] = noted+ wrong = [o for o in reversed(ref) if now[o] != want[o] and not (want[o] is None and o in emptied)]+ await _date_segment_state(page, list(ref), {o: want[o] if o in wrong else "drop" for o in ref})+ # A restore's keys can also land in the segment just written, which no caller re-reads after this.+ wrong += [label] if now[label] != want[label] else []+ if not wrong and restored:+ # Named as put back only where the segment holds the wanted value; a widget default is shown as is.+ put_back = ", ".join(+ f"put back the {o} {'empty' if a is None else a} -> {'empty' if want[o] is None else want[o]}"+ if now[o] == want[o]+ else f"saw the {o} changed to {now[o]}"+ for o, (a, _) in restored.items()+ )+ return ToolResult.ok(f"typed into {selector}; the write moved and the tool {put_back}"), now, noted+ if not wrong:+ return None, now, noted+ error = ToolResult.error(+ f"typed into {selector}, but the {' and '.join(wrong)} of the same date moved and could not be put "+ f"back. The date is NOT correct: re-type the {', then the '.join(wrong)} one segment per call.",+ error_class="date_sibling_moved",+ )+ return error, now, noted+ finally:+ with contained_effect("date siblings settled log"):+ LOG.info("taskv3 date siblings settled", segment=label, **stats)+def _date_segment_committed(rendered: str, expected_digits: str) -> bool:match = _DATE_SEGMENT_DIGITS_RE.search(rendered)if not match:@@ -15968,6 +16162,14 @@ def build_browser_tools(with contextlib.suppress(Exception):await layer.dispose()+ async def _segment_focused(locator: Any) -> bool:+ # Keys go to whatever holds focus: refused when that is outside the tagged group or another of its segments,+ # allowed on the segment or on an input the widget moved focus to inside the group.+ try:+ return bool(await locator.evaluate(_DATE_SEGMENT_FOCUS_JS, timeout=2000))+ except Exception:+ return False+async def _type_one_date_segment(page: Any, selector: str, digits: str) -> tuple[bool, str]:locator = page.locator(selector).firsttry:@@ -16054,6 +16256,8 @@ def build_browser_tools(page: Any, selector: str, components: dict[str, str], order: list[str], *, arm: bool, aimed: bool) -> ToolResult:written: list[tuple[str, str, str]] = []+ # Every segment is rewritten, so no earlier restore's record still describes the date.+ await _date_segment_state(page, order, dict.fromkeys(order, "drop"))for label in _DATE_SEGMENT_ORDER:segment_selector = f'[data-tv3-dateseg="{label}"]'committed, aim = await _type_one_date_segment(page, segment_selector, components[label])@@ -16104,47 +16308,37 @@ def build_browser_tools(# element the probe established is this segment, where re-resolving the caller's selector# would act on whatever it matches now.segment_selector = f'[data-tv3-dateseg="{label}"]'- siblings = [other for other in labels if other != label]-- async def moved_segments(before_siblings: dict[str, str]) -> int:- # Read by value or text, so a segment rendered as text is counted when it moves too.- now = {other: await _read_date_segment(page, f'[data-tv3-dateseg="{other}"]') for other in siblings}- return sum(now[other] != before_siblings[other] for other in siblings)-- # Exactly one segment is being written, so a sibling that moves while the keys are sent took- # them by misrouting and is owed them back -- the same repair the plain path performs, which- # this path would otherwise drop. The group fill cannot reuse it: writing its siblings is the- # job there, so their movement is indistinguishable from a misroute.+ # Exactly one segment is being written, so every other segment of the group is held to its value from+ # before the call; fields outside the group that moved are only reported.arm = _date_segment_aim_on()- before = await _read_date_segment(page, segment_selector)- before_siblings = (- {other: await _read_date_segment(page, f'[data-tv3-dateseg="{other}"]') for other in siblings}- if arm- else {}- )+ ref = await _date_siblings_begin(page, label, labels)collateral = await _capture_collateral(page, segment_selector)- outside = await _collateral_outside_date_segments(page, collateral) if arm else []+ outside = await _collateral_outside_date_segments(page, collateral)committed, aim = await _type_one_date_segment(page, segment_selector, digits)- moved = await _collateral_moved_while_typing(page, collateral) if collateral else []- moved_outside = await _collateral_moved_while_typing(page, outside) if outside else []LOG.info("taskv3 date segment fill",segment=label,committed=committed,whole_date=False,- siblings_moved=await moved_segments(before_siblings) + len(moved_outside) if arm else len(moved),aim=aim,group_shape=_date_group_shape(labels),date_segment_aim_arm=arm,)+ # The siblings are put back by keys even when this segment did not commit: a fill() take-back writes around+ # the widget's own state, which can keep the stray key.+ if (navigated := await _commit_with_tab(page, selector)) is not None:+ return navigated+ date_error, now, noted = await _settle_date_group(page, selector, digits, {"label": label, "ref": ref})+ if date_error is not None and committed and date_error.status != "ok":+ return date_error+ # A restore the settle made leads the ok; a field outside the group that moved is still reported after it.+ head = date_error.content if date_error is not None else f"typed into {selector}; filled its {label} segment"if not committed:- # Ownership is decided exactly as the plain path decides it: the keys are ours to take back- # only where the segment proves it took none of them -- still holding what it held, or empty- # because this call's own clear left it so. A segment holding anything else took some of the- # text, and a sibling that moved with it is the widget distributing that value.- held = await _read_date_segment(page, segment_selector)- if moved and (not held or held == before):- await _restore_collateral(page, moved)+ # The target took none of the keys, so an in-group field outside the date that moved holds them (as base).+ still = 0+ if outside and (moved_outside := await _collateral_moved_while_typing(page, outside)):+ await _restore_collateral(page, moved_outside)+ still = len(await _collateral_moved_while_typing(page, moved_outside))reach = (" It could only be focused, not clicked, so the widget may have sent the keys elsewhere."if arm and aim == "focus"@@ -16153,36 +16347,19 @@ def build_browser_tools(return ToolResult.error(f"typed into {selector}, but its {label} segment did not commit the value afterward -- "f"the field is NOT filled.{reach} Re-observe and retry."+ + (f" {still} other field(s) in the group still hold keys it sent." if still else ""))- if await _drifted_date_segment(page, [(label, segment_selector, digits)]) is not None:- if not arm:- return ToolResult.error(- f"typed into {selector}'s {label} segment, but it changed afterward, so the segment may now "- "hold a different value than requested. The page changed it, and it was left as the page "- "set it. Re-observe it to see what value the field holds.",- error_class="value_changed_by_page",- )- now = _DATE_SEGMENT_DIGITS_RE.search(await _read_date_segment(page, segment_selector))- return await _value_changed_by_page_error(- page, selector, digits, now.group(0) if now else "", echo=not text_is_secret- )- # Read the siblings a second time, because the blur above is itself an event a widget derives- # or clamps another component on -- and that fires after the read the restore decision used,- # which has to stay next to the keystrokes to be able to attribute them.- if arm:- settled_outside = await _collateral_moved_while_typing(page, outside) if outside else []- changed = await moved_segments(before_siblings) + len(settled_outside)- else:- changed = len(await _collateral_moved_while_typing(page, collateral) if collateral else moved)+ if now is not None and now[label] != int(digits):+ held = "" if now[label] is None else str(now[label])+ return await _value_changed_by_page_error(page, selector, digits, held, echo=not text_is_secret)+ changed = noted + len(await _collateral_moved_while_typing(page, outside) if outside else [])if changed:- # The keys landed in the segment, so by the ownership rule above these other fields are- # not ours to take back -- but they did move, and saying so is the tool reporting what- # happened rather than deciding whether it matters.+ # Values the page set (a default, a clamp) and fields outside the group are kept, but reported.return ToolResult.ok(- f"typed into {selector}; filled its {label} segment. {changed} other field(s) in "+ f"{head}. {changed} other field(s) in ""the same group changed while it was typed -- re-observe the date before relying on it")- return ToolResult.ok(f"typed into {selector}; filled its {label} segment")+ return ToolResult.ok(head)def _resolves_to_one_time_code(raw_text: str) -> bool:# The provenance _resolve_text judges a one-time code by: a TOTP placeholder, or a value that resolves@@ -16374,6 +16551,7 @@ def build_browser_tools(# The tab's URL, like click's: the re-ask's URL rule reads where an Enter submission started.url_before = await _url(_current_page()) if press_enter else Noneclear = args.get("clear", True)+ date_group: dict[str, Any] | None = None# A segmented date input truncates a whole date typed into one segment at that segment's# maxlength, so a confirmed month/day/year group is filled segment by segment instead. A# caller may equally address ONE segment and write just its component, which no whole-date@@ -16420,6 +16598,16 @@ def build_browser_tools(labels,text_is_secret=text != args.get("text", ""),)+ # The plain path types a month/year or year-only segment, so its group is tagged here only to read+ # and restore the other segments around the write.+ missing = group.get("reason") == "missing"+ probe = await _date_segment_group(page, selector, tag_partial=True) if missing else group+ target = str(probe.get("targetLabel"))+ if probe.get("ok") and _DATE_SEGMENT_TEXT_RE.fullmatch(text.strip()):+ ref = await _date_siblings_begin(page, target, probe.get("order") or [])+ # None: the siblings could not be read before the write, so it can only end unverified.+ date_group = {"label": target, "ref": ref} if ref != {} else None+ LOG.info("taskv3 date segment group declined", date_group_reject=group.get("reason"))field_type: str | None = Nonemaxlength: int | None = Noneif text:@@ -16482,7 +16670,9 @@ def build_browser_tools(if not await _anchor_typeable(page, selector) and await _anchor_has_list_semantics(page, selector):return await _open_observe_pick(page, selector, text)opened_by_typing = await _list_opened_on_an_empty_field(page, selector)- result = await _type_typeahead_commit(page, selector, text, text_is_secret=text != args.get("text", ""))+ result = await _type_typeahead_commit(+ page, selector, text, text_is_secret=text != args.get("text", ""), date_group=date_group+ )return await _close_own_list_on_exit(page, selector, result, opened_by_typing=opened_by_typing)# The types that skip the typeahead probe still must not be typed into through an overlay.# They reach fill()/type(), which do no hit-testing, so nothing here would fail on its own --@@ -16694,7 +16884,9 @@ def build_browser_tools(error_class="value_changed_by_page",)- async def _type_typeahead_commit(page: Any, selector: str, text: str, *, text_is_secret: bool) -> ToolResult:+ async def _type_typeahead_commit(+ page: Any, selector: str, text: str, *, text_is_secret: bool, date_group: dict[str, Any] | None = None+ ) -> ToolResult:# keystroke-type (via _type_and_commit) so a widget that fetches suggestions on key events —# not just on a single `input` from fill — still surfaces them, then commit the best match.collateral: list[list[str]] = []@@ -16724,27 +16916,9 @@ def build_browser_tools(await asyncio.sleep(0.3)reacted = await _find_suggestion_rows(page, selector, text, any_region=True) is not Noneif not reacted:- try:- planted = await page.evaluate("() => { window.__tv3_doc = 1; return true; }") is True- except Exception:- planted = False- try:- await input_dispatch.press(_current_page(), None, "Tab")- await page.wait_for_load_state("domcontentloaded", timeout=1000)- except Exception:- pass- try:- same_document = planted and bool(await page.evaluate("() => window.__tv3_doc === 1"))- except Exception:- same_document = False- if not same_document:- # Leaving the field submitted or navigated, or the check could not run: the selector may- # match something else now, so nothing is read back.- return ToolResult.error(- f"typed into {selector}, then the page navigated, or could not be checked, when focus "- "left the field -- the field may not hold the text. Re-observe before doing anything else.",- data={"navigated": True, "page_state_changed": True},- )+ if (navigated := await _commit_with_tab(page, selector)) is not None:+ return navigated+ date_error, *_ = await _settle_date_group(page, selector, text.strip(), date_group)held = await _read_field_value(page, selector)landed = _typed_text_landed(held, text)siblings_moved = len(collateral)@@ -16754,6 +16928,17 @@ def build_browser_tools(page_changed=bool(held) and not landed,siblings_moved=siblings_moved,)+ # The settle only overrides an ok; a write that did not land keeps its own error and restore below.+ if date_error is not None and landed:+ outside = (+ await _collateral_outside_date_segments(page, collateral) if date_error.status == "ok" else []+ )+ tail = (+ f". {len(outside)} other field(s) in the same group changed while it was typed"+ if outside+ else ""+ )+ return ToolResult.ok(date_error.content + tail) if tail else date_errorif landed and siblings_moved:# The keys reached the target, so the siblings are not ours to take back -- but a# segment that took the first key of the next one's value must not pass as filled.@@ -16883,6 +17068,13 @@ def build_browser_tools(f"clicked suggestion {suggestion!r} for {selector} but it did not commit — the field is NOT ""filled; re-observe and retry, do not proceed")+ if date_group:+ # A segment the click reached is not exempt: its keys can still land in an earlier segment.+ if (navigated := await _commit_with_tab(page, selector)) is not None:+ return navigated+ date_error, *_ = await _settle_date_group(page, selector, text.strip(), date_group)+ if date_error is not None:+ return date_error# No suggestion list surfaced. The finder pierces open shadow roots, so it can see a list# inside one -- but not one the widget portals elsewhere in the page or renders in a# closed root, so inside a component this is still not evidence of absence. Sayingdiff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.pyindex 083d35ffe..8cf359685 100644--- a/tests/unit/test_taskv3_tools.py+++ b/tests/unit/test_taskv3_tools.py@@ -2546,12 +2546,22 @@ class _DateSegmentFakePage(_TypeaheadFakePage):if "targetLabel" in js:self.group_probe_calls += 1return self._group_probe+ if "__tv3_doc" in js:+ return True+ if "tv3-date-restore" in js:+ # The group read: each segment's committed digits as a number, with no restore record.+ return [[int(v) if (v := self._segment_digits(label)) else None, "none"] for label in arg["labels"]]if ".blur()" in js:self._blur_current_segment()self.focused_segment = Nonereturn Nonereturn await super().evaluate(js, arg)+ def _segment_digits(self, label: str) -> str:+ if self._committed_override is not None:+ return self._committed_override.get(label) or ""+ return self.typed_digits.get(label, "")+def _blur_current_segment(self) -> None:if self._blur_clamp:clamp_label, from_value, to_value = self._blur_clamp@@ -2587,7 +2597,9 @@ class _DateSegmentFakePage(_TypeaheadFakePage):outer.typed_digits[label] = digitsouter.log.append(("type", label, digits))- async def evaluate(self, js: str, timeout: int | None = None) -> str:+ async def evaluate(self, js: str, timeout: int | None = None) -> Any:+ if "activeElement" in js:+ return outer.focused_segment == labelif outer._committed_override is not None:return outer._committed_override.get(label) or ""return outer.typed_digits.get(label, "")@@ -13911,16 +13923,15 @@ _CONFIRMED_GROUP_DERIVES_A_SIBLING_HTML = """@_skip_no_browser@pytest.mark.asyncio-async def test_a_single_segment_write_never_takes_back_a_sibling_the_page_derived() -> None:- # Ownership is not "the write failed", it is "the segment took none of the keys". Widen it to the- # former and this restore erases a year the widget itself computed -- a value the run never entered- # and cannot recompute, which is worse than the failed write it was trying to clean up after.+async def test_a_single_segment_write_puts_back_a_sibling_the_page_derived() -> None:+ # A write to one segment holds every other segment to the value it had before the call, so the year the widget+ # derived from a month that did not commit goes back to the year the caller had; the month write still fails.async with _content_page(_CONFIRMED_GROUP_DERIVES_A_SIBLING_HTML) as page:tools = build_browser_tools(_fixed_page_provider(page))r = await _tool(tools, "type").handler({"selector": "#month", "text": "9"})assert r.status == "error", r.contentassert await page.eval_on_selector("#month", "el => el.value") == "12"- assert await page.eval_on_selector("#year", "el => el.value") == "2030"+ assert await page.eval_on_selector("#year", "el => el.value") == "1999"# The segment takes the keys AND the widget writes a sibling off the back of them. The write is a@@ -13947,17 +13958,15 @@ _CONFIRMED_GROUP_MOVES_A_SIBLING_ON_SUCCESS_HTML = """@_skip_no_browser@pytest.mark.asyncio-async def test_a_successful_single_segment_write_reports_a_sibling_that_moved() -> None:- # The evidence is already paid for; dropping it hands back a clean success on a group that no- # longer holds the date the caller thinks it does. Reporting is not adjudicating: the status- # stays ok, because turning a landed write into an error is the failure this path exists to stop.+async def test_a_successful_single_segment_write_puts_back_a_sibling_that_moved() -> None:+ # A sibling the write moved is restored to its value from before the call, and the ok says so, since the page+ # may have meant the change.async with _content_page(_CONFIRMED_GROUP_MOVES_A_SIBLING_ON_SUCCESS_HTML) as page:tools = build_browser_tools(_fixed_page_provider(page))r = await _tool(tools, "type").handler({"selector": "#month", "text": "9"})- assert r.status == "ok", r.content- assert "other field(s)" in r.content+ assert r.status == "ok" and "the year 2030 -> 1999" in r.content, r.contentassert await page.eval_on_selector("#month", "el => el.value") == "09"- assert await page.eval_on_selector("#year", "el => el.value") == "2030"+ assert await page.eval_on_selector("#year", "el => el.value") == "1999"# The same success, but the widget derives the sibling on BLUR -- which the segment path fires@@ -13984,17 +13993,510 @@ _CONFIRMED_GROUP_MOVES_A_SIBLING_ON_BLUR_HTML = """@_skip_no_browser@pytest.mark.asyncio-async def test_a_successful_single_segment_write_reports_a_sibling_derived_on_blur() -> None:- # The restore decision has to read the siblings next to the keystrokes, or it cannot attribute- # them -- so the REPORT cannot come from that same read, because this path blurs the segment- # afterwards and a widget is entitled to rewrite another component on exactly that event.+async def test_a_successful_single_segment_write_puts_back_a_sibling_derived_on_commit() -> None:+ # The widget rewrites the sibling only when focus leaves the segment, so the restore must read after the commit.async with _content_page(_CONFIRMED_GROUP_MOVES_A_SIBLING_ON_BLUR_HTML) as page:tools = build_browser_tools(_fixed_page_provider(page))r = await _tool(tools, "type").handler({"selector": "#month", "text": "9"})assert r.status == "ok", r.content- assert "other field(s)" in r.contentassert await page.eval_on_selector("#month", "el => el.value") == "09"- assert await page.eval_on_selector("#year", "el => el.value") == "2030"+ assert await page.eval_on_selector("#year", "el => el.value") == "1999"+++# A month/day/year group whose year's first key also lands in the month and the day.+_CONFIRMED_GROUP_YEAR_FIRST_KEY_MOVES_MONTH_AND_DAY_HTML = """+<div role="group" aria-label="Start date" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="03" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="07" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" style="width:60px">+</div>+<script>+ const year = document.getElementById("year");+ year.addEventListener("keydown", (e) => {+ if (year.value || !/^[0-9]$/.test(e.key)) return;+ document.getElementById("month").value = e.key;+ document.getElementById("day").value = e.key;+ });+</script>+"""+++@_skip_no_browser+async def test_a_single_segment_year_write_restores_the_segments_its_first_key_moved() -> None:+ async with _content_page(_CONFIRMED_GROUP_YEAR_FIRST_KEY_MOVES_MONTH_AND_DAY_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok", r.content+ values = [await page.eval_on_selector(f"#{s}", "el => el.value") for s in ("month", "day", "year")]+ assert values == ["03", "07", "2023"]+++# A month/day/year widget where the first key after focus enters a segment also lands in every earlier segment,+# Backspace included. Writing the year of a February date leaves the month equal to the bled digit.+_FIRST_KEY_REACHES_EARLIER_SEGMENTS_HTML = """+<div role="group" aria-label="Start date" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="02" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="14" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" style="width:60px">+</div>+<script>+ const ids = ["month", "day", "year"];+ ids.forEach((id, i) => {+ const el = document.getElementById(id);+ let fresh = false;+ el.addEventListener("focus", () => { fresh = true; });+ el.addEventListener("keydown", (e) => {+ if (!fresh) return;+ fresh = false;+ for (const earlier of ids.slice(0, i).map((x) => document.getElementById(x))) {+ if (e.key === "Backspace") earlier.value = earlier.value.slice(0, -1);+ else if (/^[0-9]$/.test(e.key)) earlier.value = e.key;+ }+ });+ });+</script>+"""+++@_skip_no_browser+async def test_a_year_write_converges_when_putting_back_the_day_moves_the_month() -> None:+ # The month reads unchanged after the year's bleed, and only the day's restore moves it, so each segment is read+ # again just before deciding whether to restore it.+ async with _content_page(_FIRST_KEY_REACHES_EARLIER_SEGMENTS_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok", r.content+ values = [await page.eval_on_selector(f"#{s}", "el => el.value") for s in ("month", "day", "year")]+ assert values == ["02", "14", "2023"]+++# A widget that clamps the day to the end of the month it holds and auto-advances a full segment to the next one.+# With window.BLEED set, that many year keys go to the month instead (and re-clamp the day).+def _clamping_group(month: str, day: str, year: str, extra: str = "") -> str:+ return (+ f"""+<div role="group" aria-label="Start date" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="{month}" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="{day}" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" value="{year}" style="width:60px">+</div>+<input id="other" type="text" value="">+{extra}+"""+ + """+<script>+ const $ = (id) => document.getElementById(id);+ const dim = () => new Date(Number($("year").value) || 2024, Number($("month").value) || 1, 0).getDate();+ const nextOf = { month: "day", day: "year", year: null };+ let entered = "";+ window.BLEED = window.BLEED || 0;+ for (const id of ["month", "day", "year"]) {+ const el = $(id);+ el.addEventListener("focus", () => { entered = ""; });+ el.addEventListener("keydown", (e) => {+ if (e.key === "Backspace") { e.preventDefault(); el.value = el.value.slice(0, -1); entered = el.value; return; }+ if (!/^[0-9]$/.test(e.key)) return;+ e.preventDefault();+ window.__keys = (window.__keys || []).concat(id);+ if (id === "year" && window.BLEED > 0) {+ window.BLEED--;+ $("month").value = e.key;+ if (Number($("day").value) > dim()) $("day").value = String(dim());+ return;+ }+ const max = id === "month" ? 12 : id === "day" ? dim() : 9999;+ let v = entered + e.key;+ if (Number(v) > max) v = e.key;+ entered = v;+ el.value = v;+ if (id !== "day" && Number($("day").value) > dim()) $("day").value = String(dim());+ const full = id === "year" ? v.length >= 4 : (Number(v + "0") > max || v.length >= 2);+ if (full && nextOf[id]) $(nextOf[id]).focus();+ });+ }+</script>+"""+ )+++async def _date_values(page: Any) -> list[str]:+ return [await page.eval_on_selector(f"#{s}", "el => el.value") for s in ("month", "day", "year", "other")]+++@_skip_no_browser+async def test_a_month_write_keeps_the_day_the_page_clamped_and_leaves_the_year_alone() -> None:+ # 31 does not exist in February, so the page clamping the day is right; typing 31 back would auto-advance its+ # second key into the year.+ async with _content_page(_clamping_group("01", "31", "2024")) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#month", "text": "02"})+ assert r.status == "ok", r.content+ assert await _date_values(page) == ["02", "29", "2024", ""]+++@_skip_no_browser+async def test_a_year_write_puts_the_month_back_before_the_day_it_clamped() -> None:+ # The year's first key lands in the month and the page clamps the day to that month. Restoring the day first would+ # be clamped again, and its second key would auto-advance into the year just written.+ async with _content_page(_clamping_group("01", "31", "2024")) as page:+ await page.evaluate("() => { window.BLEED = 1; }")+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok", r.content+ assert await _date_values(page) == ["01", "31", "2023", ""]+ keys = await page.evaluate("() => window.__keys")+ assert [k for k in keys if k != "year"] == ["month"] * 2 + ["day"] * 2+ assert keys.index("month") > max(i for i, k in enumerate(keys) if k == "year")+++@_skip_no_browser[email protected]("siblings", [("year",), ("day", "year")], ids=["month_year", "month_day_year"])+async def test_an_impossible_month_is_never_confirmed(siblings: tuple[str, ...]) -> None:+ # A day/month flip types "13" into a lenient month input; the date cannot be right, so it must not read as ok.+ values = {"day": "15", "year": "2024"}+ segments = "".join(+ f'<input id="{label}" type="text" role="spinbutton" aria-label="{label.title()}" value="{values.get(label, "03")}"'+ ' style="width:60px">'+ for label in ("month", *siblings)+ )+ html = f'<div role="group" aria-label="Start" style="display:flex;width:300px;height:30px">{segments}</div>'+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#month", "text": "13"})+ assert r.status == "error" and r.error_class == "date_sibling_unverified", r.content+++@_skip_no_browser[email protected]("siblings", [("month",), ("month", "day")], ids=["month_year", "month_day_year"])+async def test_a_sibling_that_cannot_be_read_before_the_write_leaves_the_date_unverified(+ siblings: tuple[str, ...],+) -> None:+ # The page strips the tag from the month as soon as it is set, so the siblings cannot be read before the write;+ # the date must not then be confirmed by default.+ segments = "".join(+ f'<input id="{label}" type="text" role="spinbutton" aria-label="{label.title()}" value="{value}"'+ ' style="width:60px">'+ for label, value in [*((s, "03") for s in siblings), ("year", "2024")]+ )+ html = (+ f'<div role="group" aria-label="Start" style="display:flex;width:300px;height:30px">{segments}</div>'+ "<script>new MutationObserver(() => document.getElementById('month').removeAttribute('data-tv3-dateseg'))"+ ".observe(document.getElementById('month'), {attributes: true, attributeFilter: ['data-tv3-dateseg']});"+ "</script>"+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "error" and r.error_class == "date_sibling_unverified", r.content+++@_skip_no_browser+async def test_a_restore_stops_when_a_segment_cannot_be_read_and_types_nowhere_else() -> None:+ # The page marks the day read-only for a moment after the commit, so the group cannot be re-found; a restore that+ # carried on would send its keys to whatever field the Tab focused.+ readonly = (+ "<script>let outs = 0; document.querySelector('[role=group]').addEventListener('focusout', () => {"+ " outs++; if (outs === 2) { $('day').setAttribute('aria-readonly', 'true');"+ " setTimeout(() => $('day').removeAttribute('aria-readonly'), 1500); } });</script>"+ )+ async with _content_page(_clamping_group("01", "31", "2024", readonly)) as page:+ await page.evaluate("() => { window.BLEED = 1; }")+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "error" and r.error_class == "date_sibling_unverified", r.content+ # The month is put back before the read fails; after that nothing is typed: not the day, not the field the+ # Tab focused.+ assert "day" not in await page.evaluate("() => window.__keys")+ values = await _date_values(page)+ assert values[0] == "01" and values[2:] == ["2023", ""], values+++# Each segment is a focusable span that hands focus to one hidden input inside the group, which takes the keys and+# writes them into the span it came from.+_FOCUS_REDIRECT_GROUP_HTML = """+<div role="group" aria-label="Date" style="display:flex;gap:8px;font:16px monospace">+ <span id="month" role="spinbutton" aria-label="Month" tabindex="0" style="width:40px;display:inline-block">01</span>+ <span id="day" role="spinbutton" aria-label="Day" tabindex="0" style="width:40px;display:inline-block">15</span>+ <span id="year" role="spinbutton" aria-label="Year" tabindex="0" style="width:60px;display:inline-block">2024</span>+ <input id="sink" style="position:absolute;left:-9999px">+</div>+<script>+ const sink = document.getElementById("sink");+ let cur = null;+ for (const id of ["month", "day", "year"]) {+ const el = document.getElementById(id);+ el.addEventListener("focus", () => { cur = el; sink.focus(); });+ }+ sink.addEventListener("keydown", (e) => {+ if (!cur) return;+ if (e.key === "Backspace") { e.preventDefault(); cur.textContent = cur.textContent.slice(0, -1); return; }+ if (/^[0-9]$/.test(e.key)) { e.preventDefault(); cur.textContent += e.key; }+ });+</script>+"""+++@_skip_no_browser+async def test_a_segment_whose_widget_moves_focus_to_its_own_input_is_still_written() -> None:+ async with _content_page(_FOCUS_REDIRECT_GROUP_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok", r.content+ texts = [await page.eval_on_selector(f"#{s}", "el => el.textContent") for s in ("month", "day", "year")]+ assert texts == ["01", "15", "2023"]+++@_skip_no_browser+async def test_a_restore_that_moves_the_written_segment_is_never_ok() -> None:+ # The month write makes the page derive the year; putting the year back sends its first key into the month.+ html = _CONFIRMED_GROUP_MOVES_A_SIBLING_ON_SUCCESS_HTML.replace(+ "</script>",+ 'const yr = document.getElementById("year"); let fresh = false;'+ ' yr.addEventListener("focus", () => { fresh = true; });'+ ' yr.addEventListener("keydown", (e) => { if (fresh && /^[0-9]$/.test(e.key)) month.value = e.key;'+ " fresh = false; });</script>",+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#month", "text": "9"})+ month = await page.eval_on_selector("#month", "el => el.value")+ assert r.status == "error" or month == "09", (r.content, month)+++# A month/year group with ordinary clickable segments, whose year's first key also lands in the month.+_CLICKABLE_MONTH_YEAR_BLEED_HTML = """+<div role="group" aria-label="Expiry" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="03" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" style="width:60px">+</div>+<script>+ const year = document.getElementById("year");+ year.addEventListener("keydown", (e) => {+ if (year.value || !/^[0-9]$/.test(e.key)) return;+ document.getElementById("month").value = e.key;+ });+</script>+"""+++@_skip_no_browser+async def test_a_day_clamped_against_a_passing_year_is_put_back() -> None:+ # The month write briefly derives a 2023 year, which clamps 29 February to 28; once the year is restored to 2024+ # the 29th is a valid day again and must be put back, not kept as a clamp.+ html = """+<div role="group" aria-label="Start date" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="01" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="29" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" value="2024" style="width:60px">+</div>+<script>+ const [m, d, y] = ["month", "day", "year"].map((id) => document.getElementById(id));+ const clamp = () => {+ const last = new Date(Number(y.value) || 2000, Number(m.value) || 1, 0).getDate();+ if (Number(d.value) > last) d.value = String(last);+ };+ m.addEventListener("input", () => { if (m.value.length === 2) y.value = "2023"; clamp(); });+ y.addEventListener("input", clamp);+</script>+"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#month", "text": "02"})+ day = await page.eval_on_selector("#day", "el => el.value")+ assert r.status == "error" or day == "29", (r.content, day)+++@_skip_no_browser+async def test_a_restore_that_lands_in_the_written_year_is_never_ok() -> None:+ # Putting the month back sends a key into the year just written, so the year no longer holds what was typed.+ html = _CLICKABLE_MONTH_YEAR_BLEED_HTML.replace(+ "</script>",+ 'document.getElementById("month").addEventListener("keydown", (e) => {'+ ' if (/^[0-9]$/.test(e.key)) document.getElementById("year").value = "2099"; });</script>',+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ year = await page.eval_on_selector("#year", "el => el.value")+ assert r.status == "error" and r.error_class == "date_sibling_moved" and "year" in r.content, (r.content, year)+++@_skip_no_browser+async def test_a_blank_month_that_keeps_a_bled_digit_is_never_ok() -> None:+ # The month starts blank, takes the year's first key, and refuses the clear that would empty it again.+ html = _CLICKABLE_MONTH_YEAR_BLEED_HTML.replace(' value="03"', "").replace(+ "</script>",+ 'document.getElementById("month").addEventListener("keydown", (e) => {'+ ' if (e.key === "Backspace" || e.key === "Delete") e.preventDefault(); });</script>',+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ month = await page.eval_on_selector("#month", "el => el.value")+ assert r.status == "error" or month == "", (r.content, month)+++@_skip_no_browser+async def test_a_retry_after_an_unverified_write_is_judged_against_the_month_before_it() -> None:+ # The first write bleeds into the month and the group is unreadable while the month is briefly read-only, so it+ # ends unverified; the retry, once the month is writable, must not take the bled month as its reference.+ html = _CLICKABLE_MONTH_YEAR_BLEED_HTML.replace(+ "</script>",+ "let outs = 0; document.querySelector('[role=group]').addEventListener('focusout', () => {"+ " if (++outs === 1) { const m = document.getElementById('month'); m.setAttribute('aria-readonly', 'true');"+ " setTimeout(() => m.removeAttribute('aria-readonly'), 1500); } });</script>",+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ first = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ await page.wait_for_timeout(1600)+ await page.evaluate("() => { document.getElementById('year').value = ''; }")+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ month = await page.eval_on_selector("#month", "el => el.value")+ assert first.status == "error", first.content+ assert r.status == "error" or month == "03", (r.content, month)+++@_skip_no_browser+async def test_a_put_back_ok_still_reports_another_field_the_keys_changed() -> None:+ # Focus-reached segments: the year's first key lands in the month (put back) and also rewrites a note field.+ html = """+<div role="group" aria-label="Start" style="position:absolute;left:-500px;top:0;display:flex">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="03" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" style="width:60px">+ <input id="note" type="text" aria-label="Note" value="keep" style="width:60px">+</div>+<script>+ const year = document.getElementById("year");+ year.addEventListener("keydown", (e) => {+ if (year.value || !/^[0-9]$/.test(e.key)) return;+ document.getElementById("month").value = e.key;+ document.getElementById("note").value = "moved";+ });+</script>+"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status != "ok" or "other field(s)" in r.content, r.content+++@_skip_no_browser+async def test_a_put_back_names_what_the_segment_holds_not_the_target() -> None:+ # The widget refills a blank month with its default whenever it is left empty, so a put-back to empty ends at 01.+ html = _CLICKABLE_MONTH_YEAR_BLEED_HTML.replace(' value="03"', "").replace(+ "</script>",+ 'const mo = document.getElementById("month");'+ ' mo.addEventListener("blur", () => { if (!mo.value) mo.value = "01"; });</script>',+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ month = await page.eval_on_selector("#month", "el => el.value")+ assert r.status != "ok" or ("-> empty" not in r.content and "month changed to 1" in r.content), (r.content, month)+++@_skip_no_browser+async def test_a_blank_sibling_moved_again_by_a_later_restore_is_never_ok() -> None:+ # Writing the day bleeds into the blank month; emptying the month corrupts the year, and putting the year back+ # sends a key into the month again after it was already emptied.+ html = """+<div role="group" aria-label="Start" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="15" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" value="2024" style="width:60px">+</div>+<script>+ const [m, d, y] = ["month", "day", "year"].map((id) => document.getElementById(id));+ let bled = false;+ d.addEventListener("keydown", (e) => { if (!bled && /^[0-9]$/.test(e.key)) { bled = true; m.value = e.key; } });+ m.addEventListener("keydown", (e) => { if (e.key === "Backspace") y.value = "1999"; });+ y.addEventListener("keydown", (e) => { if (/^[0-9]$/.test(e.key)) m.value = "7"; });+</script>+"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#day", "text": "20"})+ month = await page.eval_on_selector("#month", "el => el.value")+ assert r.status != "ok" or month == "", (r.content, month)+++@_skip_no_browser+async def test_a_day_write_that_did_not_commit_restores_the_note_its_keys_reached() -> None:+ # The day refuses the keys and the widget hands them to a note field inside the same group.+ html = """+<div role="group" aria-label="Start" style="display:flex;width:400px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="01" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="15" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" value="2024" style="width:60px">+ <input id="note" type="text" aria-label="Note" value="keep" style="width:60px">+</div>+<script>+ const note = document.getElementById("note");+ document.getElementById("day").addEventListener("keydown", (e) => {+ if (!/^[0-9]$/.test(e.key)) return;+ e.preventDefault();+ note.value += e.key;+ });+</script>+"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#day", "text": "20"})+ note = await page.eval_on_selector("#note", "el => el.value")+ assert r.status == "error", r.content+ assert note == "keep" or "still hold keys" in r.content, (r.content, note)+++@_skip_no_browser[email protected]("day_after", ["31", "", "1"], ids=["left", "cleared", "reset_to_1"])+async def test_a_day_the_widget_did_not_clamp_to_the_last_day_is_never_ok(day_after: str) -> None:+ html = f"""+<div role="group" aria-label="Start" style="display:flex;width:300px;height:30px">+ <input id="month" type="text" role="spinbutton" aria-label="Month" value="01" style="width:40px">+ <input id="day" type="text" role="spinbutton" aria-label="Day" value="31" style="width:40px">+ <input id="year" type="text" role="spinbutton" aria-label="Year" value="2024" style="width:60px">+</div>+<script>+ const m = document.getElementById("month");+ m.addEventListener("input", () => {{ if (m.value.length === 2) document.getElementById("day").value = "{day_after}"; }});+</script>+"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#month", "text": "02"})+ day = await page.eval_on_selector("#day", "el => el.value")+ assert r.status != "ok" or day == "29", (r.content, day)+++@_skip_no_browser+async def test_a_retried_year_on_a_clickable_month_year_group_is_never_ok_on_a_wrong_month() -> None:+ async with _content_page(_CLICKABLE_MONTH_YEAR_BLEED_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ for _ in range(2):+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ month = await page.eval_on_selector("#month", "el => el.value")+ assert r.status == "error" or month == "03", (r.content, month)+ assert month == "03"# The group is declared on a custom element HOST and the segments live in its open shadow root, so@@ -14439,8 +14941,121 @@ async def test_type_never_reports_a_clean_fill_when_a_sibling_segment_took_a_keytools = build_browser_tools(_fixed_page_provider(page))r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})assert r.status == "ok", r.content- assert "1 other field(s) in the same group changed" in r.content, r.content- assert await page.eval_on_selector("#month", "el => el.value") == "2"+ assert await page.eval_on_selector("#month", "el => el.value") == "03"+++# The month/year widget whose month takes the year's first digit only when the year commits on blur, so a+# sibling read taken before the commit Tab sees nothing move.+_SEGMENTED_DATE_BLEED_ON_COMMIT_HTML = _SEGMENTED_DATE_COMMIT_ON_BLUR_HTML.replace(+ "window.__committedYear = year.value;",+ 'window.__committedYear = year.value; document.getElementById("month").value = year.value[0];',+)+++@_skip_no_browser+async def test_type_restores_a_month_the_commit_tab_moved() -> None:+ async with _content_page(_SEGMENTED_DATE_BLEED_ON_COMMIT_HTML) as page:+ await page.eval_on_selector("#month", "el => { el.value = '03'; }")+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok", r.content+ assert await page.eval_on_selector("#month", "el => el.value") == "03"+ assert await page.evaluate("() => window.__committedYear") == "2023"+++# The same widget, but its month refuses typed digits, so the tool cannot put it back.+_SEGMENTED_DATE_BLEED_ON_COMMIT_UNRESTORABLE_HTML = _SEGMENTED_DATE_BLEED_ON_COMMIT_HTML + (+ '<script>document.getElementById("month").addEventListener("keydown", (e) => {'+ " if (/^[0-9]$/.test(e.key)) e.preventDefault(); });</script>"+)+++@_skip_no_browser+async def test_type_never_passes_a_retried_year_on_the_month_an_earlier_call_could_not_restore() -> None:+ # The retry finds the month already holding the bled digit and writes the same digit again, so only the value the+ # first call recorded can tell that the month is wrong.+ async with _content_page(_SEGMENTED_DATE_BLEED_ON_COMMIT_UNRESTORABLE_HTML) as page:+ await page.eval_on_selector("#month", "el => { el.value = '03'; }")+ tools = build_browser_tools(_fixed_page_provider(page))+ for _ in range(2):+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "error" and r.error_class == "date_sibling_moved", r.content+ assert "re-type the month" in r.content, r.content+++# A widget that fills an empty month with a default on the year's first key, and again whenever the month is left+# empty: the restore to empty cannot hold, and must not loop.+_SEGMENTED_DATE_DEFAULTS_HTML = _SEGMENTED_DATE_COMMIT_ON_BLUR_HTML.replace(+ "year.value += e.key;",+ 'const m = document.getElementById("month"); if (!m.value) m.value = "01"; year.value += e.key;',+) + (+ '<script>const mo = document.getElementById("month");'+ ' mo.addEventListener("blur", () => { if (!mo.value) mo.value = "01"; });</script>'+)+++@_skip_no_browser+async def test_type_keeps_a_month_the_widget_defaults_without_looping() -> None:+ async with _content_page(_SEGMENTED_DATE_DEFAULTS_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ for _ in range(2):+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok", r.content+ assert await page.eval_on_selector("#month", "el => el.value") == "01"+++@_skip_no_browser+async def test_type_errors_when_the_other_date_segment_cannot_be_read_back() -> None:+ html = _SEGMENTED_DATE_COMMIT_ON_BLUR_HTML.replace(+ "window.__committedYear = year.value;",+ 'window.__committedYear = year.value; document.getElementById("month").remove();',+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "error" and r.error_class == "date_sibling_unverified", r.content+++@_skip_no_browser+async def test_type_a_year_that_leaves_its_month_alone_stays_ok() -> None:+ async with _content_page(_SEGMENTED_DATE_COMMIT_ON_BLUR_HTML) as page:+ await page.eval_on_selector("#month", "el => { el.value = '03'; }")+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})+ assert r.status == "ok" and "other field" not in r.content, r.content+ assert await page.eval_on_selector("#month", "el => el.value") == "03"+++# A postal code that fills its city when it commits: a field of the same group moving after the Tab is not a date.+_POSTAL_CODE_FILLS_CITY_HTML = """+<div role="group" aria-label="Address" style="display:flex;width:300px;height:30px">+ <div style="position:relative;width:80px;height:30px">+ <input id="zip" type="text" aria-label="ZIP"+ style="position:absolute;left:4px;top:4px;width:1px;height:0.5px;padding:0;border:0;box-sizing:border-box">+ <div aria-hidden="true" style="position:absolute;inset:0;z-index:1;background:#fff">ZIP</div>+ </div>+ <input id="city" type="text" aria-label="City" style="width:120px">+</div>+<script>+ const zip = document.getElementById("zip");+ zip.addEventListener("blur", () => { if (zip.value.length === 5) document.getElementById("city").value = "Northfield"; });+</script>+"""+++@_skip_no_browser+async def test_type_a_field_whose_commit_fills_a_non_date_neighbour_stays_ok() -> None:+ async with _content_page(_POSTAL_CODE_FILLS_CITY_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#zip", "text": "12345"})+ assert r.status == "ok" and r.content.splitlines()[0] == "typed into #zip", r.content+ assert await page.eval_on_selector("#city", "el => el.value") == "Northfield"_COMMIT_ON_BLUR = 'year.addEventListener("blur", () => { window.__committedYear = year.value; });'