Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Type a whole verification code into one-character boxes one box at a time in Task V3 (#8717)
pedrohsdb24f917460e18
diff --git a/skyvern-frontend/src/components/EngineSelector.test.tsx b/skyvern-frontend/src/components/EngineSelector.test.tsxindex cadd34123..fc37967af 100644--- a/skyvern-frontend/src/components/EngineSelector.test.tsx+++ b/skyvern-frontend/src/components/EngineSelector.test.tsx@@ -102,4 +102,50 @@ describe("RunEngineSelector", () => {expect(onChange).toHaveBeenCalledWith(RunEngine.SkyvernV3);});++ test("falls back to Default (Skyvern 1.0, routable) when value is null", () => {+ render(<RunEngineSelector value={null} onChange={() => {}} />);++ expect(screen.getAllByText("Default").length).toBeGreaterThan(0);+ });++ test("renders Default with no badge for Skyvern 1.0", () => {+ render(+ <RunEngineSelector value={RunEngine.SkyvernV1} onChange={() => {}} />,+ );++ expect(screen.getAllByText("Default").length).toBeGreaterThan(0);+ expect(+ screen.getAllByText(+ /follows routing; most new self-serve workflows run on 3\.0/,+ ),+ ).not.toHaveLength(0);+ expect(screen.queryByText("Skyvern 1.0")).toBeNull();+ });++ test("marks Skyvern 3.0 as Recommended", () => {+ render(+ <RunEngineSelector+ value={RunEngine.SkyvernV3}+ onChange={() => {}}+ availableEngines={[RunEngine.SkyvernV1, RunEngine.SkyvernV3]}+ />,+ );++ expect(screen.getAllByText("Skyvern 3.0").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Recommended").length).toBeGreaterThan(0);+ });++ test("marks Skyvern 2.0 as Legacy", () => {+ render(+ <RunEngineSelector+ value={RunEngine.SkyvernV2}+ onChange={() => {}}+ availableEngines={[RunEngine.SkyvernV1, RunEngine.SkyvernV2]}+ />,+ );++ expect(screen.getAllByText("Skyvern 2.0").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Legacy").length).toBeGreaterThan(0);+ });});diff --git a/skyvern-frontend/src/components/EngineSelector.tsx b/skyvern-frontend/src/components/EngineSelector.tsxindex 0623fcdda..8e82badec 100644--- a/skyvern-frontend/src/components/EngineSelector.tsx+++ b/skyvern-frontend/src/components/EngineSelector.tsx@@ -1,3 +1,5 @@+import type { ReactNode } from "react";+import { RunEngine } from "@/api/types";import {Select,@@ -10,11 +12,20 @@ import { BadgeLabel, type BadgeVariant } from "./BadgeLabel";type EngineOption = {value: RunEngine;- label: string;+ label: ReactNode;badge?: string;badgeVariant?: BadgeVariant;};+const defaultEngineLabel = (+ <span className="flex items-center gap-1.5">+ <span>Default</span>+ <span className="text-xs text-muted-foreground">+ follows routing; most new self-serve workflows run on 3.0+ </span>+ </span>+);+type Props = {value: RunEngine | null;onChange: (value: RunEngine) => void;@@ -25,9 +36,7 @@ type Props = {const allEngineOptions: Array<EngineOption> = [{value: RunEngine.SkyvernV1,- label: "Skyvern 1.0",- badge: "Recommended",- badgeVariant: "success",+ label: defaultEngineLabel,},{value: RunEngine.SkyvernV2,@@ -38,8 +47,8 @@ const allEngineOptions: Array<EngineOption> = [{value: RunEngine.SkyvernV3,label: "Skyvern 3.0",- badge: "Beta",- badgeVariant: "warning",+ badge: "Recommended",+ badgeVariant: "success",},{value: RunEngine.OpenaiCua,diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.tsindex 795943cba..24c345403 100644--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts@@ -30,7 +30,7 @@ export const baseHelpTooltipContent = {includeActionHistoryInVerification:"Include the action history in the completion verification.",engine:- "Skyvern 1.0 is the default for new browser tasks. Skyvern 3.0 (Beta) pins this block to the new engine; blocks that rely on download completion fall back to 1.0. Existing V2 blocks remain supported.",+ "Default follows the workflow's engine routing (most new self-serve workflows run on Skyvern 3.0). Choosing Skyvern 3.0 or 2.0 pins this block to that engine.",} as const;export const basePlaceholderContent = {diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.tsindex 75d6503b2..5154d45a1 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts@@ -1,13 +1,46 @@import { describe, expect, test } from "vitest";+import { RunEngine } from "@/api/types";+import type { AppNode } from "./nodes";+import type { WorkflowBlock } from "../types/workflowTypes";import {blockRunErrors,+ convertToNode,+ createNode,getWorkflowErrors,pendingGoalChangesOf,withGoalUndoRecordsFrom,} from "./workflowEditorUtils";+function minimalTaskBlock(overrides: { engine?: RunEngine } = {}) {+ return {+ block_type: "task",+ label: "b1",+ continue_on_failure: false,+ next_loop_on_failure: false,+ model: null,+ ignore_workflow_system_prompt: false,+ url: null,+ navigation_goal: null,+ data_extraction_goal: null,+ data_schema: null,+ error_code_mapping: null,+ complete_on_download: false,+ download_suffix: null,+ max_retries: null,+ max_steps_per_run: null,+ parameters: [],+ totp_identifier: null,+ totp_verification_url: null,+ disable_cache: false,+ complete_criterion: null,+ terminate_criterion: null,+ include_action_history_in_verification: false,+ ...overrides,+ } as unknown as WorkflowBlock;+}+function codeBlock(goalNeedsRegeneration: boolean | null): AppNode {return {id: "cb1",@@ -116,3 +149,35 @@ describe("blockRunErrors", () => {).toEqual([]);});});++describe("createNode", () => {+ test("defaults a new task block to the routable Skyvern 1.0 engine, not a V3 pin", () => {+ const node = createNode({ id: "n1" }, "task", "My Task");++ expect((node.data as { engine: RunEngine | null }).engine).toBe(+ RunEngine.SkyvernV1,+ );+ });+});++describe("convertToNode", () => {+ test("fills a saved task block missing an engine with Skyvern 1.0, not the new-node default", () => {+ const node = convertToNode({ id: "n1" }, minimalTaskBlock(), true);++ expect((node.data as { engine: RunEngine | null }).engine).toBe(+ RunEngine.SkyvernV1,+ );+ });++ test("keeps a saved block's explicit engine unchanged", () => {+ const node = convertToNode(+ { id: "n1" },+ minimalTaskBlock({ engine: RunEngine.SkyvernV3 }),+ true,+ );++ expect((node.data as { engine: RunEngine | null }).engine).toBe(+ RunEngine.SkyvernV3,+ );+ });+});diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex 6e61dfe5a..f2f0200ae 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -75,7 +75,8 @@ 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` with clear=false: the field does not hold the appended text afterwards (partial or unchanged).+ # `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","covered","inert",diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.pyindex efc8d1189..c80a13327 100644--- a/skyvern/forge/taskv3/tools.py+++ b/skyvern/forge/taskv3/tools.py@@ -3860,6 +3860,11 @@ _ACTION_TIMEOUT_MS = 15000# the delay between keys, so a key gets ~3x that; the cap keeps a field that never takes keys from stalling the run._PER_KEY_TIMEOUT_MS = 250_TYPING_TIMEOUT_CAP_MS = 120_000+# How long one box of a one-character-per-box code field may stay disabled once the box before it holds a character.+_CODE_BOX_ENABLE_WAIT_MS = 1500+# Fewer adjacent one-character boxes (initials, a two-box suffix) are separate fields, not one segmented field.+_CODE_BOX_MIN = 4+_CODE_BOX_SEPARATOR_RE = re.compile(r"[\s-]")def _typing_timeout_ms(text: str) -> int:@@ -5570,6 +5575,143 @@ _DATE_SEGMENT_READBACK_JS = ("el => [el.value, el.textContent].filter(v => v != null && String(v).trim() !== '').join('|')")+# The run of rendered maxlength=1 boxes (domUtils' isOtpDigitBox, not a date spinbutton, disabled ones included)+# from the target on, widened one container at a time while shorter than `arg.n` and inside the nearest form,+# section-like or group boundary. A container widens the run only when its boxes read as one field: no visible+# text but separators and no other control between them, and names that differ at most by digits (the first box+# may carry the group's label). `before` counts the boxes right before the target. With `arg.tag`, a run of+# exactly `arg.n` is tagged data-tv3-codebox=i and its boxes marked for OTP masking; with `arg.secret` the document+# also records the group size as mark_totp_box does, so masking survives a widget remounting the boxes untagged.+_CODE_BOX_GROUP_JS = (+ r"""(arg) => {+ const _q = """+ + _ROOT_QUERY_JS+ + r""";+"""+ + OTP_INPUT_PRIVACY_JS+ + r"""+ const isCodeBox = (el) =>+ isOtpDigitBox(el)+ && String(el.getAttribute('maxlength') || '').trim() === '1'+ && String(el.getAttribute('role') || '').trim().toLowerCase() !== 'spinbutton';+ _q.all('[data-tv3-codebox]').forEach((e) => e.removeAttribute('data-tv3-codebox'));+ const target = _q.find(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);+ if (!target || !isCodeBox(target)) return { run: 0, before: 0, ok: false };+ const BOUNDARY_TAGS = ['form', 'fieldset', 'section', 'article', 'main', 'aside', 'nav', 'header', 'footer', 'dialog'];+ const nodesUnder = (root) => {+ const out = [];+ const pending = [root];+ while (pending.length) {+ const node = pending.pop();+ if (node !== root) out.push(node);+ const children = [...(node.childNodes || [])];+ if (node.shadowRoot) children.unshift(...node.shadowRoot.childNodes);+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]);+ }+ return out;+ };+ const shown = (el) => !!el && el.getClientRects().length > 0 && el.offsetWidth > 1 && el.offsetHeight > 1;+ const nameKey = (el) =>+ [+ el.getAttribute('aria-label'),+ el.getAttribute('placeholder'),+ el.getAttribute('name'),+ el.getAttribute('title'),+ ...[...(el.labels || [])].map((l) => l.textContent),+ ...String(el.getAttribute('aria-labelledby') || '')+ .split(/\s+/)+ .filter(Boolean)+ .map((id) => (el.getRootNode().getElementById?.(id) || document.getElementById(id) || {}).textContent),+ ]+ .map((v) => String(v || '').toLowerCase().replace(/[0-9\s]+/g, ' ').trim())+ .join('|');+ const SEPARATORS = /[\s\-\u2010-\u2015_.\/|:\u00b7\u2022]+/g;+ const CONTROL_TAGS = ['select', 'textarea', 'button', 'label'];+ // A label wrapping a box (in the light DOM or inside the box's shadow host) is that box's own, not another control.+ const holdsBox = (node, boxes) =>+ boxes.some((b) => {+ for (let p = b; p; p = otpComposedParent(p)) if (p === node) return true;+ return false;+ });+ const oneField = (nodes, boxes) => {+ const keys = new Set(boxes.slice(1).map(nameKey));+ if (keys.size > 1) return false;+ for (let b = 0; b + 1 < boxes.length; b++) {+ const from = nodes.indexOf(boxes[b]);+ const to = nodes.indexOf(boxes[b + 1]);+ for (let i = from + 1; i < to; i++) {+ const node = nodes[i];+ if (node.nodeType === 3) {+ if (String(node.textContent || '').replace(SEPARATORS, '') && shown(node.parentElement)) return false;+ } else if (+ CONTROL_TAGS.includes((node.tagName || '').toLowerCase()) && shown(node) && !holdsBox(node, boxes)+ ) {+ return false;+ }+ }+ }+ return true;+ };+ let run = 1;+ let before = 0;+ for (let container = otpComposedParent(target), depth = 0; container && depth < 8; depth++) {+ const tag = (container.tagName || '').toLowerCase();+ if (tag === 'html' || tag === 'body') break;+ const nodes = nodesUnder(container);+ const inputs = nodes.filter(+ (el) => (el.tagName || '').toLowerCase() === 'input' && (el === target || el.getClientRects().length > 0),+ );+ const at = inputs.indexOf(target);+ let start = at;+ while (start > 0 && isCodeBox(inputs[start - 1])) start--;+ let end = at;+ while (end + 1 < inputs.length && isCodeBox(inputs[end + 1])) end++;+ // Unrelated one-character fields are never widened into a group; they fall back to the single-box fill.+ if (end > start && !oneField(nodes, inputs.slice(start, end + 1))) break;+ run = Math.max(run, end - at + 1);+ before = Math.max(before, at - start);+ if (end - at + 1 === arg.n) {+ if (arg.tag) {+ inputs.slice(at, end + 1).forEach((el, i) => {+ el.setAttribute('data-tv3-codebox', String(i));+ el.setAttribute('data-skyvern-otp-box', '1');+ });+ if (arg.secret) {+ const root = target.ownerDocument.documentElement;+ const previous = Number(root.getAttribute('data-skyvern-otp-filled'));+ root.setAttribute(+ 'data-skyvern-otp-filled',+ String(Number.isInteger(previous) && previous >= 2 ? Math.min(previous, arg.n) : arg.n),+ );+ }+ }+ return { run, before, ok: true };+ }+ const role = String(container.getAttribute('role') || '').trim().toLowerCase();+ if (end - at + 1 > arg.n || BOUNDARY_TAGS.includes(tag) || role === 'group' || role === 'radiogroup') break;+ container = otpComposedParent(container);+ }+ return { run, before, ok: false };+}"""+)++# Per tagged box: null once any box is gone (the field was replaced or the page moved on), else its value and+# whether it is still disabled or readonly.+_CODE_BOX_STATE_JS = (+ r"""(n) => {+ const _q = """+ + _ROOT_QUERY_JS+ + r""";+ const out = [];+ for (let i = 0; i < n; i++) {+ const el = _q.find('[data-tv3-codebox="' + i + '"]');+ if (!el || !el.isConnected) return null;+ out.push({ value: String(el.value ?? ''), locked: el.disabled === true || el.readOnly === true });+ }+ return out;+}"""+)+# Where a press at a sub-pixel segment's centre would land: a layer inside the date group whose path up to the# group covers no other segment. Whether a control sits anywhere on the press's path is decided separately._DATE_SEGMENT_AIM_JS = r"""(el) => {@@ -14478,16 +14620,22 @@ def build_browser_tools(return "we cannot resolve that selector ourselves"return None- async def _field_type(page: Any, selector: str) -> str:+ async def _field_shape(page: Any, selector: str) -> tuple[str, int | None]:+ # The input type and its maxlength attribute in one read, taken on every type with text: press_enter and+ # clear=false included, since a one-character box is detected from the maxlength whatever the flags.try:- return (- await page.eval_on_selector(- selector,- "el => el.tagName === 'TEXTAREA' ? 'textarea' : (el.getAttribute('type') || 'text').toLowerCase()",- )- ) or "text"+ shape = await page.eval_on_selector(+ selector,+ "el => [el.tagName === 'TEXTAREA' ? 'textarea' : (el.getAttribute('type') || 'text').toLowerCase(),"+ " el.getAttribute('maxlength')]",+ )except Exception:- return "text"+ return "text", None+ if not isinstance(shape, list) or len(shape) != 2:+ return "text", None+ field_type = shape[0] if isinstance(shape[0], str) and shape[0] else "text"+ raw_maxlength = shape[1].strip() if isinstance(shape[1], str) else ""+ return field_type, int(raw_maxlength) if re.fullmatch(r"\d+", raw_maxlength) else Noneasync def _declares_spinbutton_role(page: Any, selector: str) -> bool | None:# A date segment declares role=spinbutton, so one property read answers "could this be one at@@ -14898,9 +15046,9 @@ def build_browser_tools()return ToolResult.ok(f"typed into {selector}; filled its month/day/year segments from one date")- async def _date_segment_write_blocked(page: Any, selector: str) -> ToolResult | None:+ async def _segmented_write_blocked(page: Any, selector: str) -> ToolResult | None:# Mirrors the reachability/occluder guard the normal typing path performs -- the segment paths- # also reach the field by focus()+keyboard, so a date field under a modal or consent wall must+ # also write the field box by box, so a date or code field under a modal or consent wall must# not silently report success either.try:reachable, _, occluder = await _reachable_for_typing(page, selector)@@ -14997,6 +15145,183 @@ def build_browser_tools()return ToolResult.ok(f"typed into {selector}; filled its {label} segment")+ 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+ # to a vault's TOTP marker.+ if is_unresolved_totp_placeholder(raw_text):+ return True+ if resolve_typed_text is None:+ return False+ try:+ return is_totp_sentinel(resolve_typed_text(raw_text))+ except Exception:+ return False++ async def _code_box_group(+ page: Any, selector: str, n: int, *, tag: bool, secret: bool = False+ ) -> tuple[int, int, bool]:+ # (boxes from the target on, boxes right before it, whether the boxes from it on number exactly n)+ try:+ probe = await page.evaluate(+ _CODE_BOX_GROUP_JS, {**await _probe_arg(page, selector), "n": n, "tag": tag, "secret": secret}+ )+ except Exception:+ return 0, 0, False+ if not isinstance(probe, dict) or not isinstance(probe.get("run"), int):+ return 0, 0, False+ before = probe.get("before")+ return probe["run"], before if isinstance(before, int) else 0, probe.get("ok") is True++ async def _code_box_state(page: Any, n: int) -> list[dict[str, Any]] | None:+ try:+ state = await page.evaluate(_CODE_BOX_STATE_JS, n)+ except Exception:+ return None+ return state if isinstance(state, list) and len(state) == n else None++ async def _fill_code_box_group(+ page: Any,+ selector: str,+ text: str,+ *,+ boxes_before: int,+ secret: bool,+ press_enter: bool,+ url_before: str | None,+ ) -> ToolResult:+ n = len(text)+ # Registered as a secret only where it came from one: the one-time-code resolver registers the whole code.+ url_before_fill = await _url(_current_page())+ field = f"the {n}-box code field at {selector}"++ def outcome(name: str, typed: int) -> None:+ LOG.info("taskv3 code box group fill", boxes=n, typed=typed, outcome=name)++ def delivered_unverified(typed: int) -> ToolResult:+ if typed < n:+ # A page that moves on before every box was typed cannot have taken the whole code.+ outcome("page_moved_on_partial", typed)+ return ToolResult.error(+ f"typed one character per box into {field}, but the page moved on after only {typed} of {n} "+ "boxes were typed, so the code is NOT entered. Re-observe the page before typing again.",+ error_class="text_not_held",+ )+ # v1's rule: only a page that moved on after taking the code is delivered. An error would invite+ # typing a consumed code again.+ outcome("page_moved_on", typed)+ return ToolResult.ok(+ f"typed one character per box into {field} ({typed} of {n} boxes), and the page then moved on, "+ "so what the boxes held could not be read back. Re-observe the page before typing the code "+ "again: it may already have been accepted."+ )++ async def moved_on() -> bool:+ return await _url(_current_page()) != url_before_fill++ async def remounted_state() -> list[dict[str, Any]] | None:+ # A widget that rejects a code may remount fresh boxes at the target, which drops our tags; a group of+ # n boxes still there is the same field, so it is tagged again and read, not taken for a page that+ # moved on.+ if not (await _code_box_group(page, selector, n, tag=True, secret=secret))[2]:+ return None+ return await _code_box_state(page, n)++ for i, char in enumerate(text):+ box = page.locator(f'[data-tv3-codebox="{i}"]').first+ typed = i+ held: str | None = None+ try:+ # fill() waits for the box to be enabled, so its timeout bounds the wait for the box before it.+ await box.fill(char, timeout=_CODE_BOX_ENABLE_WAIT_MS)+ typed = i + 1+ held = await box.input_value(timeout=1000)+ if not held:+ # v1's fallback: a box that drops a programmatic value may still take the key.+ await box.press_sequentially(char, timeout=1000)+ held = await box.input_value(timeout=1000)+ except Exception:+ held = None+ if held:+ continue+ # The boxes are read before the URL: a page that changes its URL but keeps the boxes is judged on+ # what they hold.+ state = await _code_box_state(page, n)+ if state is None and typed == n:+ break+ if state is None and await moved_on():+ return delivered_unverified(typed)+ if state is None:+ outcome("field_replaced", typed)+ return ToolResult.error(+ f"typed one character per box into {field}, but the page replaced the field after {typed} of "+ f"{n} boxes were typed, so the code is NOT entered. Re-observe the field before typing again.",+ error_class="text_not_held",+ )+ kept = sum(bool(box_state.get("value")) for box_state in state)+ if state[i].get("locked"):+ outcome("box_disabled", typed)+ return ToolResult.error(+ f"typed one character per box into {field}, but box {i + 1} stayed disabled, so the code is "+ f"NOT entered: {kept} of {n} boxes hold a character. Re-observe the field before typing again.",+ error_class="disabled",+ )+ outcome("box_not_held", typed)+ return ToolResult.error(+ f"typed one character per box into {field}, but box {i + 1} did not keep its character, so the "+ f"code is NOT entered: {kept} of {n} boxes hold a character. Re-observe the field before typing "+ "again.",+ error_class="text_not_held",+ )+ # A field that rejects an entry on a timer clears it a moment after the write.+ await asyncio.sleep(0.15)+ state = await _code_box_state(page, n)+ remounted = False+ if state is None:+ # Boxes re-rendered at the selector are read even when the URL changed: a page may push an error URL+ # and remount the field empty. Only a page with no such group left moved on.+ state = await remounted_state()+ if state is None:+ return delivered_unverified(n)+ remounted = True+ held_code = "".join(str(box_state.get("value") or "") for box_state in state)+ # A box that upper- or lower-cases what it is given still holds the code.+ if held_code.casefold() == text.casefold():+ outcome("filled", n)+ filled = f"typed one character into each of the {n} boxes of the code field at {selector}"+ if boxes_before:+ filled = (+ f"typed one character into each of boxes {boxes_before + 1}..{boxes_before + n} of the "+ f"{boxes_before + n}-box code field, from {selector} on; the {boxes_before} box(es) before it "+ "were not written"+ )+ if not press_enter:+ return ToolResult.ok(filled)+ await page.press(f'[data-tv3-codebox="{n - 1}"]', "Enter")+ return ToolResult.ok(f"{filled}, then pressed Enter", data={"url_before": url_before})+ kept = sum(bool(box_state.get("value")) for box_state in state)+ if remounted:+ outcome("reset", n)+ return ToolResult.error(+ f"typed one character into each box of {field}, but the page then reset the boxes, replacing them "+ f"with new ones of which {kept} of {n} hold a character, so the code is NOT entered. The page may "+ "have rejected it. Re-observe the field before typing again.",+ error_class="text_not_held",+ )+ if kept == n:+ outcome("changed", n)+ return ToolResult.error(+ f"typed one character into each box of {field}, but afterwards the boxes hold a different code "+ "than the one typed. The page changed it, and it was left as the page set it. Re-observe the "+ "field before typing again.",+ error_class="value_changed_by_page",+ )+ outcome("not_held", n)+ return ToolResult.error(+ f"typed one character into each box of {field}, but afterwards only {kept} of the {n} boxes hold a "+ "character, so the code is NOT entered. Re-observe the field before typing again.",+ error_class="text_not_held",+ )+async def type_text(args: dict[str, Any]) -> ToolResult:page, error = await _resolve_page()if error is not None:@@ -15041,12 +15366,12 @@ def build_browser_tools(None if parsed_date is not None else _resolve_date_segment_digits(target_label, text))if date_components is not None:- blocked = await _date_segment_write_blocked(page, selector)+ blocked = await _segmented_write_blocked(page, selector)if blocked is not None:return blockedreturn await _fill_date_segment_group(page, selector, date_components, labels)if segment_digits is not None:- blocked = await _date_segment_write_blocked(page, selector)+ blocked = await _segmented_write_blocked(page, selector)if blocked is not None:return blockedreturn await _fill_one_date_segment(@@ -15057,12 +15382,60 @@ def build_browser_tools(labels,text_is_secret=text != args.get("text", ""),)+ field_type: str | None = None+ maxlength: int | None = None+ if text:+ field_type, maxlength = await _field_shape(page, selector)+ # One box of a field of one-character boxes cannot hold more than one character, so a longer text is+ # either written one character per box and read back from every box, or not written at all.+ box_text = maxlength == 1 and len(text) > 1+ if box_text:+ raw_text = args.get("text", "")+ stored_credential = text != raw_text and not _resolves_to_one_time_code(raw_text)+ # A code copied as shown ("482 913", "482-913") keeps only what goes into the boxes.+ code = text if stored_credential else _CODE_BOX_SEPARATOR_RE.sub("", text)+ run, boxes_before, matched = await _code_box_group(page, selector, len(code), tag=False)+ if boxes_before + run >= _CODE_BOX_MIN:+ if stored_credential:+ return ToolResult.error(+ f"{selector} is one of {boxes_before + run} boxes that take a code typed one character per "+ "box, and a stored credential cannot be split across boxes, so nothing was typed. "+ "Type the code the page asks for.",+ error_class="not_editable",+ )+ if not matched:+ return ToolResult.error(+ f"the field at {selector} has {run} one-character boxes from that box on, but the text has {len(code)} "+ "characters once spaces and dashes are dropped. The length does not match the box count, "+ "so nothing was typed. Re-observe the field and type one character for each box.",+ error_class="text_not_held",+ )+ blocked = await _segmented_write_blocked(page, selector)+ if blocked is not None:+ return blocked+ # Only a code a secret source produced marks the document; an ordinary value never does.+ secret = text != raw_text+ if not (await _code_box_group(page, selector, len(code), tag=True, secret=secret))[2]:+ return ToolResult.error(+ f"the one-character boxes at {selector} changed before they could be typed into, so "+ "nothing was typed. Re-observe the field before typing again.",+ error_class="text_not_held",+ )+ return await _fill_code_box_group(+ page,+ selector,+ code,+ boxes_before=boxes_before,+ secret=secret,+ press_enter=bool(press_enter),+ url_before=url_before,+ )# A typeahead silently rejects raw typed text — it only accepts a picked suggestion — and the# model does not reliably reach for select_combobox on its own. So after typing into a plain text# field, check whether the page REACTED with a suggestion list and, if so, commit the best match# here. Detection is behavioral (no per-site rules), so this holds across ATSes; non-text inputs# and append/enter typing skip it and fill normally (fast path, no polling).- if text and clear and not press_enter and await _field_type(page, selector) not in _NON_TYPEAHEAD_TYPES:+ if text and clear and not press_enter and not box_text and field_type not in _NON_TYPEAHEAD_TYPES:# A non-typeable anchor (a button/div, not an <input>/<textarea>/contenteditable) can never# take page.fill()'s keystrokes — but one that declares list semantics is a click-to-open# single-select in disguise, so route it to the same open→enumerate→pick path select_combobox@@ -15084,6 +15457,12 @@ def build_browser_tools(return _covered_error(selector, occluder)if clear:await page.fill(selector, text, timeout=_ACTION_TIMEOUT_MS)+ if box_text and await _read_field_value(page, selector) != text:+ return ToolResult.error(+ f"typed into {selector}, but it takes one character and does not hold the typed text "+ "afterwards, so the text is NOT entered. Re-observe the field before typing again.",+ error_class="text_not_held",+ )elif text:# Keys go to whatever has focus, so a wrapper or label is focused first and the field focus lands on is# the one checked. The caret is then moved to the end, which collapses a synchronous select-on-focus.diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.pyindex 4f3bcf920..ac7f2995b 100644--- a/tests/unit/test_taskv3_tools.py+++ b/tests/unit/test_taskv3_tools.py@@ -365,9 +365,9 @@ class _FakePage:for cb in list(self._request_listeners):cb(request)- async def eval_on_selector(self, selector: str, js: str) -> str:- # Field-type probe: report a non-typeahead type so legacy tests exercise the plain fill path.- return "password"+ async def eval_on_selector(self, selector: str, js: str) -> Any:+ # Field-shape probe: report a non-typeahead type so legacy tests exercise the plain fill path.+ return ["password", None] if "maxlength" in js else "password"async def evaluate_handle(self, js: str, arg: Any = None) -> _FakeObservePayload:# observe() reads through evaluate_handle (json digest + one live handle per element, paired@@ -1792,11 +1792,12 @@ def _credential_totp_run(page_url: str | None = None,other_credentials: dict[str, str] | None = None,window_wait: Callable[[_FakePage], None] | None = None,+ page: Any = None,) -> Any:"""A workflow run whose login credential carries a TOTP field, wired through the real resolvers:the typed-text resolver v3 injects and the VerificationState that owns the one-time code.`other_credentials` (key -> TOTP placeholder) adds more credentials sharing the vault marker;- `window_wait`, if given, forces a wait for a fresh TOTP window and runs during it."""+ `window_wait`, if given, forces a wait for a fresh TOTP window and runs during it; `page` replaces the fake."""now = datetime.now(UTC)run_context = WorkflowRunContext(workflow_title="t",@@ -1822,7 +1823,7 @@ def _credential_totp_run(manager = WorkflowContextManager()manager.workflow_run_contexts["wr_totp"] = run_contextmonkeypatch.setattr(app, "WORKFLOW_CONTEXT_MANAGER", manager)- page = _FakePage()+ page = page if page is not None else _FakePage()if page_url is not None:page.url = page_urlmin_remaining_seconds = 0@@ -2216,8 +2217,8 @@ class _TypeaheadFakePage:return _FakeLocator(self._match_count)- async def eval_on_selector(self, selector: str, js: str) -> str:- return self._field_type+ async def eval_on_selector(self, selector: str, js: str) -> Any:+ return [self._field_type, None] if "maxlength" in js else self._field_typeasync def evaluate(self, js: str, arg: Any = None) -> Any:# Order matters: the verify JS also references data-tv3-sugg (its list-closed check), so match@@ -2390,7 +2391,7 @@ class _DateSegmentFakePage(_TypeaheadFakePage):# a segment's clear happened BEFORE its digits were typed, not just that both happened.self.log: list[tuple[str, ...]] = []- async def eval_on_selector(self, selector: str, js: str) -> str:+ async def eval_on_selector(self, selector: str, js: str) -> Any:# The role read that gates the group probe, and the field-type read the typeahead gate uses,# go through the same accessor; answer each with what it asked for.if "role" in js:@@ -12059,8 +12060,8 @@ class _AliasTypeaheadPage(_FakeAliasPage):self._suggestion_text = suggestion_textself._committed = committed- async def eval_on_selector(self, selector: str, js: str) -> str:- return "text"+ async def eval_on_selector(self, selector: str, js: str) -> Any:+ return ["text", None] if "maxlength" in js else "text"async def evaluate(self, js: str, arg: Any = None) -> Any:# Order matters: the verify JS also references data-tv3-sugg (its list-closed check), and the@@ -12726,6 +12727,475 @@ async def test_type_date_widget_clamping_a_segment_on_blur_is_not_reported_as_fiassert await page.eval_on_selector("#day", "el => el.value") == "28"+def _code_boxes_html(input_type: str, *, submit_on_last: bool = False) -> str:+ # A controlled one-character-per-box code field: a multi-character write re-renders the box from its stored+ # state (empty), and each box stays disabled until the one before it holds a character.+ submit = "document.getElementById('code').innerHTML = '<p>Verified</p>';" if submit_on_last else ""+ boxes = "".join(+ f'<input class="box" type="{input_type}" maxlength="1" aria-label="Code character {i + 1}"'+ f"{' disabled' if i else ''}>"+ for i in range(6)+ )+ return f"""+<div id="code">{boxes}</div>+<script>+ const boxes = [...document.querySelectorAll('.box')];+ const held = boxes.map(() => '');+ boxes.forEach((box, i) => box.addEventListener('input', () => {{+ if (box.value.length > 1) {{ box.value = held[i]; return; }}+ held[i] = box.value;+ if (box.value && boxes[i + 1]) boxes[i + 1].disabled = false;+ if (held.every(Boolean)) {{ {submit} }}+ }}));+</script>+"""+++_BOXES_JS = "els => els.map((e) => e.value).join('')"+++def _plain_boxes(n: int, *, input_type: str = "text", start: int = 0) -> str:+ return "".join(+ f'<input class="box" type="{input_type}" maxlength="1" aria-label="Code character {i + 1}">'+ for i in range(start, start + n)+ )+++# A 3+3 layout with a separator; boxes that upper-case what they are given; a widget that rebuilds its boxes on+# every input, which strips any tag a caller put on them.+_CODE_BOXES_SPLIT_HTML = f"<div><div>{_plain_boxes(3)}</div><span>-</span><div>{_plain_boxes(3, start=3)}</div></div>"+_CODE_BOXES_UPPERCASE_HTML = f"""<div>{_plain_boxes(6)}</div><script>+document.querySelectorAll('.box').forEach((b) => b.addEventListener('input', () => {{ b.value = b.value.toUpperCase(); }}));+</script>"""+_CODE_BOXES_REMOUNT_HTML = """<div id="code"></div><script>+const held = ['', '', '', '', '', ''];+function render() {+ const c = document.getElementById('code');+ c.innerHTML = held.map((v, i) =>+ `<input class="box" type="text" maxlength="1" aria-label="Code character ${i + 1}" value="${v}">`).join('');+ c.querySelectorAll('.box').forEach((b, i) => b.addEventListener('input', () => { held[i] = b.value.slice(-1); render(); }));+}+render();+</script>"""+_CODE_BOXES_REDIRECT_MIDWAY_HTML = (+ f'<div id="code">{_plain_boxes(3)}'+ '<input class="box" type="text" maxlength="1" aria-label="Code character 4" disabled>'+ '<input class="box" type="text" maxlength="1" aria-label="Code character 5" disabled>'+ '<input class="box" type="text" maxlength="1" aria-label="Code character 6" disabled>'+ "</div>"+ "<script>"+ "document.querySelectorAll('.box')[2].addEventListener("+ "'input', () => { history.pushState(null, '', '#redirected'); });"+ "</script>"+)+++@_skip_no_browser+ ("html", "text", "held"),+ [+ (_code_boxes_html("number"), "482913", "482913"),+ (_code_boxes_html("text"), "482913", "482913"),+ (_code_boxes_html("text"), "482 913", "482913"),+ (_code_boxes_html("number"), "482-913", "482913"),+ (_CODE_BOXES_SPLIT_HTML, "482913", "482913"),+ (_CODE_BOXES_UPPERCASE_HTML, "ab12cd", "AB12CD"),+ (_code_boxes_html("number", submit_on_last=True), "482913", None),+ ],+ ids=[+ "number-boxes",+ "text-boxes",+ "code-with-space",+ "code-with-dash",+ "split-3-3",+ "box-upper-cases",+ "auto-submit-on-last-box",+ ],+)+async def test_type_a_whole_code_into_the_first_of_its_one_character_boxes_fills_each_box(+ html: str, text: str, held: str | None+) -> None:+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": '[aria-label="Code character 1"]', "text": text})+ assert r.status == "ok", r.content+ assert text not in r.content+ if held is None:+ # Every box was typed and the page consumed the code: delivered, never an error inviting a retype.+ assert "moved on" in r.content, r.content+ return+ assert "6 boxes" in r.content, r.content+ assert await page.eval_on_selector_all(".box", _BOXES_JS) == held+ observed = await _tool(tools, "observe").handler({})+ assert "Code character 6" in observed.content, observed.content+ for line in observed.content.splitlines():+ if "Code character" in line:+ assert "value=" not in line or "value='(hidden)'" in line, line+++@_skip_no_browser+async def test_type_a_code_into_boxes_the_page_replaces_midway_is_an_error_naming_what_was_typed() -> None:+ async with _content_page(_CODE_BOXES_REMOUNT_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": '[aria-label="Code character 1"]', "text": "482913"})+ assert r.status == "error", r.content+ assert "1 of 6" in r.content, r.content+ assert "482913" not in r.content+++@_skip_no_browser+async def test_type_a_code_into_boxes_the_page_redirects_before_every_box_typed_is_an_error() -> None:+ # A 3-of-6 code cannot have been accepted; only a page that moves on AFTER every box was typed is delivered.+ async with _content_page(_CODE_BOXES_REDIRECT_MIDWAY_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": '[aria-label="Code character 1"]', "text": "482913"})+ assert r.status == "error", r.content+ assert "3 of 6" in r.content, r.content+ assert "482913" not in r.content+++@_skip_no_browser+async def test_type_a_code_leaves_unrelated_numeric_fields_readable_in_observe() -> None:+ html = f"""<div>{_plain_boxes(4, input_type="tel")}</div>+<form><input id="zip" inputmode="numeric" aria-label="Zip"><input id="phone" inputmode="numeric" aria-label="Phone">+<input id="acct" inputmode="numeric" aria-label="Account"><input id="last4" inputmode="numeric" aria-label="Last4"></form>"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ await _tool(tools, "type").handler({"selector": "#zip", "text": "94107"})+ r = await _tool(tools, "type").handler({"selector": '[aria-label="Code character 1"]', "text": "4829"})+ assert r.status == "ok", r.content+ observed = (await _tool(tools, "observe").handler({})).content+ assert "94107" in observed, observed+ assert "4829" not in observed+++# Two unrelated one-character pairs (initials, a rating) in sibling sections: four boxes, but not one field.+_TWO_SECTIONS_OF_BOXES_HTML = (+ "<main><section>"+ + "".join(f'<input id="part{i}" type="text" maxlength="1" aria-label="Initial {i}">' for i in range(2))+ + "</section><section>"+ + "".join(f'<input id="part{i}" type="text" maxlength="1" aria-label="Rating {i}">' for i in range(2, 4))+ + "</section></main>"+)+++_ONE_CHARACTER_FIELD_NAMES = ["Middle initial", "Answer Y or N", "Suffix digit", "Grade", "Shift", "Unit letter"]+++def _unrelated_one_character_fields_html(n: int, *, label: str) -> str:+ # n unrelated one-character fields in one form, each in its own field wrapper, named by a visible label beside+ # it, a label wrapping it, only its own aria-label, or a column header above the row via aria-labelledby.+ fields = []+ if label == "labelledby":+ headers = "".join(f'<span id="h{i}">{name}</span>' for i, name in enumerate(_ONE_CHARACTER_FIELD_NAMES[:n]))+ boxes = "".join(f'<input id="part{i}" type="text" maxlength="1" aria-labelledby="h{i}">' for i in range(n))+ return f"<form><div>{headers}</div><div>{boxes}</div></form>"+ for i, name in enumerate(_ONE_CHARACTER_FIELD_NAMES[:n]):+ aria = f' aria-label="{name}"' if label == "aria" else ""+ box = f'<input id="part{i}" type="text" maxlength="1"{aria}>'+ if label == "beside":+ fields.append(f'<div class="field"><label for="part{i}">{name}</label>{box}</div>')+ elif label == "wrapping":+ fields.append(f'<div class="field"><label>{name} {box}</label></div>')+ else:+ fields.append(f'<div class="field">{box}</div>')+ return f"<form>{''.join(fields)}</form>"+++def _split_field_html(maxlengths: list[int], *, input_type: str = "tel", role: str = "") -> str:+ role_attr = f' role="{role}"' if role else ""+ parts = "".join(+ f'<input id="part{i}" type="{input_type}" maxlength="{n}"{role_attr} aria-label="Part {i}">'+ for i, n in enumerate(maxlengths)+ )+ return f"<div>{parts}</div>"+++@_skip_no_browser+ ("html", "text", "status"),+ [+ (_split_field_html([3, 3, 4]), "5551234567", "ok"),+ (_split_field_html([2, 2, 4], input_type="text"), "09182026", "ok"),+ (_split_field_html([2, 2, 4], input_type="text", role="spinbutton"), "09182026", "ok"),+ (_split_field_html([4, 4, 4, 4], input_type="text"), "4111111111111111", "ok"),+ (_split_field_html([1], input_type="text"), "QZ", "error"),+ (_split_field_html([1, 1], input_type="text"), "JR", "error"),+ (_TWO_SECTIONS_OF_BOXES_HTML, "AB12", "error"),+ (_unrelated_one_character_fields_html(4, label="beside"), "AY3B", "error"),+ (_unrelated_one_character_fields_html(5, label="wrapping"), "AY3BN", "error"),+ (_unrelated_one_character_fields_html(6, label="aria"), "AY3BNC", "error"),+ (_unrelated_one_character_fields_html(6, label="labelledby"), "AY3BNC", "error"),+ ],+ ids=[+ "split-phone",+ "split-date",+ "split-date-spinbuttons",+ "split-card",+ "lone-one-character-box",+ "initial-and-suffix-boxes",+ "boxes-in-separate-sections",+ "four-labelled-fields-in-a-form",+ "five-label-wrapped-fields-in-a-form",+ "six-aria-named-fields-in-a-form",+ "six-fields-named-by-column-headers",+ ],+)+async def test_type_into_a_split_field_that_is_not_a_one_character_code_group_is_not_distributed(+ html: str, text: str, status: str+) -> None:+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#part0", "text": text})+ # A multi-character part takes a plain fill of the target; a one-character box cannot hold the text, so+ # that type is an error. Either way every other field keeps its (empty) value.+ assert r.status == status, r.content+ siblings = await page.eval_on_selector_all("input:not(#part0)", "els => els.map((e) => e.value)")+ assert not any(siblings), siblings+ assert (+ await page.evaluate("document.querySelectorAll('[data-tv3-codebox], [data-skyvern-otp-box]').length") == 0+ )+++_CODE_BOXES_BOX3_REJECTS_LETTERS_HTML = f"""<div>{_plain_boxes(6)}</div><script>+const third = document.querySelectorAll('.box')[2];+third.addEventListener('input', () => {{ if (!/^[0-9]$/.test(third.value)) third.value = ''; }});+</script>"""++# A widget that rejects the code a moment after the last box and remounts six fresh empty boxes in place.+_CODE_BOXES_REMOUNT_ON_REJECT_HTML = """<div id="code"></div><script>+function render() {+ const c = document.getElementById('code');+ c.innerHTML = [0, 1, 2, 3, 4, 5].map((i) =>+ `<input class="box" type="text" maxlength="1" aria-label="Code character ${i + 1}">`).join('');+ const boxes = [...c.querySelectorAll('.box')];+ boxes.forEach((b) => b.addEventListener('input', () => {+ if (boxes.every((x) => x.value)) setTimeout(render, 30);+ }));+}+render();+</script>"""+# A widget that submits on the last box, moves the URL to an error state and clears the boxes it keeps.+_CODE_BOXES_PUSHSTATE_RESET_HTML = f"""<div>{_plain_boxes(6)}</div><script>+const boxes = [...document.querySelectorAll('.box')];+boxes.forEach((b) => b.addEventListener('input', () => {{+ if (boxes.every((x) => x.value)) {{+ history.pushState(null, '', '#error');+ boxes.forEach((x) => {{ x.value = ''; }});+ }}+}}));+</script>"""++# A widget that submits on the last box, pushes an error URL and remounts six fresh empty boxes in place.+_CODE_BOXES_PUSHSTATE_REMOUNT_HTML = """<div id="code"></div><script>+function render() {+ const c = document.getElementById('code');+ c.innerHTML = [0, 1, 2, 3, 4, 5].map((i) =>+ `<input class="box" type="text" maxlength="1" aria-label="Code character ${i + 1}">`).join('');+ const boxes = [...c.querySelectorAll('.box')];+ boxes.forEach((b) => b.addEventListener('input', () => {+ if (boxes.every((x) => x.value)) setTimeout(() => { history.pushState(null, '', '#error'); render(); }, 30);+ }));+}+render();+</script>"""+# Each box wrapped in its own label, in the light DOM or inside a per-box shadow host.+_CODE_BOXES_LABEL_WRAPPED_HTML = (+ "<div>"+ + "".join(+ f'<label><input class="box" type="text" maxlength="1" aria-label="Code character {i + 1}"></label>'+ for i in range(6)+ )+ + "</div>"+)+_CODE_BOXES_SHADOW_LABEL_WRAPPED_HTML = """<div id="code"></div><script>+customElements.define('x-code-box', class extends HTMLElement {+ connectedCallback() {+ this.attachShadow({mode: 'open'}).innerHTML = '<label><input class="box" type="text" maxlength="1" aria-label="'+ + this.getAttribute('name') + '"></label>';+ }+});+document.getElementById('code').innerHTML = [1, 2, 3, 4, 5, 6].map((i) =>+ `<x-code-box name="Code character ${i}"></x-code-box>`).join('');+</script>"""++# Group shape -> whether it holds a 6-character code whose characters are given, or None when the page moves on.+_CODE_BOX_GROUP_SHAPES = {+ "plain": (f"<div>{_plain_boxes(6)}</div>", lambda code: True),+ "controlled": (_code_boxes_html("text"), lambda code: True),+ "label-wrapped": (_CODE_BOXES_LABEL_WRAPPED_HTML, lambda code: True),+ "shadow-label-wrapped": (_CODE_BOXES_SHADOW_LABEL_WRAPPED_HTML, lambda code: True),+ "box-3-rejects-letters": (_CODE_BOXES_BOX3_REJECTS_LETTERS_HTML, lambda code: code[2].isdigit()),+ "moves-on-midway": (_CODE_BOXES_REDIRECT_MIDWAY_HTML, lambda code: False),+ "moves-on-after-last": (_code_boxes_html("text", submit_on_last=True), None),+ "remounts-empty-after-last": (_CODE_BOXES_REMOUNT_ON_REJECT_HTML, lambda code: False),+ "url-changes-and-boxes-reset": (_CODE_BOXES_PUSHSTATE_RESET_HTML, lambda code: False),+ "url-changes-and-boxes-remount-empty": (_CODE_BOXES_PUSHSTATE_REMOUNT_HTML, lambda code: False),+}+++@_skip_no_browser[email protected]("press_enter", [False, True], ids=["no-enter", "enter"])[email protected]("text", ["482913", "a1b2c3", "48-29-13", "482 913", "4829", "4829137", "4829137512"])[email protected]("shape", list(_CODE_BOX_GROUP_SHAPES))+async def test_type_into_one_character_boxes_is_ok_only_when_every_box_reads_back_its_character(+ shape: str, text: str, press_enter: bool+) -> None:+ html, accepts = _CODE_BOX_GROUP_SHAPES[shape]+ code = text.replace("-", "").replace(" ", "")+ async with _content_page(html) as page:+ await page.evaluate(+ "window.enters = 0; "+ "document.addEventListener('keydown', (e) => { if (e.key === 'Enter') window.enters++; }, true)"+ )+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler(+ {"selector": '[aria-label="Code character 1"]', "text": text, "press_enter": press_enter}+ )+ boxes = await page.eval_on_selector_all(".box", "els => els.map((e) => e.value)")+ enters = await page.evaluate("window.enters")+ if accepts is None and len(code) == 6:+ # Every box was typed and then the page consumed the code: delivered, never an error inviting a retype.+ assert r.status == "ok" and "moved on" in r.content, r.content+ assert enters == 0+ return+ every_box_holds_it = len(boxes) == 6 and boxes == list(code)+ assert (r.status == "ok") == every_box_holds_it, (r.status, r.content, boxes)+ # Enter goes only after every box read back the code, so a code the boxes did not hold is never submitted.+ assert enters == (1 if press_enter and every_box_holds_it else 0), (enters, r.content)+ assert every_box_holds_it == (len(code) == 6 and accepts is not None and accepts(code)), boxes+ if len(code) != 6:+ assert "does not match the box count" in r.content, r.content+ assert not any(boxes), boxes+++@_skip_no_browser+async def test_type_a_code_from_a_middle_box_says_which_boxes_it_wrote_and_that_the_earlier_ones_were_not() -> None:+ async with _content_page(f"<div>{_plain_boxes(6)}</div>") as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": '[aria-label="Code character 3"]', "text": "4829"})+ assert r.status == "ok", r.content+ assert "boxes 3..6 of the 6-box" in r.content and "not written" in r.content, r.content+ assert await page.eval_on_selector_all(".box", "els => els.map((e) => e.value)") == ["", "", "4", "8", "2", "9"]+++@_skip_no_browser+async def test_an_ordinary_value_typed_into_one_character_boxes_is_not_a_secret_and_keeps_the_goal_judge() -> None:+ # A birth year in 4 boxes is not a secret, so it must neither be redacted nor mark the run as having entered+ # one, which would skip the finish-time goal judge for the rest of the run.+ from skyvern.forge.taskv3.goal_check import ToolTrail+ from skyvern.forge.taskv3.loop import make_finish_tool, run_agent_tool_loop++ async with _content_page(f"<div>{_plain_boxes(4)}</div>") as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ trail = ToolTrail()+ context = SkyvernContext(task_id="tsk_v3")+ with skyvern_context.scoped(context):+ await run_agent_tool_loop(+ llm_caller=_ScriptedCaller(+ [+ [("type", {"selector": '[aria-label="Code character 1"]', "text": "1987"})],+ [("finish", {"status": "completed", "reason": "typed"})],+ ]+ ),+ system_prompt="sys",+ user_prompt="goal",+ tools=tools + [make_finish_tool()],+ max_turns=5,+ max_tool_calls=5,+ tool_trail=trail,+ )+ assert await page.eval_on_selector_all(".box", _BOXES_JS) == "1987"+ assert await page.evaluate("document.documentElement.hasAttribute('data-skyvern-otp-filled')") is False+ assert context.runtime_secret_values == set()+ assert trail.secret_entered is False+++@_skip_no_browser+async def test_a_stored_totp_typed_into_one_character_boxes_goes_one_digit_per_box_as_one_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async with _content_page(_code_boxes_html("number")) as page:+ with _credential_totp_run(monkeypatch, seed=_TOTP_SEED, page=page) as run:+ before = time.time()+ r = await _tool(run.tools, "type").handler(+ {"selector": '[aria-label="Code character 1"]', "text": _TOTP_PLACEHOLDER}+ )+ after = time.time()+ held = await page.eval_on_selector_all(".box", _BOXES_JS)+ # A controlled widget re-rendering the boxes drops their per-box tags; the code must stay masked.+ await page.evaluate(+ "document.getElementById('code').innerHTML = [...document.querySelectorAll('.box')].map((b, i) => "+ '`<input class="box" type="number" maxlength="1" aria-label="Code character ${i + 1}" '+ "value=\"${b.value}\">`).join('')"+ )+ observed = (await _tool(run.tools, "observe").handler({})).content+ assert r.status == "ok", r.content+ assert "Code character 6" in observed, observed+ for line in observed.splitlines():+ if "Code character" in line:+ assert "value=" not in line or "value='(hidden)'" in line, line+ totp = pyotp.TOTP(_TOTP_SEED)+ assert held in {totp.at(before), totp.at(after)}+ assert run.context.runtime_secret_values == {held}+ assert held not in r.content and _TOTP_PLACEHOLDER not in r.content+++@_skip_no_browser+async def test_type_more_than_one_character_into_a_short_run_of_boxes_that_rejects_it_is_an_error() -> None:+ # Two boxes are not a code group, so nothing is split; the one box written must still read back the text.+ html = f"""<div>{_plain_boxes(2)}</div><script>+document.querySelectorAll('.box').forEach((b) => b.addEventListener('input', () => {{+ if (b.value.length > 1) b.value = '';+}}));+</script>"""+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": '[aria-label="Code character 1"]', "text": "JR"})+ assert r.status == "error", r.content+ assert r.error_class == "text_not_held", r.error_class+++@_skip_no_browser+async def test_type_one_character_into_a_lone_one_character_box_is_unchanged() -> None:+ async with _content_page(_split_field_html([1], input_type="text")) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "type").handler({"selector": "#part0", "text": "Q"})+ assert r.status == "ok", r.content+ assert r.content == "typed into #part0"+ assert await page.eval_on_selector("#part0", "el => el.value") == "Q"+++@_skip_no_browser+async def test_type_a_credential_into_one_character_boxes_is_refused_not_split_across_them() -> None:+ # A stored credential is never spread over code boxes, and the refusal must not fall back to a one-fill "ok".+ async with _content_page(_code_boxes_html("text")) as page:+ tools = build_browser_tools(+ _fixed_page_provider(page),+ resolve_typed_text=lambda text: "pw4821" if text == "placeholder_pw" else text,+ )+ r = await _tool(tools, "type").handler(+ {"selector": '[aria-label="Code character 1"]', "text": "placeholder_pw"}+ )+ assert r.status == "error", r.content+ assert r.error_class == "not_editable", r.error_class+ assert "one character per box" in r.content, r.content+ assert "pw4821" not in r.content+ assert await page.eval_on_selector_all(".box", _BOXES_JS) == ""++# The same unclickable shape on a field that only commits a picked suggestion: the raw query sits in# the input until blur, so reading it back proves nothing.# A refusal only proves the target does not hold EXACTLY what was typed -- not that the keystrokes