Skip to content

Automate browser based workflows with AI

Record a challenge raised by a scouted click as an effect (SKY-16363) (#8600)

Andrew Neilsone3194369d067
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index e88ff6204..b5e25d4ca 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -229,7 +229,10 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (
hydrate_prior_run_packet,
run_workflow_end_to_end,
)
-from skyvern.forge.sdk.copilot.tools.scouting import hydrate_prior_carried_trajectory
+from skyvern.forge.sdk.copilot.tools.scouting import (
+ _release_scout_challenge_listeners,
+ hydrate_prior_carried_trajectory,
+)
from skyvern.forge.sdk.copilot.tools.workflow_update import (
publish_workflow_candidate,
restore_pending_workflow_proposal,
@@ -4995,6 +4998,11 @@ async def run_copilot_agent(
finally:
turn_end_ctx = ctx_sink[0] if ctx_sink else None
finalize_outcome_verification_trace(turn_end_ctx, turn_span)
+ if turn_end_ctx is not None:
+ # A click cancelled or failed between its pre-hook and post-hook never reaches the
+ # post-hook's release, which would leave its frame listener on the persistent page
+ # holding this context. Released before the driver detaches, while the page is live.
+ _release_scout_challenge_listeners(turn_end_ctx)
if turn_end_ctx is not None and turn_end_ctx.attached_browser_drivers:
# Concurrently, so one session's wedged detach can neither skip the sessions
# behind it nor stack another cleanup timeout onto the turn's exit.
diff --git a/skyvern/forge/sdk/copilot/code_block_steps.py b/skyvern/forge/sdk/copilot/code_block_steps.py
index 4f55ddab6..7f68b250a 100644
--- a/skyvern/forge/sdk/copilot/code_block_steps.py
+++ b/skyvern/forge/sdk/copilot/code_block_steps.py
@@ -74,6 +74,9 @@ _READ_METHODS: dict[str, str] = {
# Methods whose natural-language `prompt` is the first positional argument (it is keyword-only on the
# interaction methods, which the keyword scan below already covers).
_PROMPT_POSITIONAL_METHODS: frozenset[str] = frozenset({"complete", "solve_captcha", "verification_code"})
+# Injected into the code block's namespace as a bare builtin rather than a page method
+# (block.py build_safe_vars), so it is called as `await solve_captcha(page)` with no receiver.
+_BARE_NAME_METHODS: frozenset[str] = frozenset({"solve_captcha"})
# Awaited calls that are sync/no-op helpers — never surfaced as their own step.
_IGNORED_METHODS: frozenset[str] = frozenset(
{"wait_for_load_state", "wait_for_selector", "wait_for_url", "wait_for_function"}
@@ -132,9 +135,15 @@ def analyze_code_actions(code: str) -> list[CodeActionSpan]:
if not isinstance(node, ast.Await) or not isinstance(node.value, ast.Call):
continue
call = node.value
- if not isinstance(call.func, ast.Attribute):
+ receiver_node: ast.expr | None
+ if isinstance(call.func, ast.Attribute):
+ method = call.func.attr
+ receiver_node = call.func.value
+ elif isinstance(call.func, ast.Name) and call.func.id in _BARE_NAME_METHODS:
+ method = call.func.id
+ receiver_node = None
+ else:
continue
- method = call.func.attr
if method in _IGNORED_METHODS:
continue
action_type = _METHOD_ACTION_TYPES.get(method) or _READ_METHODS.get(method)
@@ -142,7 +151,7 @@ def analyze_code_actions(code: str) -> list[CodeActionSpan]:
continue
goto_url = _goto_url_node(call, method)
goto_arg = goto_url if isinstance(goto_url, ast.Name) else None
- first_arg = call.args[0] if call.args else goto_url
+ first_arg = (call.args[0] if call.args else goto_url) if receiver_node is not None else None
goto_literal = None
if goto_arg is not None:
if bindings is None:
@@ -154,12 +163,14 @@ def analyze_code_actions(code: str) -> list[CodeActionSpan]:
line_start=node.lineno,
line_end=getattr(node, "end_lineno", None) or node.lineno,
method=method,
- receiver=_safe_unparse(call.func.value),
+ receiver=_safe_unparse(receiver_node) if receiver_node is not None else "",
first_arg=_safe_unparse(first_arg) if first_arg is not None else None,
prompt=_prompt_literal(call, method),
loop_var=_enclosing_loop_var(node, parents, loop_vars),
store_name=_store_name(node, parents, store_names) if action_type == "extract" else None,
- element_name=_element_name(call.func.value) if action_type == "extract" else None,
+ element_name=(
+ _element_name(receiver_node) if action_type == "extract" and receiver_node is not None else None
+ ),
goto_name=goto_arg.id if goto_arg else None,
goto_literal=goto_literal,
)
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 4c7816f74..d536be12b 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -66,7 +66,7 @@ from skyvern.webeye.browser_state import BrowserState
from skyvern.webeye.persistent_session_errors import BrowserSessionCreditAdmissionRefusal
if TYPE_CHECKING:
- from playwright.async_api import Page
+ from playwright.async_api import Frame, Page
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.build_test_outcome import (
@@ -323,6 +323,8 @@ class ScoutedInteraction(TypedDict):
source_url: NotRequired[str]
result_url: NotRequired[str]
observed_effects: NotRequired[dict[str, bool]]
+ # The vendor signature literal matched in the challenge frame's URL, so no page-controlled host is kept.
+ challenge_vendor: NotRequired[str]
observed_wait_ms: NotRequired[int]
input_id: NotRequired[str]
input_value: NotRequired[str]
@@ -665,6 +667,20 @@ class AgentContext:
pending_scout_download_detachers: list[Callable[[], None]] = field(default_factory=list)
pending_scout_popup: Page | None = None
pending_scout_popup_content_type: str | None = None
+ # Every child frame that navigated to a challenge vendor during the in-flight click. A widget can
+ # arrive with hidden helper frames beside it, so which one is on screen is decided at report time.
+ pending_scout_challenge_frames: list[Frame] = field(default_factory=list)
+ # The records this click wrote in each collection, so an effect observed after the fact updates
+ # them directly instead of searching for a locator the scrub may have dropped.
+ pending_scout_click_records: list[ScoutedInteraction] = field(default_factory=list)
+ # When the listener for the in-flight click went live, so the settle counts time already spent.
+ pending_scout_challenge_armed_at: float | None = None
+ # Removers for the frame listener armed for the in-flight click, run when the click post-hook
+ # returns, so one click's widget cannot land in another click's window.
+ pending_scout_challenge_detachers: list[Callable[[], None]] = field(default_factory=list)
+ # Vendor frames already present when the click was armed, with the area each rendered at then, so
+ # one the click reveals rather than navigates is still the click's effect.
+ pending_scout_challenge_prior_frames: list[tuple[Frame, float | None]] = field(default_factory=list)
# (selector, ambiguous) verdict from a pre-dispatch live count probe, applied to the recorded
# interaction only when the post-action resolved selector matches the probed one.
pending_scout_ambiguous: tuple[str, bool] | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index 9158d2374..649c6729d 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -101,6 +101,7 @@ from .page_observation import (
)
from .scouting import (
_SCOUT_RESULT_CHAR_CAP,
+ _arm_scout_challenge_listener,
_arm_scout_download_listener,
_arm_scout_popup_listener,
_attach_evaluate_page_facts,
@@ -111,8 +112,10 @@ from .scouting import (
_capture_scout_source_url,
_clear_pending_browser_interaction_observation,
_clear_pending_scout_selector_facts,
+ _close_scout_challenge_baseline,
_consume_scout_source_url,
_mark_pending_browser_interaction_observation,
+ _maybe_attach_observed_challenge,
_maybe_attach_observed_download_target,
_maybe_attach_observed_render_target,
_page_evidence_location_fingerprint,
@@ -122,10 +125,12 @@ from .scouting import (
_record_scout_trajectory_fact,
_record_scouted_interaction,
_register_scout_interaction_observation,
+ _release_scout_challenge_listeners,
_resolve_scout_role_name,
_scout_act_observe_page_evidence,
_scout_session_download_names,
_shed_scout_page_summary_section,
+ _start_scout_challenge_settle,
record_signed_out_page_observation,
)
@@ -565,6 +570,7 @@ _MODEL_SCOUT_FACT_KEYS = (
"source_url",
"result_url",
"observed_effects",
+ "challenge_vendor",
"observed_wait_ms",
"observation_step",
"input_id",
@@ -731,19 +737,27 @@ async def _click_pre_hook(
ctx.pending_scout_download = False
ctx.pending_scout_popup = None
ctx.pending_scout_popup_content_type = None
+ ctx.pending_scout_challenge_frames = []
+ ctx.pending_scout_challenge_prior_frames = []
+ ctx.pending_scout_challenge_armed_at = None
+ ctx.pending_scout_click_records = []
+ _release_scout_challenge_listeners(ctx)
sensitive_page_refusal = _sensitive_origin_page_action_refusal(ctx)
if sensitive_page_refusal is not None:
return sensitive_page_refusal
await _capture_scout_source_url(ctx)
selector = params.get("selector", "")
await _capture_scout_pre_action(ctx, selector if isinstance(selector, str) else None)
- if not selector:
- return None
- ctx.pending_scout_click_selector = selector if isinstance(selector, str) else None
- if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
- ctx.pending_scout_download_snapshot = await _scout_session_download_names(ctx)
- await _arm_scout_download_listener(ctx)
- await _arm_scout_popup_listener(ctx)
+ # Armed before the selector check: an intent or coordinate click carries no selector going in but
+ # reports the element it resolved, and the challenge it raises is recorded against that.
+ await _arm_scout_challenge_listener(ctx)
+ if selector:
+ ctx.pending_scout_click_selector = selector if isinstance(selector, str) else None
+ if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ ctx.pending_scout_download_snapshot = await _scout_session_download_names(ctx)
+ await _arm_scout_download_listener(ctx)
+ await _arm_scout_popup_listener(ctx)
+ await _close_scout_challenge_baseline(ctx)
return None
@@ -966,6 +980,20 @@ async def _click_post_hook(
result: dict[str, Any],
raw: dict[str, Any],
ctx: AgentContext,
+) -> dict[str, Any]:
+ _start_scout_challenge_settle(ctx)
+ try:
+ return await _click_post_hook_body(result, raw, ctx)
+ finally:
+ ctx.pending_scout_challenge_frames = []
+ ctx.pending_scout_challenge_armed_at = None
+ _release_scout_challenge_listeners(ctx)
+
+
+async def _click_post_hook_body(
+ result: dict[str, Any],
+ raw: dict[str, Any],
+ ctx: AgentContext,
) -> dict[str, Any]:
ctx.last_scout_act_observe_outcome = None
ctx.last_scout_act_observe_packet = None
@@ -1055,6 +1083,7 @@ async def _click_post_hook(
# href-shape prediction — and is the only source that sees a command-URL download.
await _maybe_attach_observed_download_target(ctx, result, selector=selector, url=url)
await _maybe_attach_observed_render_target(ctx, result, selector=selector, url=url)
+ await _maybe_attach_observed_challenge(ctx, result, url=url)
if page_evidence is not None:
_attach_scout_page_summary(ctx, result, page_evidence)
elif ctx.last_scout_act_observe_outcome == "unchanged":
@@ -1103,7 +1132,11 @@ async def _click_post_hook(
page_evidence = await _scout_act_observe_page_evidence(ctx, url=url)
if page_evidence is not None:
_attach_scout_page_summary(ctx, result, page_evidence)
+ # A handler can mount a challenge and then stall the navigation the click was waiting on.
+ await _maybe_attach_observed_challenge(ctx, result, url=url)
_bound_failed_click_result(ctx, result)
+ else:
+ await _maybe_attach_observed_challenge(ctx, result, url=source_url or "")
# The round-trip is skipped only when the evidence positively names the obstruction a frame
# would have shown; evidence that merely parsed is not a substitute for looking at the page.
if ctx.last_scout_act_observe_outcome != "attached" or not _page_evidence_names_obstruction(page_evidence):
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index 562aa11a2..62e8e0c42 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -10,7 +10,7 @@ from typing import Any, Literal, cast
from urllib.parse import urlparse, urlsplit
import structlog
-from playwright.async_api import BrowserContext, Download, Page, Response
+from playwright.async_api import BrowserContext, Download, Frame, Page, Response
from skyvern.config import settings
from skyvern.forge import app
@@ -90,6 +90,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
scrub_secrets_from_text,
)
from skyvern.webeye.browser_state import BrowserState
+from skyvern.webeye.utils.challenge_signature import CHALLENGE_VENDOR_SIGNATURE
from ._shared import (
_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
@@ -951,7 +952,14 @@ def _record_scouted_interaction(
interactions.append(artifact)
ctx.scouted_interactions = _capped_with_eviction_accounting(interactions, collection="scouted_interactions")
- _record_scout_trajectory_fact(ctx, artifact)
+ recorded = _record_scout_trajectory_fact(ctx, artifact)
+ if artifact["tool_name"] == "click":
+ # Both collections hold their own object for this click, and an effect observed after the
+ # fact updates these rather than re-finding them by an identity the scrub may have removed.
+ click_records: list[ScoutedInteraction] = [artifact]
+ if recorded is not None:
+ click_records.append(recorded)
+ ctx.pending_scout_click_records = click_records
LOG.info(
"copilot_scout_interaction_captured",
@@ -2027,6 +2035,153 @@ async def _arm_scout_popup_listener(ctx: AgentContext) -> None:
LOG.warning("copilot_scout_popup_listener_failed", exc_info=True)
+_CHALLENGE_VENDOR_FRAME_URL = re.compile(CHALLENGE_VENDOR_SIGNATURE, re.IGNORECASE)
+
+
+def _release_scout_challenge_listeners(ctx: AgentContext) -> None:
+ for detach in ctx.pending_scout_challenge_detachers:
+ try:
+ detach()
+ except Exception:
+ LOG.debug("copilot_scout_challenge_listener_detach_failed", exc_info=True)
+ ctx.pending_scout_challenge_detachers = []
+
+
+# A managed widget preloads small and grows when it actually challenges, so "rendered" cannot mean
+# "has a box": a 1x1 iframe measures 25 once default borders are counted. Anything at or under this
+# much on-screen area is a placeholder rather than a challenge a person could answer.
+# ponytail: one sentinel for every vendor — revisit if a vendor's real widget ships smaller than 16x16.
+_CHALLENGE_FRAME_PLACEHOLDER_AREA = 256.0
+
+# Layout area is not screen area: a widget preloaded at full size can sit off-viewport, inside a
+# zero-size overflow:hidden ancestor, under a clip-path, behind visibility:hidden, or under an
+# opacity:0 ancestor, and still report its whole box. checkVisibility answers the style half;
+# IntersectionObserver answers the geometry half, ancestor clip rects included, so neither the
+# viewport nor a clipping container has to be walked by hand.
+_CHALLENGE_FRAME_ONSCREEN_AREA_JS = """
+el => {
+ if (el.checkVisibility && !el.checkVisibility({
+ opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true,
+ })) return 0;
+ return new Promise(resolve => {
+ let observer = null;
+ let timer = null;
+ const done = area => {
+ if (observer) observer.disconnect();
+ if (timer) clearTimeout(timer);
+ resolve(area);
+ };
+ observer = new IntersectionObserver(entries => {
+ const rect = entries[entries.length - 1].intersectionRect;
+ done(rect.width * rect.height);
+ });
+ timer = setTimeout(() => done(null), 1000);
+ observer.observe(el);
+ });
+}
+"""
+
+
+_ELEMENT_STYLE_VISIBLE_JS = """
+el => !el.checkVisibility || el.checkVisibility({
+ opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true,
+})
+"""
+
+
+async def _frame_element_style_visible(frame: Frame) -> bool:
+ try:
+ element = await frame.frame_element()
+ return bool(await element.evaluate(_ELEMENT_STYLE_VISIBLE_JS))
+ except Exception:
+ return False
+
+
+async def _embedding_frames_style_visible(frame: Frame) -> bool:
+ """Whether every iframe embedding this one, up to the top page, is visible by style.
+
+ The observer's implicit root already clips geometry through each ancestor frame, but style is judged
+ per document: an opacity:0 or visibility:hidden iframe further up still lets this frame report its
+ full box. An ancestor that cannot be read counts as hidden.
+ """
+ ancestors: list[Frame] = []
+ current = frame.parent_frame
+ while current is not None and current.parent_frame is not None:
+ ancestors.append(current)
+ current = current.parent_frame
+ return all(await asyncio.gather(*(_frame_element_style_visible(ancestor) for ancestor in ancestors)))
+
+
+# The script's own timer cannot fire in a renderer that never yields, and the click pre-hook runs outside
+# the MCP call timeout, so the deadline is held here.
+_CHALLENGE_FRAME_PROBE_TIMEOUT_SECONDS = 2.0
+
+
+async def _challenge_frame_rendered_area(frame: Frame) -> float | None:
+ """On-screen area of the frame's own element, or None when it cannot be measured in time."""
+ try:
+ return await asyncio.wait_for(
+ _measure_challenge_frame_area(frame), timeout=_CHALLENGE_FRAME_PROBE_TIMEOUT_SECONDS
+ )
+ except Exception:
+ return None
+
+
+async def _measure_challenge_frame_area(frame: Frame) -> float | None:
+ element = await frame.frame_element()
+ area = await element.evaluate(_CHALLENGE_FRAME_ONSCREEN_AREA_JS)
+ if area is None:
+ return None
+ if not await _embedding_frames_style_visible(frame):
+ return 0.0
+ return float(area)
+
+
+async def _arm_scout_challenge_listener(ctx: AgentContext) -> None:
+ """Arm a frame-navigation listener for the click about to dispatch.
+
+ A widget already mounted before the click is not this click's effect, so only navigations
+ inside the click's window count; main-frame navigations are left to ``url_changed`` and the
+ page summary. A preloaded widget the click merely reveals never navigates, so its rendered area
+ is measured here and compared after the settle."""
+ _release_scout_challenge_listeners(ctx)
+ ctx.pending_scout_challenge_frames = []
+ ctx.pending_scout_challenge_prior_frames = []
+ ctx.pending_scout_challenge_armed_at = None
+ try:
+ browser_state = await resolve_browser_state_for_context(ctx)
+ if browser_state is None:
+ return
+ page = await browser_state.get_or_create_page()
+ # A widget already showing a vendor URL re-navigates to refresh its token, and that fires
+ # framenavigated on the same frame — which is the widget's own upkeep, not this click.
+ already_challenged = [
+ frame
+ for frame in page.frames
+ if frame.parent_frame is not None and _CHALLENGE_VENDOR_FRAME_URL.search(frame.url or "")
+ ]
+
+ def _capture(frame: Frame) -> None:
+ if frame.parent_frame is None:
+ return
+ baseline = (seen for seen, _area in ctx.pending_scout_challenge_prior_frames)
+ if any(frame is seen for seen in (*already_challenged, *baseline, *ctx.pending_scout_challenge_frames)):
+ return
+ if _CHALLENGE_VENDOR_FRAME_URL.search(frame.url or ""):
+ ctx.pending_scout_challenge_frames.append(frame)
+
+ # Listening before the measurement below yields, so a frame that mounts while it runs is still seen.
+ page.on("framenavigated", _capture)
+ ctx.pending_scout_challenge_detachers.append(lambda: page.remove_listener("framenavigated", _capture))
+ ctx.pending_scout_challenge_armed_at = time.monotonic()
+ # Measured together: each reading stops itself after its observer timeout, so a page with several
+ # vendor frames costs one bound before the click dispatches rather than one per frame.
+ prior_areas = await asyncio.gather(*(_challenge_frame_rendered_area(frame) for frame in already_challenged))
+ ctx.pending_scout_challenge_prior_frames = list(zip(already_challenged, prior_areas, strict=True))
+ except Exception:
+ LOG.warning("copilot_scout_challenge_listener_failed", exc_info=True)
+
+
# Bounded so a page that stalls the probe cannot spend the turn budget one click at a time.
_RENDER_PROBE_TIMEOUT_MS = 5000.0
@@ -2035,27 +2190,29 @@ def _attach_observed_click_effect(
ctx: AgentContext,
result: dict[str, Any],
*,
- selector: str,
effect: str,
+ challenge_vendor: str | None = None,
) -> None:
- """Attach a browser-observed click effect without choosing a future action or locator."""
+ """Attach a browser-observed click effect without choosing a future action or locator.
+
+ The records this click just wrote are updated directly. Searching for them by selector would miss
+ a click whose locator the scrub removed, and could land the effect on an older click that used
+ the same selector.
+ """
data = result.get("data")
if not isinstance(data, dict):
return
result_effects = data.setdefault("observed_effects", {})
if isinstance(result_effects, dict):
result_effects[effect] = True
- for collection_name in ("scout_trajectory", "scouted_interactions"):
- collection = getattr(ctx, collection_name, None)
- if not isinstance(collection, list):
- continue
- for interaction in reversed(collection):
- if interaction.get("tool_name") != "click" or interaction.get("selector") != selector:
- continue
- effects = dict(interaction.get("observed_effects") or {})
- effects[effect] = True
- interaction["observed_effects"] = effects
- break
+ if challenge_vendor is not None:
+ data["challenge_vendor"] = challenge_vendor
+ for interaction in ctx.pending_scout_click_records:
+ effects = dict(interaction.get("observed_effects") or {})
+ effects[effect] = True
+ interaction["observed_effects"] = effects
+ if challenge_vendor is not None:
+ interaction["challenge_vendor"] = challenge_vendor
async def _maybe_attach_observed_render_target(
@@ -2082,7 +2239,7 @@ async def _maybe_attach_observed_render_target(
if not content_type.lower().startswith("image/"):
LOG.debug("copilot_observed_render_declined", reason="not_image_render", url=url, content_type=content_type)
return
- _attach_observed_click_effect(ctx, result, selector=selector, effect="rendered_document_opened")
+ _attach_observed_click_effect(ctx, result, effect="rendered_document_opened")
except Exception:
LOG.warning("copilot_observed_render_target_attach_failed", exc_info=True)
@@ -2113,11 +2270,101 @@ async def _maybe_attach_observed_download_target(
return
download_signal = "store_diff"
LOG.info("copilot_observed_download_signal", signal=download_signal, url=url)
- _attach_observed_click_effect(ctx, result, selector=selector, effect="download_started")
+ _attach_observed_click_effect(ctx, result, effect="download_started")
except Exception:
LOG.warning("copilot_observed_download_target_attach_failed", exc_info=True)
+async def _close_scout_challenge_baseline(ctx: AgentContext) -> None:
+ """Close the pre-click window at the dispatch boundary.
+
+ Frames that navigated since the listener went on arrived before the click, so they join the baseline:
+ one the click later reveals is still credited through the reveal check, a visible one is not.
+ """
+ if ctx.pending_scout_challenge_armed_at is None:
+ return
+ arrivals = list(ctx.pending_scout_challenge_frames)
+ ctx.pending_scout_challenge_frames.clear()
+ areas = await asyncio.gather(*(_challenge_frame_rendered_area(frame) for frame in arrivals))
+ ctx.pending_scout_challenge_prior_frames.extend(zip(arrivals, areas, strict=True))
+ # Frames that navigated during that measurement are baselined unmeasured, with no await before dispatch:
+ # an unmeasured baseline frame is never credited, as new or as revealed.
+ ctx.pending_scout_challenge_prior_frames.extend((frame, None) for frame in ctx.pending_scout_challenge_frames)
+ ctx.pending_scout_challenge_frames.clear()
+
+
+def _start_scout_challenge_settle(ctx: AgentContext) -> None:
+ """Start the settle window when the click tool returns.
+
+ The browser clicks somewhere inside the tool call, after resolving and waiting for its target, which
+ can outlast the window; the return is the first moment known to follow the click.
+ """
+ if ctx.pending_scout_challenge_armed_at is not None:
+ ctx.pending_scout_challenge_armed_at = time.monotonic()
+
+
+async def _on_screen_challenge_vendor(ctx: AgentContext) -> str | None:
+ """Vendor of the first challenge frame the click put on screen, whether it mounted one or revealed a placeholder.
+
+ A widget often arrives with hidden helper frames beside it, so every candidate is measured rather
+ than the first to navigate. A hidden vendor frame is still a marker the solve ladder acts on, and
+ crediting one would send a solve through the whole ladder against nothing a person could answer.
+ """
+ # A preload is only revealable if it measured as a placeholder before the click: without that
+ # reading there is no growth to observe, and an already-challenging widget would be credited to
+ # whatever click happened to follow it.
+ revealable = [
+ frame
+ for frame, prior_area in ctx.pending_scout_challenge_prior_frames
+ if prior_area is not None and prior_area <= _CHALLENGE_FRAME_PLACEHOLDER_AREA
+ ]
+ # A captured frame can navigate away before this runs, so each is matched on its current URL.
+ candidates = [
+ (frame, match)
+ for frame in [*ctx.pending_scout_challenge_frames, *revealable]
+ if (match := _CHALLENGE_VENDOR_FRAME_URL.search(frame.url or "")) is not None
+ ]
+ areas = await asyncio.gather(*(_challenge_frame_rendered_area(frame) for frame, _match in candidates))
+ for (_frame, match), area in zip(candidates, areas, strict=True):
+ if area is not None and area > _CHALLENGE_FRAME_PLACEHOLDER_AREA:
+ # The matched text is one of the signature's own literals, so the vendor is named from a closed
+ # vocabulary. A hostname would carry whatever the page put in it — a tenant slug or a secret, in
+ # any case or encoding — and no scrub can enumerate every spelling of that.
+ return match.group(0).casefold()
+ return None
+
+
+async def _maybe_attach_observed_challenge(ctx: AgentContext, result: dict[str, Any], *, url: str) -> None:
+ """Report when the scout's click raised an anti-bot challenge.
+
+ Needs no locator: a coordinate click has none, and still raises challenges. The effect goes on the
+ tool result either way, and onto whatever records this click wrote, which for a click with no
+ locator is none. A failed click may carry no data at all, and gets some only when a challenge is found.
+ """
+ if result.get("data") is not None and not isinstance(result.get("data"), dict):
+ return
+ armed_at = ctx.pending_scout_challenge_armed_at
+ if armed_at is None:
+ return
+ vendor = await _on_screen_challenge_vendor(ctx)
+ if vendor is None:
+ # The window started when the click returned, and the observation between then and now usually
+ # outlasts it by itself. Wait only for what is left of it, so a widget
+ # that mounts or grows a beat late still lands without adding a delay to every click.
+ owed = settings.COPILOT_SCOUT_ACT_OBSERVE_RECAPTURE_DELAY_SECONDS - (time.monotonic() - armed_at)
+ if owed > 0:
+ await asyncio.sleep(owed)
+ vendor = await _on_screen_challenge_vendor(ctx)
+ if vendor is None:
+ return
+ try:
+ LOG.info("copilot_observed_challenge_signal", vendor=vendor, page_origin=safe_page_origin(url))
+ result.setdefault("data", {})
+ _attach_observed_click_effect(ctx, result, effect="challenge_raised", challenge_vendor=vendor)
+ except Exception:
+ LOG.warning("copilot_observed_challenge_attach_failed", exc_info=True)
+
+
async def _attach_evaluate_page_facts(ctx: AgentContext, result: dict[str, Any], *, url: str) -> None:
"""Attach bounded page facts without selecting or suggesting the model's next action."""
if not isinstance(result.get("data"), dict):
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index fb4d8f8c0..b25fcd7bf 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -67,6 +67,7 @@ from skyvern.forge.taskv3.target_label import TARGET_KIND_TOKENS, TARGET_NAME_CA
from skyvern.webeye.actions.key_names import normalize_key_chord
from skyvern.webeye.browser_driver_errors import is_driver_timeout_error
from skyvern.webeye.browser_state import BLANK_PAGE_URLS
+from skyvern.webeye.utils.challenge_signature import CHALLENGE_VENDOR_SIGNATURE
from skyvern.webeye.utils.page import OTP_INPUT_PRIVACY_JS, OTP_SAFE_FRAGMENT_HTML_JS, mask_otp_values_in_html
if TYPE_CHECKING:
@@ -6745,7 +6746,9 @@ async () => {
// input is not actionable.
const INTERACTIVE_SEL = ':is(a[href],button,input:not([type="hidden" i]),select,textarea,[role=button],[role=option],[role=combobox],[role=checkbox],[role=radio],[role=tab],[role=menuitem],[role=menuitemcheckbox],[role=menuitemradio],[role=listbox],[role=switch],[role=spinbutton],[contenteditable=""],[contenteditable="true"]):not(:disabled):not([aria-disabled="true" i])';
try {
- const sig = /captcha|turnstile|challenges\.cloudflare|arkoselabs|funcaptcha|datadome|perimeterx|verify you are human|security challenge/i;
+ const sig = /"""
+ + CHALLENGE_VENDOR_SIGNATURE
+ + r"""/i;
const vw = window.innerWidth || document.documentElement.clientWidth || 0;
const vh = window.innerHeight || document.documentElement.clientHeight || 0;
// A design system packages the widget inside its own shadow root, where a document query cannot
diff --git a/skyvern/webeye/utils/challenge_signature.py b/skyvern/webeye/utils/challenge_signature.py
new file mode 100644
index 000000000..671b65fa2
--- /dev/null
+++ b/skyvern/webeye/utils/challenge_signature.py
@@ -0,0 +1,12 @@
+"""Vendor signature shared by the Task V3 observe scan and the copilot scout click hooks.
+
+Spliced verbatim into a JavaScript regex literal as well as compiled by ``re``, so it must stay
+inside the syntax both engines read the same way: no named groups, no lookbehind, no ``/``.
+"""
+
+from __future__ import annotations
+
+CHALLENGE_VENDOR_SIGNATURE = (
+ r"captcha|turnstile|challenges\.cloudflare|arkoselabs|funcaptcha|datadome|perimeterx"
+ r"|verify you are human|security challenge"
+)
diff --git a/tests/unit/test_cli_bootstrap.py b/tests/unit/test_cli_bootstrap.py
index f8e84d93d..c33f9243a 100644
--- a/tests/unit/test_cli_bootstrap.py
+++ b/tests/unit/test_cli_bootstrap.py
@@ -95,9 +95,13 @@ def test_prepare_cli_runtime_loads_env_before_logger(monkeypatch, tmp_path) -> N
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
- monkeypatch.delenv("SKYVERN_API_KEY", raising=False)
- monkeypatch.delenv(BACKEND_ENV_INTENT_ENV_VAR, raising=False)
+ # prepare_cli_runtime writes os.environ directly, and delenv on an unset variable records nothing to undo,
+ # so each is set first to make teardown remove what the call loads.
+ for name in ("SKYVERN_API_KEY", BACKEND_ENV_INTENT_ENV_VAR):
+ monkeypatch.setenv(name, "")
+ monkeypatch.delenv(name)
monkeypatch.setattr(cli_bootstrap, "_RUNTIME_LOGGING_CONFIGURED", False)
+ monkeypatch.setattr(cli_bootstrap, "_CLI_RUNTIME_PREPARED", False)
monkeypatch.setitem(sys.modules, "skyvern.forge.sdk.forge_log", fake_forge_log)
assert cli_bootstrap.prepare_cli_runtime(intent=EnvIntent.CLOUD) == project_env
diff --git a/tests/unit/test_code_block_steps.py b/tests/unit/test_code_block_steps.py
index bebb0e7d2..0bbca6b4b 100644
--- a/tests/unit/test_code_block_steps.py
+++ b/tests/unit/test_code_block_steps.py
@@ -57,6 +57,32 @@ def test_analyze_maps_page_evaluate_and_other_recorder_calls_to_action_types():
]
+def test_analyze_maps_the_bare_solve_captcha_builtin_to_a_step_with_its_line():
+ code = (
+ "async def run(page):\n"
+ " await page.goto('https://example.com/')\n"
+ " await page.get_by_role('button', name='Search').click()\n"
+ " await solve_captcha(page)\n"
+ " await page.get_by_role('button', name='Continue').click()\n"
+ )
+ spans = analyze_code_actions(code)
+ assert [(s.action_type, s.line_start) for s in spans] == [
+ ("goto_url", 2),
+ ("click", 3),
+ ("solve_captcha", 4),
+ ("click", 5),
+ ]
+ solve = spans[2]
+ assert solve.receiver == ""
+ assert solve.first_arg is None
+ assert solve.prompt is None
+
+
+def test_analyze_ignores_a_bare_call_that_is_not_a_code_block_builtin():
+ code = "async def run(page):\n await fetch_rows(page)\n await page.click('#next')\n"
+ assert [(s.action_type, s.line_start) for s in analyze_code_actions(code)] == [("click", 3)]
+
+
def test_derive_steps_surfaces_page_evaluate_with_a_label():
code = (
"async def run(page):\n"
diff --git a/tests/unit/test_copilot_context.py b/tests/unit/test_copilot_context.py
index c5bed71f2..8c99f4f35 100644
--- a/tests/unit/test_copilot_context.py
+++ b/tests/unit/test_copilot_context.py
@@ -590,6 +590,24 @@ def test_finalize_context_persists_carried_trajectory() -> None:
]
+def test_carried_trajectory_keeps_the_challenge_a_click_raised() -> None:
+ carry = _carried_trajectory_from_scout_trajectory(
+ [
+ {
+ "tool_name": "click",
+ "selector": "#submit-search",
+ "source_url": "https://records.example.test/search",
+ "result_url": "https://records.example.test/search",
+ "observed_effects": {"url_changed": False, "challenge_raised": True},
+ "challenge_vendor": "turnstile",
+ }
+ ]
+ )
+
+ assert carry[0]["observed_effects"] == {"url_changed": False, "challenge_raised": True}
+ assert carry[0]["challenge_vendor"] == "turnstile"
+
+
def test_carried_trajectory_records_credential_field_inventory() -> None:
carry = _carried_trajectory_from_scout_trajectory(
[
diff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.py
index a1fae8d7e..6a1e9d585 100644
--- a/tests/unit/test_copilot_fill_credential_field.py
+++ b/tests/unit/test_copilot_fill_credential_field.py
@@ -94,6 +94,11 @@ def _ctx(**overrides: Any) -> SimpleNamespace:
pending_scout_download_detachers=[],
pending_scout_popup=None,
pending_scout_popup_content_type=None,
+ pending_scout_challenge_frames=[],
+ pending_scout_challenge_detachers=[],
+ pending_scout_challenge_prior_frames=[],
+ last_scout_act_observe_recapture_attempted=False,
+ pending_scout_challenge_armed_at=None,
authoring_parameter_binding_snapshot=None,
pending_browser_interaction_observation=None,
discovery_mcp_server=None,
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index de55eb625..bf2323080 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -2,7 +2,9 @@
from __future__ import annotations
+import asyncio
import json
+import time
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
@@ -15,6 +17,7 @@ import pytest
import yaml
from structlog.testing import capture_logs
+from skyvern.config import settings
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.build_test_connect_failure import SUPERSEDED_BY_NEWER_TEST_REASON
from skyvern.forge.sdk.copilot.code_block_synthesis import synthesize_code_block
@@ -63,6 +66,7 @@ from tests.unit.copilot_test_helpers import (
remove_sensitive_disclosure_prerequisite,
taint_by_terminal_run,
)
+from tests.unit.scoped_asyncio import ScopedAsyncio
READBACK_OUTCOME_CASES = yaml.safe_load((Path(__file__).parent / "credential_readback_outcome_cases.yaml").read_text())[
"cases"
@@ -85,6 +89,85 @@ class _FakeContext:
gate_precedence_conflict_events: list[Any] = field(default_factory=list)
+_ON_SCREEN_AREA = 300.0 * 65.0
+
+
+class _ListenerFrameElement:
+ def __init__(self, frame: _ListenerFrame) -> None:
+ self._frame = frame
+
+ async def evaluate(self, script: str) -> float | bool | None:
+ if self._frame.unresponsive:
+ await asyncio.Event().wait()
+ if script == scouting_module._ELEMENT_STYLE_VISIBLE_JS:
+ return self._frame.style_visible
+ return self._frame.area
+
+
+class _ListenerFrame:
+ """Answers the shipped on-screen measure with a set area, so the real helper runs against it."""
+
+ def __init__(
+ self,
+ url: str,
+ parent_frame: _ListenerFrame | None,
+ area: float | None = _ON_SCREEN_AREA,
+ style_visible: bool = True,
+ unresponsive: bool = False,
+ ) -> None:
+ self.url = url
+ self.parent_frame = parent_frame
+ self.area = area
+ self.style_visible = style_visible
+ self.unresponsive = unresponsive
+
+ async def frame_element(self) -> _ListenerFrameElement:
+ return _ListenerFrameElement(self)
+
+
+class _ScopedClock:
+ """A monotonic clock bound to one module, leaving the event loop's own clock running."""
+
+ def __init__(self, now: float) -> None:
+ self.now = now
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def __getattr__(self, name: str) -> object:
+ return getattr(time, name)
+
+
+class _ListenerPage:
+ def __init__(self, child_frame_urls: list[str] | None = None) -> None:
+ self.listeners: dict[str, list[Callable[[Any], None]]] = {}
+ self.removed: list[str] = []
+ main = _ListenerFrame("https://records.example.test/search", None)
+ self.frames = [main, *(_ListenerFrame(url, main) for url in child_frame_urls or [])]
+
+ def on(self, event: str, handler: Callable[[Any], None]) -> None:
+ self.listeners.setdefault(event, []).append(handler)
+
+ def remove_listener(self, event: str, handler: Callable[[Any], None]) -> None:
+ self.listeners[event].remove(handler)
+ self.removed.append(event)
+
+ def _dispatch(self, frame: _ListenerFrame) -> None:
+ for handler in list(self.listeners.get("framenavigated", [])):
+ handler(frame)
+
+ def navigate_frame(self, url: str, *, child_frame: bool, area: float | None = _ON_SCREEN_AREA) -> None:
+ frame = _ListenerFrame(url, self.frames[0] if child_frame else None, area)
+ self.frames.append(frame)
+ self._dispatch(frame)
+
+ def renavigate_child_frame(self, index: int, url: str) -> None:
+ """Playwright fires framenavigated on the same Frame object when an existing frame reloads."""
+ frame = self.frames[1 + index]
+ frame.url = url
+ self._dispatch(frame)
+
+
# `on_tool_end(context, agent, tool, result)` only reads `tool` and `result`;
# `context` and `agent` are unused by CopilotRunHooks, so a single sentinel
# mock stands in for both across every test.
@@ -1133,6 +1216,11 @@ class TestBrowserInteractionObservationHooks:
pending_scout_download_detachers=[],
pending_scout_popup=None,
pending_scout_popup_content_type=None,
+ pending_scout_challenge_frames=[],
+ pending_scout_challenge_detachers=[],
+ pending_scout_challenge_prior_frames=[],
+ last_scout_act_observe_recapture_attempted=False,
+ pending_scout_challenge_armed_at=None,
discovery_mcp_server=None,
scouted_interactions=[],
scout_trajectory=[],
@@ -1180,6 +1268,11 @@ class TestBrowserInteractionObservationHooks:
pending_scout_download_detachers=[],
pending_scout_popup=None,
pending_scout_popup_content_type=None,
+ pending_scout_challenge_frames=[],
+ pending_scout_challenge_detachers=[],
+ pending_scout_challenge_prior_frames=[],
+ last_scout_act_observe_recapture_attempted=False,
+ pending_scout_challenge_armed_at=None,
discovery_mcp_server=None,
scouted_interactions=[],
scout_trajectory=[],
@@ -1281,6 +1374,11 @@ class TestScoutedInteractionCapture:
pending_scout_download_detachers=[],
pending_scout_popup=None,
pending_scout_popup_content_type=None,
+ pending_scout_challenge_frames=[],
+ pending_scout_challenge_detachers=[],
+ pending_scout_challenge_prior_frames=[],
+ last_scout_act_observe_recapture_attempted=False,
+ pending_scout_challenge_armed_at=None,
discovery_mcp_server=None,
browser_session_id=None,
last_run_blocks_workflow_run_id=None,
@@ -2228,6 +2326,792 @@ class TestScoutedInteractionCapture:
)
assert ctx.scouted_interactions[-1].get("ambiguous") is True
+ async def _arm(
+ self, monkeypatch: pytest.MonkeyPatch, page: _ListenerPage, params: dict[str, Any] | None = None
+ ) -> SimpleNamespace:
+ ctx = self._ctx(source_url="https://records.example.test/search")
+ ctx.browser_session_id = "pbs-debug"
+ ctx.sensitive_origin_browser_session_ids = set()
+ ctx.codeblock_redaction_parameters = {}
+ monkeypatch.setattr(
+ scouting_module,
+ "resolve_browser_state_for_context",
+ AsyncMock(return_value=SimpleNamespace(get_or_create_page=AsyncMock(return_value=page))),
+ )
+ await _click_pre_hook(params or {"selector": "#submit-search"}, ctx)
+ return ctx
+
+ async def _post(self, ctx: SimpleNamespace) -> dict[str, Any]:
+ return await _click_post_hook(
+ {"ok": True, "data": {"selector": "#submit-search"}},
+ {"browser_context": {"url": "https://records.example.test/search", "title": "Search"}},
+ ctx,
+ )
+
+ @pytest.mark.asyncio
+ async def test_pre_existing_challenge_frame_that_only_refreshes_is_not_this_clicks_effect(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage(child_frame_urls=["https://challenge.vendor.test/turnstile/v0/api.html?token=first"])
+ ctx = await self._arm(monkeypatch, page)
+ page.renavigate_child_frame(0, "https://challenge.vendor.test/turnstile/v0/api.html?token=refreshed")
+
+ result = await self._post(ctx)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+ assert "challenge_vendor" not in result["data"]
+
+ async def _timed_click(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ page: _ListenerPage,
+ *,
+ elapsed: float,
+ params: dict[str, Any] | None = None,
+ ) -> tuple[SimpleNamespace, _ScopedClock, list[float]]:
+ """The click returns at the clock's current time and is reported `elapsed` seconds later, on a clock
+ scoped to the module."""
+ clock = _ScopedClock(now=0.0)
+ monkeypatch.setattr(scouting_module, "time", clock)
+ ctx = await self._arm(monkeypatch, page, params)
+ start_settle = mcp_hooks._start_scout_challenge_settle
+
+ def _start_then_observe(settling_ctx: Any) -> None:
+ start_settle(settling_ctx)
+ clock.now += elapsed
+
+ monkeypatch.setattr(mcp_hooks, "_start_scout_challenge_settle", _start_then_observe)
+ sleeps: list[float] = []
+ return ctx, clock, sleeps
+
+ def _settle_already_over(self, monkeypatch: pytest.MonkeyPatch, ctx: SimpleNamespace) -> None:
+ """Report as though the click returned longer ago than the settle window, so nothing waits."""
+ monkeypatch.setattr(mcp_hooks, "_start_scout_challenge_settle", lambda _ctx: None)
+ ctx.pending_scout_challenge_armed_at = (
+ time.monotonic() - settings.COPILOT_SCOUT_ACT_OBSERVE_RECAPTURE_DELAY_SECONDS - 1.0
+ )
+
+ @pytest.mark.asyncio
+ async def test_a_widget_mounting_inside_what_is_left_of_the_window_is_recorded(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ ctx, _clock, sleeps = await self._timed_click(monkeypatch, page, elapsed=0.1)
+
+ async def _mount_during_settle(seconds: float) -> None:
+ sleeps.append(seconds)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+
+ monkeypatch.setattr(scouting_module, "asyncio", ScopedAsyncio(sleep=_mount_during_settle))
+
+ result = await self._post(ctx)
+
+ assert sleeps == [pytest.approx(settings.COPILOT_SCOUT_ACT_OBSERVE_RECAPTURE_DELAY_SECONDS - 0.1)]
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.asyncio
+ async def test_a_click_whose_observation_outlasted_the_window_adds_no_wait(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """The listener is live from the moment the click is armed, so time the observation already
+ spent counts toward the window instead of being waited out a second time."""
+ page = _ListenerPage()
+ ctx, _clock, sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+
+ async def _record(seconds: float) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(scouting_module, "asyncio", ScopedAsyncio(sleep=_record))
+
+ await self._post(ctx)
+
+ assert sleeps == []
+
+ @pytest.mark.asyncio
+ async def test_a_click_that_never_armed_a_listener_neither_waits_nor_records(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """With no listener there is nothing a wait could catch, so the report must not sleep. The clock
+ sits just past zero so that treating a missing arm as "armed at t=0" would still owe a wait."""
+ monkeypatch.setattr(scouting_module, "time", _ScopedClock(now=0.1))
+ ctx = self._ctx(source_url="https://records.example.test/search")
+ ctx.browser_session_id = "pbs-debug"
+ ctx.sensitive_origin_browser_session_ids = set()
+ ctx.codeblock_redaction_parameters = {}
+ sleeps: list[float] = []
+
+ async def _record(seconds: float) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(scouting_module, "asyncio", ScopedAsyncio(sleep=_record))
+
+ result = await self._post(ctx)
+
+ assert sleeps == []
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ @pytest.mark.asyncio
+ async def test_a_hidden_helper_frame_does_not_hide_the_visible_challenge_beside_it(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ page.navigate_frame("https://helper.vendor.test/turnstile/v0/api.html", child_frame=True, area=0.0)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+
+ result = await self._post(ctx)
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.asyncio
+ async def test_an_intent_click_that_fails_after_mounting_a_challenge_still_reports_it(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ result, _ctx = await self._selectorless_click(
+ monkeypatch,
+ {"intent": "the search button"},
+ {"ok": False, "error": "Timeout 30000ms exceeded while waiting for navigation"},
+ )
+
+ assert result["error"] == "Timeout 30000ms exceeded while waiting for navigation"
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.parametrize(
+ "params",
+ [{"selector": "#submit-search"}, {"intent": "the search button"}, {"x": 120, "y": 40}],
+ ids=["selector", "intent", "coordinate"],
+ )
+ @pytest.mark.asyncio
+ async def test_a_visible_widget_mounted_while_the_click_is_being_armed_is_not_credited_to_it(
+ self, monkeypatch: pytest.MonkeyPatch, params: dict[str, Any]
+ ) -> None:
+ page = _ListenerPage(child_frame_urls=["https://existing.vendor.test/turnstile/v0/api.html"])
+ existing = page.frames[1]
+ measure = scouting_module._challenge_frame_rendered_area
+
+ async def _mount_while_measuring(frame: Any) -> float | None:
+ if frame is existing and len(page.frames) == 2:
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+ return await measure(frame)
+
+ monkeypatch.setattr(scouting_module, "_challenge_frame_rendered_area", _mount_while_measuring)
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0, params=params)
+
+ result = await self._post(ctx)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ @pytest.mark.asyncio
+ async def test_a_visible_widget_mounted_during_code_only_click_setup_is_not_credited_to_it(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Nor when it refreshes its token after the click, which re-fires the navigation."""
+ page = _ListenerPage()
+
+ async def _mount_during_download_snapshot(_ctx: Any) -> frozenset[str]:
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+ return frozenset()
+
+ monkeypatch.setattr(
+ mcp_hooks, "_copilot_block_authoring_policy", lambda _ctx: BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ )
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", _mount_during_download_snapshot)
+ monkeypatch.setattr(mcp_hooks, "_arm_scout_download_listener", AsyncMock())
+ monkeypatch.setattr(mcp_hooks, "_arm_scout_popup_listener", AsyncMock())
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ page.renavigate_child_frame(0, "https://challenge.vendor.test/turnstile/v0/api.html?token=refreshed")
+
+ result = await self._post(ctx)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ @pytest.mark.asyncio
+ async def test_a_widget_mounted_while_the_dispatch_baseline_is_measured_is_not_credited_to_the_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ measure = scouting_module._challenge_frame_rendered_area
+
+ async def _mount_during_download_snapshot(_ctx: Any) -> frozenset[str]:
+ page.navigate_frame("https://first.vendor.test/turnstile/v0/api.html", child_frame=True)
+ return frozenset()
+
+ async def _mount_while_measuring(frame: Any) -> float | None:
+ if len(page.frames) == 2:
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+ return await measure(frame)
+
+ monkeypatch.setattr(
+ mcp_hooks, "_copilot_block_authoring_policy", lambda _ctx: BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ )
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", _mount_during_download_snapshot)
+ monkeypatch.setattr(mcp_hooks, "_arm_scout_download_listener", AsyncMock())
+ monkeypatch.setattr(mcp_hooks, "_arm_scout_popup_listener", AsyncMock())
+ monkeypatch.setattr(scouting_module, "_challenge_frame_rendered_area", _mount_while_measuring)
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+
+ result = await self._post(ctx)
+
+ assert len(page.frames) == 3
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ @pytest.mark.parametrize("before_return", [1.0, 5.0], ids=["slow_pre_click_measurement", "slow_target_resolution"])
+ @pytest.mark.asyncio
+ async def test_time_before_the_click_returns_does_not_use_up_the_settle_window(
+ self, monkeypatch: pytest.MonkeyPatch, before_return: float
+ ) -> None:
+ """An intent click can resolve its target for seconds inside the tool before the browser clicks."""
+ page = _ListenerPage(child_frame_urls=["https://existing.vendor.test/turnstile/v0/api.html"])
+ measure = scouting_module._challenge_frame_rendered_area
+ ctx, clock, sleeps = await self._timed_click(monkeypatch, page, elapsed=0.1, params={"intent": "search"})
+
+ async def _record(seconds: float) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(scouting_module, "_challenge_frame_rendered_area", measure)
+ monkeypatch.setattr(scouting_module, "asyncio", ScopedAsyncio(sleep=_record))
+ clock.now = before_return
+
+ await self._post(ctx)
+
+ assert sleeps == [pytest.approx(settings.COPILOT_SCOUT_ACT_OBSERVE_RECAPTURE_DELAY_SECONDS - 0.1)]
+
+ @pytest.mark.asyncio
+ async def test_a_widget_mounted_while_the_click_is_being_armed_is_credited_when_revealed(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage(child_frame_urls=["https://existing.vendor.test/turnstile/v0/api.html"])
+ existing = page.frames[1]
+ mounted: list[_ListenerFrame] = []
+ measure = scouting_module._challenge_frame_rendered_area
+
+ async def _mount_while_measuring(frame: Any) -> float | None:
+ if frame is existing and not mounted:
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True, area=0.0)
+ mounted.append(page.frames[-1])
+ return await measure(frame)
+
+ monkeypatch.setattr(scouting_module, "_challenge_frame_rendered_area", _mount_while_measuring)
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ existing.area = 0.0
+ mounted[0].area = _ON_SCREEN_AREA
+
+ result = await self._post(ctx)
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+
+ @pytest.mark.asyncio
+ async def test_a_click_that_times_out_after_mounting_a_challenge_still_reports_it(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+
+ result = await _click_post_hook(
+ {"ok": False, "error": "Timeout 30000ms exceeded while waiting for navigation"},
+ {"browser_context": {"url": "https://records.example.test/search", "title": "Search"}},
+ ctx,
+ )
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.asyncio
+ async def test_a_captured_frame_that_navigated_away_does_not_hide_the_challenge_after_it(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ page.navigate_frame("https://first.vendor.test/turnstile/v0/api.html", child_frame=True)
+ page.frames[-1].url = "https://records.example.test/embedded-help"
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+
+ result = await self._post(ctx)
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.asyncio
+ async def test_a_captured_hidden_helper_does_not_cut_the_wait_for_the_real_widget(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Only an on-screen frame ends the wait: a hidden helper that navigated first must not let the
+ report skip the window the visible widget arrives in."""
+ page = _ListenerPage()
+ ctx, _clock, sleeps = await self._timed_click(monkeypatch, page, elapsed=0.1)
+ page.navigate_frame("https://helper.vendor.test/turnstile/v0/api.html", child_frame=True, area=0.0)
+
+ async def _mount_during_settle(seconds: float) -> None:
+ sleeps.append(seconds)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+
+ monkeypatch.setattr(scouting_module, "asyncio", ScopedAsyncio(sleep=_mount_during_settle))
+
+ result = await self._post(ctx)
+
+ assert sleeps == [pytest.approx(settings.COPILOT_SCOUT_ACT_OBSERVE_RECAPTURE_DELAY_SECONDS - 0.1)]
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ async def _selectorless_click(
+ self, monkeypatch: pytest.MonkeyPatch, params: dict[str, Any], tool_result: dict[str, Any]
+ ) -> tuple[dict[str, Any], SimpleNamespace]:
+ """Drive a click with no selector going in, reporting exactly what `skyvern_click` emits for it."""
+ page = _ListenerPage()
+ ctx = self._ctx(source_url="https://records.example.test/search")
+ ctx.browser_session_id = "pbs-debug"
+ ctx.sensitive_origin_browser_session_ids = set()
+ ctx.codeblock_redaction_parameters = {}
+ monkeypatch.setattr(
+ scouting_module,
+ "resolve_browser_state_for_context",
+ AsyncMock(return_value=SimpleNamespace(get_or_create_page=AsyncMock(return_value=page))),
+ )
+ await _click_pre_hook(params, ctx)
+ assert ctx.pending_scout_challenge_armed_at is not None
+ self._settle_already_over(monkeypatch, ctx)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True)
+ result = await _click_post_hook(
+ tool_result,
+ {"browser_context": {"url": "https://records.example.test/search", "title": "Search"}},
+ ctx,
+ )
+ return result, ctx
+
+ @pytest.mark.asyncio
+ async def test_a_coordinate_click_reports_the_challenge_it_raised(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """`skyvern_click` with x/y returns `selector: null` and a `resolved_target`, never a
+ `resolved_selector`, so the report cannot depend on a locator to say a challenge appeared."""
+ result, ctx = await self._selectorless_click(
+ monkeypatch,
+ {"x": 120, "y": 40},
+ {
+ "ok": True,
+ "data": {"selector": None, "x": 120, "y": 40, "resolved_target": {"tag": "button", "text": "Search"}},
+ },
+ )
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+ assert ctx.scout_trajectory == []
+
+ @pytest.mark.asyncio
+ async def test_an_intent_click_records_the_challenge_against_the_element_it_resolved(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """An intent click has no selector going in but reports the element it resolved, so the challenge
+ reaches the demonstrated step as well as the tool result."""
+ result, ctx = await self._selectorless_click(
+ monkeypatch,
+ {"intent": "the search button"},
+ {
+ "ok": True,
+ "data": {"selector": None, "intent": "the search button", "resolved_selector": "#submit-search"},
+ },
+ )
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert ctx.scout_trajectory[-1]["observed_effects"]["challenge_raised"] is True
+ assert ctx.scout_trajectory[-1]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.asyncio
+ async def test_every_candidate_challenge_frame_is_measured_at_once(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Each reading stops itself after the observer timeout, so measuring them one at a time would
+ add that timeout per vendor frame to the click; measured together they cost one."""
+ frames = 4
+ in_flight = 0
+ peak = 0
+ started = asyncio.Event()
+
+ async def _measure(_frame: _ListenerFrame) -> float:
+ nonlocal in_flight, peak
+ in_flight += 1
+ peak = max(peak, in_flight)
+ if in_flight == frames:
+ started.set()
+ try:
+ await asyncio.wait_for(started.wait(), timeout=0.5)
+ except asyncio.TimeoutError:
+ pass
+ in_flight -= 1
+ return 1.0
+
+ monkeypatch.setattr(scouting_module, "_challenge_frame_rendered_area", _measure)
+ page = _ListenerPage(child_frame_urls=["https://challenge.vendor.test/turnstile/v0/api.html"] * frames)
+ ctx = await self._arm(monkeypatch, page)
+ assert peak == frames, "before the click dispatches"
+
+ # The same frames measured as placeholders, so the report re-reads all of them after the click.
+ peak = 0
+ started.clear()
+ self._settle_already_over(monkeypatch, ctx)
+ await self._post(ctx)
+ assert peak == frames, "after the click, when the report scans for one on screen"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("outer_style_visible", "credited"),
+ [(False, False), (True, True)],
+ ids=["outer_iframe_hidden_by_style", "outer_iframe_visible"],
+ )
+ async def test_a_nested_vendor_frame_counts_only_when_every_embedding_iframe_is_visible(
+ self, monkeypatch: pytest.MonkeyPatch, outer_style_visible: bool, credited: bool
+ ) -> None:
+ """The observer clips geometry through each ancestor frame, but style is judged per document, so an
+ opacity:0 or visibility:hidden outer iframe would otherwise let a nested helper look on screen."""
+ page = _ListenerPage()
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ outer = _ListenerFrame("https://embed.example.test/form", page.frames[0], style_visible=outer_style_visible)
+ vendor = _ListenerFrame("https://challenge.vendor.test/turnstile/v0/api.html", outer)
+ page.frames.extend([outer, vendor])
+ page._dispatch(vendor)
+
+ result = await self._post(ctx)
+
+ assert ("challenge_raised" in (result["data"].get("observed_effects") or {})) is credited
+
+ @pytest.mark.asyncio
+ async def test_a_click_mounted_vendor_frame_that_is_not_on_screen_is_not_recorded(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """A hidden vendor frame is still a solve-ladder marker, so crediting it would send a solve
+ that runs the whole ladder against nothing a person could answer."""
+ page = _ListenerPage()
+ ctx, _clock, _sleeps = await self._timed_click(monkeypatch, page, elapsed=1.0)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/v0/api.html", child_frame=True, area=0.0)
+
+ result = await self._post(ctx)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+ assert "challenge_vendor" not in result["data"]
+
+ async def _reveal_cycle(
+ self, monkeypatch: pytest.MonkeyPatch, *, before: float | None, after: float | None
+ ) -> dict[str, Any]:
+ """A vendor frame already in the document that never navigates, only changes size."""
+ page = _ListenerPage(child_frame_urls=["https://challenge.vendor.test/turnstile/v0/api.html"])
+ readings = [before]
+ monkeypatch.setattr(
+ scouting_module,
+ "_challenge_frame_rendered_area",
+ AsyncMock(side_effect=lambda _frame: readings.pop(0) if readings else after),
+ )
+ ctx = await self._arm(monkeypatch, page)
+ self._settle_already_over(monkeypatch, ctx)
+ return await self._post(ctx)
+
+ @pytest.mark.asyncio
+ async def test_a_renderer_that_never_answers_does_not_hold_up_the_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ page.frames.append(
+ _ListenerFrame("https://challenge.vendor.test/turnstile/v0/api.html", page.frames[0], unresponsive=True)
+ )
+ monkeypatch.setattr(scouting_module, "_CHALLENGE_FRAME_PROBE_TIMEOUT_SECONDS", 0.05)
+
+ ctx = await asyncio.wait_for(self._arm(monkeypatch, page), timeout=5)
+
+ assert ctx.pending_scout_challenge_armed_at is not None
+ assert ctx.pending_scout_challenge_prior_frames == [(page.frames[1], None)]
+
+ @pytest.mark.asyncio
+ async def test_preloaded_widget_the_click_reveals_is_recorded(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ result = await self._reveal_cycle(monkeypatch, before=1.0, after=300.0 * 65.0)
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ @pytest.mark.asyncio
+ async def test_widget_already_on_screen_before_the_click_is_not_recorded(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ result = await self._reveal_cycle(monkeypatch, before=300.0 * 65.0, after=300.0 * 65.0)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ @pytest.mark.asyncio
+ async def test_preloaded_widget_that_stays_a_placeholder_is_not_recorded(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ result = await self._reveal_cycle(monkeypatch, before=1.0, after=1.0)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ async def _challenge_on_host(
+ self, monkeypatch: pytest.MonkeyPatch, host: str
+ ) -> tuple[dict[str, Any], SimpleNamespace, list[dict[str, Any]]]:
+ page = _ListenerPage()
+ ctx = await self._arm(monkeypatch, page)
+ self._settle_already_over(monkeypatch, ctx)
+ page.navigate_frame(f"https://{host}/turnstile/", child_frame=True)
+ with capture_logs() as logs:
+ result = await self._post(ctx)
+ return result, ctx, logs
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("host", "fragment"),
+ [
+ ("s3cr3t-tenant.challenge.vendor.test", "s3cr3t-tenant"),
+ ("xn--mnchen-3ya.challenge.vendor.test", "xn--mnchen-3ya"),
+ ],
+ ids=["lowercased_slug", "punycode_label"],
+ )
+ async def test_the_challenge_is_named_by_vendor_and_no_part_of_the_host_is_retained(
+ self, monkeypatch: pytest.MonkeyPatch, host: str, fragment: str
+ ) -> None:
+ """A hostname carries whatever the page put in it, in whatever spelling the browser normalised
+ it to, so the only safe host to keep is none: the vendor comes from the signature's literals."""
+ result, ctx, logs = await self._challenge_on_host(monkeypatch, host)
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+ signal = next(entry for entry in logs if entry.get("event") == "copilot_observed_challenge_signal")
+ for retained in (result["data"], ctx.scout_trajectory[-1], ctx.scouted_interactions[-1], signal):
+ assert fragment not in json.dumps(retained)
+
+ @pytest.mark.asyncio
+ async def test_a_click_whose_locator_the_scrub_removed_still_gets_its_effect(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """A selector carrying a registered value loses its locator fields when the interaction is
+ scrubbed, so the effect cannot be found again by that selector — and an older click using the
+ same one must not receive it instead."""
+ secret = "s3cr3t-tenant"
+ page = _ListenerPage()
+ ctx = await self._arm(monkeypatch, page)
+ self._settle_already_over(monkeypatch, ctx)
+ earlier_click = {"tool_name": "click", "selector": f"#row-{secret}", "observed_effects": {}}
+ ctx.scout_trajectory = [earlier_click]
+ ctx.scouted_interactions = [earlier_click]
+ ctx.secret_scrub_values = [secret]
+ page.navigate_frame("https://challenge.vendor.test/turnstile/", child_frame=True)
+
+ result = await _click_post_hook(
+ {"ok": True, "data": {"selector": f"#row-{secret}"}},
+ {"browser_context": {"url": "https://records.example.test/search", "title": "Search"}},
+ ctx,
+ )
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert earlier_click["observed_effects"] == {}
+ for collection in (ctx.scout_trajectory, ctx.scouted_interactions):
+ assert collection[-1] is not earlier_click
+ assert collection[-1]["observed_effects"]["challenge_raised"] is True
+
+ @pytest.mark.asyncio
+ async def test_challenge_log_carries_the_page_origin_not_the_landed_url(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage()
+ ctx = await self._arm(monkeypatch, page)
+ self._settle_already_over(monkeypatch, ctx)
+ page.navigate_frame("https://challenge.vendor.test/turnstile/", child_frame=True)
+
+ with capture_logs() as logs:
+ await _click_post_hook(
+ {"ok": True, "data": {"selector": "#submit-search"}},
+ {
+ "browser_context": {
+ "url": "https://records.example.test/search?session_token=abc123#magic",
+ "title": "Search",
+ }
+ },
+ ctx,
+ )
+
+ signal = next(entry for entry in logs if entry.get("event") == "copilot_observed_challenge_signal")
+ assert "session_token" not in json.dumps(signal)
+ assert "abc123" not in json.dumps(signal)
+ assert signal["page_origin"] == "https://records.example.test/"
+
+ @pytest.mark.asyncio
+ async def test_a_click_that_never_arms_does_not_inherit_the_previous_clicks_listener_state(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """A previous click's arm time must not make this click look armed, or already settled."""
+ ctx = self._ctx(source_url="https://records.example.test/search")
+ ctx.browser_session_id = "pbs-debug"
+ ctx.sensitive_origin_browser_session_ids = set()
+ ctx.codeblock_redaction_parameters = {}
+ ctx.pending_scout_challenge_armed_at = 123.0
+ ctx.pending_scout_challenge_frames = [object()]
+
+ await _click_pre_hook({"selector": "#submit-search"}, ctx)
+
+ assert ctx.pending_scout_challenge_armed_at is None
+ assert ctx.pending_scout_challenge_frames == []
+ assert ctx.pending_scout_challenge_prior_frames == []
+
+ @pytest.mark.asyncio
+ async def test_a_frame_whose_pre_click_state_was_never_measured_is_not_a_reveal(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Without a pre-click reading there is no growth to observe, so an already-challenging
+ widget must not be credited to whatever click followed it."""
+ result = await self._reveal_cycle(monkeypatch, before=None, after=300.0 * 65.0)
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+
+ @pytest.mark.asyncio
+ async def test_placeholder_frame_that_navigates_to_a_vendor_url_is_this_clicks_effect(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _ListenerPage(child_frame_urls=["about:blank"])
+ ctx = await self._arm(monkeypatch, page)
+ page.renavigate_child_frame(0, "https://challenge.vendor.test/turnstile/v0/api.html?sitekey=abc")
+
+ result = await self._post(ctx)
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+
+ async def _armed_click(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ frame_url: str,
+ child_frame: bool,
+ ) -> tuple[_ListenerPage, SimpleNamespace]:
+ ctx = self._ctx(source_url="https://records.example.test/search")
+ ctx.browser_session_id = "pbs-debug"
+ ctx.sensitive_origin_browser_session_ids = set()
+ ctx.codeblock_redaction_parameters = {}
+ page = _ListenerPage()
+ monkeypatch.setattr(
+ scouting_module,
+ "resolve_browser_state_for_context",
+ AsyncMock(return_value=SimpleNamespace(get_or_create_page=AsyncMock(return_value=page))),
+ )
+ await _click_pre_hook({"selector": "#submit-search"}, ctx)
+ page.navigate_frame(frame_url, child_frame=child_frame)
+ return page, ctx
+
+ async def _click_cycle_with_frame_navigation(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ frame_url: str,
+ child_frame: bool,
+ sensitive_origin: bool = False,
+ click_ok: bool = True,
+ ) -> tuple[dict[str, Any], _ListenerPage, SimpleNamespace]:
+ page, ctx = await self._armed_click(monkeypatch, frame_url=frame_url, child_frame=child_frame)
+ if sensitive_origin:
+ ctx.sensitive_origin_browser_session_ids = {"pbs-debug"}
+ tool_result: dict[str, Any] = (
+ {"ok": True, "data": {"selector": "#submit-search"}}
+ if click_ok
+ else {"ok": False, "error": "element is not visible"}
+ )
+ result = await _click_post_hook(
+ tool_result,
+ {"browser_context": {"url": "https://records.example.test/search", "title": "Search"}},
+ ctx,
+ )
+ return result, page, ctx
+
+ @pytest.mark.asyncio
+ async def test_click_that_raises_a_vendor_challenge_frame_records_the_effect_and_host(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ result, page, ctx = await self._click_cycle_with_frame_navigation(
+ monkeypatch,
+ frame_url="https://challenge.vendor.test/turnstile/v0/api.html?sitekey=abc",
+ child_frame=True,
+ )
+
+ assert result["data"]["observed_effects"]["challenge_raised"] is True
+ assert result["data"]["challenge_vendor"] == "turnstile"
+ for collection in (ctx.scout_trajectory, ctx.scouted_interactions):
+ recorded = collection[-1]
+ assert recorded["observed_effects"]["challenge_raised"] is True
+ assert recorded["challenge_vendor"] == "turnstile"
+ click_fact = next(fact for fact in mcp_hooks._demonstrated_step_facts(ctx) if fact["tool_name"] == "click")
+ assert click_fact["challenge_vendor"] == "turnstile"
+ assert page.removed == ["framenavigated"]
+ assert ctx.pending_scout_challenge_frames == []
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("frame_url", "child_frame"),
+ [
+ ("https://challenge.vendor.test/turnstile/v0/api.html", False),
+ ("https://cdn.example.test/analytics.html", True),
+ ],
+ ids=["main_frame_navigation", "non_vendor_child_frame"],
+ )
+ async def test_click_without_a_vendor_child_frame_records_no_challenge(
+ self, monkeypatch: pytest.MonkeyPatch, frame_url: str, child_frame: bool
+ ) -> None:
+ result, page, ctx = await self._click_cycle_with_frame_navigation(
+ monkeypatch, frame_url=frame_url, child_frame=child_frame
+ )
+
+ assert "challenge_raised" not in (result["data"].get("observed_effects") or {})
+ assert "challenge_vendor" not in result["data"]
+ for collection in (ctx.scout_trajectory, ctx.scouted_interactions):
+ assert "challenge_vendor" not in collection[-1]
+ assert page.removed == ["framenavigated"]
+
+ @pytest.mark.asyncio
+ async def test_sensitive_origin_refusal_releases_the_challenge_listener(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ result, page, ctx = await self._click_cycle_with_frame_navigation(
+ monkeypatch,
+ frame_url="https://challenge.vendor.test/turnstile/v0/api.html",
+ child_frame=True,
+ sensitive_origin=True,
+ )
+
+ assert result["ok"] is False
+ assert result["error"] == SENSITIVE_ORIGIN_PAGE_ERROR
+ assert page.removed == ["framenavigated"]
+ assert ctx.pending_scout_challenge_frames == []
+
+ @pytest.mark.asyncio
+ async def test_failed_click_releases_the_challenge_listener(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ result, page, ctx = await self._click_cycle_with_frame_navigation(
+ monkeypatch,
+ frame_url="https://challenge.vendor.test/turnstile/v0/api.html",
+ child_frame=True,
+ click_ok=False,
+ )
+
+ assert result["ok"] is False
+ assert page.removed == ["framenavigated"]
+ assert ctx.pending_scout_challenge_detachers == []
+ assert ctx.pending_scout_challenge_frames == []
+
+ @pytest.mark.asyncio
+ async def test_post_hook_exception_releases_the_challenge_listener(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ page, ctx = await self._armed_click(
+ monkeypatch,
+ frame_url="https://challenge.vendor.test/turnstile/v0/api.html",
+ child_frame=True,
+ )
+ monkeypatch.setattr(
+ mcp_hooks,
+ "_consume_scout_source_url",
+ MagicMock(side_effect=RuntimeError("browser context lost")),
+ )
+
+ with pytest.raises(RuntimeError):
+ await _click_post_hook(
+ {"ok": True, "data": {"selector": "#submit-search"}},
+ {"browser_context": {"url": "https://records.example.test/search", "title": "Search"}},
+ ctx,
+ )
+
+ assert page.removed == ["framenavigated"]
+ assert ctx.pending_scout_challenge_detachers == []
+ assert ctx.pending_scout_challenge_frames == []
+
def _ctx_with_scripted_reads(
self,
*,
diff --git a/tests/unit/test_copilot_outcome_verification_trace.py b/tests/unit/test_copilot_outcome_verification_trace.py
index aab21985c..8ae609fe9 100644
--- a/tests/unit/test_copilot_outcome_verification_trace.py
+++ b/tests/unit/test_copilot_outcome_verification_trace.py
@@ -218,6 +218,7 @@ async def test_run_copilot_agent_finalizes_false_gate_on_turn_span(
workflow_verification_evidence=WorkflowVerificationEvidence(test_attempted_but_incomplete=True),
request_policy=RequestPolicy(),
attached_browser_drivers={},
+ pending_scout_challenge_detachers=[],
)
record_gate_decision(
ctx,
diff --git a/tests/unit/test_copilot_runtime.py b/tests/unit/test_copilot_runtime.py
index 879e8e63e..45bfe367f 100644
--- a/tests/unit/test_copilot_runtime.py
+++ b/tests/unit/test_copilot_runtime.py
@@ -1618,6 +1618,29 @@ async def test_every_turn_exit_releases_the_driver_it_attached(monkeypatch: pyte
assert result.turn_outcome.terminal_reason == _TURN_EXIT_TERMINAL_REASONS[exit_path]
[email protected]("exit_path", TURN_EXIT_PATHS)
+async def test_every_turn_exit_releases_a_click_listener_its_post_hook_never_reached(
+ monkeypatch: pytest.MonkeyPatch, exit_path: str
+) -> None:
+ """A click cancelled between its pre-hook and post-hook never reaches the post-hook's release, so
+ the turn's own exit is the last place its listener on the persistent page can be removed."""
+ detached: list[str] = []
+
+ async def _armed_click_that_never_reported(ctx: AgentContext) -> None:
+ ctx.pending_scout_challenge_detachers.append(lambda: detached.append("framenavigated"))
+
+ await run_turn_to_exit(
+ monkeypatch,
+ manager=_release_manager(),
+ exit_path=exit_path,
+ browser_state=MagicMock(),
+ on_attached=_armed_click_that_never_reported,
+ )
+
+ assert detached == ["framenavigated"]
+
+
@pytest.mark.asyncio
async def test_a_cancel_during_prior_run_hydration_still_releases_the_driver_it_attached(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index 19df5e0a1..3e707062b 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -197,6 +197,11 @@ def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleN
reached_download_target=None,
pending_scout_popup=None,
pending_scout_popup_content_type=None,
+ pending_scout_challenge_frames=[],
+ pending_scout_challenge_detachers=[],
+ pending_scout_challenge_prior_frames=[],
+ last_scout_act_observe_recapture_attempted=False,
+ pending_scout_challenge_armed_at=None,
pre_run_gated_output_warning_fingerprint=(),
)
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 5081d6098..c6d827b80 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -4115,6 +4115,15 @@ def test_the_frame_census_control_set_cannot_silently_fall_behind_the_scanners_o
assert not missing, f"census control set fell behind `q`: {sorted(missing)}"
+def test_observe_js_renders_the_shared_challenge_signature_verbatim() -> None:
+ # The alternation is spliced in from a constant the copilot scout also compiles, so a change
+ # made for the scout's benefit must not quietly rewrite the regex this script evaluates.
+ assert (
+ r" const sig = /captcha|turnstile|challenges\.cloudflare|arkoselabs|funcaptcha|datadome"
+ r"|perimeterx|verify you are human|security challenge/i;"
+ ) in taskv3_tools._OBSERVE_JS
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_frame_census_leaves_the_capped_frames_countable() -> None: