Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11534): re-perceive grounded click targets after a non-advancing click (#6877)
Andrew Neilsonc5f970216d1c
diff --git a/skyvern/config.py b/skyvern/config.pyindex cd7013f45..0635cd6c0 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -178,6 +178,14 @@ class Settings(BaseSettings):# copilot stops re-running and escalates honestly. Set very high to disable the ceiling.COPILOT_REPAIR_CEILING_CONSECUTIVE_IDENTICAL: int = 3COPILOT_SCOUT_ACT_OBSERVE_TIMEOUT_SECONDS: float = 4.0+ # Bounded settle-then-re-perceive after a non-advancing click on a precondition-gated control:+ # re-probe the side-effect-free extractor a few times (hard-capped) until a just-issued AJAX populates.+ COPILOT_CLICK_SETTLE_MAX_PROBES: int = 3+ COPILOT_CLICK_SETTLE_DELAY_SECONDS: float = 0.6+ COPILOT_CLICK_SETTLE_DEADLINE_SECONDS: float = 3.5+ # Kill switch for the clickable-controls grounding channel: when off, composition evidence omits the+ # clickable_controls key entirely, reverting both the re-perception attach and the evaluate steer.+ COPILOT_CLICK_REPERCEPTION_ATTACH_ENABLED: bool = True# Staged rollout for treating omitted runtime workflow proxy values as direct/no-proxy.# Off preserves the historical implicit residential default for anti-bot-sensitive traffic.RUNTIME_PROXY_DEFAULT_NONE_ENABLED: bool = Falsediff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.pyindex e2c5e80b8..c70caab6e 100644--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py@@ -8,6 +8,7 @@ from skyvern.forge.sdk.copilot.composition_evidence import (_ANTI_BOT_PATTERNS,_ANTI_BOT_SCAN_BYTES,_MAX_CHALLENGE_CONTROLS,+ _MAX_CLICKABLE_CONTROLS,_MAX_FIELDS_PER_FORM,_MAX_FORMS,_MAX_MODAL_DISMISS_CONTROLS,@@ -100,6 +101,13 @@ def scout_accessible_role_name_expression(css_selector: str) -> str:)+# Live count of elements a CSS selector resolves to right now. An invalid selector returns -1 so the+# caller can tell "matched nothing" (0) apart from "could not evaluate" (-1).+def selector_match_count_expression(css_selector: str) -> str:+ sel = json.dumps(css_selector)+ return f"(() => {{ try {{ return document.querySelectorAll({sel}).length; }} catch (e) {{ return -1; }}}})()"++COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION = ("(() => {"" const body = document.body; if (!body) return [];"@@ -164,6 +172,7 @@ _STRUCTURED_CONST_HEADER = (f"const MAX_RESULT_CONTAINERS={int(_MAX_RESULT_CONTAINERS)};"f"const MAX_SELECT_OPTIONS={int(_MAX_SELECT_OPTIONS)};"f"const MAX_CHALLENGE_CONTROLS={int(_MAX_CHALLENGE_CONTROLS)};"+ f"const MAX_CLICKABLE_CONTROLS={int(_MAX_CLICKABLE_CONTROLS)};"f"const MAX_MODAL_OVERLAYS={int(_MAX_MODAL_OVERLAYS)};"f"const MAX_MODAL_DISMISS_CONTROLS={int(_MAX_MODAL_DISMISS_CONTROLS)};"f"const MAX_PAGE_OBSTRUCTIONS={int(_MAX_PAGE_OBSTRUCTIONS)};"@@ -330,6 +339,43 @@ for (const link of document.querySelectorAll('a[href]')) {navTargets.push(entry);}+const clickableSelector = (el) => {+ const tag = (el.tagName || '*').toLowerCase();+ const id = attr(el, 'id'); if (id) return '#' + id;+ const da = attr(el, 'data-action'); if (da) return tag + '[data-action="' + cssAttr(da) + '"]';+ const al = attr(el, 'aria-label'); if (al) return tag + '[aria-label="' + cssAttr(al) + '"]';+ const name = attr(el, 'name'); const value = attr(el, 'value');+ if (name && value) return tag + '[name="' + cssAttr(name) + '"][value="' + cssAttr(value) + '"]';+ const cs = classSelector(classesFor(el));+ if (cs) return tag + cs;+ return '';+};+const clickableText = (el) => nodeText(el) || attr(el, 'aria-label') || attr(el, 'value') || attr(el, 'title');+const usedClickableSelectors = new Set();+for (const f of forms) for (const sc of (f.submit_controls || [])) if (sc.selector) usedClickableSelectors.add(sc.selector);+for (const n of navTargets) if (n.selector) usedClickableSelectors.add(n.selector);+const clickableControls = [];+const seenClickableText = new Set();+for (const el of document.querySelectorAll('button,[role="button"],[data-action]')) {+ if (clickableControls.length >= MAX_CLICKABLE_CONTROLS) break;+ const tag = (el.tagName || '').toLowerCase();+ if (SKIP_TAGS.has(tag)) continue;+ if (el.closest && el.closest('form')) continue;+ const text = clickableText(el);+ const selector = clickableSelector(el);+ let unique = false;+ if (selector) { try { unique = document.querySelectorAll(selector).length === 1; } catch (e) { unique = false; } }+ if (selector && unique && !usedClickableSelectors.has(selector)) {+ clickableControls.push({ text: text, selector: selector, tag: tag });+ usedClickableSelectors.add(selector);+ if (text) seenClickableText.add(text);+ continue;+ }+ if (!text || seenClickableText.has(text)) continue;+ clickableControls.push({ text: text, tag: tag });+ seenClickableText.add(text);+}+const resultContainers = [];const resultRowTextIsContent = (s) => {const text = lower(String(s || '').replace(/\s+/g, ' ').trim());@@ -437,6 +483,7 @@ return JSON.stringify({forms: forms,navigation_targets: navTargets,result_containers: resultContainers,+ clickable_controls: clickableControls,challenge_controls: challengeControls,modal_overlays: modalOverlays,visual_obstruction_candidates: visualObstructionCandidates,diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.pyindex ddc18edad..ca3525687 100644--- a/skyvern/forge/sdk/copilot/composition_evidence.py+++ b/skyvern/forge/sdk/copilot/composition_evidence.py@@ -14,6 +14,7 @@ try:except ImportError: # pragma: no cover - bs4 is a transitive dep but inspection degrades gracefully.BeautifulSoup = None # type: ignore[assignment, misc]+from skyvern.config import settingsfrom skyvern.forge.sdk.copilot.build_phase import BuildPhasefrom skyvern.forge.sdk.copilot.reached_download_target import (NAV_TARGET_DOWNLOAD_KIND_KEY,@@ -52,6 +53,7 @@ _MAX_MODAL_OVERLAYS = 5_MAX_MODAL_DISMISS_CONTROLS = 6_MAX_PAGE_OBSTRUCTIONS = 5_MAX_VISIBLE_CONTROLS = 6+_MAX_CLICKABLE_CONTROLS = 12_MODAL_IDENTITY_PATTERNS: frozenset[str] = frozenset({"modal", "popup", "overlay", "dialog", "drawer", "lightbox"})_MODAL_ROLE_VALUES: frozenset[str] = frozenset({"dialog", "alertdialog"})_MODAL_DISMISS_HINTS: frozenset[str] = frozenset(@@ -635,6 +637,17 @@ def has_bounded_page_schema(evidence: dict[str, Any]) -> bool:return evidence.get("observed_empty_page") is True+def has_actionable_steer_content(evidence: dict[str, Any]) -> bool:+ """Steer gate wider than has_bounded_page_schema: it also passes pages whose only+ affordances are standalone clickable controls, which stay steer-able yet must never+ feed has_bounded_page_schema or the no-progress reset.+ """+ if has_bounded_page_schema(evidence):+ return True+ clickable_controls = evidence.get("clickable_controls")+ return isinstance(clickable_controls, list) and bool(clickable_controls)++def _is_scout_interaction_evidence(evidence: dict[str, Any]) -> bool:# A scout interaction that resolved a concrete selector proves the page rendered# and the element was actionable, so it is non-hollow evidence of the reached@@ -1118,6 +1131,7 @@ def _empty_evidence(inspected_url: str, current_url: str) -> dict[str, Any]:"forms": [],"navigation_targets": [],"result_containers": [],+ **_clickable_controls_channel([]),"visible_text_excerpt": "","anti_bot_indicators": [],"challenge_controls": [],@@ -1297,6 +1311,87 @@ def _selector_for(node: Any) -> str:return str(tag_name)+def _clickable_controls_channel(controls: list[dict[str, Any]] | None) -> dict[str, Any]:+ if not settings.COPILOT_CLICK_REPERCEPTION_ATTACH_ENABLED:+ return {}+ return {"clickable_controls": controls or []}+++def _clickable_control_selector(node: Any) -> str:+ """Build a selector for a standalone clickable control, preferring attributes _selector_for+ never emits (data-action/aria-label) so a tile authored against [data-action=...] can be grounded."""+ tag_name = getattr(node, "name", None) or "*"+ node_id = _attr_value(node, "id")+ if node_id:+ return f"#{node_id}"+ data_action = _attr_value(node, "data-action")+ if data_action:+ return f'{tag_name}[data-action="{_css_attr(data_action)}"]'+ aria_label = _attr_value(node, "aria-label")+ if aria_label:+ return f'{tag_name}[aria-label="{_css_attr(aria_label)}"]'+ node_name = _attr_value(node, "name")+ node_value = _attr_value(node, "value")+ if node_name and node_value:+ return f'{tag_name}[name="{_css_attr(node_name)}"][value="{_css_attr(node_value)}"]'+ class_selector = _class_selector(_classes_for(node))+ if class_selector:+ return f"{tag_name}{class_selector}"+ return ""+++def _clickable_control_text(node: Any) -> str:+ for value in (+ _node_text(node),+ _attr_value(node, "aria-label"),+ _attr_value(node, "value"),+ _attr_value(node, "title"),+ ):+ if value:+ return value+ return ""+++def _selector_is_live_unique_in_soup(soup: Any, selector: str) -> bool:+ if not selector:+ return False+ try:+ return len(soup.select(selector)) == 1+ except Exception:+ return False+++def _clickable_controls_html(soup: Any, *, used_selectors: set[str]) -> list[dict[str, Any]]:+ controls: list[dict[str, Any]] = []+ seen_selectors = set(used_selectors)+ seen_text: set[str] = set()+ try:+ candidates = soup.select('button, [role="button"], [data-action]')+ except Exception:+ candidates = soup.find_all("button")+ for node in candidates:+ if len(controls) >= _MAX_CLICKABLE_CONTROLS:+ break+ tag_name = str(getattr(node, "name", "") or "").lower()+ if tag_name in {"script", "style", "noscript"}:+ continue+ if hasattr(node, "find_parent") and node.find_parent("form") is not None:+ continue+ text = _schema_text(_clickable_control_text(node), 120)+ selector = _clickable_control_selector(node)+ if selector and selector not in seen_selectors and _selector_is_live_unique_in_soup(soup, selector):+ controls.append({"text": text, "selector": selector[:160], "tag": tag_name})+ seen_selectors.add(selector)+ if text:+ seen_text.add(text)+ continue+ if not text or text in seen_text:+ continue+ controls.append({"text": text, "tag": tag_name})+ seen_text.add(text)+ return controls++def _adjacent_text(field: Any) -> str:for siblings in (getattr(field, "next_siblings", []), getattr(field, "previous_siblings", [])):for index, sibling in enumerate(siblings):@@ -1716,6 +1811,18 @@ def parse_composition_html(html: str, *, inspected_url: str, current_url: str) -if tag_name == "table" or any(hint in result_identity for hint in _RESULT_CONTAINER_HINTS):result_containers.append(_result_container_entry(node))+ used_selectors: set[str] = set()+ for form in forms:+ for control in form.get("submit_controls") or []:+ selector = control.get("selector")+ if isinstance(selector, str) and selector:+ used_selectors.add(selector)+ for target in navigation_targets:+ selector = target.get("selector")+ if isinstance(selector, str) and selector:+ used_selectors.add(selector)+ clickable_controls = _clickable_controls_html(soup, used_selectors=used_selectors)+field_count = sum(len(form.get("fields") or []) for form in forms)control_count = sum(len(form.get("submit_controls") or []) for form in forms)body_text = _node_text(soup.body if soup.body is not None else soup).strip()@@ -1737,6 +1844,7 @@ def parse_composition_html(html: str, *, inspected_url: str, current_url: str) -"forms": forms,"navigation_targets": navigation_targets,"result_containers": result_containers,+ **_clickable_controls_channel(clickable_controls),"visible_text_excerpt": _schema_text(visible_text, _MAX_VISIBLE_TEXT_EXCERPT_CHARS),"anti_bot_indicators": anti_bot_indicators,"challenge_controls": challenge_controls,@@ -1905,6 +2013,28 @@ def _structured_result_containers(value: Any) -> list[dict[str, Any]]:return containers+def _structured_clickable_controls(value: Any) -> list[dict[str, Any]]:+ controls: list[dict[str, Any]] = []+ if not isinstance(value, list):+ return controls+ for item in value[:_MAX_CLICKABLE_CONTROLS]:+ if not isinstance(item, dict):+ continue+ text = _schema_text(_structured_str(item.get("text")), 120)+ selector = _structured_str(item.get("selector"))[:160]+ entry: dict[str, Any] = {}+ if text:+ entry["text"] = text+ if selector:+ entry["selector"] = selector+ tag = (_structured_str(item.get("tag")) or "").lower()[:40]+ if tag:+ entry["tag"] = tag+ if entry.get("selector") or entry.get("text"):+ controls.append(entry)+ return controls++def _structured_challenge_controls(value: Any) -> list[dict[str, Any]]:controls: list[dict[str, Any]] = []if not isinstance(value, list):@@ -2004,6 +2134,7 @@ def parse_composition_structured(data: Any, *, inspected_url: str, current_url:forms = forms[:_MAX_FORMS]navigation_targets = _structured_navigation_targets(data.get("navigation_targets"), base_url=base_url)result_containers = _structured_result_containers(data.get("result_containers"))+ clickable_controls = _structured_clickable_controls(data.get("clickable_controls"))challenge_controls = _structured_challenge_controls(data.get("challenge_controls"))modal_overlays = _structured_modal_overlays(data.get("modal_overlays"))page_obstructions = _page_obstructions_from_modal_overlays(modal_overlays)@@ -2035,6 +2166,7 @@ def parse_composition_structured(data: Any, *, inspected_url: str, current_url:"forms": forms,"navigation_targets": navigation_targets,"result_containers": result_containers,+ **_clickable_controls_channel(clickable_controls),"visible_text_excerpt": visible_text,"anti_bot_indicators": anti_bot_indicators,"challenge_controls": challenge_controls,diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex af91789e8..d4ef5a7d2 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -208,6 +208,7 @@ class AgentContext:# click or a hollow post-click observe); resets on verified progress.consecutive_no_progress_interaction_count: int = 0last_scout_act_observe_outcome: str | None = None+ last_scout_act_observe_packet: dict[str, Any] | None = Nonepending_code_authoring_runtime_repair_context: CodeAuthoringRepairContext | None = Nonelast_code_authoring_repair_context: CodeAuthoringRepairContext | None = Nonechallenge_gated_proxy_retry_count: int = 0@@ -298,6 +299,9 @@ class AgentContext:# (selector, role, accessible_name) read before an in-flight click that may navigate: a post-action# read would describe the landing element, so a navigating click's anchor is captured pre-navigation.pending_scout_role_name: tuple[str, str, str] | None = None+ # Selector of an in-flight click, captured pre-dispatch so a failed/timed-out click can gate a+ # settle re-perception on whether that selector still resolves to a live element.+ pending_scout_click_selector: str | None = None# Exact secret strings filled into the live browser this turn (passwords,# call-time-minted OTP codes). Page-readback tool results are exact-string# scrubbed against this set before being recorded or returned to the model.diff --git a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py b/skyvern/forge/sdk/copilot/runtime_authoring_repair.pyindex d73fea69f..31aa95b55 100644--- a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py+++ b/skyvern/forge/sdk/copilot/runtime_authoring_repair.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport refrom typing import Any, TypeGuard+import structlog+from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schemafrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, normalize_block_authoring_policyfrom skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext@@ -11,6 +13,8 @@ from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_promfrom skyvern.forge.sdk.copilot.run_outcome import trusted_terminal_challenge_category_namefrom skyvern.forge.sdk.copilot.workflow_credential_utils import url_origin+LOG = structlog.get_logger()+_RUNTIME_AUTHORING_REASON_CODE = "runtime_block_failure"_RUNTIME_SUMMARY_MAX_CHARS = 120_RUNTIME_SUMMARY_MAX_ITEMS = 5@@ -76,6 +80,58 @@ def _runtime_summary_list(value: Any, keys: tuple[str, ...]) -> list[str]:return summaries+def _runtime_form_summaries(value: Any) -> list[str]:+ if not isinstance(value, list):+ return []+ summaries: list[str] = []+ for form in value:+ if not isinstance(form, dict):+ continue+ for field in form.get("fields") or []:+ summary = _runtime_summary_entry(field, ("label", "selector"))+ if summary:+ summaries.append(summary)+ for control in form.get("submit_controls") or []:+ summary = _runtime_summary_entry(control, ("text", "selector", "disabled"))+ if summary:+ summaries.append(summary)+ return summaries[:_RUNTIME_SUMMARY_MAX_ITEMS]+++def _runtime_result_summaries(value: Any) -> list[str]:+ if not isinstance(value, list):+ return []+ summaries: list[str] = []+ for container in value:+ if not isinstance(container, dict):+ continue+ primary = _runtime_summary_entry(container, ("selector", "text_excerpt", "row_selector"))+ if primary:+ summaries.append(primary)+ for toggle in container.get("expand_toggle_candidates") or []:+ summary = _bounded_runtime_text(toggle, 80)+ if summary:+ summaries.append(summary)+ for row in container.get("sample_rows") or []:+ summary = _bounded_runtime_text(row, 80)+ if summary:+ summaries.append(summary)+ break+ return summaries[:_RUNTIME_SUMMARY_MAX_ITEMS]+++def post_run_inspection_cleanly_matches(evidence: Any, run_id: Any) -> bool:+ return (+ isinstance(evidence, dict)+ and evidence.get("source_tool") == _INSPECT_PAGE_SOURCE_TOOL+ and evidence.get("observed_after_workflow_run") is True+ and isinstance(run_id, str)+ and bool(run_id)+ and evidence.get("workflow_run_id") == run_id+ and has_bounded_page_schema(evidence)+ )++def _post_run_terminal_page_evidence(evidence: dict[str, Any]) -> bool:if evidence.get("observed_after_workflow_run") is not True:return False@@ -279,10 +335,10 @@ def finalize_runtime_authoring_repair_context_from_page_observation("current_title_present": isinstance(page_title, str) and bool(page_title.strip()),"page_evidence_source": _bounded_runtime_text(evidence.get("source_tool"), 80) or None,"observed_after_workflow_run": True,- "page_form_summaries": _runtime_summary_list(evidence.get("forms"), ("label", "selector")),- "page_result_summaries": _runtime_summary_list(evidence.get("result_containers"), ("label", "text")),+ "page_form_summaries": _runtime_form_summaries(evidence.get("forms")),+ "page_result_summaries": _runtime_result_summaries(evidence.get("result_containers")),"page_action_summaries": _runtime_summary_list(- evidence.get("navigation_targets"), ("label", "selector", "disabled")+ evidence.get("navigation_targets"), ("text", "selector", "disabled")),"page_challenge_summaries": _runtime_summary_list(evidence.get("challenge_controls"), ("text", "selector", "disabled")@@ -315,4 +371,12 @@ def inject_runtime_authoring_repair_context(copilot_ctx: Any, result: dict[str,returnrepair_context = pendingcopilot_ctx.last_code_authoring_repair_context = repair_context+ LOG.info(+ "Injected runtime authoring repair context",+ observed_after_workflow_run=repair_context.observed_after_workflow_run,+ workflow_run_id=repair_context.workflow_run_id,+ page_form_summary_count=len(repair_context.page_form_summaries),+ page_result_summary_count=len(repair_context.page_result_summaries),+ page_action_summary_count=len(repair_context.page_action_summaries),+ )data["authoring_repair_context"] = repair_context.model_dump(mode="json")diff --git a/skyvern/forge/sdk/copilot/tools/composition_capture.py b/skyvern/forge/sdk/copilot/tools/composition_capture.pyindex eb1459aeb..f6dd3533b 100644--- a/skyvern/forge/sdk/copilot/tools/composition_capture.py+++ b/skyvern/forge/sdk/copilot/tools/composition_capture.py@@ -653,6 +653,23 @@ async def _capture_composition_evidence(return evidence, None+def store_post_run_page_evidence(+ copilot_ctx: Any,+ evidence: dict[str, Any],+ *,+ run_id: str,+ current_url: str,+) -> dict[str, Any]:+ stamped = {**evidence, "workflow_run_id": run_id, "observed_after_workflow_run": True}+ if current_url and not stamped.get("current_url"):+ stamped["current_url"] = current_url+ copilot_ctx.composition_page_evidence = stamped+ page_title = stamped.get("page_title")+ if isinstance(page_title, str) and page_title:+ _workflow_verification_evidence(copilot_ctx).page_title = page_title[:160]+ return stamped++def _normalized_inspect_url(url: str | None) -> str | None:"""Normalized full URL for strict same-page comparison, or None when not comparable.@@ -828,21 +845,15 @@ async def _inspect_page_for_composition_impl(run_id = getattr(copilot_ctx, "last_run_blocks_workflow_run_id", None)if isinstance(run_id, str) and run_id:- evidence = {- **evidence,- "workflow_run_id": run_id,- "observed_after_workflow_run": True,- }+ evidence = store_post_run_page_evidence(copilot_ctx, evidence, run_id=run_id, current_url=current_url)_mark_post_run_page_observed(copilot_ctx, source_tool="inspect_page_for_composition", url=current_url)- page_title = evidence.get("page_title")- if isinstance(page_title, str) and page_title:- _workflow_verification_evidence(copilot_ctx).page_title = page_title[:160]+ else:+ copilot_ctx.composition_page_evidence = evidenceif not bypass_budget_for_post_run_current_page:copilot_ctx.page_inspection_calls_this_turn += 1if bypass_budget_for_post_run_current_page:copilot_ctx.post_run_current_page_inspection_workflow_run_id = run_id- copilot_ctx.composition_page_evidence = evidencefinalize_runtime_authoring_repair_context_from_page_observation(copilot_ctx)if (isinstance(run_id, str)diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 926c3b952..5da38403d 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -3,10 +3,12 @@ from __future__ import annotationsimport asyncioimport jsonimport re+import timefrom typing import Anyimport structlog+from skyvern.config import settingsfrom skyvern.forge.sdk.copilot.block_type_aliases import normalize_copilot_block_type_aliasfrom skyvern.forge.sdk.copilot.build_phase import (BuildPhase,@@ -21,7 +23,7 @@ from skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlayfrom skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.typed_value_policy import safe_typed_default_value, should_reject_type_text_value-from ._shared import _DISCOVERY_PER_CALL_TIMEOUT_SECONDS+from ._shared import _DISCOVERY_PER_CALL_TIMEOUT_SECONDS, _composition_get_structured_evidencefrom .banned_blocks import (_CODE_ONLY_SELECTOR_ACTION_TOOLS,_CODE_ONLY_TARGET_EVIDENCE_KEYS,@@ -40,10 +42,13 @@ from .page_observation import (_resolve_url_title,)from .scouting import (+ _PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS,+ _actionable_targets_for_result,_attach_scout_page_summary,_capture_scout_role_name,_capture_scout_source_url,_clear_pending_browser_interaction_observation,+ _click_affordance_target_identities,_consume_scout_source_url,_mark_page_inspected,_mark_pending_browser_interaction_observation,@@ -53,6 +58,7 @@ from .scouting import (_register_scout_interaction_observation,_reset_evaluate_tracker,_resolve_scout_role_name,+ _selector_live_match_count,_steer_evaluate_result,account_no_progress_interaction_click,)@@ -293,6 +299,7 @@ async def _click_pre_hook(# Cleared up front so an early return below (deterministic result, jQuery reject, no selector)# cannot leave a prior click's stash for this click's post-hook to consume.ctx.pending_scout_role_name = None+ ctx.pending_scout_click_selector = Noneawait _capture_scout_source_url(ctx)deterministic_result = _strip_intent_for_code_only_selector_action(params, ctx, tool_name="click")if deterministic_result is not None:@@ -300,6 +307,7 @@ async def _click_pre_hook(selector = params.get("selector", "")if not selector:return None+ ctx.pending_scout_click_selector = selector if isinstance(selector, str) else Noneif _JQUERY_SELECTOR_RE.search(selector):return {"ok": False,@@ -409,10 +417,13 @@ async def _click_post_hook(ctx: AgentContext,) -> dict[str, Any]:ctx.last_scout_act_observe_outcome = None+ ctx.last_scout_act_observe_packet = None_clear_pending_browser_interaction_observation(ctx)source_url = _consume_scout_source_url(ctx)pending_role_name = ctx.pending_scout_role_namectx.pending_scout_role_name = None+ attempted_selector = ctx.pending_scout_click_selector+ ctx.pending_scout_click_selector = Noneif result.get("ok") and result.get("data"):data = result["data"]selector = _selector_from_tool_data(data, prefer_resolved_when_empty=True)@@ -447,9 +458,138 @@ async def _click_post_hook(if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:await _maybe_attach_reached_download_target(ctx, result, url=url, page_evidence=page_evidence)account_no_progress_interaction_click(ctx, result)+ try:+ await _attach_reperception_targets_on_non_advancing_click(result, raw, ctx, attempted_selector)+ except Exception:+ LOG.warning("copilot_click_reperception_attach_failed", exc_info=True)return result+_SETTLE_GROUNDED_TARGETS_INSTRUCTION = (+ "The page updated after your click; click one of the grounded targets below instead of re-evaluating."+)+++def _grounded_actionable_targets(parsed: dict[str, Any] | None) -> list[dict[str, str]]:+ if parsed is None:+ return []+ return _actionable_targets_for_result(_click_affordance_target_identities(parsed))+++def _attach_actionable_targets(result: dict[str, Any], targets: list[dict[str, str]], *, settle_steer: bool) -> None:+ if not targets:+ return+ container = result.get("data")+ if not isinstance(container, dict):+ container = {}+ result["data"] = container+ container["actionable_targets"] = targets+ if settle_steer:+ container["next_action"] = "click"+ container["next_action_reason"] = _SETTLE_GROUNDED_TARGETS_INSTRUCTION+ LOG.info(+ "copilot_click_grounded_targets_attached",+ target_count=len(targets),+ via="settle" if settle_steer else "reperception",+ )+++async def _safe_composition_evidence(ctx: AgentContext, url: str, *, timeout_seconds: float) -> dict[str, Any] | None:+ if timeout_seconds <= 0:+ return None+ try:+ return await _composition_get_structured_evidence(+ ctx,+ inspected_url=url,+ current_url=url,+ timeout_seconds=timeout_seconds,+ )+ except Exception:+ return None+++async def _click_failure_warrants_settle(+ ctx: AgentContext, attempted_selector: str | None, *, timeout_seconds: float+) -> bool:+ """Pay the bounded settle only for a precondition-gated control: the attempted selector resolves to+ a live element now (exists-but-was-not-actionable). A zero-match invented selector, or one that can+ no longer be read, never warrants it, so the common invented-selector path stays fast."""+ match_count = await _selector_live_match_count(ctx, attempted_selector, timeout_seconds=timeout_seconds)+ return match_count is not None and match_count >= 1+++async def _settle_grounded_targets_on_pending_update(+ ctx: AgentContext,+ *,+ url: str,+ attempted_selector: str | None,+) -> list[dict[str, str]]:+ """Bounded re-probe of the side-effect-free extractor until a precondition-gated control's+ grounded targets appear (a just-issued AJAX populated the page) or the settle deadline expires."""+ deadline = time.monotonic() + settings.COPILOT_CLICK_SETTLE_DEADLINE_SECONDS++ def _remaining_budget(default: float) -> float:+ return min(default, max(0.0, deadline - time.monotonic()))++ warrants_budget = _remaining_budget(_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS)+ if warrants_budget <= 0:+ return []+ if not await _click_failure_warrants_settle(ctx, attempted_selector, timeout_seconds=warrants_budget):+ return []+ probes_run = 0+ for _ in range(max(0, settings.COPILOT_CLICK_SETTLE_MAX_PROBES)):+ sleep_budget = _remaining_budget(settings.COPILOT_CLICK_SETTLE_DELAY_SECONDS)+ if sleep_budget <= 0 and time.monotonic() >= deadline:+ break+ await asyncio.sleep(sleep_budget)+ probe_budget = _remaining_budget(settings.COPILOT_SCOUT_ACT_OBSERVE_TIMEOUT_SECONDS)+ if probe_budget <= 0:+ break+ probes_run += 1+ targets = _grounded_actionable_targets(await _safe_composition_evidence(ctx, url, timeout_seconds=probe_budget))+ if targets:+ LOG.info("copilot_click_settle_reprobe", warranted=True, probes_run=probes_run, target_count=len(targets))+ return targets+ LOG.info("copilot_click_settle_reprobe", warranted=True, probes_run=probes_run, target_count=0)+ return []+++async def _attach_reperception_targets_on_non_advancing_click(+ result: dict[str, Any],+ raw: dict[str, Any],+ ctx: AgentContext,+ attempted_selector: str | None,+) -> None:+ """Re-perceive after a click that did not advance the build (a zero-match failure or a+ successful-but-hollow observe), so the next attempt copies a grounded selector instead of+ re-emitting an invented one. Side-effect-free parse: the no-progress counter and+ last_scout_act_observe_outcome are settled by the caller and left untouched."""+ ok = bool(result.get("ok"))+ non_advancing = (not ok) or ctx.last_scout_act_observe_outcome == "hollow"+ if not non_advancing:+ return+ existing = result.get("data")+ if isinstance(existing, dict) and existing.get("actionable_targets"):+ return+ if ok:+ immediate = _grounded_actionable_targets(ctx.last_scout_act_observe_packet)+ if immediate:+ _attach_actionable_targets(result, immediate, settle_steer=False)+ return+ url, _ = await _resolve_url_title(raw, ctx)+ if not url:+ return+ parsed = await _safe_composition_evidence(+ ctx, url, timeout_seconds=settings.COPILOT_SCOUT_ACT_OBSERVE_TIMEOUT_SECONDS+ )+ targets = _grounded_actionable_targets(parsed)+ if targets:+ _attach_actionable_targets(result, targets, settle_steer=False)+ return+ settled = await _settle_grounded_targets_on_pending_update(ctx, url=url, attempted_selector=attempted_selector)+ _attach_actionable_targets(result, settled, settle_steer=True)++_TYPE_READBACK_SETTLE_SECONDS = 0.3diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex e96858cb5..944ada7da 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -36,6 +36,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (CompletionVerificationResult,CriterionVerdict,)+from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schemafrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.diagnosis_repair_contract import (@@ -86,6 +87,7 @@ from skyvern.forge.sdk.copilot.runtime import (from skyvern.forge.sdk.copilot.runtime_authoring_repair import (clear_runtime_authoring_repair_context,inject_runtime_authoring_repair_context,+ post_run_inspection_cleanly_matches,record_pending_runtime_authoring_repair_context,)from skyvern.forge.sdk.copilot.terminal_predicates import outcome_fully_verified@@ -139,6 +141,8 @@ from .composition_capture import (_active_run_terminal_evidence_result,_active_run_terminal_evidence_sample,_active_run_terminal_monitor_enabled,+ _capture_composition_evidence,+ store_post_run_page_evidence,)from .credentials import (_credential_ids_validation_error,@@ -157,7 +161,7 @@ from .guardrails import (_parameter_binding_invariant_error,_placeholder_for_parameter_type,)-from .scouting import _mark_page_inspected+from .scouting import _mark_page_inspected, _mark_post_run_page_observedLOG = structlog.get_logger()@@ -165,6 +169,8 @@ _ACTIVE_RUN_TERMINAL_MONITOR_INITIAL_DELAY_SECONDS = 30.0_ACTIVE_RUN_TERMINAL_MONITOR_INTERVAL_SECONDS = 30.0_ACTIVE_RUN_TERMINAL_MONITOR_MAX_SAMPLES = 8+_POST_RUN_REPAIR_CAPTURE_TIMEOUT_SECONDS = 30.0+# Primary exit condition: seconds of no observed progress across the combined# run / block / step heartbeat. Sized to accommodate the slowest single LLM# round-trip (~30-60 s in practice) with headroom; going tighter risks@@ -981,6 +987,37 @@ async def _attach_registered_output_parameter_values(return values_by_label+async def _capture_and_store_post_run_failure_page(+ ctx: CopilotContext,+ *,+ run_session_id: str,+ run_id: str,+ current_url: str,+) -> None:+ """Observe-only capture of the run-session failure page; the discovery extractor reads+ ctx.browser_session_id per call, so the rebind targets the run session and is restored in a finally.+ A failed or hollow capture neutralizes stale evidence to None only when it would not cleanly match+ this run_id, so the matcher's destructive clear cannot fire on the pending failure-string context."""+ prior_session_id = ctx.browser_session_id+ ctx.browser_session_id = run_session_id+ evidence: dict[str, Any] | None = None+ try:+ evidence, _ = await asyncio.wait_for(+ _capture_composition_evidence(ctx, inspected_url=current_url, current_url=current_url),+ timeout=_POST_RUN_REPAIR_CAPTURE_TIMEOUT_SECONDS,+ )+ except Exception:+ LOG.debug("Post-run runtime-repair page capture failed", exc_info=True)+ evidence = None+ finally:+ ctx.browser_session_id = prior_session_id+ if isinstance(evidence, dict) and has_bounded_page_schema(evidence):+ store_post_run_page_evidence(ctx, evidence, run_id=run_id, current_url=current_url)+ return+ if not post_run_inspection_cleanly_matches(ctx.composition_page_evidence, run_id):+ ctx.composition_page_evidence = None++async def _run_blocks_and_collect_debug(params: dict[str, Any],ctx: CopilotContext,@@ -1542,6 +1579,19 @@ async def _run_blocks_and_collect_debug(except Exception:LOG.debug("Failed to capture post-run screenshot", exc_info=True)+ if (+ not run_ok+ and run_session_id+ and _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER+ and not ctx.copilot_total_timeout_exceeded+ ):+ await _capture_and_store_post_run_failure_page(+ ctx,+ run_session_id=run_session_id,+ run_id=workflow_run.workflow_run_id,+ current_url=current_url,+ )+result_data: dict[str, Any] = {"workflow_run_id": workflow_run.workflow_run_id,"browser_session_id": run_session_id,@@ -2326,6 +2376,18 @@ async def _send_run_outcome_update(LOG.debug("copilot run_outcome send failed", exc_info=True)+def _mark_stored_post_run_failure_page(copilot_ctx: Any) -> None:+ run_id = copilot_ctx.last_run_blocks_workflow_run_id+ evidence = copilot_ctx.composition_page_evidence+ if not post_run_inspection_cleanly_matches(evidence, run_id):+ return+ url = evidence.get("current_url") or evidence.get("inspected_url") or ""+ _mark_post_run_page_observed(copilot_ctx, source_tool="inspect_page_for_composition", url=url)+ page_title = evidence.get("page_title")+ if isinstance(page_title, str) and page_title:+ _workflow_verification_evidence(copilot_ctx).page_title = page_title[:160]++async def _verify_and_record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any], handler_start: float) -> CompletionVerificationResult | None:@@ -2336,6 +2398,7 @@ async def _verify_and_record_run_blocks_result(if not run_ok:completion_verification = await _maybe_run_completion_verification(copilot_ctx, result, handler_start)_record_run_blocks_result(copilot_ctx, result, completion_verification=completion_verification)+ _mark_stored_post_run_failure_page(copilot_ctx)return completion_verificationawait _send_run_outcome_update(copilot_ctx, result, verdict="evaluating", reason_code=None, display_reason=None)diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex fdc91682c..997866421 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -15,8 +15,12 @@ from skyvern.forge import appfrom skyvern.forge.sdk.copilot.composition_browser_expressions import (scout_accessible_role_name_expression as _scout_accessible_role_name_expression,)+from skyvern.forge.sdk.copilot.composition_browser_expressions import (+ selector_match_count_expression as _selector_match_count_expression,+)from skyvern.forge.sdk.copilot.composition_evidence import (SCOUT_INTERACTION_EVIDENCE_TOOL,+ has_actionable_steer_content,has_bounded_page_schema,)from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy@@ -194,6 +198,38 @@ async def _capture_accessible_role_name(_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS = 2.0+async def _selector_live_match_count(+ ctx: AgentContext, selector: str | None, *, timeout_seconds: float | None = None+) -> int | None:+ """Live element count for a selector, or None when the page read is unavailable or the selector+ is invalid; lets a failed click tell an invented zero-match selector from a not-yet-actionable one."""+ selector = _selector_text(selector)+ if not selector:+ return None+ server = getattr(ctx, "discovery_mcp_server", None)+ if server is None:+ return None+ timeout = _PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS if timeout_seconds is None else timeout_seconds+ if timeout <= 0:+ return None+ try:+ result = await asyncio.wait_for(+ server.call_internal_tool(+ "skyvern_evaluate",+ {"expression": _selector_match_count_expression(selector)},+ ),+ timeout=timeout,+ )+ except Exception:+ return None+ if not isinstance(result, dict) or not result.get("ok"):+ return None+ value = (result.get("data") or {}).get("result")+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return None+ return value++async def _capture_scout_role_name(ctx: AgentContext, selector: str | None) -> None:"""Stash (selector, role, accessible_name) before an in-flight click that may navigate.@@ -346,6 +382,10 @@ async def _scout_act_observe_page_evidence(ctx: AgentContext, *, url: str) -> di)if parsed is not None and has_bounded_page_schema(parsed):outcome = "attached"+ elif parsed is not None and has_actionable_steer_content(parsed):+ # Standalone clickable controls are steer-able grounding but not forward progress:+ # keep parsed for the steer while the hollow outcome still climbs the no-progress counter.+ outcome = "hollow"elif parsed is not None:outcome = "hollow"parsed = None@@ -355,6 +395,7 @@ async def _scout_act_observe_page_evidence(ctx: AgentContext, *, url: str) -> diparsed = Noneoutcome = "error"ctx.last_scout_act_observe_outcome = outcome+ ctx.last_scout_act_observe_packet = parsedLOG.info("copilot_scout_act_observe",outcome=outcome,@@ -385,7 +426,7 @@ async def _register_scout_interaction_observation(page_evidence: dict[str, Any] | None = Noneif tool_name in _ACT_OBSERVE_TOOLS:parsed = await _scout_act_observe_page_evidence(ctx, url=url)- if parsed is not None:+ if parsed is not None and has_bounded_page_schema(parsed):# Identity keys overwrite the parsed packet so the entry stays a# scout_interaction observation, with the schema merged before append.evidence = {**parsed, **evidence}@@ -553,27 +594,73 @@ def _reset_evaluate_tracker(ctx: AgentContext) -> None:def _actionable_target_identities(evidence: dict[str, Any]) -> list[tuple[str, str]]:+ affordances: list[tuple[str, str]] = []+ fields: list[tuple[str, str]] = []++ def identity(control: Any) -> tuple[str, str] | None:+ if not isinstance(control, dict):+ return None+ selector = _summary_text(control.get("selector"))+ text = _summary_text(control.get("text") or control.get("value") or control.get("aria_label"))+ if selector or text:+ return (selector, text)+ return None++ def add_affordance(control: Any) -> None:+ ident = identity(control)+ if ident is not None:+ affordances.append(ident)++ for form in evidence.get("forms") or []:+ if not isinstance(form, dict):+ continue+ for control in form.get("submit_controls") or []:+ add_affordance(control)+ for field_entry in form.get("fields") or []:+ ident = identity(field_entry)+ if ident is not None:+ fields.append(ident)+ for target in evidence.get("navigation_targets") or []:+ add_affordance(target)+ for control in evidence.get("clickable_controls") or []:+ add_affordance(control)+ for overlay in evidence.get("modal_overlays") or []:+ if not isinstance(overlay, dict):+ continue+ for control in overlay.get("dismiss_controls") or []:+ add_affordance(control)+ for container in evidence.get("result_containers") or []:+ add_affordance(container)+ # Click affordances precede plain input fields, and selector-bearing controls precede+ # text-only ones, so the capped payload surfaces executable selectors first.+ affordances.sort(key=lambda item: 0 if item[0] else 1)+ return affordances + fields+++def _click_affordance_target_identities(evidence: dict[str, Any]) -> list[tuple[str, str]]:+ """Selector-bearing click affordances only (submit controls, navigation targets, standalone+ clickable controls, modal dismiss controls), so the re-perception attach hands back a real+ selector to copy and never a plain input field, result container, or text-only control."""identities: list[tuple[str, str]] = []def add(control: Any) -> None:if not isinstance(control, dict):returnselector = _summary_text(control.get("selector"))+ if not selector:+ returntext = _summary_text(control.get("text") or control.get("value") or control.get("aria_label"))- if selector or text:- identities.append((selector, text))+ identities.append((selector, text))for form in evidence.get("forms") or []:if not isinstance(form, dict):continue- for field_entry in form.get("fields") or []:- add(field_entry)for control in form.get("submit_controls") or []:add(control)for target in evidence.get("navigation_targets") or []:add(target)- for container in evidence.get("result_containers") or []:- add(container)+ for control in evidence.get("clickable_controls") or []:+ add(control)for overlay in evidence.get("modal_overlays") or []:if not isinstance(overlay, dict):continue@@ -851,7 +938,7 @@ async def _maybe_steer_evaluate_to_action(if isinstance(page_evidence, _UnsetEvidence)else page_evidence)- if parsed is None or not has_bounded_page_schema(parsed):+ if parsed is None or not has_actionable_steer_content(parsed):_reset_evaluate_tracker(ctx)return Falseloaded_results = loaded_result_composition_evidence_from_page(parsed)diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.pyindex de71f98a4..71438ae4e 100644--- a/tests/unit/test_copilot_composition_evidence.py+++ b/tests/unit/test_copilot_composition_evidence.py@@ -12,6 +12,7 @@ from unittest.mock import patchimport pytestimport yaml+from skyvern.config import settingsfrom skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.build_phase import BuildPhasefrom skyvern.forge.sdk.copilot.composition_browser_expressions import (@@ -19,7 +20,9 @@ from skyvern.forge.sdk.copilot.composition_browser_expressions import (COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION,)from skyvern.forge.sdk.copilot.composition_evidence import (+ _MAX_CLICKABLE_CONTROLS,composition_page_evidence_error,+ has_actionable_steer_content,has_bounded_page_schema,merge_visual_composition_evidence,normalize_block_observation_refs,@@ -2172,6 +2175,100 @@ def test_structured_blank_payload_is_not_schema_empty() -> None:assert parsed["schema_empty_page"] is False+_STANDALONE_CONTROLS_URL = "https://app.example.com/account"+_STANDALONE_CONTROLS_HTML = """<!DOCTYPE html>+<html><head><title>Account Information</title></head>+<body>+ <h2>Business address</h2>+ <button id="biz-tile" data-action="business">Business</button>+ <div role="button" data-action="selectAddress">2468 Peach Orchard Ct</div>+ <button class="tile">Duplicate</button>+ <button class="tile">Duplicate</button>+ <p>Choose an account type to continue.</p>+</body></html>+"""+++def test_clickable_controls_surface_grounded_selectors_outside_forms() -> None:+ parsed = parse_composition_html(+ _STANDALONE_CONTROLS_HTML,+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ by_selector = {control.get("selector"): control for control in parsed["clickable_controls"]}+ assert "#biz-tile" in by_selector+ assert 'div[data-action="selectAddress"]' in by_selector+ assert by_selector['div[data-action="selectAddress"]']["text"] == "2468 Peach Orchard Ct"+++def test_clickable_controls_exclude_in_form_buttons() -> None:+ parsed = parse_composition_html(+ "<html><body><form><button id='in-form' data-action='business'>In form</button></form>"+ "<button id='out-form' data-action='business'>Out</button></body></html>",+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ selectors = {control.get("selector") for control in parsed["clickable_controls"]}+ assert "#in-form" not in selectors+ assert "#out-form" in selectors+++def test_clickable_controls_with_shared_class_fall_back_to_text_only() -> None:+ parsed = parse_composition_html(+ _STANDALONE_CONTROLS_HTML,+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ duplicates = [control for control in parsed["clickable_controls"] if control.get("text") == "Duplicate"]+ assert len(duplicates) == 1+ assert "selector" not in duplicates[0]+++def test_clickable_controls_key_absent_when_channel_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_REPERCEPTION_ATTACH_ENABLED", False)+ parsed = parse_composition_html(+ _STANDALONE_CONTROLS_HTML,+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ assert "clickable_controls" not in parsed+ assert has_actionable_steer_content(parsed) is False+++def test_structured_clickable_controls_key_absent_when_channel_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_REPERCEPTION_ATTACH_ENABLED", False)+ parsed = parse_composition_structured(+ {"page_title": "Account", "clickable_controls": [{"selector": "#biz-tile", "text": "Business"}]},+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ assert "clickable_controls" not in parsed+ assert has_actionable_steer_content(parsed) is False+++def test_standalone_control_page_splits_steer_content_from_bounded_schema() -> None:+ parsed = parse_composition_html(+ _STANDALONE_CONTROLS_HTML,+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ assert has_bounded_page_schema(parsed) is False+ assert has_actionable_steer_content(parsed) is True+ assert parsed["schema_empty_page"] is True+++def test_clickable_controls_dedup_against_navigation_and_respect_cap() -> None:+ many = "".join(f'<button data-action="tile{i}">Tile {i}</button>' for i in range(_MAX_CLICKABLE_CONTROLS + 8))+ parsed = parse_composition_html(+ f"<html><body><a href='/go' id='nav'>Go</a>{many}</body></html>",+ inspected_url=_STANDALONE_CONTROLS_URL,+ current_url=_STANDALONE_CONTROLS_URL,+ )+ selectors = [control.get("selector") for control in parsed["clickable_controls"]]+ assert "#nav" not in selectors+ assert len(parsed["clickable_controls"]) <= _MAX_CLICKABLE_CONTROLS++# JS-DOM fidelity: run the real extractor against a live DOM and compare to the HTML parser@@ -2233,6 +2330,9 @@ def _ac_projection(evidence: dict[str, Any]) -> dict[str, Any]:"page_title": evidence["page_title"],"forms": forms,"navigation_targets": sorted(target["href"] for target in evidence["navigation_targets"]),+ "clickable_controls": sorted(+ (control.get("selector", ""), control.get("text", "")) for control in evidence["clickable_controls"]+ ),"result_containers": sorted((rc["tag"], rc["selector"]) for rc in evidence["result_containers"]),"result_content": sorted((rc["selector"], rc.get("row_count"), tuple(rc.get("sample_rows") or []), rc.get("text_excerpt", ""))@@ -2359,6 +2459,46 @@ async def test_structured_extractor_matches_html_parser_on_heavy_results_cart_doassert structured["forms"]+_STANDALONE_CONTROLS_LIVE_URL = "https://app.example.com/account-info"+++@_skip_no_browser+async def test_structured_extractor_matches_html_parser_on_standalone_controls_dom() -> None:+ from playwright.async_api import async_playwright++ async def _handle(route: Any) -> None:+ if route.request.url == _STANDALONE_CONTROLS_LIVE_URL:+ await route.fulfill(status=200, content_type="text/html", body=_STANDALONE_CONTROLS_HTML)+ else:+ await route.abort()++ async with async_playwright() as p:+ browser = await p.chromium.launch(headless=True)+ context = await browser.new_context()+ await context.route("**/*", _handle)+ page = await context.new_page()+ await page.goto(_STANDALONE_CONTROLS_LIVE_URL, wait_until="domcontentloaded")+ await page.wait_for_selector("#biz-tile")+ raw = await page.evaluate(COMPOSITION_STRUCTURED_EVIDENCE_EXPRESSION)+ content = await page.content()+ await context.close()+ await browser.close()++ structured = parse_composition_structured(+ json.loads(raw), inspected_url=_STANDALONE_CONTROLS_LIVE_URL, current_url=_STANDALONE_CONTROLS_LIVE_URL+ )+ html_parsed = parse_composition_html(+ content, inspected_url=_STANDALONE_CONTROLS_LIVE_URL, current_url=_STANDALONE_CONTROLS_LIVE_URL+ )++ assert structured is not None+ assert _ac_projection(structured) == _ac_projection(html_parsed)+ surfaced = {control.get("selector", "") for control in structured["clickable_controls"]}+ assert "#biz-tile" in surfaced+ assert 'div[data-action="selectAddress"]' in surfaced++# Tools-layer invariant: cheap path skips get_html; failure falls backdiff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.pyindex 848fd92c5..61f57065b 100644--- a/tests/unit/test_copilot_diagnosis_repair_contract.py+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py@@ -6,6 +6,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest+from structlog.testing import capture_logsfrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.code_block_preflight import SANDBOX_UNRESOLVED_NAME_REASON_CODE@@ -24,8 +25,10 @@ from skyvern.forge.sdk.copilot.run_outcome import (from skyvern.forge.sdk.copilot.runtime_authoring_repair import (finalize_runtime_authoring_repair_context_from_page_observation,inject_runtime_authoring_repair_context,+ post_run_inspection_cleanly_matches,)from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module+from skyvern.forge.sdk.copilot.tools.composition_capture import store_post_run_page_evidencefrom skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode@@ -333,9 +336,14 @@ def test_failed_run_finalizes_runtime_authoring_repair_context_after_matching_pa"source_tool": "inspect_page_for_composition","current_url": "https://example.test/search?case=secret","page_title": "Search results",- "forms": [{"label": "Search", "selector": "#search", "input_type": "text"}],- "result_containers": [{"label": "No results", "text": "No matching records"}],- "navigation_targets": [{"label": "Search", "selector": "button.search", "disabled": True}],+ "forms": [+ {+ "fields": [{"label": "Search", "selector": "#search"}],+ "submit_controls": [{"text": "Go", "selector": "button.search", "disabled": True}],+ }+ ],+ "result_containers": [{"selector": "#results", "text_excerpt": "No matching records"}],+ "navigation_targets": [{"text": "Next page", "selector": "a.next"}],}result = {"ok": False,@@ -355,9 +363,9 @@ def test_failed_run_finalizes_runtime_authoring_repair_context_after_matching_paassert repair_context.current_title_present is Trueassert repair_context.page_evidence_source == "inspect_page_for_composition"assert repair_context.observed_after_workflow_run is True- assert repair_context.page_form_summaries == ["Search #search"]- assert repair_context.page_result_summaries == ["No results No matching records"]- assert repair_context.page_action_summaries == ["Search button.search disabled"]+ assert repair_context.page_form_summaries == ["Search #search", "Go button.search disabled"]+ assert repair_context.page_result_summaries == ["#results No matching records"]+ assert repair_context.page_action_summaries == ["Next page a.next"]assert "case=secret" not in repair_context.model_dump_json()@@ -405,6 +413,85 @@ def test_failed_run_injects_pending_runtime_authoring_context_before_page_observassert contract.repair_decision.target_blocks == ["search_registry"]+def _injected_repair_log(events: list[dict[str, object]]) -> dict[str, object]:+ matches = [event for event in events if event.get("event") == "Injected runtime authoring repair context"]+ assert len(matches) == 1+ return matches[0]+++def test_runtime_authoring_repair_injection_logs_observed_flip() -> None:+ grounded_ctx = _ctx()+ grounded_ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ run_execution_module._record_run_blocks_result(+ grounded_ctx,+ {+ "ok": False,+ "error": "Run failed.",+ "data": {+ "workflow_run_id": "wr_failed",+ "overall_status": "failed",+ "blocks": [+ {+ "label": "search_registry",+ "status": "failed",+ "failure_reason": 'Timeout waiting for locator("#results")',+ }+ ],+ },+ },+ )+ grounded_ctx.composition_page_evidence = {+ "workflow_run_id": "wr_failed",+ "observed_after_workflow_run": True,+ "source_tool": "inspect_page_for_composition",+ "current_url": "https://example.test/search",+ "page_title": "Search results",+ "forms": [{"fields": [{"label": "Search", "selector": "#search"}]}],+ "result_containers": [{"selector": "#results", "text_excerpt": "No matching records"}],+ "navigation_targets": [{"text": "Next page", "selector": "a.next"}],+ }+ grounded_result = {+ "ok": False,+ "error": "Run failed.",+ "data": {"workflow_run_id": "wr_failed", "overall_status": "failed"},+ }+ with capture_logs() as grounded_events:+ inject_runtime_authoring_repair_context(grounded_ctx, grounded_result)+ grounded_log = _injected_repair_log(grounded_events)+ assert grounded_log["observed_after_workflow_run"] is True+ assert grounded_log["workflow_run_id"] == "wr_failed"+ assert grounded_log["page_form_summary_count"] > 0+ assert grounded_log["page_result_summary_count"] > 0+ assert grounded_log["page_action_summary_count"] > 0++ fallback_ctx = _ctx()+ fallback_ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ fallback_result = {+ "ok": False,+ "error": "Run failed.",+ "data": {+ "workflow_run_id": "wr_failed",+ "overall_status": "failed",+ "blocks": [+ {+ "label": "search_registry",+ "status": "failed",+ "failure_reason": 'Locator.wait_for: strict mode violation: get_by_text("Order Details")',+ }+ ],+ },+ }+ run_execution_module._record_run_blocks_result(fallback_ctx, fallback_result)+ with capture_logs() as fallback_events:+ inject_runtime_authoring_repair_context(fallback_ctx, fallback_result)+ fallback_log = _injected_repair_log(fallback_events)+ assert fallback_log["observed_after_workflow_run"] is False+ assert fallback_log["workflow_run_id"] == "wr_failed"+ assert fallback_log["page_form_summary_count"] == 0+ assert fallback_log["page_result_summary_count"] == 0+ assert fallback_log["page_action_summary_count"] == 0++def test_runtime_authoring_repair_context_suppressed_for_stale_or_successful_runs() -> None:stale_ctx = _ctx()run_execution_module._record_run_blocks_result(@@ -724,8 +811,13 @@ def test_runtime_authoring_repair_context_sanitizes_failure_and_page_summaries()"source_tool": "inspect_page_for_composition","current_url": "https://user:[email protected]/search?password=hunter2","page_title": "Search",- "forms": [{"label": "Password password=hunter2", "selector": "#password"}],- "result_containers": [{"label": "Result", "text": "token=secret-token"}],+ "forms": [+ {+ "fields": [{"label": "Password password=hunter2", "selector": "#password"}],+ "submit_controls": [{"text": "Submit", "selector": "#submit"}],+ }+ ],+ "result_containers": [{"selector": "#result", "text_excerpt": "token=secret-token"}],}result = {"ok": False, "data": {"workflow_run_id": "wr_secret", "overall_status": "failed"}}@@ -1809,3 +1901,256 @@ def test_diagnosis_tool_error_preserves_terminal_challenge_blocker_category() ->== DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER)assert ctx.latest_diagnosis_repair_contract.repair_decision.next_action == RepairNextAction.STOP+++def _failed_run_result(run_id: str = "wr_failed") -> dict[str, object]:+ return {+ "ok": False,+ "error": "Run failed.",+ "data": {+ "workflow_run_id": run_id,+ "overall_status": "failed",+ "blocks": [+ {+ "label": "search_registry",+ "status": "failed",+ "failure_reason": 'Timeout waiting for locator("button.icon-btn")',+ }+ ],+ },+ }+++def _bounded_failure_page_evidence() -> dict[str, object]:+ return {+ "source_tool": "inspect_page_for_composition",+ "current_url": "https://example.test/app/results",+ "page_title": "Results",+ "forms": [+ {+ "fields": [{"label": "Query", "selector": "#q"}],+ "submit_controls": [{"text": "", "selector": "button.icon-btn", "disabled": False}],+ }+ ],+ "navigation_targets": [{"text": "Details", "selector": "a.detail"}],+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results",+ "row_selector": "#results tbody tr",+ "expand_toggle_candidates": ["#results tbody tr button"],+ "sample_rows": ["First result row"],+ }+ ],+ "challenge_controls": [],+ }+++def test_post_run_failure_page_store_mark_inject_grounds_repair_without_finalizing_early() -> None:+ ctx = _ctx()+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER++ stored = store_post_run_page_evidence(+ ctx, _bounded_failure_page_evidence(), run_id="wr_failed", current_url="https://example.test/app/results"+ )+ assert ctx.composition_page_evidence is stored+ assert stored["observed_after_workflow_run"] is True+ assert stored["workflow_run_id"] == "wr_failed"+ assert ctx.last_code_authoring_repair_context is None++ run_execution_module._record_run_blocks_result(ctx, _failed_run_result())+ assert ctx.pending_code_authoring_runtime_repair_context is not None+ assert ctx.post_run_page_observation_workflow_run_id is None++ run_execution_module._mark_stored_post_run_failure_page(ctx)+ assert ctx.post_run_page_observation_tool == "inspect_page_for_composition"+ assert ctx.post_run_page_observation_workflow_run_id == "wr_failed"+ assert ctx.post_run_page_observation_after_failed_test is True+ assert ctx.last_code_authoring_repair_context is None++ result = {"ok": False, "data": {"workflow_run_id": "wr_failed", "overall_status": "failed"}}+ inject_runtime_authoring_repair_context(ctx, result)++ repair_context = ctx.last_code_authoring_repair_context+ assert isinstance(repair_context, CodeAuthoringRepairContext)+ assert repair_context.observed_after_workflow_run is True+ assert result["data"]["authoring_repair_context"]["observed_after_workflow_run"] is True+ grounded = repair_context.page_form_summaries + repair_context.page_action_summaries+ assert any("button.icon-btn" in summary for summary in grounded)+ assert repair_context.page_result_summaries+++def test_stored_terminal_challenge_page_feeds_classifier_and_suppresses_authoring_context() -> None:+ ctx = _ctx()+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ ctx.composition_page_evidence = {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": True,+ "workflow_run_id": "wr_failed",+ "current_url": "https://example.test/challenge",+ "anti_bot_indicators": ["verify you are human"],+ "challenge_controls": [{"text": "Verify", "selector": "#verify"}],+ "challenge_state": {"detected": True, "gates_submit_controls": True},+ "forms": [{"fields": [{"label": "Query", "selector": "#q"}], "submit_controls": []}],+ }++ run_execution_module._record_run_blocks_result(ctx, _failed_run_result())+ assert ctx.last_test_anti_bot++ result = {"ok": False, "data": {"workflow_run_id": "wr_failed", "overall_status": "failed"}}+ inject_runtime_authoring_repair_context(ctx, result)+ assert "authoring_repair_context" not in result["data"]+ assert ctx.last_code_authoring_repair_context is None+++ "evidence,run_id,expected",+ [+ (+ {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": True,+ "workflow_run_id": "wr",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ "wr",+ True,+ ),+ (+ {+ "source_tool": "evaluate",+ "observed_after_workflow_run": True,+ "workflow_run_id": "wr",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ "wr",+ False,+ ),+ (+ {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": False,+ "workflow_run_id": "wr",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ "wr",+ False,+ ),+ (+ {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": True,+ "workflow_run_id": "other",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ "wr",+ False,+ ),+ (+ {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": True,+ "workflow_run_id": "wr",+ "forms": [],+ },+ "wr",+ False,+ ),+ (None, "wr", False),+ ],+)+def test_post_run_inspection_cleanly_matches_predicate(evidence: object, run_id: str, expected: bool) -> None:+ assert post_run_inspection_cleanly_matches(evidence, run_id) is expected+++async def test_bounded_seam_capture_is_stored_stamped_without_touching_budget(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = _ctx()+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ captured = _bounded_failure_page_evidence()+ captured.pop("workflow_run_id", None)++ async def fake_capture(+ _ctx: CopilotContext, *, inspected_url: str, current_url: str+ ) -> tuple[dict[str, object], None]:+ return dict(captured), None++ monkeypatch.setattr(run_execution_module, "_capture_composition_evidence", fake_capture)++ await run_execution_module._capture_and_store_post_run_failure_page(+ ctx, run_session_id="run_session", run_id="wr_failed", current_url="https://example.test/app/results"+ )++ evidence = ctx.composition_page_evidence+ assert isinstance(evidence, dict)+ assert evidence["workflow_run_id"] == "wr_failed"+ assert evidence["observed_after_workflow_run"] is True+ assert post_run_inspection_cleanly_matches(evidence, "wr_failed")+ assert ctx.page_inspection_calls_this_turn == 0+ assert ctx.browser_session_id is None+++ "stale",+ [+ {+ "source_tool": "evaluate",+ "observed_after_workflow_run": True,+ "workflow_run_id": "wr_failed",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": False,+ "workflow_run_id": "wr_failed",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ {+ "source_tool": "inspect_page_for_composition",+ "observed_after_workflow_run": True,+ "workflow_run_id": "wr_other",+ "forms": [{"fields": [{"label": "a", "selector": "#a"}]}],+ },+ ],+)+async def test_failed_seam_capture_neutralizes_non_matching_evidence(+ monkeypatch: pytest.MonkeyPatch, stale: dict[str, object]+) -> None:+ ctx = _ctx()+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ ctx.composition_page_evidence = stale++ async def fake_capture(_ctx: CopilotContext, *, inspected_url: str, current_url: str) -> tuple[None, None]:+ return None, None++ monkeypatch.setattr(run_execution_module, "_capture_composition_evidence", fake_capture)++ await run_execution_module._capture_and_store_post_run_failure_page(+ ctx, run_session_id="run_session", run_id="wr_failed", current_url="https://example.test/app"+ )+ assert ctx.composition_page_evidence is None+++async def test_failed_seam_capture_preserves_clean_matching_evidence(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = _ctx()+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ clean = _bounded_failure_page_evidence()+ clean["observed_after_workflow_run"] = True+ clean["workflow_run_id"] = "wr_failed"+ ctx.composition_page_evidence = clean++ async def fake_capture(_ctx: CopilotContext, *, inspected_url: str, current_url: str) -> tuple[None, None]:+ return None, None++ monkeypatch.setattr(run_execution_module, "_capture_composition_evidence", fake_capture)++ await run_execution_module._capture_and_store_post_run_failure_page(+ ctx, run_session_id="run_session", run_id="wr_failed", current_url="https://example.test/app"+ )+ assert ctx.composition_page_evidence is cleandiff --git a/tests/unit/test_copilot_evaluate_page_evidence.py b/tests/unit/test_copilot_evaluate_page_evidence.pyindex d1da0f987..d1669e9ec 100644--- a/tests/unit/test_copilot_evaluate_page_evidence.py+++ b/tests/unit/test_copilot_evaluate_page_evidence.py@@ -281,8 +281,8 @@ async def test_current_page_inspection_finalizes_runtime_repair_context_for_next"current_url": current_url,"page_title": "Search","source_tool": "inspect_page_for_composition",- "forms": [{"label": "Search", "selector": "#search"}],- "result_containers": [{"label": "No results", "text": "No matching records"}],+ "forms": [{"fields": [{"label": "Search", "selector": "#search"}], "submit_controls": []}],+ "result_containers": [{"selector": "#results", "text_excerpt": "No matching records"}],"navigation_targets": [],"challenge_controls": [],},@@ -312,7 +312,7 @@ async def test_current_page_inspection_finalizes_runtime_repair_context_for_nextassert ctx.pending_code_authoring_runtime_repair_context is Noneassert ctx.last_code_authoring_repair_context is not Noneassert ctx.last_code_authoring_repair_context.current_origin == "https://example.test"- assert ctx.last_code_authoring_repair_context.page_result_summaries == ["No results No matching records"]+ assert ctx.last_code_authoring_repair_context.page_result_summaries == ["#results No matching records"]assert "runtime_failure_class: timeout_waiting_for_selector" in prompt- assert "page_results: No results No matching records" in prompt+ assert "page_results: #results No matching records" in promptassert "case=secret" not in ctx.last_code_authoring_repair_context.model_dump_json()diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex ad67d5ad4..4c35bc638 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -1009,6 +1009,7 @@ class TestBrowserInteractionObservationHooks:pending_browser_interaction_observation=None,pending_scout_typed_value=None,pending_scout_role_name=None,+ pending_scout_click_selector=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -1042,6 +1043,7 @@ class TestBrowserInteractionObservationHooks:),pending_scout_typed_value=None,pending_scout_role_name=None,+ pending_scout_click_selector=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -1096,6 +1098,7 @@ class TestScoutedInteractionCapture:pending_browser_interaction_observation=None,pending_scout_typed_value=None,pending_scout_role_name=None,+ pending_scout_click_selector=None,discovery_mcp_server=None,browser_session_id=None,scouted_interactions=[],diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.pyindex dff3cc4bd..d6afa5cd5 100644--- a/tests/unit/test_copilot_scout_act_observe.py+++ b/tests/unit/test_copilot_scout_act_observe.py@@ -10,16 +10,21 @@ import copyimport jsonfrom types import SimpleNamespacefrom typing import Any-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, MagicMockimport pytestfrom skyvern.config import settings+from skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.composition_evidence import (_auto_credit_interaction_observation,has_bounded_page_schema,)-from skyvern.forge.sdk.copilot.enforcement import _RECENT_TOOL_OUTPUT_CHAR_CAP+from skyvern.forge.sdk.copilot.enforcement import (+ _RECENT_TOOL_OUTPUT_CHAR_CAP,+ MAX_NO_PROGRESS_INTERACTION_ATTEMPTS,+)+from skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.tools import _click_post_hookfrom skyvern.forge.sdk.copilot.tools.scouting import (_consume_pending_browser_interaction_observation,@@ -71,6 +76,7 @@ def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleNpending_browser_interaction_observation=None,pending_scout_typed_value=None,pending_scout_role_name=None,+ pending_scout_click_selector=None,discovery_mcp_server=server,scouted_interactions=[],scout_trajectory=[],@@ -428,3 +434,305 @@ class TestNoProgressInteractionAccounting:assert consumed is Trueassert ctx.consecutive_no_progress_interaction_count == 0+++def _standalone_controls_payload() -> dict[str, Any]:+ return {+ "page_title": "Account Information",+ "forms": [],+ "navigation_targets": [],+ "result_containers": [],+ "clickable_controls": [+ {"selector": "#biz-tile", "text": "Business"},+ {"selector": 'div[data-action="selectAddress"]', "text": "2468 Peach Orchard Ct"},+ ],+ }+++def _ungroundable_payload() -> dict[str, Any]:+ return {"page_title": "Loading", "forms": []}+++class TestNonAdvancingClickReperception:+ @pytest.mark.asyncio+ async def test_hollow_click_attaches_grounded_targets_without_touching_outcome(self) -> None:+ ctx = _np_ctx(server=_server_returning(_standalone_controls_payload()))++ result = await _run_click(ctx)++ assert ctx.last_scout_act_observe_outcome == "hollow"+ assert ctx.consecutive_no_progress_interaction_count == 1+ selectors = {target.get("selector") for target in result["data"]["actionable_targets"]}+ assert "#biz-tile" in selectors+ assert 'div[data-action="selectAddress"]' in selectors++ @pytest.mark.asyncio+ async def test_failed_click_attaches_grounded_targets(self) -> None:+ ctx = _np_ctx(server=_server_returning(_standalone_controls_payload()))++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 5000ms exceeded"},+ {"browser_context": {"url": _LANDING_URL}},+ ctx,+ )++ assert ctx.consecutive_no_progress_interaction_count == 1+ selectors = {target.get("selector") for target in result["data"]["actionable_targets"]}+ assert "#biz-tile" in selectors++ @pytest.mark.asyncio+ async def test_ungroundable_non_advancing_click_attaches_no_targets(self) -> None:+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))++ result = await _run_click(ctx)++ assert ctx.last_scout_act_observe_outcome == "hollow"+ assert ctx.consecutive_no_progress_interaction_count == 1+ assert "actionable_targets" not in result["data"]++ @pytest.mark.asyncio+ async def test_empty_url_attaches_no_targets(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def no_url(_raw: dict[str, Any], _ctx: AgentContext) -> tuple[str, str]:+ return "", ""++ monkeypatch.setattr(tools_module.mcp_hooks, "_resolve_url_title", no_url)+ ctx = _np_ctx(server=_server_returning(_standalone_controls_payload()))++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 5000ms exceeded"},+ {"browser_context": {}},+ ctx,+ )++ assert ctx.consecutive_no_progress_interaction_count == 1+ assert "actionable_targets" not in (result.get("data") or {})++ @pytest.mark.asyncio+ async def test_attached_click_does_not_attach_reperception_targets(self) -> None:+ ctx = _np_ctx(server=_server_returning(_bounded_extractor_payload()))++ result = await _run_click(ctx)++ assert ctx.last_scout_act_observe_outcome == "attached"+ assert "actionable_targets" not in result["data"]++ @pytest.mark.asyncio+ async def test_ungroundable_churn_still_halts_at_max_without_reset(self) -> None:+ ctx = AgentContext(+ organization_id="o_1",+ workflow_id="w_1",+ workflow_permanent_id="wpid_1",+ workflow_yaml="",+ browser_session_id="pbs_1",+ stream=MagicMock(),+ )+ ctx.discovery_mcp_server = _server_returning(_ungroundable_payload())++ for expected in range(1, MAX_NO_PROGRESS_INTERACTION_ATTEMPTS + 1):+ result = await _run_click(ctx)+ assert "actionable_targets" not in result["data"]+ assert ctx.consecutive_no_progress_interaction_count == expected++ assert ctx.consecutive_no_progress_interaction_count == MAX_NO_PROGRESS_INTERACTION_ATTEMPTS+ assert ctx.blocker_signal is not None+++def _sequenced_evidence(parses: list[dict[str, Any] | None]) -> Any:+ calls = {"n": 0}++ async def fake(_ctx: Any, *, inspected_url: str, current_url: str, timeout_seconds: float) -> dict[str, Any] | None:+ index = calls["n"]+ calls["n"] += 1+ return parses[index] if index < len(parses) else parses[-1]++ fake.calls = calls # type: ignore[attr-defined]+ return fake+++def _live_match(count: int | None) -> Any:+ async def fake(_ctx: Any, _selector: str | None, *, timeout_seconds: float | None = None) -> int | None:+ return count++ return fake+++class TestPreconditionGatedClickSettle:+ @pytest.mark.asyncio+ async def test_settle_attaches_grounded_targets_and_steer_after_pending_ajax(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)+ monkeypatch.setattr(+ tools_module.mcp_hooks,+ "_composition_get_structured_evidence",+ _sequenced_evidence([None, None, _standalone_controls_payload()]),+ )+ monkeypatch.setattr(tools_module.mcp_hooks, "_selector_live_match_count", _live_match(1))+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))+ ctx.pending_scout_click_selector = 'button[data-action="selectAddress"]'++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 10000ms exceeded"},+ {"browser_context": {"url": _LANDING_URL}},+ ctx,+ )++ data = result["data"]+ selectors = {target.get("selector") for target in data["actionable_targets"]}+ assert "#biz-tile" in selectors+ assert data["next_action"] == "click"+ assert data["next_action_reason"]+ assert ctx.consecutive_no_progress_interaction_count == 1+ assert ctx.last_scout_act_observe_outcome is None++ @pytest.mark.asyncio+ async def test_zero_match_invented_selector_skips_settle(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)+ evidence = _sequenced_evidence([None, _standalone_controls_payload()])+ monkeypatch.setattr(tools_module.mcp_hooks, "_composition_get_structured_evidence", evidence)+ monkeypatch.setattr(tools_module.mcp_hooks, "_selector_live_match_count", _live_match(0))+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))+ ctx.pending_scout_click_selector = "button[data-action='invented']"++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 10000ms exceeded"},+ {"browser_context": {"url": _LANDING_URL}},+ ctx,+ )++ assert "actionable_targets" not in (result.get("data") or {})+ assert evidence.calls["n"] == 1+ assert ctx.consecutive_no_progress_interaction_count == 1++ @pytest.mark.asyncio+ async def test_settle_is_bounded_and_attaches_nothing_when_never_populates(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_MAX_PROBES", 3)+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DEADLINE_SECONDS", 5.0)+ evidence = _sequenced_evidence([None])+ monkeypatch.setattr(tools_module.mcp_hooks, "_composition_get_structured_evidence", evidence)+ monkeypatch.setattr(tools_module.mcp_hooks, "_selector_live_match_count", _live_match(1))+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))+ ctx.pending_scout_click_selector = 'button[data-action="selectAddress"]'++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 10000ms exceeded"},+ {"browser_context": {"url": _LANDING_URL}},+ ctx,+ )++ assert "actionable_targets" not in (result.get("data") or {})+ assert evidence.calls["n"] == 4+ assert ctx.consecutive_no_progress_interaction_count == 1++ @pytest.mark.asyncio+ async def test_unreadable_selector_skips_settle(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)+ evidence = _sequenced_evidence([None, _standalone_controls_payload()])+ monkeypatch.setattr(tools_module.mcp_hooks, "_composition_get_structured_evidence", evidence)+ monkeypatch.setattr(tools_module.mcp_hooks, "_selector_live_match_count", _live_match(None))+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 10000ms exceeded"},+ {"browser_context": {"url": _LANDING_URL}},+ ctx,+ )++ assert "actionable_targets" not in (result.get("data") or {})+ assert evidence.calls["n"] == 1+ assert ctx.consecutive_no_progress_interaction_count == 1++ @pytest.mark.asyncio+ async def test_expired_deadline_runs_no_warrants_or_extractor_probe(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_MAX_PROBES", 5)+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DEADLINE_SECONDS", 0.0)+ evidence = _sequenced_evidence([None, _standalone_controls_payload()])+ monkeypatch.setattr(tools_module.mcp_hooks, "_composition_get_structured_evidence", evidence)+ live = _counting_live_match(1)+ monkeypatch.setattr(tools_module.mcp_hooks, "_selector_live_match_count", live)+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))+ ctx.pending_scout_click_selector = 'button[data-action="selectAddress"]'++ result = await _click_post_hook(+ {"ok": False, "error": "Timeout 10000ms exceeded"},+ {"browser_context": {"url": _LANDING_URL}},+ ctx,+ )++ assert "actionable_targets" not in (result.get("data") or {})+ assert evidence.calls["n"] == 1+ assert live.calls["n"] == 0+ assert ctx.consecutive_no_progress_interaction_count == 1+++def _counting_live_match(count: int | None) -> Any:+ calls = {"n": 0}++ async def fake(_ctx: Any, _selector: str | None, *, timeout_seconds: float | None = None) -> int | None:+ calls["n"] += 1+ return count++ fake.calls = calls # type: ignore[attr-defined]+ return fake+++class TestClickReperceptionHardening:+ @pytest.mark.asyncio+ async def test_ok_hollow_empty_packet_falls_through_to_settle(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)+ monkeypatch.setattr(+ tools_module.mcp_hooks,+ "_composition_get_structured_evidence",+ _sequenced_evidence([None, _standalone_controls_payload()]),+ )+ monkeypatch.setattr(tools_module.mcp_hooks, "_selector_live_match_count", _live_match(1))+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))+ ctx.pending_scout_click_selector = 'button[data-action="selectAddress"]'++ result = await _run_click(ctx)++ assert ctx.last_scout_act_observe_outcome == "hollow"+ data = result["data"]+ selectors = {target.get("selector") for target in data["actionable_targets"]}+ assert "#biz-tile" in selectors+ assert data["next_action"] == "click"+ assert ctx.consecutive_no_progress_interaction_count == 1++ @pytest.mark.asyncio+ async def test_attach_exception_is_swallowed_and_increment_survives(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def boom(*_args: object, **_kwargs: object) -> None:+ raise RuntimeError("attach blew up")++ monkeypatch.setattr(tools_module.mcp_hooks, "_attach_reperception_targets_on_non_advancing_click", boom)+ ctx = _np_ctx(server=_server_returning(_ungroundable_payload()))++ result = await _run_click(ctx)++ assert result["ok"] is True+ assert ctx.consecutive_no_progress_interaction_count == 1+ assert "actionable_targets" not in result["data"]++ @pytest.mark.asyncio+ async def test_channel_off_attaches_nothing_and_counter_climbs(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_REPERCEPTION_ATTACH_ENABLED", False)+ ctx = _np_ctx(server=_server_returning(_standalone_controls_payload()))++ result = await _run_click(ctx)++ assert ctx.last_scout_act_observe_outcome == "hollow"+ assert "actionable_targets" not in result["data"]+ assert ctx.consecutive_no_progress_interaction_count == 1++ @pytest.mark.asyncio+ async def test_channel_off_leaves_bounded_steer_intact(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_CLICK_REPERCEPTION_ATTACH_ENABLED", False)+ ctx = _np_ctx(server=_server_returning(_bounded_extractor_payload()), counter=2)++ await _run_click(ctx)++ assert ctx.last_scout_act_observe_outcome == "attached"+ assert ctx.consecutive_no_progress_interaction_count == 0diff --git a/tests/unit/test_evaluate_actionable_target.py b/tests/unit/test_evaluate_actionable_target.pyindex 74b38e3db..8e02cf2e7 100644--- a/tests/unit/test_evaluate_actionable_target.py+++ b/tests/unit/test_evaluate_actionable_target.py@@ -91,6 +91,25 @@ def test_signature_changes_when_controls_change() -> None:assert scouting._actionable_target_signature(base) != scouting._actionable_target_signature(mutated)+async def test_standalone_controls_only_page_surfaces_grounded_targets(monkeypatch) -> None:+ async def fake_evidence(ctx, *, url):+ return {+ "forms": [],+ "navigation_targets": [],+ "result_containers": [],+ "clickable_controls": [{"selector": "#biz-tile", "text": "Business"}],+ }++ monkeypatch.setattr(scouting, "_scout_act_observe_page_evidence", fake_evidence)+ ctx = _ctx()+ ctx.last_evaluate_actionable_signature = None+ ctx.last_evaluate_actionable_url = None+ result = {"ok": True, "data": {"url": "https://example.com/account"}}+ await scouting._maybe_steer_evaluate_to_action(ctx, result, url="https://example.com/account")+ assert result["data"]["actionable_targets"] == [{"selector": "#biz-tile", "text": "Business"}]++@pytest.mark.asyncioasync def test_first_evaluate_names_targets_without_next_action(monkeypatch) -> None:async def fake_evidence(ctx, *, url):@@ -343,6 +362,69 @@ def test_identities_cover_all_collections() -> None:assert {"#user", "#login", "#print", "#results", "#close"} <= selectors+def test_identities_include_clickable_controls() -> None:+ packet = {+ "forms": [],+ "navigation_targets": [],+ "result_containers": [],+ "clickable_controls": [+ {"selector": "#biz-tile", "text": "Business"},+ {"text": "Residential"},+ ],+ }+ identities = scouting._actionable_target_identities(packet)+ assert ("#biz-tile", "Business") in identities+ assert ("", "Residential") in identities+++def test_identities_order_affordances_before_fields_and_selectors_first() -> None:+ packet = {+ "forms": [+ {+ "fields": [{"selector": "#user", "text": "Username"}],+ "submit_controls": [{"selector": "#login", "text": "Log In"}],+ }+ ],+ "navigation_targets": [],+ "result_containers": [],+ "clickable_controls": [+ {"text": "Text only tile"},+ {"selector": "#biz-tile", "text": "Business"},+ ],+ }+ identities = scouting._actionable_target_identities(packet)+ positions = {ident: index for index, ident in enumerate(identities)}+ field_pos = positions[("#user", "Username")]+ # Click affordances (selector-bearing and text-only) precede the plain input field.+ assert positions[("#login", "Log In")] < field_pos+ assert positions[("#biz-tile", "Business")] < field_pos+ assert positions[("", "Text only tile")] < field_pos+ # Selector-bearing affordances precede text-only ones.+ assert positions[("#biz-tile", "Business")] < positions[("", "Text only tile")]+++def test_click_affordance_identities_only_selector_bearing_affordances() -> None:+ packet = {+ "forms": [+ {+ "fields": [{"selector": "#user", "text": "Username"}],+ "submit_controls": [{"selector": "#login", "text": "Log In"}],+ }+ ],+ "navigation_targets": [{"selector": "a.nav", "text": "Nav"}],+ "result_containers": [{"selector": "#results", "text": "Results"}],+ "clickable_controls": [+ {"selector": "#tile", "text": "Tile"},+ {"text": "Text only"},+ ],+ "modal_overlays": [{"dismiss_controls": [{"selector": "#close", "text": "Close"}]}],+ }+ identities = scouting._click_affordance_target_identities(packet)+ selectors = {selector for selector, _ in identities}+ assert selectors == {"#login", "a.nav", "#tile", "#close"}+ assert all(selector for selector, _ in identities)++@pytest.mark.asyncioasync def test_probe_none_leaves_data_untouched_and_resets(monkeypatch) -> None:ctx = _ctx()