Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-12612): run-list outcome-risk marker (#7526)
pedrohsdb0ed96a30d5ea
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsxindex dd5f34fda..efec970d4 100644--- a/skyvern-frontend/src/routes/history/RunHistory.tsx+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx@@ -79,6 +79,8 @@ import { OnboardingEmptyState } from "@/components/onboarding/OnboardingEmptyStaimport { useFeatureFlagVariantKey } from "posthog-js/react";import { EXPERIMENT, isABVariant } from "@/util/onboarding/experimentConfig";import { useRunTagsBatchQuery } from "@/routes/tasks/hooks/useRunTagsBatchQuery";+import { useRunsHealSummaryBatchQuery } from "@/routes/workflows/hooks/useRunsHealSummaryBatchQuery";+import { RunOutcomeRiskMarker } from "@/routes/workflows/workflowRun/RunOutcomeRiskMarker";import { useRunTagSuggestionsQuery } from "@/routes/tasks/hooks/useRunTagSuggestionsQuery";import { useTagKeysQuery } from "@/routes/workflows/hooks/useTagKeysQuery";import { useTagValuesQuery } from "@/routes/workflows/hooks/useTagValuesQuery";@@ -277,6 +279,7 @@ function RunHistory() {const { data: runTagsMap = {} } = useRunTagsBatchQuery(runIds, {enabled: taggingEnabled,});+ const { data: runHealMap = {} } = useRunsHealSummaryBatchQuery(runIds);const { data: tagKeys = [] } = useTagKeysQuery({ enabled: taggingEnabled });const tagDescriptions = useMemo(() =>@@ -492,13 +495,20 @@ function RunHistory() {</div></TableCell><TableCell>- {isKnownStatus(run.status) ? (- <StatusBadge status={run.status} />- ) : (- <span className="text-sm text-neutral-600 dark:text-slate-400">- {run.status}- </span>- )}+ <div className="flex items-center gap-1.5">+ {isKnownStatus(run.status) ? (+ <StatusBadge status={run.status} />+ ) : (+ <span className="text-sm text-neutral-600 dark:text-slate-400">+ {run.status}+ </span>+ )}+ <RunOutcomeRiskMarker+ outcomeRisk={+ (runHealMap[run.run_id]?.blocks_outcome_risk?.length ?? 0) > 0+ }+ />+ </div></TableCell><TableCellclassName="max-w-0 truncate"diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsxindex 23be1e093..2e53e097e 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx@@ -76,6 +76,10 @@ vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({useRunTagsBatchQuery: () => ({ data: {} }),}));+vi.mock("./hooks/useRunsHealSummaryBatchQuery", () => ({+ useRunsHealSummaryBatchQuery: () => ({ data: {} }),+}));+vi.mock("@/routes/tasks/hooks/useRunTagSuggestionsQuery", () => ({useRunTagSuggestionsQuery: () => ({data: { keys: [], valuesByKey: new Map(), labels: [] },diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsxindex 4dfe8317d..f4240796f 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx@@ -100,6 +100,8 @@ import { useRowSelection } from "@/hooks/useRowSelection";import { RunBulkActionBar } from "@/routes/runs/RunBulkActionBar";import { RunRowContextMenu } from "@/routes/runs/RunRowContextMenu";import { WorkflowReliabilityPanel } from "./workflowRun/WorkflowReliabilityPanel";+import { RunOutcomeRiskMarker } from "./workflowRun/RunOutcomeRiskMarker";+import { useRunsHealSummaryBatchQuery } from "./hooks/useRunsHealSummaryBatchQuery";function WorkflowPage() {const { workflowPermanentId } = useParams();@@ -190,6 +192,7 @@ function WorkflowPage() {const { data: runTagsMap = {} } = useRunTagsBatchQuery(runIds, {enabled: taggingEnabled,});+ const { data: runHealMap = {} } = useRunsHealSummaryBatchQuery(runIds);const { data: runTagSuggestions } = useRunTagSuggestionsQuery({enabled: taggingEnabled,});@@ -498,6 +501,12 @@ function WorkflowPage() {workflowRun.retried_from_workflow_run_id}/>+ <RunOutcomeRiskMarker+ outcomeRisk={+ (runHealMap[workflowRun.workflow_run_id]+ ?.blocks_outcome_risk?.length ?? 0) > 0+ }+ /></div></TableCell><TableCelldiff --git a/skyvern-frontend/src/routes/workflows/hooks/useRunsHealSummaryBatchQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useRunsHealSummaryBatchQuery.tsnew file mode 100644index 000000000..8e0a36a34--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/hooks/useRunsHealSummaryBatchQuery.ts@@ -0,0 +1,56 @@+import { getClient } from "@/api/AxiosClient";+import { useCredentialGetter } from "@/hooks/useCredentialGetter";+import { useQuery } from "@tanstack/react-query";+import type {+ RunHealSummary,+ RunsHealSummaryBatchResponse,+} from "../types/healTypes";++// Backend rejects more than this many ids per request; chunk so a long run+// list never drops markers.+const BATCH_RUN_HEAL_MAX_IDS = 100;++// One batch fetch of per-run heal summaries for the visible runs (avoids the+// N+1 of the single-run heal-episodes call). Ids are sorted so the query key+// is order-independent and identical sets share a cache entry. Run ids are+// globally unique, so the key needs no org scope (mirrors the run-tags batch).+function useRunsHealSummaryBatchQuery(workflowRunIds: Array<string>) {+ const credentialGetter = useCredentialGetter();+ const sortedIds = [...workflowRunIds].sort();++ return useQuery<Record<string, RunHealSummary>>({+ queryKey: ["run-heal-summary", "batch", sortedIds],+ enabled: sortedIds.length > 0,+ queryFn: async ({ signal }) => {+ const client = await getClient(credentialGetter, "sans-api-v1");+ const chunks: Array<Array<string>> = [];+ for (let i = 0; i < sortedIds.length; i += BATCH_RUN_HEAL_MAX_IDS) {+ chunks.push(sortedIds.slice(i, i + BATCH_RUN_HEAL_MAX_IDS));+ }+ const responses = await Promise.all(+ chunks.map((ids) =>+ client+ .post<RunsHealSummaryBatchResponse>(+ "/runs/heal_summary/batch",+ { workflow_run_ids: ids },+ { signal },+ )+ .then((response) => response.data.summaries),+ ),+ );+ // Chunks are disjoint slices, so run-id keys never collide on merge.+ const merged: Record<string, RunHealSummary> = {};+ for (const response of responses) {+ // A response-shape skew (SKY-10683) shipped once already; skip a+ // malformed chunk payload rather than let it inject garbage keys.+ if (response === null || typeof response !== "object") {+ continue;+ }+ Object.assign(merged, response);+ }+ return merged;+ },+ });+}++export { useRunsHealSummaryBatchQuery };diff --git a/skyvern-frontend/src/routes/workflows/types/healTypes.ts b/skyvern-frontend/src/routes/workflows/types/healTypes.tsindex 74e68fcac..29ee37cc8 100644--- a/skyvern-frontend/src/routes/workflows/types/healTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/healTypes.ts@@ -45,3 +45,7 @@ export type RunHealEpisodesResponse = {episodes: HealEpisodeView[];summary: RunHealSummary;};++export type RunsHealSummaryBatchResponse = {+ summaries: Record<string, RunHealSummary>;+};diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/RunOutcomeRiskMarker.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/RunOutcomeRiskMarker.test.tsxnew file mode 100644index 000000000..5a5e5e75c--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/workflowRun/RunOutcomeRiskMarker.test.tsx@@ -0,0 +1,22 @@+// @vitest-environment jsdom++import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import { RunOutcomeRiskMarker } from "./RunOutcomeRiskMarker";++describe("RunOutcomeRiskMarker", () => {+ it("renders an amber marker when the run has outcome risk", () => {+ render(<RunOutcomeRiskMarker outcomeRisk={true} />);++ const marker = screen.getByLabelText("Completed with outcome risk");+ expect(marker).toBeDefined();+ expect(marker.className).toContain("text-warning");+ });++ it("renders nothing when the run has no outcome risk", () => {+ const { container } = render(<RunOutcomeRiskMarker outcomeRisk={false} />);++ expect(container.firstChild).toBeNull();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/RunOutcomeRiskMarker.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/RunOutcomeRiskMarker.tsxnew file mode 100644index 000000000..0125382fc--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/workflowRun/RunOutcomeRiskMarker.tsx@@ -0,0 +1,43 @@+import { ExclamationTriangleIcon } from "@radix-ui/react-icons";++import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";++type Props = {+ outcomeRisk: boolean;+};++// Amber, never red — the run status owns red; an outcome-risk run still+// completed, it just could not verify its recovered outcome.+function RunOutcomeRiskMarker({ outcomeRisk }: Props) {+ if (!outcomeRisk) {+ return null;+ }++ return (+ <TooltipProvider>+ <Tooltip delayDuration={300}>+ <TooltipTrigger asChild>+ <span+ role="img"+ aria-label="Completed with outcome risk"+ tabIndex={0}+ className="inline-flex items-center text-warning"+ >+ <ExclamationTriangleIcon aria-hidden className="h-4 w-4" />+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-[260px] text-[11px]">+ Completed, but a recovery may not have fully verified the outcome —+ review recommended. Your workflow version is unchanged.+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+}++export { RunOutcomeRiskMarker };diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex c5fa5e6af..b88e2cb8b 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -1045,9 +1045,17 @@ class NoElementBoudingBox(SkyvernException):super().__init__(f"Element does not have a bounding box. element_id={element_id}")-class NoIncrementalElementFoundForAutoCompletion(SkyvernException):- def __init__(self, element_id: str, text: str) -> None:- super().__init__(f"No auto completion shown up after fill in [{text}]. element_id={element_id}")+class AutoCompletionCommitFailure(SkyvernException):+ def __init__(self, stage: str, attempt_trail: list[str] | None = None) -> None:+ trail = attempt_trail or [stage]+ super().__init__(f"Autocomplete selection failed. stage={stage} attempt_trail={','.join(trail)}")+ self.stage = stage+ self.attempt_trail = trail+++# Deprecated: superseded by AutoCompletionCommitFailure, which carries the failing stage.+# Kept for one release so downstream `except` clauses keep working.+NoIncrementalElementFoundForAutoCompletion = AutoCompletionCommitFailureclass NoSuitableAutoCompleteOption(SkyvernException):diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 969dec298..5d9b711a8 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -33,6 +33,7 @@ from skyvern.constants import (from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_stemfrom skyvern.errors.errors import TOTPExpiredError, UserDefinedError, filter_to_user_defined_codesfrom skyvern.exceptions import (+ AutoCompletionCommitFailure,CaptchaSolveError,CardNumberInputMismatch,EmptySelect,@@ -61,7 +62,6 @@ from skyvern.exceptions import (NoAutoCompleteOptionMeetCondition,NoAvailableOptionFoundForCustomSelection,NoElementMatchedForTargetOption,- NoIncrementalElementFoundForAutoCompletion,NoIncrementalElementFoundForCustomSelection,NoSuitableAutoCompleteOption,NoTOTPSecretFound,@@ -214,6 +214,31 @@ DOWNLOAD_EVENT_ACTIVE_DIR_GRACE_SECONDS = 60DOWNLOAD_DUPLICATE_STEM_SUFFIX_RE = re.compile(r"(?:\s+\(\d{1,3}\)|_\d{1,3})$")SELECT_SHADOW_MATCH_APOSTROPHE_RE = re.compile(r"['`‘’]")SELECT_SHADOW_MATCH_WORD_RE = re.compile(r"\w+")+AUTOCOMPLETE_COMMIT_REQUIRED_FLAG = "AUTOCOMPLETE_COMMIT_REQUIRED"+AUTOCOMPLETE_COMMIT_WORD_RE = re.compile(r"[^\W_]+")+AUTOCOMPLETE_POLL_INTERVAL_SECONDS = 0.5+AUTOCOMPLETE_POLL_MAX_ATTEMPTS = 16+AUTOCOMPLETE_POLL_DEFAULT_BUDGET_SECONDS = 4.0+AUTOCOMPLETE_TOTAL_DEADLINE_SECONDS = 8.0+AUTOCOMPLETE_READBACK_TIMEOUT_SECONDS = 2.0+AUTOCOMPLETE_TEARDOWN_ERROR_MARKERS = (+ "context was destroyed",+ "navigation",+ "target closed",+ "has been closed",+ "frame was detached",+)+AUTOCOMPLETE_DETACHED_ERROR_MARKERS = (+ "not attached",+ "detached",+)+AUTOCOMPLETE_RERESOLVE_FAILURE_MARKERS = (+ "timeout",+ "timed out",+ "not found",+ "no element",+ "failed to find",+)def _select_shadow_match_enabled() -> bool:@@ -440,6 +465,16 @@ def _resolve_autocomplete_candidate(return matched_index, candidates[matched_index]+def _autocomplete_candidate_for_element_id(+ elements: list[dict], element_id: str+) -> tuple[int, dict[str, str | None]] | None:+ candidates = _autocomplete_candidates_from_elements(elements)+ for index, candidate in enumerate(candidates):+ if candidate.get("element_id") == element_id:+ return index, candidate+ return None++async def _read_autocomplete_option_identity(*,skyvern_frame: SkyvernFrame,@@ -476,39 +511,202 @@ async def _verify_autocomplete_option_identity(LOG.info("Autocomplete option index differed from deterministic candidate; accepting label match",expected_index=matched_index,- expected_label=matched_label,+ expected_label_length=len(matched_label),actual_index=actual_index,- actual_label=actual_label,+ actual_label_length=len(str(actual_label or "")),)return TrueLOG.info("Autocomplete option identity did not match deterministic candidate",expected_index=matched_index,- expected_label=matched_label,+ expected_label_length=len(matched_label),actual_index=actual_index,- actual_label=actual_label,+ actual_label_length=len(str(actual_label or "")),)return False+class AutocompleteCommitOutcome(BaseModel):+ committed: bool = False+ side_effects_observed: bool = False+++def _autocomplete_commit_tokens(value: str | None) -> list[str]:+ return AUTOCOMPLETE_COMMIT_WORD_RE.findall(str(value or "").casefold())+++async def _read_autocomplete_committed_value(skyvern_element: SkyvernElement) -> tuple[str | None, bool]:+ detached_error_observed = False+ for attempt in range(2):+ try:+ async with asyncio.timeout(AUTOCOMPLETE_READBACK_TIMEOUT_SECONDS):+ value = await get_input_value(skyvern_element.get_tag_name(), skyvern_element.get_locator())+ return str(value or ""), False+ except Exception as exc:+ message = str(exc).casefold()+ if any(marker in message for marker in AUTOCOMPLETE_TEARDOWN_ERROR_MARKERS):+ return None, True+ detached_error = any(marker in message for marker in AUTOCOMPLETE_DETACHED_ERROR_MARKERS)+ if attempt == 0 and detached_error:+ detached_error_observed = True+ continue+ reresolution_failed = (+ detached_error+ or isinstance(exc, TimeoutError)+ or any(marker in message for marker in AUTOCOMPLETE_RERESOLVE_FAILURE_MARKERS)+ )+ if detached_error_observed and reresolution_failed:+ LOG.info(+ "Autocomplete read-back element stayed unreachable after detach, treating as implicit commit",+ element_id=skyvern_element.get_id(),+ error=type(exc).__name__,+ )+ return None, True+ LOG.info(+ "Autocomplete read-back could not read the input value",+ element_id=skyvern_element.get_id(),+ error=type(exc).__name__,+ )+ return None, False+ return None, False+++async def _autocomplete_suggestions_closed(locator: Locator | None) -> bool | None:+ if locator is None:+ return None+ try:+ async with asyncio.timeout(AUTOCOMPLETE_READBACK_TIMEOUT_SECONDS):+ if await locator.count() == 0:+ return True+ return not await locator.is_visible()+ except Exception:+ return None+++async def _autocomplete_selection_state(locator: Locator | None) -> bool | None:+ if locator is None:+ return None+ try:+ async with asyncio.timeout(AUTOCOMPLETE_READBACK_TIMEOUT_SECONDS):+ aria_selected = await locator.get_attribute("aria-selected")+ except Exception:+ return None+ if aria_selected is None:+ return None+ return str(aria_selected).casefold() == "true"+++async def _autocomplete_input_reports_closed(skyvern_element: SkyvernElement) -> bool | None:+ try:+ async with asyncio.timeout(AUTOCOMPLETE_READBACK_TIMEOUT_SECONDS):+ # Must be a live read: get_attr defaults to static-first, and an input scraped before the+ # dropdown opened carries a cached aria-expanded="false" that would read as commit evidence+ # no matter what the keypress actually did.+ aria_expanded = await skyvern_element.get_attr("aria-expanded", mode="dynamic")+ except Exception:+ return None+ if aria_expanded is None:+ return None+ normalized = str(aria_expanded).casefold()+ if normalized not in ("true", "false"):+ return None+ return normalized == "false"++async def _verify_autocomplete_input_readback(*,skyvern_element: SkyvernElement,- matched_index: int,matched_label: str,-) -> bool:- actual_value = await get_input_value(skyvern_element.get_tag_name(), skyvern_element.get_locator())- if _normalize_select_shadow_text(actual_value) == _normalize_select_shadow_text(matched_label):- return True+ typed_prefix: str,+ pre_action_value: str | None = None,+ suggestions_closed: bool | None = None,+ selection_state_present: bool | None = None,+ allow_unchanged_value: bool = False,+ commit_required: bool = False,+) -> AutocompleteCommitOutcome:+ actual_value, teardown_observed = await _read_autocomplete_committed_value(skyvern_element)+ if teardown_observed:+ return AutocompleteCommitOutcome(committed=True, side_effects_observed=True)+ if actual_value is None:+ return AutocompleteCommitOutcome(committed=False, side_effects_observed=bool(suggestions_closed))++ actual_tokens = _autocomplete_commit_tokens(actual_value)+ matched_tokens = _autocomplete_commit_tokens(matched_label)+ baseline = typed_prefix if pre_action_value is None else pre_action_value+ baseline_tokens = _autocomplete_commit_tokens(baseline)+ actual_normalized = " ".join(actual_tokens)+ matched_normalized = " ".join(matched_tokens)+ baseline_normalized = " ".join(baseline_tokens)+ prefix_normalized = " ".join(_autocomplete_commit_tokens(typed_prefix))++ value_changed = actual_normalized != baseline_normalized+ side_effects_observed = value_changed or bool(suggestions_closed)+ actual_set = set(actual_tokens)+ matched_set = set(matched_tokens)+ # Field shows the whole label (plus any prefix like "Selected:"), or a shorter read-back that still+ # covers at least half the label - a lone token of a multi-word label does not identify the selection.+ token_superset = matched_set <= actual_set+ token_subset = actual_set <= matched_set and len(actual_set) * 2 >= len(matched_set)+ token_match = bool(actual_tokens) and bool(matched_tokens) and (token_superset or token_subset)++ committed = False+ if allow_unchanged_value:+ committed = token_match or (bool(actual_tokens) and actual_normalized == prefix_normalized)+ elif not actual_tokens:+ # Chip/token widgets clear the input after committing, so cleared + closed listbox is a commit.+ # Under commit-required a dismissal click that clears the field looks identical, so an+ # affirmative selection signal is needed on top of the closed listbox.+ committed = bool(suggestions_closed) and (not commit_required or bool(selection_state_present))+ elif token_match:+ label_distinguishable = matched_normalized != baseline_normalized+ if label_distinguishable:+ committed = value_changed+ else:+ committed = value_changed or bool(suggestions_closed) or bool(selection_state_present)- LOG.info(- "Autocomplete read-back did not match deterministic option",- expected_index=matched_index,- expected_label=matched_label,- actual_value=actual_value,- )- return False+ if not committed:+ LOG.info(+ "Autocomplete read-back did not confirm selected suggestion",+ element_id=skyvern_element.get_id(),+ expected_length=len(matched_normalized),+ actual_length=len(actual_normalized),+ value_changed=value_changed,+ suggestions_closed=suggestions_closed,+ )+ return AutocompleteCommitOutcome(committed=committed, side_effects_observed=side_effects_observed)+++async def _poll_autocomplete_incremental_elements(+ *,+ incremental_scraped: IncrementalScrapePage,+ cleanup_factory: CleanupElementTreeFunc,+ deadline: float | None = None,+) -> list[dict]:+ loop = asyncio.get_running_loop()+ if deadline is None:+ deadline = loop.time() + AUTOCOMPLETE_POLL_DEFAULT_BUDGET_SECONDS+ extracted_elements: list[dict] = []+ for _ in range(AUTOCOMPLETE_POLL_MAX_ATTEMPTS):+ try:+ async with asyncio.timeout(AUTOCOMPLETE_POLL_INTERVAL_SECONDS):+ probe_count = int(await incremental_scraped.get_incremental_elements_num())+ except Exception:+ probe_count = 0+ # Re-extract on every positive probe rather than only on a count change: a listbox can swap a+ # loading placeholder for an option in place, leaving the incremental count constant. We return+ # as soon as an option candidate renders, so the common case still extracts at most once.+ if probe_count > 0:+ incremental_elements = await incremental_scraped.get_incremental_element_tree(cleanup_factory)+ if incremental_elements:+ extracted_elements = incremental_elements+ if _autocomplete_candidates_from_elements(incremental_elements):+ return extracted_elements+ remaining = deadline - loop.time()+ if remaining <= 0:+ break+ await asyncio.sleep(min(AUTOCOMPLETE_POLL_INTERVAL_SECONDS, remaining))+ return extracted_elementsasync def _reset_autocomplete_for_llm_fallback(@@ -522,6 +720,7 @@ async def _reset_autocomplete_for_llm_fallback(text: str,task: Task,step: Step,+ poll_deadline: float | None = None,) -> tuple[IncrementalScrapePage, list[dict], list[dict], str, list[str]]:await current_incremental_scraped.stop_listen_dom_increment()await skyvern_element.input_clear()@@ -529,13 +728,14 @@ async def _reset_autocomplete_for_llm_fallback(incremental_scraped = IncrementalScrapePage(skyvern_frame=skyvern_frame)await incremental_scraped.start_listen_dom_increment(await skyvern_element.get_element_handler())await skyvern_element.press_fill(text)- await skyvern_frame.safe_wait_for_animation_end(before_wait_sec=1, caller="autocomplete.fallback_refill")- incremental_element = await incremental_scraped.get_incremental_element_tree(- clean_and_remove_element_tree_factory(+ incremental_element = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scraped,+ cleanup_factory=clean_and_remove_element_tree_factory(task=task,step=step,check_filter_funcs=[check_existed_but_not_option_element_in_dom_factory(dom)],),+ deadline=poll_deadline,)if len(incremental_element) > 0:@@ -553,7 +753,7 @@ async def _reset_autocomplete_for_llm_fallback(if (await dom_after_open.get_skyvern_element_by_id(element_id)).is_interactable()]if len(new_interactable_element_ids) == 0:- raise NoIncrementalElementFoundForAutoCompletion(element_id=skyvern_element.get_id(), text=text)+ raise AutoCompletionCommitFailure(stage="suggestions_never_rendered")LOG.info("New elements detected after resetting autocomplete fallback input",@@ -1219,6 +1419,10 @@ async def _is_surface_blocked_form_advance_enabled(task: Task) -> bool:return await _is_org_flag_enabled(task, SURFACE_BLOCKED_FORM_ADVANCE_FLAG, "surface-blocked-form-advance")+async def _is_autocomplete_commit_required_enabled(task: Task) -> bool:+ return await _is_org_flag_enabled(task, AUTOCOMPLETE_COMMIT_REQUIRED_FLAG, "autocomplete-commit-required")++async def _resolve_collapse_xp_assignment(experimentation_provider: BaseExperimentationProvider,task: Task,@@ -1890,7 +2094,12 @@ async def check_date_format(class AutoCompletionResult(BaseModel):auto_completion_attempt: bool = Falseincremental_elements: list[dict] = []- action_result: ActionResult = ActionSuccess()+ action_result: ActionResult | None = None+ stage_outcome: str | None = None+ # A click landed and mutated the field but the commit could not be verified. Once this is+ # set the field is already dirty, so the caller must stop trying further selections instead+ # of clicking more options on top of it.+ committed_side_effects: bool = Falseclass ScopedXhrDownloadCapture:@@ -5767,8 +5976,11 @@ async def choose_auto_completion_dropdown(preserved_elements: list[dict] | None = None,relevance_threshold: float = 0.8,is_location_input: bool = False,+ commit_required: bool = False,+ verify_commit: bool = True,collapse_autocomplete_fanout_enabled: bool = False,action: InputTextAction | None = None,+ poll_deadline: float | None = None,) -> AutoCompletionResult:preserved_elements = preserved_elements or []clear_input = True@@ -5781,12 +5993,12 @@ async def choose_auto_completion_dropdown(try:await skyvern_element.press_fill(text)- # wait for new elemnts to load- await skyvern_frame.safe_wait_for_animation_end(before_wait_sec=1, caller="autocomplete.fill")- incremental_element = await incremental_scraped.get_incremental_element_tree(- clean_and_remove_element_tree_factory(+ incremental_element = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scraped,+ cleanup_factory=clean_and_remove_element_tree_factory(task=task, step=step, check_filter_funcs=[check_existed_but_not_option_element_in_dom_factory(dom)]),+ deadline=poll_deadline,)# check if elements in preserve list are still on the page@@ -5848,7 +6060,7 @@ async def choose_auto_completion_dropdown("Autocomplete deterministic option identity failed, resetting input before LLM fallback",element_id=matched_element_id,matched_index=matched_index,- matched_label=matched_label,+ matched_label_length=len(matched_label),)(incremental_scraped,@@ -5866,6 +6078,7 @@ async def choose_auto_completion_dropdown(text=text,task=task,step=step,+ poll_deadline=poll_deadline,)result.incremental_elements = copy.deepcopy(fallback_incremental_elements)cleaned_incremental_element = shadow_candidate_elements@@ -5873,32 +6086,45 @@ async def choose_auto_completion_dropdown(LOG.info("Autocomplete deterministic fast path: exact/stem option found, skipping LLM",element_id=matched_element_id,- input_value=text,+ input_length=len(text),matched_index=matched_index,- matched_label=matched_label,+ matched_label_length=len(matched_label),)try:await matched_locator.click(timeout=settings.BROWSER_ACTION_TIMEOUT_MS)- if await _verify_autocomplete_input_readback(+ # This deterministic read-back predates the commit-verification feature+ # (it is the one verify site that exists on main), so it stays on+ # regardless of verify_commit - gating it would reintroduce the silent+ # deterministic-click success this whole change exists to stop.+ commit_outcome = await _verify_autocomplete_input_readback(skyvern_element=skyvern_element,- matched_index=matched_index,matched_label=matched_label,- ):+ typed_prefix=text,+ pre_action_value=text,+ suggestions_closed=await _autocomplete_suggestions_closed(matched_locator),+ selection_state_present=await _autocomplete_selection_state(matched_locator),+ commit_required=commit_required,+ )+ if commit_outcome.committed:clear_input = Falseresult.action_result = ActionSuccess()return result+ result.stage_outcome = "clicked_but_not_committed"+ if commit_outcome.side_effects_observed:+ result.committed_side_effects = True+ raise AutoCompletionCommitFailure(stage="clicked_but_not_committed")LOG.info("Autocomplete deterministic read-back failed, resetting input before LLM fallback",element_id=matched_element_id,matched_index=matched_index,- matched_label=matched_label,)+ except AutoCompletionCommitFailure:+ raiseexcept Exception:LOG.info("Autocomplete deterministic fast-path click/read-back failed, falling through to LLM",element_id=matched_element_id,matched_index=matched_index,- matched_label=matched_label,exc_info=True,)(@@ -5917,6 +6143,7 @@ async def choose_auto_completion_dropdown(text=text,task=task,step=step,+ poll_deadline=poll_deadline,)result.incremental_elements = copy.deepcopy(fallback_incremental_elements)cleaned_incremental_element = shadow_candidate_elements@@ -5928,7 +6155,7 @@ async def choose_auto_completion_dropdown("Autocomplete deterministic option detached before click, resetting input before LLM fallback",element_id=matched_element_id,matched_index=matched_index,- matched_label=matched_label,+ matched_label_length=len(matched_label),)(incremental_scraped,@@ -5946,6 +6173,7 @@ async def choose_auto_completion_dropdown(text=text,task=task,step=step,+ poll_deadline=poll_deadline,)result.incremental_elements = copy.deepcopy(fallback_incremental_elements)cleaned_incremental_element = shadow_candidate_elements@@ -5965,18 +6193,62 @@ async def choose_auto_completion_dropdown(LOG.info("Location auto-completion fast path: single option found, skipping LLM",element_id=fast_path_element_id,- input_value=text,+ input_length=len(text),)try:await fast_path_locator.click(timeout=settings.BROWSER_ACTION_TIMEOUT_MS)- clear_input = False- result.action_result = ActionSuccess()- return result+ if verify_commit:+ commit_outcome = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_element,+ matched_label=only_element.get("text") or "",+ typed_prefix=text,+ pre_action_value=text,+ suggestions_closed=await _autocomplete_suggestions_closed(fast_path_locator),+ selection_state_present=await _autocomplete_selection_state(fast_path_locator),+ commit_required=commit_required,+ )+ else:+ commit_outcome = AutocompleteCommitOutcome(committed=True)+ if commit_outcome.committed:+ clear_input = False+ result.action_result = ActionSuccess()+ return result+ result.stage_outcome = "clicked_but_not_committed"+ if commit_outcome.side_effects_observed:+ result.committed_side_effects = True+ raise AutoCompletionCommitFailure(stage="clicked_but_not_committed")+ LOG.info(+ "Location fast-path read-back failed, resetting input before LLM fallback",+ element_id=fast_path_element_id,+ )+ except AutoCompletionCommitFailure:+ raiseexcept Exception:LOG.info("Location fast-path click failed, falling through to LLM",element_id=fast_path_element_id,+ exc_info=True,)+ (+ incremental_scraped,+ fallback_incremental_elements,+ shadow_candidate_elements,+ html,+ new_interactable_element_ids,+ ) = await _reset_autocomplete_for_llm_fallback(+ current_incremental_scraped=incremental_scraped,+ skyvern_frame=skyvern_frame,+ skyvern_element=skyvern_element,+ page=page,+ scraped_page=scraped_page,+ dom=dom,+ text=text,+ task=task,+ step=step,+ poll_deadline=poll_deadline,+ )+ result.incremental_elements = copy.deepcopy(fallback_incremental_elements)+ cleaned_incremental_element = shadow_candidate_elementsif not html:html = incremental_scraped.build_html_tree(cleaned_incremental_element)@@ -5993,7 +6265,7 @@ async def choose_auto_completion_dropdown(if (await dom_after_open.get_skyvern_element_by_id(element_id)).is_interactable()]if len(new_interactable_element_ids) == 0:- raise NoIncrementalElementFoundForAutoCompletion(element_id=skyvern_element.get_id(), text=text)+ raise AutoCompletionCommitFailure(stage="suggestions_never_rendered")LOG.info("New elements detected after the input",new_elements_ids=new_interactable_element_ids,@@ -6040,11 +6312,31 @@ async def choose_auto_completion_dropdown(if json_response.get("direct_searching", False):LOG.info("Decided to directly search with the current value",- value=text,+ element_id=skyvern_element.get_id(),+ input_length=len(text),)await skyvern_element.press_key("Enter")- clear_input = False- return result+ matched_label = str(json_response.get("value") or "")+ # Searching with the typed text leaves the value unchanged by design, so an unchanged+ # read-back is a commit here - but not on a field that must commit a real suggestion,+ # where it is indistinguishable from Enter doing nothing at all.+ if verify_commit:+ commit_outcome = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_element,+ matched_label=matched_label or text,+ typed_prefix=text,+ pre_action_value=text,+ allow_unchanged_value=not commit_required,+ commit_required=commit_required,+ )+ else:+ commit_outcome = AutocompleteCommitOutcome(committed=True)+ if commit_outcome.committed:+ clear_input = False+ result.action_result = ActionSuccess()+ return result+ result.committed_side_effects = commit_outcome.side_effects_observed+ raise AutoCompletionCommitFailure(stage="clicked_but_not_committed")if not element_id:reasoning = json_response.get("reasoning")@@ -6073,6 +6365,15 @@ async def choose_auto_completion_dropdown(if await locator.count() == 0:raise MissingElement(element_id=element_id)+ candidate_match = _autocomplete_candidate_for_element_id(shadow_candidate_elements, element_id)+ if candidate_match is None:+ raise NoSuitableAutoCompleteOption(+ reasoning="Selected element was not a rendered suggestion",+ target_value=text,+ )+ _matched_index, candidate = candidate_match+ matched_label = candidate.get("label") or ""+# Use SkyvernElement.click() so we get the full fallback chain# (Playwright click → coordinate click → JavaScript click). Plain# locator.click() can fail when the item or one of its ancestors has@@ -6084,16 +6385,36 @@ async def choose_auto_completion_dropdown()await selected_element.scroll_into_view()await selected_element.click(page=page)- clear_input = False- return result+ if verify_commit:+ commit_outcome = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_element,+ matched_label=matched_label,+ typed_prefix=text,+ pre_action_value=text,+ suggestions_closed=await _autocomplete_suggestions_closed(locator),+ selection_state_present=await _autocomplete_selection_state(locator),+ commit_required=commit_required,+ )+ else:+ commit_outcome = AutocompleteCommitOutcome(committed=True)+ if commit_outcome.committed:+ clear_input = False+ result.action_result = ActionSuccess()+ return result+ result.committed_side_effects = commit_outcome.side_effects_observed+ raise AutoCompletionCommitFailure(stage="clicked_but_not_committed")except Exception as e:+ stage = e.stage if isinstance(e, AutoCompletionCommitFailure) else "suggestion_not_matched"LOG.info("Failed to choose the auto completion dropdown",sampling=True,+ element_id=skyvern_element.get_id(),+ input_length=len(text),+ stage=stage,exc_info=True,- input_value=text,)+ result.stage_outcome = stageresult.action_result = ActionFailure(exception=e)return resultfinally:@@ -6114,6 +6435,21 @@ def remove_duplicated_HTML_element(elements: list[dict]) -> list[dict]:return new_elements+def _autocomplete_side_effect_terminal(+ *, commit_required: bool, attempt_trail: list[str], element_id: str+) -> ActionResult | None:+ LOG.info(+ "Autocomplete click mutated the field without a verified commit; stopping to avoid clicking further options on a dirty field",+ element_id=element_id,+ attempt_trail=attempt_trail,+ )+ if commit_required:+ return ActionFailure(+ AutoCompletionCommitFailure(stage="clicked_but_not_committed", attempt_trail=attempt_trail)+ )+ return None++async def input_or_auto_complete_input(input_or_select_context: InputOrSelectContext,scraped_page: ScrapedPage,@@ -6141,6 +6477,16 @@ async def input_or_auto_complete_input(current_attemp = 0current_value = textresult = AutoCompletionResult()+ attempt_trail: list[str] = []+ is_location = input_or_select_context.is_location_input or False+ # Commit verification (and everything downstream of a failed read-back) only runs behind the+ # flag, so flag-off orgs keep the pre-verification behavior: a selection click is assumed+ # committed, with no read-back cost and no extra LLM fall-through.+ verify_commit = await _is_autocomplete_commit_required_enabled(task)+ # A location-search widget can be both. Search bars keep their documented fall-through, so they+ # never enter strict commit mode - otherwise the search-bar branch below returns a hard failure.+ commit_required = is_location and not input_or_select_context.is_search_bar and verify_commit+ poll_deadline = asyncio.get_running_loop().time() + AUTOCOMPLETE_TOTAL_DEADLINE_SECONDSwhile current_attemp < MAX_AUTO_COMPLETE_ATTEMP:current_attemp += 1@@ -6150,9 +6496,9 @@ async def input_or_auto_complete_input(LOG.info("Try the potential value for auto completion",sampling=True,- input_value=current_value,+ attempt=current_attemp,+ input_length=len(current_value),)- is_location = input_or_select_context.is_location_input or Falseresult = await choose_auto_completion_dropdown(context=input_or_select_context,page=page,@@ -6164,19 +6510,30 @@ async def input_or_auto_complete_input(step=step,task=task,is_location_input=is_location,+ commit_required=commit_required,+ verify_commit=verify_commit,collapse_autocomplete_fanout_enabled=collapse_autocomplete_fanout_enabled,action=action,+ poll_deadline=poll_deadline,)if isinstance(result.action_result, ActionSuccess):return ActionSuccess()+ attempt_trail.append(f"attempt_{len(attempt_trail) + 1}:{result.stage_outcome or 'suggestion_not_matched'}")if input_or_select_context.is_search_bar:+ # commit_required is derived with `and not is_search_bar`, so it is always False here;+ # search bars keep their documented fall-through.LOG.info("Stop generating potential values for the auto-completion since it's a search bar",context=input_or_select_context,)return None+ if result.committed_side_effects:+ return _autocomplete_side_effect_terminal(+ commit_required=commit_required, attempt_trail=attempt_trail, element_id=skyvern_element.get_id()+ )+tried_values.append(current_value)whole_new_elements.extend(result.incremental_elements)@@ -6198,7 +6555,7 @@ async def input_or_auto_complete_input(LOG.info("Ask LLM to give potential values based on the current value",- current_value=current_value,+ input_length=len(current_value),potential_value_count=AUTO_COMPLETION_POTENTIAL_VALUES_COUNT,)if collapse_autocomplete_fanout_enabled and action is not None:@@ -6213,13 +6570,14 @@ async def input_or_auto_complete_input(if not value:LOG.info("Empty potential value, skip this attempt",- value=each_value,+ attempt=current_attemp,)continueLOG.info("Try the potential value for auto completion",sampling=True,- input_value=value,+ attempt=current_attemp,+ input_length=len(value),)result = await choose_auto_completion_dropdown(context=input_or_select_context,@@ -6232,11 +6590,20 @@ async def input_or_auto_complete_input(step=step,task=task,is_location_input=is_location,+ commit_required=commit_required,+ verify_commit=verify_commit,collapse_autocomplete_fanout_enabled=collapse_autocomplete_fanout_enabled,action=action,+ poll_deadline=poll_deadline,)if isinstance(result.action_result, ActionSuccess):return ActionSuccess()+ attempt_trail.append(f"attempt_{len(attempt_trail) + 1}:{result.stage_outcome or 'suggestion_not_matched'}")++ if result.committed_side_effects:+ return _autocomplete_side_effect_terminal(+ commit_required=commit_required, attempt_trail=attempt_trail, element_id=skyvern_element.get_id()+ )tried_values.append(value)whole_new_elements.extend(result.incremental_elements)@@ -6245,8 +6612,8 @@ async def input_or_auto_complete_input(if current_attemp < MAX_AUTO_COMPLETE_ATTEMP:LOG.info("Ask LLM to tweak the current value based on tried input values",- current_value=current_value,current_attemp=current_attemp,+ input_length=len(current_value),)cleaned_new_elements = remove_duplicated_HTML_element(whole_new_elements)prompt = prompt_engine.load_prompt(@@ -6265,12 +6632,15 @@ async def input_or_auto_complete_input(context_reasoning = json_respone.get("reasoning")new_current_value = json_respone.get("tweaked_value", "")if not new_current_value:+ if commit_required:+ stage = result.stage_outcome or "suggestion_not_matched"+ return ActionFailure(AutoCompletionCommitFailure(stage=stage, attempt_trail=attempt_trail))return ActionFailure(ErrEmptyTweakValue(reasoning=context_reasoning, current_value=current_value))LOG.info("Ask LLM tweaked the current value with a new value",field_information=input_or_select_context.field,- current_value=current_value,- new_value=new_current_value,+ previous_length=len(current_value),+ new_length=len(new_current_value),)current_value = new_current_value@@ -6279,26 +6649,38 @@ async def input_or_auto_complete_input(LOG.info("Auto completion attempts exhausted, trying discover-all-options fallback",element_id=skyvern_element.get_id(),- original_text=text,- )- fallback_result = await discover_and_select_from_full_dropdown(- context=input_or_select_context,- page=page,- scraped_page=scraped_page,- dom=dom,- original_text=text,- skyvern_element=skyvern_element,- step=step,- task=task,+ input_length=len(text),)- if fallback_result is not None:- return fallback_result+ try:+ fallback_result = await discover_and_select_from_full_dropdown(+ context=input_or_select_context,+ page=page,+ scraped_page=scraped_page,+ dom=dom,+ original_text=text,+ skyvern_element=skyvern_element,+ step=step,+ task=task,+ commit_required=commit_required,+ verify_commit=verify_commit,+ )+ except AutoCompletionCommitFailure as fallback_failure:+ fallback_stage = fallback_failure.stage+ else:+ if isinstance(fallback_result, ActionSuccess):+ return fallback_result+ fallback_stage = "suggestion_not_matched"+ attempt_trail.append(f"attempt_{len(attempt_trail) + 1}:{fallback_stage}")LOG.info("Auto completion didn't finish, this might leave the input value to be empty.",sampling=True,context=input_or_select_context,+ attempt_trail=attempt_trail,)+ if commit_required:+ final_stage = attempt_trail[-1].split(":", 1)[1] if attempt_trail else "suggestion_not_matched"+ return ActionFailure(AutoCompletionCommitFailure(stage=final_stage, attempt_trail=attempt_trail))return None@@ -6313,6 +6695,8 @@ async def discover_and_select_from_full_dropdown(step: Step,task: Task,relevance_threshold: float = 0.6,+ commit_required: bool = False,+ verify_commit: bool = True,) -> ActionResult | None:"""Fallback for auto-completion: clear input, click/ArrowDown to reveal all options,then ask LLM to pick the best semantic match from actual dropdown values."""@@ -6421,7 +6805,7 @@ async def discover_and_select_from_full_dropdown(LOG.info("Discover fallback: asking LLM to pick from actual options",element_id=skyvern_element.get_id(),- original_text=original_text,+ input_length=len(original_text),)json_response = await app.AUTO_COMPLETION_LLM_API_HANDLER(prompt=prompt, step=step, prompt_name="auto-completion-choose-option"@@ -6444,7 +6828,7 @@ async def discover_and_select_from_full_dropdown("Discover fallback: found suitable option, typing discovered value to trigger auto-completion",element_id=element_id,relevance_float=relevance_float,- discovered_value=discovered_value,+ discovered_value_length=len(discovered_value),)if not discovered_value:@@ -6465,24 +6849,48 @@ async def discover_and_select_from_full_dropdown(try:await skyvern_element.press_key("ArrowDown")await skyvern_element.press_key("Enter")- LOG.info(- "Discover fallback: selected option via keyboard",- discovered_value=discovered_value,- )- return ActionSuccess()+ # This path fills the field with the option text itself, so a widget that commits that text+ # verbatim reads back identical to the fill and the value alone proves nothing. aria-expanded+ # is the tiebreak: closed means Enter took, open means it did not. A widget that exposes no+ # expanded state at all - the shadow-DOM case this fallback exists for - leaves the verbatim+ # read-back as the only evidence there is, so accept it rather than fail a committed field.+ if verify_commit:+ suggestions_closed = await _autocomplete_input_reports_closed(skyvern_element)+ commit_outcome = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_element,+ matched_label=discovered_value,+ typed_prefix=discovered_value,+ pre_action_value=discovered_value,+ suggestions_closed=suggestions_closed,+ allow_unchanged_value=suggestions_closed is None,+ commit_required=commit_required,+ )+ else:+ commit_outcome = AutocompleteCommitOutcome(committed=True)+ if commit_outcome.committed:+ LOG.info(+ "Discover fallback: selected option via keyboard",+ element_id=skyvern_element.get_id(),+ )+ return ActionSuccess()+ raise AutoCompletionCommitFailure(stage="clicked_but_not_committed")+ except AutoCompletionCommitFailure:+ raiseexcept Exception:LOG.info("Discover fallback: keyboard selection failed",+ discovered_value_length=len(discovered_value),exc_info=True,- discovered_value=discovered_value,)return None+ except AutoCompletionCommitFailure:+ raiseexcept Exception:LOG.warning("Discover fallback failed",+ input_length=len(original_text),exc_info=True,- original_text=original_text,)return Nonefinally:diff --git a/tests/unit/test_auto_completion_discover_fallback.py b/tests/unit/test_auto_completion_discover_fallback.pyindex bc7a8bc1e..3126078f6 100644--- a/tests/unit/test_auto_completion_discover_fallback.py+++ b/tests/unit/test_auto_completion_discover_fallback.py@@ -13,6 +13,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from skyvern.exceptions import AutoCompletionCommitFailurefrom skyvern.forge.sdk.models import StepStatusfrom skyvern.webeye.actions.actions import InputOrSelectContextfrom skyvern.webeye.actions.handler import (@@ -70,7 +71,10 @@ def _mock_skyvern_element(frame: MagicMock | None = None) -> MagicMock:# get_locator().click() needs to be async for the discover fallback's click callmock_locator = MagicMock()mock_locator.click = AsyncMock()+ mock_locator.input_value = AsyncMock(return_value="I do not wish to disclose")el.get_locator.return_value = mock_locator+ el.get_tag_name.return_value = "input"+ el.get_attr = AsyncMock(return_value="false")return el@@ -95,6 +99,7 @@ def _mock_incremental_scrape(elements: list[dict]) -> MagicMock:inc = MagicMock()inc.start_listen_dom_increment = AsyncMock()inc.stop_listen_dom_increment = AsyncMock()+ inc.get_incremental_elements_num = AsyncMock(return_value=len(elements))inc.get_incremental_element_tree = AsyncMock(return_value=copy.deepcopy(elements))inc.build_html_tree.return_value = "<div>mocked options</div>"inc.id_to_element_dict = {e["id"]: e for e in elements}@@ -165,6 +170,260 @@ async def test_discover_fallback_succeeds_when_options_appear() -> None:inc_scrape.stop_listen_dom_increment.assert_awaited()+async def test_discover_fallback_noop_keyboard_selection_is_not_a_commit() -> None:+ """The input still holding the fallback's own fill with the listbox open is not commit evidence."""+ frame = _mock_frame(locator_count=1)+ skyvern_el = _mock_skyvern_element(frame)+ skyvern_el.get_attr = AsyncMock(return_value="true")+ inc_scrape = _mock_incremental_scrape(DROPDOWN_OPTIONS)++ llm_response = {+ "auto_completion_attempt": True,+ "relevance_float": 0.9,+ "id": "OPT3",+ "value": "I do not wish to disclose",+ "reasoning": "'I do not wish to disclose' matches 'Decline to Self Identify'",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ return_value=inc_scrape,+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ with pytest.raises(AutoCompletionCommitFailure) as exc_info:+ await discover_and_select_from_full_dropdown(+ context=_make_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ original_text="Decline to Self Identify",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert exc_info.value.stage == "clicked_but_not_committed"+ inc_scrape.stop_listen_dom_increment.assert_awaited()+++async def test_discover_fallback_assumes_commit_when_verification_disabled() -> None:+ """Flag off: the keyboard selection is assumed committed - same scenario the noop test above+ rejects with verification enabled."""+ frame = _mock_frame(locator_count=1)+ skyvern_el = _mock_skyvern_element(frame)+ skyvern_el.get_attr = AsyncMock(return_value="true")+ inc_scrape = _mock_incremental_scrape(DROPDOWN_OPTIONS)++ llm_response = {+ "auto_completion_attempt": True,+ "relevance_float": 0.9,+ "id": "OPT3",+ "value": "I do not wish to disclose",+ "reasoning": "'I do not wish to disclose' matches 'Decline to Self Identify'",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ return_value=inc_scrape,+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await discover_and_select_from_full_dropdown(+ context=_make_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ original_text="Decline to Self Identify",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ verify_commit=False,+ )++ assert isinstance(result, ActionSuccess)+ inc_scrape.stop_listen_dom_increment.assert_awaited()+++async def test_discover_fallback_canonicalized_commit_succeeds() -> None:+ """A widget that expands the committed value beyond the fallback's own fill counts as a commit."""+ frame = _mock_frame(locator_count=1)+ skyvern_el = _mock_skyvern_element(frame)+ skyvern_el.get_attr = AsyncMock(return_value=None)+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value="I do not wish to disclose (private)")+ inc_scrape = _mock_incremental_scrape(DROPDOWN_OPTIONS)++ llm_response = {+ "auto_completion_attempt": True,+ "relevance_float": 0.9,+ "id": "OPT3",+ "value": "I do not wish to disclose",+ "reasoning": "Best semantic match",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ return_value=inc_scrape,+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await discover_and_select_from_full_dropdown(+ context=_make_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ original_text="Decline to Self Identify",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert isinstance(result, ActionSuccess)+++async def test_discover_fallback_exact_echo_without_expanded_state_is_a_commit() -> None:+ """A widget that commits the option text verbatim and exposes no expanded state is a commit, not a failure."""+ frame = _mock_frame(locator_count=1)+ skyvern_el = _mock_skyvern_element(frame)+ # No aria-expanded at all: the widget gives no open/closed signal, and the committed value is the+ # option text verbatim, so it is indistinguishable from the fallback's own fill by value alone.+ skyvern_el.get_attr = AsyncMock(return_value=None)+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value="I do not wish to disclose")+ inc_scrape = _mock_incremental_scrape(DROPDOWN_OPTIONS)++ llm_response = {+ "auto_completion_attempt": True,+ "relevance_float": 0.9,+ "id": "OPT3",+ "value": "I do not wish to disclose",+ "reasoning": "Best semantic match",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ return_value=inc_scrape,+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await discover_and_select_from_full_dropdown(+ context=_make_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ original_text="Decline to Self Identify",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert isinstance(result, ActionSuccess)+++async def test_discover_fallback_ignores_stale_cached_expanded_state() -> None:+ """A no-op Enter must not read as committed just because the element was scraped before the+ dropdown opened. get_attr is static-first, so the cached aria-expanded="false" from that scrape+ would otherwise stand in as commit evidence for an unchanged value."""+ frame = _mock_frame(locator_count=1)+ skyvern_el = _mock_skyvern_element(frame)+ # Behaves like the real SkyvernElement.get_attr: static cache says "false" (scraped while closed),+ # the live DOM says "true" (the listbox is still open, so Enter did nothing).+ static_attrs = {"aria-expanded": "false"}+ live_attrs = {"aria-expanded": "true"}++ async def _get_attr(name: str, mode: str = "auto", **_kwargs: object) -> object:+ if mode == "dynamic":+ return live_attrs.get(name)+ cached = static_attrs.get(name)+ return cached if cached is not None or mode == "static" else live_attrs.get(name)++ skyvern_el.get_attr = AsyncMock(side_effect=_get_attr)+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value="I do not wish to disclose")+ inc_scrape = _mock_incremental_scrape(DROPDOWN_OPTIONS)++ llm_response = {+ "auto_completion_attempt": True,+ "relevance_float": 0.9,+ "id": "OPT3",+ "value": "I do not wish to disclose",+ "reasoning": "Best semantic match",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc_scrape),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ with pytest.raises(AutoCompletionCommitFailure):+ await discover_and_select_from_full_dropdown(+ context=_make_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ original_text="Decline to Self Identify",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++@pytest.mark.asyncioasync def test_discover_fallback_returns_none_when_no_options() -> None:"""ArrowDown produces no incremental elements → returns None."""@@ -612,7 +871,7 @@ async def test_input_or_auto_complete_skips_discover_for_search_bar() -> None:mock_prompt.load_prompt.return_value = "mocked prompt"mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)- # Note: search bars bail out early at L2989 (before potential_values),+ # Search bars fall through to plain typing (None) instead of hard-failing,# so discover_fallback is never reached. This test verifies that.result = await input_or_auto_complete_input(input_or_select_context=_make_context(is_search_bar=True),@@ -625,6 +884,225 @@ async def test_input_or_auto_complete_skips_discover_for_search_bar() -> None:task=_TASK,)- # Search bar returns None early, never reaching discover fallbackassert result is Nonemock_discover.assert_not_called()+++async def test_input_or_auto_complete_failure_includes_attempt_trail() -> None:+ """A location field with the commit-required flag on returns a typed failure with the attempt trail."""+ skyvern_el = _mock_skyvern_element()+ choose_result = AutoCompletionResult(+ action_result=ActionFailure(AutoCompletionCommitFailure(stage="suggestions_never_rendered")),+ stage_outcome="suggestions_never_rendered",+ )++ with (+ patch(+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=choose_result),+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch(+ "skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown",+ new=AsyncMock(return_value=None),+ ),+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=True)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await input_or_auto_complete_input(+ input_or_select_context=_make_context(is_location_input=True),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="private value",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert isinstance(result, ActionFailure)+ assert result.exception_type == AutoCompletionCommitFailure.__name__+ assert result.exception_message is not None+ assert "attempt_1:suggestions_never_rendered" in result.exception_message+ assert "attempt_2:suggestion_not_matched" in result.exception_message+ assert "private value" not in result.exception_message+++def _side_effect_choose_result() -> AutoCompletionResult:+ return AutoCompletionResult(+ action_result=ActionFailure(AutoCompletionCommitFailure(stage="clicked_but_not_committed")),+ stage_outcome="clicked_but_not_committed",+ committed_side_effects=True,+ )+++async def test_side_effectful_click_stops_retrying_with_flag_on() -> None:+ """Once a click has mutated the field but could not be verified, the orchestration loop must+ stop instead of generating more values and clicking additional options on the dirty field."""+ skyvern_el = _mock_skyvern_element()+ choose_mock = AsyncMock(return_value=_side_effect_choose_result())+ discover_mock = AsyncMock(return_value=ActionSuccess())++ with (+ patch("skyvern.webeye.actions.handler.choose_auto_completion_dropdown", new=choose_mock),+ patch("skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown", new=discover_mock),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=True)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await input_or_auto_complete_input(+ input_or_select_context=_make_context(is_location_input=True),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="private value",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert choose_mock.call_count == 1+ discover_mock.assert_not_called()+ mock_app.SECONDARY_LLM_API_HANDLER.assert_not_called()+ assert isinstance(result, ActionFailure)+ assert result.exception_type == AutoCompletionCommitFailure.__name__+ assert "clicked_but_not_committed" in (result.exception_message or "")+++async def test_side_effectful_click_stops_retrying_with_flag_off() -> None:+ """With the flag off the loop still stops after a side-effectful click (returning None to fall+ through to plain typing) rather than clicking more options on the mutated field."""+ skyvern_el = _mock_skyvern_element()+ choose_mock = AsyncMock(return_value=_side_effect_choose_result())+ discover_mock = AsyncMock(return_value=ActionSuccess())++ with (+ patch("skyvern.webeye.actions.handler.choose_auto_completion_dropdown", new=choose_mock),+ patch("skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown", new=discover_mock),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await input_or_auto_complete_input(+ input_or_select_context=_make_context(is_location_input=True),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="private value",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert choose_mock.call_count == 1+ discover_mock.assert_not_called()+ assert result is None+++async def test_input_or_auto_complete_falls_through_when_flag_disabled() -> None:+ """With the commit-required flag off, an exhausted location autocomplete falls through to plain typing."""+ skyvern_el = _mock_skyvern_element()+ choose_result = AutoCompletionResult(+ action_result=ActionFailure(AutoCompletionCommitFailure(stage="suggestions_never_rendered")),+ stage_outcome="suggestions_never_rendered",+ )++ with (+ patch(+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=choose_result),+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch(+ "skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown",+ new=AsyncMock(return_value=None),+ ),+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await input_or_auto_complete_input(+ input_or_select_context=_make_context(is_location_input=True),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="private value",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert result is None+++async def test_fallback_stage_is_read_structurally_not_from_message_text() -> None:+ """The fallback stage comes from the exception's stage attribute, even when the+ message's attempt trail embeds every other stage name ahead of it."""+ skyvern_el = _mock_skyvern_element()+ choose_result = AutoCompletionResult(+ action_result=ActionFailure(AutoCompletionCommitFailure(stage="suggestions_never_rendered")),+ stage_outcome="suggestions_never_rendered",+ )+ fallback_failure = AutoCompletionCommitFailure(+ stage="clicked_but_not_committed",+ attempt_trail=["attempt_1:suggestions_never_rendered", "attempt_2:suggestion_not_matched"],+ )+ assert "suggestions_never_rendered" in str(fallback_failure)++ with (+ patch(+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=choose_result),+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch(+ "skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown",+ new=AsyncMock(side_effect=fallback_failure),+ ),+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=True)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await input_or_auto_complete_input(+ input_or_select_context=_make_context(is_location_input=True),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="private value",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert isinstance(result, ActionFailure)+ assert result.exception_type == AutoCompletionCommitFailure.__name__+ assert "attempt_2:clicked_but_not_committed" in (result.exception_message or "")+ assert "stage=clicked_but_not_committed" in (result.exception_message or "")diff --git a/tests/unit/test_auto_completion_location.py b/tests/unit/test_auto_completion_location.pyindex f33020687..778594980 100644--- a/tests/unit/test_auto_completion_location.py+++ b/tests/unit/test_auto_completion_location.py@@ -6,23 +6,27 @@ suggestion appears, we skip the LLM call and click the suggestion directly.from __future__ import annotations+import asyncioimport copyfrom datetime import UTC, datetimefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+import skyvern.webeye.actions.handler as handler_modulefrom skyvern.constants import SKYVERN_ID_ATTR-from skyvern.exceptions import NoIncrementalElementFoundForAutoCompletion+from skyvern.exceptions import AutoCompletionCommitFailure, MissingElement, NoIncrementalElementFoundForAutoCompletionfrom skyvern.forge.sdk.models import StepStatusfrom skyvern.webeye.actions.actions import InputOrSelectContextfrom skyvern.webeye.actions.handler import (AutoCompletionResult,+ _poll_autocomplete_incremental_elements,_reset_autocomplete_for_llm_fallback,+ _verify_autocomplete_input_readback,choose_auto_completion_dropdown,input_or_auto_complete_input,)-from skyvern.webeye.actions.responses import ActionSuccess+from skyvern.webeye.actions.responses import ActionFailure, ActionSuccessfrom tests.unit.helpers import make_organization, make_step, make_task# ---------------------------------------------------------------------------@@ -34,11 +38,15 @@ _ORG = make_organization(_NOW)_TASK = make_task(_NOW, _ORG, navigation_payload={"address": "123 Main St"})_STEP = make_step(_NOW, _TASK, step_id="stp-1", status=StepStatus.created, order=0, output=None)-SINGLE_ELEMENT = [{"id": "AAAA", "tag": "div", "text": "123 Main St, Springfield, IL"}]+SINGLE_ELEMENT = [+ {"id": "AAAA", "tagName": "li", "attributes": {"role": "option"}, "text": "123 Main St, Springfield, IL"}+]MULTI_ELEMENTS = [- {"id": "AAAA", "tag": "div", "text": "123 Main St, Springfield, IL"},- {"id": "AAAB", "tag": "div", "text": "123 Main St, Springfield, MO"},+ {"id": "AAAA", "tagName": "li", "attributes": {"role": "option"}, "text": "123 Main St, Springfield, IL"},+ {"id": "AAAB", "tagName": "li", "attributes": {"role": "option"}, "text": "123 Main St, Springfield, MO"},]+LOADING_ELEMENT = {"id": "LOAD", "tagName": "div", "text": "Loading..."}+OPTION_ELEMENT = {"id": "OPT", "tagName": "li", "attributes": {"role": "option"}, "text": "123 Main St, Springfield"}def _make_location_context(**overrides: object) -> InputOrSelectContext:@@ -72,75 +80,763 @@ def _mock_skyvern_element(frame: MagicMock | None = None) -> MagicMock:el.input_clear = AsyncMock()el.is_visible = AsyncMock(return_value=True)el.get_element_handler = AsyncMock(return_value=MagicMock())+ el.get_tag_name.return_value = "input"+ el.press_key = AsyncMock()+ el.get_attr = AsyncMock(return_value=None)+ input_locator = MagicMock()+ input_locator.input_value = AsyncMock(return_value="123 Main St, Springfield, IL")+ el.get_locator.return_value = input_locatorreturn el-def _mock_frame(locator_count: int = 1) -> MagicMock:- """Return a mock Playwright Frame with a configurable locator."""- frame = MagicMock()- locator = MagicMock()- locator.count = AsyncMock(return_value=locator_count)- locator.click = AsyncMock()- frame.locator.return_value = locator- return frame+def _mock_frame(locator_count: int = 1) -> MagicMock:+ """Return a mock Playwright Frame with a configurable locator."""+ frame = MagicMock()+ locator = MagicMock()+ locator.count = AsyncMock(return_value=locator_count)+ locator.click = AsyncMock()+ locator.element_handle = AsyncMock(return_value=MagicMock())+ locator.is_visible = AsyncMock(return_value=True)+ locator.get_attribute = AsyncMock(return_value=None)+ frame.locator.return_value = locator+ return frame+++def _mock_incremental_scrape(elements: list[dict]) -> MagicMock:+ """Return a mock IncrementalScrapePage that yields *elements*."""+ inc = MagicMock()+ inc.start_listen_dom_increment = AsyncMock()+ inc.stop_listen_dom_increment = AsyncMock()+ inc.get_incremental_elements_num = AsyncMock(return_value=len(elements))+ inc.get_incremental_element_tree = AsyncMock(return_value=copy.deepcopy(elements))+ inc.build_html_tree.return_value = "<div>mocked</div>"+ return inc+++class _FakeSuggestionList:+ """Stateful listbox fake: each patched sleep advances the rendered frame."""++ def __init__(self, frames: list[list[dict]]) -> None:+ self._frames = frames+ self._tick = 0++ def _current(self) -> list[dict]:+ return self._frames[min(self._tick, len(self._frames) - 1)]++ async def advance(self, _delay: float) -> None:+ self._tick += 1++ def scrape(self) -> MagicMock:+ inc = MagicMock()+ inc.start_listen_dom_increment = AsyncMock()+ inc.stop_listen_dom_increment = AsyncMock()+ inc.get_incremental_elements_num = AsyncMock(side_effect=lambda: len(self._current()))+ inc.get_incremental_element_tree = AsyncMock(side_effect=lambda _cleanup: copy.deepcopy(self._current()))+ inc.build_html_tree.return_value = "<div>mocked</div>"+ return inc+++def test_auto_completion_result_does_not_default_to_success() -> None:+ assert AutoCompletionResult().action_result is None+++def test_removed_autocomplete_exception_name_still_catchable() -> None:+ """The deprecated OSS alias must keep downstream `except` clauses working for one release."""+ with pytest.raises(NoIncrementalElementFoundForAutoCompletion):+ raise AutoCompletionCommitFailure(stage="suggestion_not_matched")+++ ("actual_value", "matched_label", "typed_prefix", "expected"),+ [+ ("123 MAIN ST., Springfield!", "123 Main St Springfield", "123 Main", True),+ ("Selected: 123 Main St, Springfield", "123 Main St Springfield", "123 Main", True),+ ("123 Main", "123 Main St Springfield", "123 Main", False),+ ("scala 5", "ca", "sc", False),+ ("123 Main St Springfield", "123 Main St, Springfield, USA", "123 Main", True),+ ],+)+async def test_autocomplete_readback_matches_on_token_boundaries(+ actual_value: str,+ matched_label: str,+ typed_prefix: str,+ expected: bool,+) -> None:+ skyvern_el = _mock_skyvern_element()+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value=actual_value)++ outcome = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label=matched_label,+ typed_prefix=typed_prefix,+ )+ assert outcome.committed is expected+++async def test_autocomplete_readback_rejects_lone_token_of_multiword_label() -> None:+ # A single token of a multi-word label (here "Springfield" of "123 Main St Springfield") no longer+ # identifies the selection, even though the value changed - the field must still cover a substantial+ # share of the label. Substantial truncation ("123 Main St" of the same label) stays a commit.+ lone_token = _mock_skyvern_element()+ lone_token.get_locator.return_value.input_value = AsyncMock(return_value="Springfield")+ weak = await _verify_autocomplete_input_readback(+ skyvern_element=lone_token,+ matched_label="123 Main St Springfield",+ typed_prefix="123 Main",+ )+ assert weak.committed is False++ substantial = _mock_skyvern_element()+ substantial.get_locator.return_value.input_value = AsyncMock(return_value="123 Main St")+ strong = await _verify_autocomplete_input_readback(+ skyvern_element=substantial,+ matched_label="123 Main St Springfield",+ typed_prefix="123",+ )+ assert strong.committed is True+++async def test_autocomplete_readback_requires_secondary_signal_when_label_equals_typed_text() -> None:+ skyvern_el = _mock_skyvern_element()+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value="Oakland, California")++ no_signal = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland, California",+ )+ assert no_signal.committed is False+ assert no_signal.side_effects_observed is False++ list_closed = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland, California",+ suggestions_closed=True,+ )+ assert list_closed.committed is True++ aria_selected = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland, California",+ selection_state_present=True,+ )+ assert aria_selected.committed is True+++async def test_autocomplete_readback_accepts_cleared_input_only_when_list_closed() -> None:+ skyvern_el = _mock_skyvern_element()+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value="")++ chip_commit = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland",+ suggestions_closed=True,+ )+ assert chip_commit.committed is True++ still_open = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland",+ )+ assert still_open.committed is False+++async def test_autocomplete_readback_empty_value_needs_selection_signal_when_commit_required() -> None:+ # A click that dismisses the suggestions while clearing the field reads back identical to a chip+ # commit; under commit-required only an affirmative selection signal separates the two.+ skyvern_el = _mock_skyvern_element()+ skyvern_el.get_locator.return_value.input_value = AsyncMock(return_value="")++ dismissal = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland",+ suggestions_closed=True,+ commit_required=True,+ )+ assert dismissal.committed is False++ affirmed = await _verify_autocomplete_input_readback(+ skyvern_element=skyvern_el,+ matched_label="Oakland, California",+ typed_prefix="Oakland",+ suggestions_closed=True,+ selection_state_present=True,+ commit_required=True,+ )+ assert affirmed.committed is True+++async def test_autocomplete_poll_returns_immediately_when_suggestions_exist() -> None:+ fake_list = _FakeSuggestionList([SINGLE_ELEMENT])+ incremental_scrape = fake_list.scrape()++ with patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock(side_effect=fake_list.advance)) as sleep:+ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert result == SINGLE_ELEMENT+ sleep.assert_not_awaited()+++async def test_autocomplete_poll_waits_until_suggestions_render() -> None:+ fake_list = _FakeSuggestionList([[], [], SINGLE_ELEMENT])+ incremental_scrape = fake_list.scrape()++ with patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock(side_effect=fake_list.advance)) as sleep:+ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert result == SINGLE_ELEMENT+ assert sleep.await_count == 2+++async def test_autocomplete_poll_keeps_waiting_past_loading_nodes_until_options_render() -> None:+ fake_list = _FakeSuggestionList([[LOADING_ELEMENT], [LOADING_ELEMENT], [LOADING_ELEMENT, OPTION_ELEMENT]])+ incremental_scrape = fake_list.scrape()++ with patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock(side_effect=fake_list.advance)):+ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert OPTION_ELEMENT in result+++async def test_autocomplete_poll_reextracts_when_placeholder_replaced_in_place() -> None:+ # A listbox can swap a loading placeholder for an option in the same node, so the incremental+ # count stays constant (1 -> 1). A count-delta guard would extract the placeholder once and never+ # re-extract, missing the rendered option.+ fake_list = _FakeSuggestionList([[LOADING_ELEMENT], [OPTION_ELEMENT]])+ incremental_scrape = fake_list.scrape()++ with patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock(side_effect=fake_list.advance)):+ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert OPTION_ELEMENT in result+++async def test_autocomplete_poll_is_bounded_when_suggestions_never_render() -> None:+ fake_list = _FakeSuggestionList([[]])+ incremental_scrape = fake_list.scrape()++ with patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock(side_effect=fake_list.advance)) as sleep:+ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert result == []+ incremental_scrape.get_incremental_element_tree.assert_not_awaited()+ assert sleep.await_count <= handler_module.AUTOCOMPLETE_POLL_MAX_ATTEMPTS+++async def test_autocomplete_poll_does_not_cancel_slow_extraction(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(handler_module, "AUTOCOMPLETE_POLL_INTERVAL_SECONDS", 0.05)+ incremental_scrape = MagicMock()+ incremental_scrape.get_incremental_elements_num = AsyncMock(return_value=1)++ async def _slow_extract(_cleanup: object) -> list[dict]:+ await asyncio.sleep(0.2)+ return copy.deepcopy(SINGLE_ELEMENT)++ incremental_scrape.get_incremental_element_tree = AsyncMock(side_effect=_slow_extract)++ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert result == SINGLE_ELEMENT+ assert incremental_scrape.get_incremental_element_tree.await_count == 1+++async def test_autocomplete_poll_bounds_a_hanging_probe(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(handler_module, "AUTOCOMPLETE_POLL_INTERVAL_SECONDS", 0.02)+ monkeypatch.setattr(handler_module, "AUTOCOMPLETE_POLL_MAX_ATTEMPTS", 2)+ incremental_scrape = MagicMock()++ async def _hanging_probe() -> int:+ await asyncio.sleep(10)+ return 1++ incremental_scrape.get_incremental_elements_num = AsyncMock(side_effect=_hanging_probe)+ incremental_scrape.get_incremental_element_tree = AsyncMock(return_value=copy.deepcopy(SINGLE_ELEMENT))++ result = await _poll_autocomplete_incremental_elements(+ incremental_scraped=incremental_scrape,+ cleanup_factory=MagicMock(),+ )++ assert result == []+ incremental_scrape.get_incremental_element_tree.assert_not_awaited()+++async def test_autocomplete_timeout_reports_suggestions_never_rendered() -> None:+ skyvern_el = _mock_skyvern_element()+ incremental_scrape = _mock_incremental_scrape([])+ scraped_page = MagicMock(id_to_css_dict={})+ scraped_after_open = MagicMock(id_to_css_dict={})+ scraped_page.generate_scraped_page_without_screenshots = AsyncMock(return_value=scraped_after_open)++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock()),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=incremental_scrape),+ patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock()),+ ):+ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=scraped_page,+ dom=MagicMock(),+ text="123 Main",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ )++ assert isinstance(result.action_result, ActionFailure)+ assert result.action_result.exception_type == AutoCompletionCommitFailure.__name__+ assert "suggestions_never_rendered" in (result.action_result.exception_message or "")+++# ---------------------------------------------------------------------------+# Tests for choose_auto_completion_dropdown+# ---------------------------------------------------------------------------+++async def test_location_single_option_skips_llm() -> None:+ """When is_location_input=True and exactly 1 option appears, the LLM must NOT be called."""+ frame = _mock_frame(locator_count=1)+ skyvern_el = _mock_skyvern_element(frame)+ inc_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ return_value=inc_scrape,+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock()++ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="123 Main St",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ )++ # The LLM should never have been called+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_not_called()++ # The locator should have been clicked+ frame.locator.assert_called_with(f'[{SKYVERN_ID_ATTR}="AAAA"]')+ frame.locator.return_value.click.assert_awaited_once()++ # Result should indicate success+ assert isinstance(result.action_result, ActionSuccess)+++async def test_location_single_option_click_with_side_effects_does_not_refire() -> None:+ """A click that changed the value (but did not match) must hard-fail instead of re-firing."""+ frame, option_locator, skyvern_el, skyvern_frame = _mock_autocomplete_input(+ selected_value="Wrong city",+ click_closes_listbox=False,+ )+ inc_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=skyvern_frame),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc_scrape),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock()++ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="123 Main",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ )++ option_locator.click.assert_awaited_once()+ skyvern_el.press_fill.assert_awaited_once()+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_not_called()+ assert isinstance(result.action_result, ActionFailure)+ assert result.action_result.exception_type == AutoCompletionCommitFailure.__name__+ assert "clicked_but_not_committed" in (result.action_result.exception_message or "")+++async def test_location_single_option_side_effect_free_noncommit_falls_back_to_llm() -> None:+ """A no-op click (value unchanged, listbox still open) resets and runs the LLM chooser in the same call."""+ _frame, option_locator, skyvern_el, skyvern_frame = _mock_autocomplete_input(+ selected_value="123 Main",+ click_closes_listbox=False,+ )+ events: list[str] = []+ skyvern_el.input_clear = AsyncMock(side_effect=lambda: events.append("clear"))+ skyvern_el.press_fill = AsyncMock(side_effect=lambda value: events.append(f"fill:{value}"))+ skyvern_el.press_key = AsyncMock()+ initial_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)+ initial_scrape.build_html_tree.return_value = "<div>stale options</div>"+ fallback_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)+ fallback_scrape.build_html_tree.return_value = "<div>fresh options</div>"++ llm_response = {+ "auto_completion_attempt": False,+ "relevance_float": 0.0,+ "id": "",+ "direct_searching": True,+ "value": "123 Main",+ "reasoning": "Read-back mismatch",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=skyvern_frame),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ side_effect=[initial_scrape, fallback_scrape],+ ) as scrape_factory,+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):++ async def _llm_handler(**_: object) -> dict[str, object]:+ events.append("llm")+ return llm_response++ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(side_effect=_llm_handler)+ mock_app.AGENT_FUNCTION = MagicMock()+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="123 Main",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ )++ option_locator.click.assert_awaited_once()+ assert scrape_factory.call_count == 2+ skyvern_el.input_clear.assert_awaited_once()+ assert skyvern_el.press_fill.await_count == 2+ assert events == ["fill:123 Main", "clear", "fill:123 Main", "llm"]+ assert mock_prompt.load_prompt.call_args.kwargs["elements"] == "<div>fresh options</div>"+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_awaited_once()+ skyvern_el.press_key.assert_awaited_once_with("Enter")+ assert isinstance(result.action_result, ActionSuccess)+++async def test_direct_searching_unchanged_value_fails_when_commit_required() -> None:+ """Searching with the typed text leaves the value unchanged, which is indistinguishable from Enter+ doing nothing. On a field that must commit a real suggestion that is a failure, not a success."""+ _frame, _option_locator, skyvern_el, skyvern_frame = _mock_autocomplete_input(+ selected_value="123 Main",+ click_closes_listbox=False,+ )+ skyvern_el.input_clear = AsyncMock()+ skyvern_el.press_fill = AsyncMock()+ skyvern_el.press_key = AsyncMock()+ initial_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)+ initial_scrape.build_html_tree.return_value = "<div>stale options</div>"+ fallback_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)+ fallback_scrape.build_html_tree.return_value = "<div>fresh options</div>"++ llm_response = {+ "auto_completion_attempt": False,+ "relevance_float": 0.0,+ "id": "",+ "direct_searching": True,+ "value": "123 Main",+ "reasoning": "Read-back mismatch",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=skyvern_frame),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ side_effect=[initial_scrape, fallback_scrape],+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_app.AGENT_FUNCTION = MagicMock()+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="123 Main",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ commit_required=True,+ )++ assert isinstance(result.action_result, ActionFailure)+ assert result.action_result.exception_type == AutoCompletionCommitFailure.__name__+ assert "clicked_but_not_committed" in (result.action_result.exception_message or "")+++async def test_unexpected_exception_surfaces_as_itself_not_commit_failure() -> None:+ """A genuine bug-shaped error keeps its identity in the ActionFailure instead of being+ rewrapped as an expected no-match commit failure."""+ skyvern_el = _mock_skyvern_element()+ skyvern_el.press_fill = AsyncMock(side_effect=MissingElement(element_id="AAAA"))+ inc_scrape = _mock_incremental_scrape([])++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock()),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc_scrape),+ ):+ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="123 Main",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ )++ assert isinstance(result.action_result, ActionFailure)+ assert result.action_result.exception_type == MissingElement.__name__+ assert result.stage_outcome == "suggestion_not_matched"+++async def test_commit_failure_keeps_its_stage_in_action_failure() -> None:+ """An AutoCompletionCommitFailure raised inside the dropdown flow keeps its own stage."""+ skyvern_el = _mock_skyvern_element()+ skyvern_el.press_fill = AsyncMock(side_effect=AutoCompletionCommitFailure(stage="suggestions_never_rendered"))+ inc_scrape = _mock_incremental_scrape([])++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock()),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc_scrape),+ ):+ result = await choose_auto_completion_dropdown(+ context=_make_location_context(),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="123 Main",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ is_location_input=True,+ )++ assert isinstance(result.action_result, ActionFailure)+ assert result.action_result.exception_type == AutoCompletionCommitFailure.__name__+ assert result.stage_outcome == "suggestions_never_rendered"++async def test_unexpected_exception_still_hard_fails_location_field_when_flag_on() -> None:+ """A preserved unexpected exception from the dropdown flow still produces the staged+ location failure when the commit-required flag is on."""+ skyvern_el = _mock_skyvern_element()+ choose_result = AutoCompletionResult(+ action_result=ActionFailure(MissingElement(element_id="AAAA")),+ stage_outcome="suggestion_not_matched",+ )-def _mock_incremental_scrape(elements: list[dict]) -> MagicMock:- """Return a mock IncrementalScrapePage that yields *elements*."""- inc = MagicMock()- inc.start_listen_dom_increment = AsyncMock()- inc.stop_listen_dom_increment = AsyncMock()- inc.get_incremental_element_tree = AsyncMock(return_value=copy.deepcopy(elements))- inc.build_html_tree.return_value = "<div>mocked</div>"- return inc+ with (+ patch(+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=choose_result),+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch(+ "skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown",+ new=AsyncMock(return_value=None),+ ),+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=True)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)+ result = await input_or_auto_complete_input(+ input_or_select_context=_make_location_context(),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="123 Main St",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )-# ----------------------------------------------------------------------------# Tests for choose_auto_completion_dropdown-# ---------------------------------------------------------------------------+ assert isinstance(result, ActionFailure)+ assert result.exception_type == AutoCompletionCommitFailure.__name__+ assert "attempt_1:suggestion_not_matched" in (result.exception_message or "")@pytest.mark.asyncio-async def test_location_single_option_skips_llm() -> None:- """When is_location_input=True and exactly 1 option appears, the LLM must NOT be called."""- frame = _mock_frame(locator_count=1)- skyvern_el = _mock_skyvern_element(frame)- inc_scrape = _mock_incremental_scrape(SINGLE_ELEMENT)+async def test_location_search_bar_keeps_fallthrough_even_with_flag_on() -> None:+ """A location-search widget is both a location input and a search bar. Search bars keep their+ documented fall-through, so strict commit mode must not claim one and hard-fail it."""+ skyvern_el = _mock_skyvern_element()+ choose_result = AutoCompletionResult(+ action_result=ActionFailure(MissingElement(element_id="AAAA")),+ stage_outcome="suggestion_not_matched",+ )with (patch(- "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",- new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=choose_result),),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,patch(- "skyvern.webeye.actions.handler.IncrementalScrapePage",- return_value=inc_scrape,+ "skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown",+ new=AsyncMock(return_value=None),),- patch("skyvern.webeye.actions.handler.app") as mock_app,):- mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock()+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=True)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)- result = await choose_auto_completion_dropdown(- context=_make_location_context(),- page=MagicMock(),+ result = await input_or_auto_complete_input(+ input_or_select_context=_make_location_context(is_search_bar=True),scraped_page=MagicMock(),+ page=MagicMock(),dom=MagicMock(),text="123 Main St",skyvern_element=skyvern_el,step=_STEP,task=_TASK,- is_location_input=True,)- # The LLM should never have been called- mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_not_called()+ assert not isinstance(result, ActionFailure)- # The locator should have been clicked- frame.locator.assert_called_with(f'[{SKYVERN_ID_ATTR}="AAAA"]')- frame.locator.return_value.click.assert_awaited_once()- # Result should indicate success- assert isinstance(result.action_result, ActionSuccess)+async def test_unexpected_exception_falls_through_to_plain_typing_when_flag_off() -> None:+ """With the commit-required flag off, a preserved unexpected exception still lets the+ location field fall through to plain typing."""+ skyvern_el = _mock_skyvern_element()+ choose_result = AutoCompletionResult(+ action_result=ActionFailure(MissingElement(element_id="AAAA")),+ stage_outcome="suggestion_not_matched",+ )++ with (+ patch(+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=choose_result),+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch(+ "skyvern.webeye.actions.handler.discover_and_select_from_full_dropdown",+ new=AsyncMock(return_value=None),+ ),+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ result = await input_or_auto_complete_input(+ input_or_select_context=_make_location_context(),+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="123 Main St",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ )++ assert result is None@pytest.mark.asyncio@@ -195,6 +891,7 @@ async def test_location_multiple_options_calls_llm() -> None:"direct_searching": False,"reasoning": "First option matches",}+ selected_element = MagicMock(scroll_into_view=AsyncMock(), click=AsyncMock())with (patch(@@ -208,13 +905,14 @@ async def test_location_multiple_options_calls_llm() -> None:patch("skyvern.webeye.actions.handler.app") as mock_app,patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch("skyvern.webeye.actions.handler.SkyvernElement", return_value=selected_element),):mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)mock_app.AGENT_FUNCTION = MagicMock()mock_prompt.load_prompt.return_value = "mocked prompt"mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)- await choose_auto_completion_dropdown(+ result = await choose_auto_completion_dropdown(context=_make_location_context(),page=MagicMock(),scraped_page=MagicMock(),@@ -228,6 +926,8 @@ async def test_location_multiple_options_calls_llm() -> None:# LLM should have been called because there are 2 optionsmock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_awaited_once()+ selected_element.click.assert_awaited_once()+ assert isinstance(result.action_result, ActionSuccess)@pytest.mark.asyncio@@ -420,12 +1120,44 @@ async def test_input_or_auto_complete_passes_false_for_non_location() -> None:assert call_kwargs["is_location_input"] is False[email protected]("flag_enabled", [True, False])+async def test_input_or_auto_complete_gates_verification_on_the_flag(flag_enabled: bool) -> None:+ """Commit verification runs only behind the flag; flag-off keeps the pre-verification behavior."""+ context = _make_location_context()++ with (+ patch(+ "skyvern.webeye.actions.handler.choose_auto_completion_dropdown",+ new=AsyncMock(return_value=AutoCompletionResult(action_result=ActionSuccess())),+ ) as mock_choose,+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=flag_enabled)++ result = await input_or_auto_complete_input(+ input_or_select_context=context,+ scraped_page=MagicMock(),+ page=MagicMock(),+ dom=MagicMock(),+ text="123 Main St",+ skyvern_element=_mock_skyvern_element(),+ step=_STEP,+ task=_TASK,+ )++ assert isinstance(result, ActionSuccess)+ call_kwargs = mock_choose.call_args.kwargs+ assert call_kwargs["verify_commit"] is flag_enabled+ assert call_kwargs["commit_required"] is flag_enabled++# ---------------------------------------------------------------------------# Integration tests: options that don't contain the input fall through to LLM# ----------------------------------------------------------------------------NO_RESULT_ELEMENTS = [{"id": "AAAA", "tag": "div", "text": "No results"}]-UNRELATED_ELEMENTS = [{"id": "AAAA", "tag": "div", "text": "Something completely different"}]+NO_RESULT_ELEMENTS = [{"id": "AAAA", "tagName": "div", "interactable": True, "text": "No results"}]+UNRELATED_ELEMENTS = [{"id": "AAAA", "tagName": "div", "interactable": True, "text": "Something completely different"}]DETERMINISTIC_ELEMENTS = [{"id": "AAAA", "tagName": "li", "attributes": {"role": "option"}, "text": "San Francisco, California"},{"id": "AAAB", "tagName": "li", "attributes": {"role": "option"}, "text": "Oakland, California"},@@ -440,12 +1172,20 @@ def _mock_autocomplete_input(*,selected_value: str,option_identity: dict[str, object] | None = None,+ click_closes_listbox: bool = True,) -> tuple[MagicMock, MagicMock, MagicMock, MagicMock]:frame = MagicMock()option_locator = MagicMock()option_locator.count = AsyncMock(return_value=1)option_locator.element_handle = AsyncMock(return_value=MagicMock())- option_locator.click = AsyncMock()+ option_locator.is_visible = AsyncMock(return_value=True)+ option_locator.get_attribute = AsyncMock(return_value=None)++ async def _click(**_: object) -> None:+ if click_closes_listbox:+ option_locator.count = AsyncMock(return_value=0)++ option_locator.click = AsyncMock(side_effect=_click)frame.locator.return_value = option_locatorinput_locator = MagicMock()@@ -475,6 +1215,7 @@ async def test_location_no_results_option_falls_through_to_llm() -> None:"relevance_float": 0.0,"id": "","direct_searching": True,+ "value": "123 Main St, Springfield, IL","reasoning": "No results shown",}@@ -651,6 +1392,7 @@ async def test_collapse_autocomplete_search_bar_exact_match_uses_llm() -> None:"relevance_float": 0.0,"id": "","direct_searching": True,+ "value": "Oakland, California","reasoning": "Search bars should direct search",}@@ -669,7 +1411,7 @@ async def test_collapse_autocomplete_search_bar_exact_match_uses_llm() -> None:mock_prompt.load_prompt.return_value = "mocked prompt"mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)- await choose_auto_completion_dropdown(+ result = await choose_auto_completion_dropdown(context=_make_non_location_context(field="Search", is_search_bar=True),page=MagicMock(),scraped_page=MagicMock(),@@ -684,6 +1426,7 @@ async def test_collapse_autocomplete_search_bar_exact_match_uses_llm() -> None:option_locator.click.assert_not_called()mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_awaited_once()skyvern_el.press_key.assert_awaited_once_with("Enter")+ assert isinstance(result.action_result, ActionSuccess)@pytest.mark.asyncio@@ -700,6 +1443,7 @@ async def test_collapse_autocomplete_ambiguous_exact_match_falls_back_to_llm() -"relevance_float": 0.0,"id": "","direct_searching": True,+ "value": "Oakland, California","reasoning": "Ambiguous duplicate labels",}@@ -758,6 +1502,7 @@ async def test_collapse_autocomplete_identity_mismatch_resets_before_llm() -> No"relevance_float": 0.0,"id": "","direct_searching": True,+ "value": "Oakland, California","reasoning": "Option rerendered",}@@ -809,10 +1554,11 @@ async def test_collapse_autocomplete_identity_mismatch_resets_before_llm() -> No@pytest.mark.asyncioasync def test_collapse_autocomplete_readback_mismatch_falls_back_to_llm() -> None:- """A deterministic click is not accepted when the input read-back is not the matched label."""+ """A no-op deterministic click (value unchanged, listbox open) is not accepted and resets before the LLM."""_frame, option_locator, skyvern_el, skyvern_frame_mock = _mock_autocomplete_input(- selected_value="Wrong city",+ selected_value="Oakland, California",option_identity={"index": 1, "label": "Oakland, California"},+ click_closes_listbox=False,)events: list[str] = []skyvern_el.input_clear = AsyncMock(side_effect=lambda: events.append("clear"))@@ -830,6 +1576,7 @@ async def test_collapse_autocomplete_readback_mismatch_falls_back_to_llm() -> No"relevance_float": 0.0,"id": "","direct_searching": True,+ "value": "Oakland, California","reasoning": "Read-back mismatch",}@@ -878,6 +1625,149 @@ async def test_collapse_autocomplete_readback_mismatch_falls_back_to_llm() -> Noskyvern_el.press_key.assert_awaited_once_with("Enter")+async def test_collapse_autocomplete_deterministic_path_verifies_even_when_flag_off() -> None:+ # The deterministic read-back is the one verify site that exists on main, so it stays on even at+ # flag-off: a click that leaves the value unchanged with the listbox open is not a commit and must+ # still reset and fall back to the LLM chooser, never be reported as a silent success.+ _frame, option_locator, skyvern_el, skyvern_frame_mock = _mock_autocomplete_input(+ selected_value="Oakland, California",+ option_identity={"index": 1, "label": "Oakland, California"},+ click_closes_listbox=False,+ )+ events: list[str] = []+ skyvern_el.input_clear = AsyncMock(side_effect=lambda: events.append("clear"))+ skyvern_el.press_fill = AsyncMock(side_effect=lambda value: events.append(f"fill:{value}"))+ skyvern_el.press_key = AsyncMock()+ initial_scrape = _mock_incremental_scrape(DETERMINISTIC_ELEMENTS)+ fallback_scrape = _mock_incremental_scrape(+ [{"id": "AAAB", "tagName": "li", "attributes": {"role": "option"}, "text": "Oakland, California"}]+ )+ llm_response = {+ "auto_completion_attempt": False,+ "relevance_float": 0.0,+ "id": "",+ "direct_searching": True,+ "value": "Oakland, California",+ "reasoning": "Read-back mismatch",+ }++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=skyvern_frame_mock),+ ),+ patch(+ "skyvern.webeye.actions.handler.IncrementalScrapePage",+ side_effect=[initial_scrape, fallback_scrape],+ ),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ ):++ async def _llm_handler(**_: object) -> dict[str, object]:+ events.append("llm")+ return llm_response++ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(side_effect=_llm_handler)+ mock_app.AGENT_FUNCTION = MagicMock()+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)++ await choose_auto_completion_dropdown(+ context=_make_non_location_context(field="Current location"),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="Oakland, California",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ verify_commit=False,+ collapse_autocomplete_fanout_enabled=True,+ )++ option_locator.click.assert_awaited_once()+ skyvern_el.get_locator.return_value.input_value.assert_awaited()+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_awaited_once()+++async def test_collapse_autocomplete_chip_widget_commit_succeeds() -> None:+ """A chip/token widget clears the input after committing; cleared value + closed listbox is a commit."""+ _frame, option_locator, skyvern_el, skyvern_frame_mock = _mock_autocomplete_input(+ selected_value="",+ option_identity={"index": 1, "label": "Oakland, California"},+ )+ inc_scrape = _mock_incremental_scrape(DETERMINISTIC_ELEMENTS)++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=skyvern_frame_mock),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc_scrape),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock()++ result = await choose_auto_completion_dropdown(+ context=_make_non_location_context(field="Current location"),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="Oakland, California",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ collapse_autocomplete_fanout_enabled=True,+ )++ option_locator.click.assert_awaited_once()+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_not_called()+ assert isinstance(result.action_result, ActionSuccess)+++async def test_collapse_autocomplete_click_with_side_effects_does_not_refire() -> None:+ """A click that changed the value (but did not match) must not be re-fired via the LLM fallback."""+ _frame, option_locator, skyvern_el, skyvern_frame_mock = _mock_autocomplete_input(+ selected_value="Wrong city",+ option_identity={"index": 1, "label": "Oakland, California"},+ click_closes_listbox=False,+ )+ inc_scrape = _mock_incremental_scrape(DETERMINISTIC_ELEMENTS)++ with (+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=skyvern_frame_mock),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc_scrape),+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock()++ result = await choose_auto_completion_dropdown(+ context=_make_non_location_context(field="Current location"),+ page=MagicMock(),+ scraped_page=MagicMock(),+ dom=MagicMock(),+ text="Oakland, California",+ skyvern_element=skyvern_el,+ step=_STEP,+ task=_TASK,+ collapse_autocomplete_fanout_enabled=True,+ )++ option_locator.click.assert_awaited_once()+ skyvern_el.press_fill.assert_awaited_once()+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_not_called()+ assert isinstance(result.action_result, ActionFailure)+ assert "clicked_but_not_committed" in (result.action_result.exception_message or "")++@pytest.mark.asyncioasync def test_collapse_autocomplete_detached_option_resets_before_llm() -> None:"""A deterministic candidate that detaches before the click must refresh before the LLM chooser."""@@ -902,6 +1792,7 @@ async def test_collapse_autocomplete_detached_option_resets_before_llm() -> None"relevance_float": 0.0,"id": "","direct_searching": True,+ "value": "Oakland, California","reasoning": "Option detached",}@@ -980,6 +1871,7 @@ async def test_reset_autocomplete_empty_incremental_rescrapes_page_elements() ->with (patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=fallback_scrape) as scrape_factory,patch("skyvern.webeye.actions.handler.DomUtil", return_value=dom_after_open),+ patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock()),):(returned_scrape,@@ -1002,9 +1894,9 @@ async def test_reset_autocomplete_empty_incremental_rescrapes_page_elements() ->current_scrape.stop_listen_dom_increment.assert_awaited_once()skyvern_el.input_clear.assert_awaited_once()skyvern_el.press_fill.assert_awaited_once_with("Oakland")- skyvern_frame.safe_wait_for_animation_end.assert_awaited_once()scrape_factory.assert_called_once_with(skyvern_frame=skyvern_frame)- fallback_scrape.get_incremental_element_tree.assert_awaited_once()+ fallback_scrape.get_incremental_elements_num.assert_awaited()+ fallback_scrape.get_incremental_element_tree.assert_not_awaited()scraped_page.generate_scraped_page_without_screenshots.assert_awaited_once()dom_after_open.get_skyvern_element_by_id.assert_awaited_once_with("FRESH")assert returned_scrape is fallback_scrape@@ -1040,7 +1932,8 @@ async def test_reset_autocomplete_empty_rescrape_without_interactable_elements_rwith (patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=fallback_scrape),patch("skyvern.webeye.actions.handler.DomUtil", return_value=dom_after_open),- pytest.raises(NoIncrementalElementFoundForAutoCompletion),+ patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock()),+ pytest.raises(AutoCompletionCommitFailure),):await _reset_autocomplete_for_llm_fallback(current_incremental_scraped=current_scrape,diff --git a/tests/unit/test_input_text_search_bar_skip.py b/tests/unit/test_input_text_search_bar_skip.pyindex c666663d9..06fd5e3cc 100644--- a/tests/unit/test_input_text_search_bar_skip.py+++ b/tests/unit/test_input_text_search_bar_skip.py@@ -9,16 +9,19 @@ and non-clobbering follow-ups (Tab/Escape/Arrow, different-element actions) arefrom __future__ import annotations+import copyfrom datetime import UTC, datetimefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from playwright.async_api import Error as PlaywrightError+from skyvern.exceptions import AutoCompletionCommitFailurefrom skyvern.forge.sdk.models import StepStatusfrom skyvern.webeye.actions.actions import InputOrSelectContext, InputTextAction, KeypressAction-from skyvern.webeye.actions.handler import handle_input_text_action+from skyvern.webeye.actions.handler import AUTOCOMPLETE_COMMIT_REQUIRED_FLAG, handle_input_text_actionfrom skyvern.webeye.actions.handler_utils import keys_include_enter, should_stop_batch_after_dropdown_select-from skyvern.webeye.actions.responses import ActionSuccess+from skyvern.webeye.actions.responses import ActionFailure, ActionSuccessfrom tests.unit.conftest import make_input_element_mockfrom tests.unit.helpers import make_organization, make_step, make_task@@ -125,6 +128,84 @@ async def _run_search_bar_input(stop_flag: bool, incremental: list[dict]) -> lis)+def _fake_experimentation_provider(enabled_flags: set[str]) -> MagicMock:+ provider = MagicMock()++ async def _is_enabled(flag: str, distinct_id: str, properties: dict | None = None) -> bool:+ return flag in enabled_flags++ provider.is_feature_enabled_cached = AsyncMock(side_effect=_is_enabled)+ provider.resolve_feature_enabled_unrecorded = AsyncMock(return_value=False)+ return provider+++async def _run_autocomplete_input_without_suggestions(+ *,+ is_search_bar: bool,+ is_location_input: bool,+ commit_flag_enabled: bool,+) -> tuple[list, MagicMock]:+ """Drive handle_input_text_action through the REAL autocomplete chain with a widget+ that never renders suggestions."""+ skyvern_el = make_input_element_mock(element_id="AADC")+ skyvern_el.is_auto_completion_input = AsyncMock(return_value=True)+ skyvern_el.press_fill = AsyncMock()+ skyvern_el.has_attr = AsyncMock(return_value=False)+ skyvern_el.get_locator.return_value.click = AsyncMock()++ dom_instance = MagicMock()+ dom_instance.get_skyvern_element_by_id = AsyncMock(return_value=skyvern_el)++ inc = MagicMock()+ inc.start_listen_dom_increment = AsyncMock()+ inc.stop_listen_dom_increment = AsyncMock()+ inc.get_incremental_elements_num = AsyncMock(return_value=0)+ inc.get_incremental_element_tree = AsyncMock(return_value=[])+ inc.build_html_tree.return_value = "<div></div>"+ inc.id_to_element_dict = {}++ skyvern_frame = MagicMock()+ skyvern_frame.safe_wait_for_animation_end = AsyncMock()++ scraped_page = MagicMock()+ scraped_page.id_to_element_dict = {"AADC": {"tagName": "input"}}+ scraped_page.id_to_css_dict = {"AADC": "#aadc"}+ scraped_after = MagicMock()+ scraped_after.id_to_css_dict = {"AADC": "#aadc"}+ scraped_page.generate_scraped_page_without_screenshots = AsyncMock(return_value=scraped_after)++ context = InputOrSelectContext(field="Account", is_search_bar=is_search_bar, is_location_input=is_location_input)+ enabled_flags = {AUTOCOMPLETE_COMMIT_REQUIRED_FLAG} if commit_flag_enabled else set()++ action = _input()++ with (+ patch("skyvern.webeye.actions.handler.DomUtil", return_value=dom_instance),+ patch("skyvern.webeye.actions.handler.SkyvernFrame.create_instance", new=AsyncMock(return_value=skyvern_frame)),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc),+ patch("skyvern.webeye.actions.handler.get_input_value", new=AsyncMock(return_value="")),+ patch(+ "skyvern.webeye.actions.handler.get_actual_value_of_parameter_if_secret_with_task",+ return_value="123456",+ ),+ patch("skyvern.webeye.actions.handler._get_input_or_select_context", new=AsyncMock(return_value=context)),+ patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock()),+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.EXPERIMENTATION_PROVIDER = _fake_experimentation_provider(enabled_flags)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value={})+ mock_app.AGENT_FUNCTION = MagicMock()+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)+ results = await handle_input_text_action(+ action=action, page=MagicMock(), scraped_page=scraped_page, task=_TASK, step=_STEP+ )+ return results, skyvern_el++@pytest.mark.asyncioasync def test_selection_with_clobbering_next_stops_batch() -> None:"""Selection committed + a clobbering next action (flag set) -> skip_remaining_actions=True."""@@ -147,3 +228,128 @@ async def test_plain_search_input_does_not_stop_batch() -> None:results = await _run_search_bar_input(stop_flag=True, incremental=[])assert len(results) == 1 and isinstance(results[0], ActionSuccess)assert not results[0].skip_remaining_actions+++async def test_search_bar_without_suggestions_falls_through_to_plain_typing() -> None:+ """A search bar whose autocomplete never renders suggestions must still be typed into (flag off)."""+ results, skyvern_el = await _run_autocomplete_input_without_suggestions(+ is_search_bar=True,+ is_location_input=False,+ commit_flag_enabled=False,+ )+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+ skyvern_el.input_sequentially.assert_awaited_once()+++async def test_location_field_without_suggestions_falls_through_when_flag_off() -> None:+ results, skyvern_el = await _run_autocomplete_input_without_suggestions(+ is_search_bar=False,+ is_location_input=True,+ commit_flag_enabled=False,+ )+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+ skyvern_el.input_sequentially.assert_awaited_once()+++async def test_search_bar_direct_search_enter_navigation_is_implicit_commit() -> None:+ """direct_searching presses Enter, the page navigates, and every post-Enter read-back hits a stale+ element; the action must succeed as an implicit commit without falling through to plain typing."""+ skyvern_el = make_input_element_mock(element_id="AADC")+ skyvern_el.is_auto_completion_input = AsyncMock(return_value=True)+ skyvern_el.press_fill = AsyncMock()+ skyvern_el.has_attr = AsyncMock(return_value=False)++ enter_pressed = False++ async def _press_key(key: str, **_: object) -> None:+ nonlocal enter_pressed+ if key == "Enter":+ enter_pressed = True++ skyvern_el.press_key = AsyncMock(side_effect=_press_key)++ async def _read_input_value(tag_name: str, locator: object) -> str:+ if enter_pressed:+ raise PlaywrightError("Element is not attached to the DOM")+ return ""++ suggestions = [+ {"id": "OPT1", "tagName": "li", "attributes": {"role": "option"}, "text": "Target 123456"},+ {"id": "OPT2", "tagName": "li", "attributes": {"role": "option"}, "text": "Target 654321"},+ ]++ dom_instance = MagicMock()+ dom_instance.get_skyvern_element_by_id = AsyncMock(return_value=skyvern_el)++ inc = MagicMock()+ inc.start_listen_dom_increment = AsyncMock()+ inc.stop_listen_dom_increment = AsyncMock()+ inc.get_incremental_elements_num = AsyncMock(return_value=len(suggestions))+ inc.get_incremental_element_tree = AsyncMock(return_value=copy.deepcopy(suggestions))+ inc.build_html_tree.return_value = "<div>options</div>"+ inc.id_to_element_dict = {}++ scraped_page = MagicMock()+ scraped_page.id_to_element_dict = {"AADC": {"tagName": "input"}}+ scraped_page.id_to_css_dict = {"AADC": "#aadc"}++ context = InputOrSelectContext(field="Search", is_search_bar=True, is_location_input=False)+ llm_response = {+ "auto_completion_attempt": False,+ "relevance_float": 0.0,+ "id": "",+ "direct_searching": True,+ "value": "123456",+ "reasoning": "Search directly",+ }++ action = _input()++ with (+ patch("skyvern.webeye.actions.handler.DomUtil", return_value=dom_instance),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),+ ),+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc),+ patch("skyvern.webeye.actions.handler.get_input_value", new=AsyncMock(side_effect=_read_input_value)),+ patch(+ "skyvern.webeye.actions.handler.get_actual_value_of_parameter_if_secret_with_task",+ return_value="123456",+ ),+ patch("skyvern.webeye.actions.handler._get_input_or_select_context", new=AsyncMock(return_value=context)),+ patch("skyvern.webeye.actions.handler.asyncio.sleep", new=AsyncMock()),+ patch("skyvern.webeye.actions.handler.prompt_engine") as mock_prompt,+ patch("skyvern.webeye.actions.handler.skyvern_context") as mock_ctx,+ patch("skyvern.webeye.actions.handler.app") as mock_app,+ ):+ mock_app.EXPERIMENTATION_PROVIDER = _fake_experimentation_provider(set())+ mock_app.AUTO_COMPLETION_LLM_API_HANDLER = AsyncMock(return_value=llm_response)+ mock_app.SECONDARY_LLM_API_HANDLER = AsyncMock(return_value={"potential_values": []})+ mock_app.AGENT_FUNCTION = MagicMock()+ mock_prompt.load_prompt.return_value = "mocked prompt"+ mock_ctx.ensure_context.return_value = MagicMock(tz_info=UTC)+ results = await handle_input_text_action(+ action=action, page=MagicMock(), scraped_page=scraped_page, task=_TASK, step=_STEP+ )++ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+ skyvern_el.press_key.assert_awaited_once_with("Enter")+ skyvern_el.input_sequentially.assert_not_awaited()+++async def test_location_field_without_commit_fails_when_flag_on() -> None:+ """With the commit-required flag on, a location field never falls through to plain typing."""+ results, skyvern_el = await _run_autocomplete_input_without_suggestions(+ is_search_bar=False,+ is_location_input=True,+ commit_flag_enabled=True,+ )+ assert len(results) == 1 and isinstance(results[0], ActionFailure)+ assert results[0].exception_type == AutoCompletionCommitFailure.__name__+ assert "suggestions_never_rendered" in (results[0].exception_message or "")+ skyvern_el.input_sequentially.assert_not_awaited()diff --git a/tests/unit/test_select_shadow_match.py b/tests/unit/test_select_shadow_match.pyindex f27a7a7f6..bf400f25f 100644--- a/tests/unit/test_select_shadow_match.py+++ b/tests/unit/test_select_shadow_match.py@@ -423,6 +423,7 @@ async def test_auto_completion_call_path_forwards_committed_value_to_shadow_matcincremental_scraped = MagicMock(start_listen_dom_increment=AsyncMock(),stop_listen_dom_increment=AsyncMock(),+ get_incremental_elements_num=AsyncMock(return_value=1),get_incremental_element_tree=AsyncMock(return_value=[_SHADOW_OPTION]),)incremental_scraped.build_html_tree.return_value = "<div>Committed Value</div>"