Skip to content

Automate browser based workflows with AI

feat(SKY-11859): reach positive page-evidence carrier on dispatched/STANDARD copilot runs (#7241)

Andrew Neilson9e49dff964a9
diff --git a/skyvern/forge/sdk/copilot/code_block_steps.py b/skyvern/forge/sdk/copilot/code_block_steps.py
index 5db19ed2b..37b2ec714 100644
--- a/skyvern/forge/sdk/copilot/code_block_steps.py
+++ b/skyvern/forge/sdk/copilot/code_block_steps.py
@@ -36,8 +36,8 @@ _METHOD_ACTION_TYPES: dict[str, str] = {
"reload": "reload_page",
"evaluate": "execute_js",
"wait_for_timeout": "wait",
- # SkyvernPage @action_wrap high-level API (mirrors skyvern_page.py)
- "extract": "extract",
+ # SkyvernPage @action_wrap high-level API (mirrors skyvern_page.py). `extract` is excluded:
+ # code blocks run on a raw Playwright page and must not reach the LLM extraction path.
"fill_autocomplete": "input_text",
"upload_file": "upload_file",
"complete": "complete",
@@ -68,7 +68,7 @@ _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({"extract", "complete", "solve_captcha", "verification_code"})
+_PROMPT_POSITIONAL_METHODS: frozenset[str] = frozenset({"complete", "solve_captcha", "verification_code"})
# 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"}
@@ -265,7 +265,7 @@ def _describe(span: CodeActionSpan) -> str:
def _consolidate_read_spans(spans: list[CodeActionSpan]) -> list[CodeActionSpan]:
- """Merge adjacent raw DOM reads into one extract span; an explicit page.extract() is not a read and stays separate."""
+ """Merge adjacent raw DOM reads into one extract span."""
consolidated: list[CodeActionSpan] = []
for span in spans:
prev = consolidated[-1] if consolidated else None
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index d9577edfb..e9be08224 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -386,11 +386,10 @@ class AgentContext:
# flaky scout pass. Cleared when the spine gains a source, on imposition, or on run dispatch.
output_contract_declick_attempted_by_signature: dict[str, bool] = field(default_factory=dict)
# One-shot per signature: a consumed advisory run whose observed output bound no required path may
- # re-enter the ladder once so the stronger page-source extraction can be imposed before any terminal.
+ # re-enter the ladder once before any terminal.
output_contract_dispatch_reopened_by_signature: dict[str, bool] = field(default_factory=dict)
- # Set once a page-source extraction (page.extract keyed to the required paths) has been imposed on a
- # signature; the exhaustion terminal requires this so a code static-return never terminals a producible shape.
- output_contract_page_source_required_by_signature: dict[str, bool] = field(default_factory=dict)
+ # The exhaustion terminal requires this, and no rung sets it while code blocks stay on raw
+ # Playwright, so that terminal is unreachable until output grounding returns.
output_contract_page_extraction_imposed_by_signature: dict[str, bool] = field(default_factory=dict)
# Run-output evidence recorded at the run-result seam: a dispatched run's output-contract signatures
# mapped to their required paths (armed at seam-admit and page-source imposition), then the observed
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index ca2d9ffef..fb852942e 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -53,7 +53,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
degraded_contract_delivered_unverified_terminal_state,
only_structural_requested_output_abstentions,
)
-from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schema
+from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schema, parse_composition_html
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
@@ -212,6 +212,13 @@ _MAX_REGISTERED_ARTIFACT_BYTES = 5 * 1024 * 1024
_MAX_REGISTERED_ARTIFACT_TEXT_CHARS = 20_000
_REGISTERED_ARTIFACT_PARSE_EXTENSIONS = frozenset({".txt", ".csv", ".json"})
+_POST_RUN_PAGE_HTML_ARTIFACT_TYPES = (ArtifactType.HTML_ACTION, ArtifactType.HTML_SCRAPE)
+_MAX_POST_RUN_PAGE_HTML_CHARS = 1_500_000
+_POST_RUN_PAGE_PARSE_TIMEOUT_SECONDS = 15.0
+# Non-S3 backends ignore an artifact's bundle_key and return the whole ZIP; page HTML never
+# starts with a ZIP local/central/spanning signature, so treat these prefixes as fail-closed.
+_ZIP_MAGIC_PREFIXES = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
+
_POST_RUN_REPAIR_CAPTURE_TIMEOUT_SECONDS = 30.0
# Primary exit condition: seconds of no observed progress across the combined
@@ -1264,6 +1271,92 @@ async def _capture_and_store_post_run_page(
ctx.composition_page_evidence = None
+def _pre_run_baseline_is_provenance_valid(evidence: Mapping[str, Any] | None) -> bool:
+ """Pre-dispatch scout evidence carries no run stamp; post-run evidence from a prior turn does.
+ Pinning the latter as this run's baseline would let a stale page launder a confirm, so reject it."""
+ if not isinstance(evidence, Mapping):
+ return False
+ if evidence.get("observed_after_workflow_run") is True:
+ return False
+ return not evidence.get("workflow_run_id")
+
+
+def _select_terminal_page_artifact(artifacts: Sequence[Artifact]) -> Artifact | None:
+ for artifact_type in _POST_RUN_PAGE_HTML_ARTIFACT_TYPES:
+ family = [artifact for artifact in artifacts if artifact.artifact_type == artifact_type]
+ if family:
+ return max(family, key=lambda artifact: (artifact.created_at, artifact.artifact_id))
+ return None
+
+
+async def _fetch_dispatched_terminal_page_evidence(
+ *, run_id: str, organization_id: str, current_url: str
+) -> dict[str, Any] | None:
+ try:
+ result = await app.DATABASE.artifacts.get_artifacts_for_run(
+ run_id,
+ organization_id=organization_id,
+ artifact_types=list(_POST_RUN_PAGE_HTML_ARTIFACT_TYPES),
+ )
+ except Exception:
+ LOG.debug("Dispatched terminal page artifact fetch failed", run_id=run_id, exc_info=True)
+ return None
+ artifacts = result if isinstance(result, list) else []
+ latest = _select_terminal_page_artifact(artifacts)
+ if latest is None:
+ return None
+ file_size = latest.file_size
+ if isinstance(file_size, int) and file_size > _MAX_REGISTERED_ARTIFACT_BYTES:
+ return None
+ try:
+ artifact_bytes = await app.ARTIFACT_MANAGER.retrieve_artifact(latest)
+ except Exception:
+ LOG.debug("Dispatched terminal page retrieve failed", artifact_id=latest.artifact_id, exc_info=True)
+ return None
+ if not artifact_bytes or len(artifact_bytes) > _MAX_REGISTERED_ARTIFACT_BYTES:
+ return None
+ if artifact_bytes.startswith(_ZIP_MAGIC_PREFIXES):
+ return None
+ html = artifact_bytes.decode("utf-8", errors="ignore")[:_MAX_POST_RUN_PAGE_HTML_CHARS]
+ if not html:
+ return None
+ try:
+ evidence = await asyncio.wait_for(
+ asyncio.to_thread(parse_composition_html, html, inspected_url=current_url, current_url=current_url),
+ timeout=_POST_RUN_PAGE_PARSE_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ LOG.debug("Dispatched terminal page parse failed", run_id=run_id, exc_info=True)
+ return None
+ return evidence if isinstance(evidence, dict) else None
+
+
+async def _capture_dispatched_terminal_page_evidence(
+ ctx: CopilotContext,
+ *,
+ run_id: str,
+ organization_id: str,
+ current_url: str,
+) -> None:
+ if _pre_run_baseline_is_provenance_valid(ctx.composition_page_evidence):
+ _pin_pre_run_page_reference(ctx, run_id)
+ evidence = await _fetch_dispatched_terminal_page_evidence(
+ run_id=run_id, organization_id=organization_id, current_url=current_url
+ )
+ if evidence is None:
+ return
+ bounded = has_bounded_page_schema(evidence)
+ if not page_evidence_prose_text(evidence).strip() and not bounded:
+ return
+ store_post_run_page_evidence(ctx, evidence, run_id=run_id, current_url=current_url)
+ LOG.info(
+ "copilot_dispatched_terminal_page_evidence_captured",
+ workflow_run_id=run_id,
+ dispatch_to_worker=True,
+ bounded_page_schema=bounded,
+ )
+
+
def _scout_ephemeral_values(ctx: CopilotContext, workflow_param_keys: set[str]) -> dict[str, str]:
trajectory = list(ctx.scout_trajectory or [])
if not trajectory:
@@ -2052,6 +2145,16 @@ async def _run_blocks_and_collect_debug(
downloaded_artifact_ids=_collect_downloaded_artifact_ids(block_outputs_by_label),
)
+ # Dispatched runs are worker-owned, so the API cannot CDP-capture the terminal page; read the
+ # worker-persisted terminal HTML artifact instead and route it through the same post-run sink.
+ if dispatch_to_worker and run_session_id and run_ok and not ctx.copilot_total_timeout_exceeded:
+ await _capture_dispatched_terminal_page_evidence(
+ ctx,
+ run_id=workflow_run.workflow_run_id,
+ organization_id=ctx.organization_id,
+ current_url=current_url,
+ )
+
result_data: dict[str, Any] = {
"workflow_run_id": workflow_run.workflow_run_id,
"browser_session_id": run_session_id,
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 04a69bfce..f18d63f2b 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -1818,7 +1818,6 @@ _MAX_OUTPUT_CONTRACT_STEERING_REJECTS = 2
_MAX_OUTPUT_CONTRACT_REJECTS = 4
_MAX_OUTPUT_CONTRACT_DEFERRALS = 3
_MAX_OUTPUT_CONTRACT_ACTUATIONS_WITHOUT_RUN = 3
-_OUTPUT_CONTRACT_PAGE_EXTRACT_VAR = "output_contract_page_values"
_OUTPUT_CONTRACT_ABLATION_GATE_ID = "output_contract_actuation"
_METADATA_PREFLIGHT_ABLATION_GATE_ID = "metadata_run_preflight_reject"
@@ -3474,19 +3473,10 @@ def _run_authority_permits_dispatch(ctx: AgentContext) -> bool:
)
-def _output_contract_page_source_required(ctx: AgentContext, signature: str) -> bool:
- return bool(signature) and bool(ctx.output_contract_page_source_required_by_signature.get(signature))
-
-
def _page_extraction_imposed(ctx: AgentContext, signature: str) -> bool:
return bool(signature) and bool(ctx.output_contract_page_extraction_imposed_by_signature.get(signature))
-def _mark_page_extraction_imposed(ctx: AgentContext, signature: str) -> None:
- if signature:
- ctx.output_contract_page_extraction_imposed_by_signature[signature] = True
-
-
def _arm_pending_run_evidence(ctx: AgentContext, signature: str, required_paths: set[str]) -> None:
if not signature or not required_paths:
return
@@ -3550,7 +3540,7 @@ def record_output_contract_run_output_evidence(ctx: AgentContext, result: object
def _reopen_dispatch_lacked_bound_extraction(ctx: AgentContext, signature: str) -> bool:
"""One-shot per signature: a consumed advisory run whose observed output bound no required path is not
exhaustion evidence — a code static-return provably cannot key values a click-only trajectory never
- captured. Reset the signature to UNUSED and require the stronger page-source extraction on the next pass."""
+ captured. Reset the signature to UNUSED so the ladder re-enters once before any terminal."""
if not signature:
return False
if _output_contract_advisory_state(ctx, signature) != OutputContractAdvisoryState.CONSUMED:
@@ -3564,7 +3554,6 @@ def _reopen_dispatch_lacked_bound_extraction(ctx: AgentContext, signature: str)
if ctx.output_contract_dispatch_reopened_by_signature.get(signature):
return False
ctx.output_contract_dispatch_reopened_by_signature[signature] = True
- ctx.output_contract_page_source_required_by_signature[signature] = True
ctx.output_contract_actuation_by_signature[signature] = OutputContractAdvisoryState.UNUSED
ctx.output_contract_actuation_count_by_signature[signature] = max(
1, int(ctx.output_contract_actuation_count_by_signature.get(signature, 0) or 0)
@@ -3576,49 +3565,6 @@ def _reopen_dispatch_lacked_bound_extraction(ctx: AgentContext, signature: str)
return True
-def _strip_top_level_returns(code: str) -> str:
- try:
- tree = ast.parse(code)
- except SyntaxError:
- return code
- kept = [node for node in tree.body if not isinstance(node, ast.Return)]
- if len(kept) == len(tree.body):
- return code
- return ast.unparse(ast.Module(body=kept, type_ignores=[]))
-
-
-def _page_source_extraction_prompt(required_paths: set[str]) -> str:
- paths = ", ".join(sorted(_metadata_contract_required_paths(required_paths)))
- return (
- "Extract the requested output values visible on the current page. "
- f"Populate these output paths when visible: {paths}."
- )
-
-
-def _page_source_extraction_code(target_code: str, required_paths: set[str]) -> str:
- body = _strip_top_level_returns(textwrap.dedent(target_code).strip())
- schema = _schema_template_for_required_paths(required_paths)
- extract_block = (
- f"{_OUTPUT_CONTRACT_PAGE_EXTRACT_VAR} = await page.extract(\n"
- f" prompt={json.dumps(_page_source_extraction_prompt(required_paths))},\n"
- f" schema={schema!r},\n"
- ")\n"
- f"return {_OUTPUT_CONTRACT_PAGE_EXTRACT_VAR}"
- )
- return f"{body}\n{extract_block}" if body else extract_block
-
-
-def _impose_page_source_extraction(
- parsed: dict[str, Any], label: str, target_code: str, required_paths: set[str]
-) -> str | None:
- keyed = _page_source_extraction_code(target_code, required_paths)
- for block in _workflow_code_blocks(parsed):
- if str(block.get("label") or "").strip() == label:
- block["code"] = keyed.rstrip() + "\n"
- return yaml.safe_dump(parsed, sort_keys=False)
- return None
-
-
def _actuate_output_contract_bail(
ctx: AgentContext,
*,
@@ -3702,15 +3648,10 @@ def _impose_output_contract_envelope_after_steering(
required_paths=required_paths,
)
_reopen_dispatch_lacked_bound_extraction(ctx, signature)
- page_source_needed = _output_contract_page_source_required(ctx, signature) and not _page_extraction_imposed(
- ctx, signature
- )
runtime_attempt_key = _runtime_output_repair_attempt_key(ctx, workflow_yaml, required_paths, source, reason_code)
- if (
- not page_source_needed
- and _output_contract_reject_count(ctx, signature) < _MAX_OUTPUT_CONTRACT_STEERING_REJECTS
- and _runtime_output_repair_attempt_recorded(ctx, runtime_attempt_key)
- ):
+ if _output_contract_reject_count(
+ ctx, signature
+ ) < _MAX_OUTPUT_CONTRACT_STEERING_REJECTS and _runtime_output_repair_attempt_recorded(ctx, runtime_attempt_key):
return workflow_yaml, raw_code_artifact_metadata, False
label, owner_labels = _target_output_contract_block_label(
ctx,
@@ -3730,27 +3671,6 @@ def _impose_output_contract_envelope_after_steering(
return workflow_yaml, raw_code_artifact_metadata, False
target_code = str(target_block.get("code") or "")
current_fingerprint = _output_contract_structural_fingerprint(workflow_yaml, signature)
- if page_source_needed:
- imposed_yaml = _impose_page_source_extraction(parsed, label, target_code, required_paths)
- if imposed_yaml is not None:
- scaffolded_metadata = _apply_metadata_contract_scaffold(
- ctx,
- imposed_yaml,
- raw_code_artifact_metadata,
- required_paths=required_paths,
- source=source,
- reason_code=reason_code,
- )
- _mark_page_extraction_imposed(ctx, signature)
- _arm_pending_run_evidence(ctx, signature, required_paths)
- _mark_output_contract_imposed(ctx, signature)
- _record_runtime_output_repair_attempt(ctx, runtime_attempt_key)
- LOG.info(
- "copilot_output_contract_page_source_extraction_imposed",
- block_label=label,
- canonical_output_contract_signature=signature,
- )
- return imposed_yaml, scaffolded_metadata, True
if _scout_spine_requires_separated_blocks(ctx):
synthesized = synthesize_code_block(
ctx.scout_trajectory,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 2acaa370a..0eb8f8d57 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -4404,7 +4404,6 @@ async def wrapper({default_args}):
recorder = CodeBlockActionRecording(
code_block=self,
page=page,
- browser_state=browser_state,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
index 586a3c211..ae5509e01 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
@@ -4,7 +4,7 @@ import sys
import time
from os import PathLike, fspath
from types import FrameType
-from typing import TYPE_CHECKING, Any, Awaitable, Callable
+from typing import Any, Awaitable, Callable
import pydantic
import structlog
@@ -12,9 +12,6 @@ import structlog
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus, SelectOption
-if TYPE_CHECKING:
- from skyvern.core.script_generations.skyvern_page import SkyvernPage
-
LOG = structlog.get_logger()
CODE_BLOCK_FILENAME = "<code_block>"
@@ -59,8 +56,9 @@ _LOCATOR_FACTORY_METHODS = frozenset(
# Mirror skyvern_page.py's @action_wrap table and the editor deriver
# (code_block_steps._METHOD_ACTION_TYPES) so extraction and the rest of the surface
# record as distinct, reader-facing steps.
+# `extract` is absent on purpose: code blocks run on a raw Playwright page and must not reach
+# the LLM extraction path, so nothing may author or record a page.extract call.
_HIGH_LEVEL_ACTION_MAP: dict[str, ActionType] = {
- "extract": ActionType.EXTRACT,
"complete": ActionType.COMPLETE,
"terminate": ActionType.TERMINATE,
"wait": ActionType.WAIT,
@@ -78,10 +76,9 @@ _HIGH_LEVEL_ACTION_MAP: dict[str, ActionType] = {
}
# High-level methods whose natural-language `prompt` (positional or keyword) is the
# reader-facing description; mirrors code_block_steps._PROMPT_POSITIONAL_METHODS.
-_PROMPT_METHODS: frozenset[str] = frozenset({"extract", "complete", "solve_captcha", "verification_code"})
+_PROMPT_METHODS: frozenset[str] = frozenset({"complete", "solve_captcha", "verification_code"})
OnAction = Callable[[Action], Awaitable[None]]
-ExtractPageFactory = Callable[[], Awaitable["SkyvernPage"]]
def _frame_user_line() -> int | None:
@@ -373,15 +370,9 @@ class RecordingPage:
treat recordings as telemetry, not a tamper-proof audit trail.
"""
- def __init__(
- self,
- page: Any,
- on_action: OnAction | None = None,
- extract_page_factory: ExtractPageFactory | None = None,
- ) -> None:
+ def __init__(self, page: Any, on_action: OnAction | None = None) -> None:
self.__page = page
self.__recorder = _Recorder(on_action)
- self.__extract_page_factory = extract_page_factory
def recorded_actions(self) -> list[Action]:
return list(self.__recorder.actions)
@@ -396,44 +387,6 @@ class RecordingPage:
def keyboard(self) -> RecordingKeyboard:
return RecordingKeyboard(self.__page.keyboard, self.__recorder)
- async def extract(
- self,
- prompt: str,
- schema: dict[str, Any] | list | str | None = None,
- error_code_mapping: dict[str, str] | None = None,
- intention: str | None = None,
- **kwargs: Any,
- ) -> dict[str, Any] | list | str | None:
- # Recorder-only narrowing of SkyvernPage.extract: authored code may not supply its own
- # system_prompt or data (the block owns prompt resolution) nor skip_refresh (set below).
- call_kwargs = {
- key: value for key, value in kwargs.items() if key not in {"data", "system_prompt", "skip_refresh"}
- }
- if schema is not None:
- call_kwargs["schema"] = schema
- if error_code_mapping is not None:
- call_kwargs["error_code_mapping"] = error_code_mapping
- if intention is not None:
- call_kwargs["intention"] = intention
- description = " ".join(prompt.split())[:200] if prompt.strip() else None
-
- async def call() -> dict[str, Any] | list | str | None:
- if self.__extract_page_factory is None:
- return await self.__page.extract(prompt, **call_kwargs)
- extract_page = await self.__extract_page_factory()
- # The factory just scraped the page; letting extract refresh again would double-scrape.
- return await extract_page.extract(prompt, skip_refresh=True, **call_kwargs)
-
- return await self.__recorder.record(
- ActionType.EXTRACT,
- "page.extract",
- None,
- call,
- (prompt,),
- call_kwargs,
- description=description,
- )
-
def __getattr__(self, name: str) -> Any:
attr = getattr(self.__page, name)
if name in _LOCATOR_FACTORY_METHODS and callable(attr):
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.py
index 3e9200d69..0c7e783f4 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recording.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py
@@ -3,13 +3,11 @@
from __future__ import annotations
import asyncio
-import importlib
from typing import TYPE_CHECKING
import structlog
from skyvern.config import settings
-from skyvern.core.script_generations.skyvern_page import SkyvernPage
from skyvern.forge import app
from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.models import StepStatus
@@ -26,19 +24,10 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
from skyvern.forge.sdk.workflow.models.block import CodeBlock
- from skyvern.webeye.browser_state import BrowserState
LOG = structlog.get_logger()
-def _real_skyvern_page_ai_class() -> type:
- # real_skyvern_page_ai and script_skyvern_page import each other; importing the latter
- # first is the only order that resolves.
- importlib.import_module("skyvern.core.script_generations.script_skyvern_page")
- module = importlib.import_module("skyvern.core.script_generations.real_skyvern_page_ai")
- return module.RealSkyvernPageAi
-
-
class CodeBlockActionRecording:
"""Records the page operations of one CodeBlock execution and persists them against a container task."""
@@ -51,11 +40,9 @@ class CodeBlockActionRecording:
workflow_run_block_id: str,
organization_id: str | None,
workflow_run_context: WorkflowRunContext,
- browser_state: BrowserState | None = None,
) -> None:
self._code_block = code_block
self._page = page
- self._browser_state = browser_state
self._workflow_run_id = workflow_run_id
self._workflow_run_block_id = workflow_run_block_id
self._organization_id = organization_id
@@ -66,11 +53,7 @@ class CodeBlockActionRecording:
self._screenshot_tasks: list[asyncio.Task[None]] = []
self._recording_enabled = False
self._finalized = False
- self.recording_page = RecordingPage(
- page,
- on_action=self._screenshot_sink,
- extract_page_factory=self._create_extract_page if browser_state is not None else None,
- )
+ self.recording_page = RecordingPage(page, on_action=self._screenshot_sink)
@property
def task(self) -> Task | None:
@@ -82,28 +65,6 @@ class CodeBlockActionRecording:
def last_recorded_exception(self) -> BaseException | None:
return self.recording_page.last_recorded_exception()
- async def _create_extract_page(self) -> SkyvernPage:
- if self._browser_state is None:
- raise AttributeError("page.extract is not available")
- # Read the label here rather than off RecordingPage: it scopes the system prompt and
- # templates to this block, and authored code can assign any attribute on objects it holds.
- current_label = self._code_block.label
- self._code_block._apply_workflow_system_prompt(self._workflow_run_context)
- scraped_page = await self._browser_state.scrape_website(
- url="",
- cleanup_element_tree=app.AGENT_FUNCTION.cleanup_element_tree_factory(),
- scrape_exclude=app.scrape_exclude,
- max_screenshot_number=settings.MAX_NUM_SCREENSHOTS,
- draw_boxes=False,
- scroll=True,
- support_empty_page=True,
- )
- ai = _real_skyvern_page_ai_class()(scraped_page, self._page)
- ai.current_label = current_label
- page = SkyvernPage(page=self._page, ai=ai)
- page.current_label = current_label
- return page
-
async def create_task_and_step(self) -> None:
"""Create the task/step that can anchor recorded actions for prompt-bearing blocks."""
if not self._code_block.prompt:
diff --git a/tests/unit/test_code_block_steps.py b/tests/unit/test_code_block_steps.py
index 758ad2f3f..169776d7a 100644
--- a/tests/unit/test_code_block_steps.py
+++ b/tests/unit/test_code_block_steps.py
@@ -292,41 +292,6 @@ def test_get_by_role_without_name_falls_back_to_the_element():
assert steps[0]["description"] == "Click the element"
-def test_extract_call_surfaces_as_a_distinct_step_with_prompt_copy():
- # page.extract() is the code-first extraction surface and must surface as its own step.
- code = (
- "async def run(page):\n"
- " await page.goto('https://example.com/')\n"
- " data = await page.extract(prompt='Extract the URLs of the top 20 posts', schema={'type': 'object'})\n"
- )
- steps = derive_code_block_steps(code)
- assert [s["action_type"] for s in steps] == ["goto_url", "extract"]
- assert steps[1]["description"] == "Extract the URLs of the top 20 posts"
-
-
-def test_multiline_prompt_literal_renders_without_backslash_escapes():
- # A YAML block-scalar / multiline prompt must collapse to readable copy, not leak
- # the source-level "\n" escape that ast.unparse would re-introduce.
- code = "async def run(page):\n await page.extract(prompt='Extract the URLs\\nof the top 20 posts')\n"
- steps = derive_code_block_steps(code)
- assert steps[0]["action_type"] == "extract"
- assert steps[0]["description"] == "Extract the URLs of the top 20 posts"
-
-
-def test_extract_without_prompt_literal_falls_back_to_a_generic_extract_label():
- code = "async def run(page):\n data = await page.extract(prompt=goal)\n"
- steps = derive_code_block_steps(code)
- assert steps[0]["action_type"] == "extract"
- assert steps[0]["description"] == "Extract information from the page"
-
-
-def test_whitespace_only_prompt_falls_back_instead_of_rendering_blank_copy():
- code = "async def run(page):\n data = await page.extract(prompt=' \\n ')\n"
- steps = derive_code_block_steps(code)
- assert steps[0]["action_type"] == "extract"
- assert steps[0]["description"] == "Extract information from the page"
-
-
def test_check_and_uncheck_map_to_checkbox_matching_the_recorder():
code = (
"async def run(page):\n"
@@ -339,30 +304,32 @@ def test_check_and_uncheck_map_to_checkbox_matching_the_recorder():
def test_extraction_then_looped_navigation_are_distinguishable():
- # The canonical failing case: open a site, extract a list of links, then for
- # each link open it and extract its contents. Every step must read as the
- # action it performs, and the two navigations must not be the same generic copy.
+ # The canonical failing case: open a site, read a list of links, then for each
+ # link open it and read its contents. The two navigations must not share copy.
code = (
"async def run(page, limit):\n"
" await page.goto('https://example.com/')\n"
- " posts = await page.extract(prompt='Extract the URLs of the top posts')\n"
- " for post in posts['posts'][:limit]:\n"
- " await page.goto(post['url'])\n"
- " await page.extract(prompt='Extract the top comment on the post')\n"
+ " posts = await page.locator('.post a').all_text_contents()\n"
+ " for post in posts[:limit]:\n"
+ " await page.goto(post)\n"
+ " await page.locator('.comment').inner_text()\n"
)
steps = derive_code_block_steps(code)
assert [s["action_type"] for s in steps] == ["goto_url", "extract", "goto_url", "extract"]
descriptions = [s["description"] for s in steps]
- assert descriptions == [
- "Open https://example.com/",
- "Extract the URLs of the top posts",
- "Open each post",
- "Extract the top comment on the post",
- ]
+ assert descriptions[0] == "Open https://example.com/"
+ assert descriptions[2] == "Open each post"
# The follow-up navigation must be distinguishable from the first, not a repeated label.
assert descriptions[0] != descriptions[2]
+def test_page_extract_is_not_a_code_block_step():
+ # Code blocks run raw Playwright; page.extract is not part of the surface and
+ # must not render a step in the editor preview.
+ code = "async def run(page):\n data = await page.extract(prompt='Extract the product names')\n"
+ assert derive_code_block_steps(code) == []
+
+
def test_goto_with_non_literal_url_outside_a_loop_describes_a_linked_page():
code = "async def run(page, target_url):\n await page.goto(target_url)\n"
steps = derive_code_block_steps(code)
@@ -439,20 +406,6 @@ def test_dom_reads_separated_by_an_action_are_distinct_steps():
assert [s["action_type"] for s in steps] == ["extract", "click", "extract"]
-def test_explicit_extract_prompt_is_preserved_alongside_raw_reads():
- # page.extract() carries the author's reader-facing prompt; consolidating raw
- # reads must never merge into it and clobber that copy.
- code = (
- "async def run(page):\n"
- " data = await page.extract(prompt='Extract the product names')\n"
- " extra = await page.locator('#x').text_content()\n"
- )
- steps = derive_code_block_steps(code)
- assert [s["action_type"] for s in steps] == ["extract", "extract"]
- assert steps[0]["description"] == "Extract the product names"
- assert steps[1]["description"] == "Extract information from the page"
-
-
def test_control_flow_reads_do_not_fabricate_an_extraction_step():
# Visibility checks and counts gate control flow; they are not data extraction
# and must not invent an extract step.
diff --git a/tests/unit/test_copilot_output_contract_actuation.py b/tests/unit/test_copilot_output_contract_actuation.py
index d40cc5890..b71163e2f 100644
--- a/tests/unit/test_copilot_output_contract_actuation.py
+++ b/tests/unit/test_copilot_output_contract_actuation.py
@@ -514,7 +514,6 @@ def _advisory_ctx() -> SimpleNamespace:
output_contract_actuation_count_by_signature={},
output_contract_declick_attempted_by_signature={},
output_contract_dispatch_reopened_by_signature={},
- output_contract_page_source_required_by_signature={},
output_contract_page_extraction_imposed_by_signature={},
output_contract_pending_run_evidence={},
output_contract_run_output_observed_by_signature={},
@@ -1168,12 +1167,12 @@ def test_observed_but_unbound_run_without_page_extraction_is_not_exhaustion() ->
assert actuation.kind != OutputContractActuationKind.BLOCKED_TERMINAL
-def test_reopen_requires_observed_unbound_run_and_arms_page_source() -> None:
+def test_reopen_requires_observed_unbound_run_and_reenters_the_ladder() -> None:
signature = "sig_reopen"
ctx = _advisory_ctx()
_mark_consumed_empty_run(ctx, signature, page_extraction=False)
assert wu._reopen_dispatch_lacked_bound_extraction(ctx, signature) is True
- assert ctx.output_contract_page_source_required_by_signature[signature] is True
+ assert ctx.output_contract_dispatch_reopened_by_signature[signature] is True
assert ctx.output_contract_actuation_by_signature[signature] == OutputContractAdvisoryState.UNUSED
@@ -1338,26 +1337,11 @@ def test_run_output_evidence_deep_leaf_binds() -> None:
assert ctx.output_contract_run_bound_required_path_by_signature[signature] is True
-def test_page_source_extraction_code_reads_page_and_is_not_click_only() -> None:
- required = {"output.confirmation_number", "output.account_number", "output.start_date"}
- keyed = wu._page_source_extraction_code(_CLICK_ONLY_CODE, required)
- assert "await page.extract(" in keyed
- assert "confirmation_number" in keyed
- assert "account_number" in keyed
- assert "start_date" in keyed
- assert keyed.strip().endswith(f"return {wu._OUTPUT_CONTRACT_PAGE_EXTRACT_VAR}")
- assert wu._output_contract_click_only_spine(keyed) is False
-
-
-def test_impose_page_source_extraction_rewrites_owner_block_code() -> None:
- parsed = {
- "workflow_definition": {"blocks": [{"block_type": "code", "label": "collect", "code": "page.click('#toggle')"}]}
- }
- imposed = wu._impose_page_source_extraction(
- parsed, "collect", "page.click('#toggle')", {"output.confirmation_number"}
- )
- assert imposed is not None
- assert "await page.extract(" in imposed
+def test_output_contract_never_imposes_a_page_extract_call() -> None:
+ """Code blocks run on a raw Playwright page, so no output-contract rung may author
+ page.extract -- it would resolve to the LLM extraction path and fail at runtime."""
+ assert not hasattr(wu, "_impose_page_source_extraction")
+ assert not hasattr(wu, "_page_source_extraction_code")
def test_advisory_grant_downgraded_to_directive_when_run_authority_forbids_dispatch() -> None:
diff --git a/tests/unit/test_copilot_positive_evidence_carriers.py b/tests/unit/test_copilot_positive_evidence_carriers.py
index 0883812fc..2458337c9 100644
--- a/tests/unit/test_copilot_positive_evidence_carriers.py
+++ b/tests/unit/test_copilot_positive_evidence_carriers.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import os
+from datetime import datetime, timezone
from types import SimpleNamespace
import pytest
@@ -14,6 +15,7 @@ from skyvern.forge.sdk.copilot.completion_output_grounding import (
from skyvern.forge.sdk.copilot.completion_verification import (
CompletionVerificationResult,
CriterionVerdict,
+ EvidenceSourceKind,
RunEvidenceSnapshot,
grade_fallback_floor_reached_end_state_criteria,
)
@@ -540,3 +542,246 @@ async def test_artifact_producer_falls_back_to_run_scan_without_ids(monkeypatch:
await run_execution_module._capture_registered_artifact_evidence(ctx, run_id="wr_1", organization_id="o_1")
assert ctx.registered_artifact_evidence is not None
assert ctx.registered_artifact_evidence.entries[0].parsed_text == "INV-4820-XZ paid"
+
+
+_HTML_WITH_VALUE = (
+ "<html><head><title>Done</title></head><body><main><h1>Request complete</h1>"
+ "<p>Your confirmation number is WTR-1842-DEMO. Thank you.</p></main></body></html>"
+)
+_HTML_NO_VALUE = (
+ "<html><body><main><h1>Submit your request</h1><p>Fill the form below to begin.</p></main></body></html>"
+)
+_HTML_SCRAPE_PREACTION = "<html><body><main><p>SCRAPEONLYTOKEN loading form</p></main></body></html>"
+
+
+def _html_artifact(
+ artifact_id: str,
+ artifact_type: ArtifactType,
+ file_size: int | None = 400,
+ created_at: datetime | None = None,
+) -> SimpleNamespace:
+ artifact = _artifact(artifact_id, f"{artifact_id}.html", file_size, artifact_type=artifact_type)
+ artifact.created_at = created_at or datetime(2026, 7, 9, tzinfo=timezone.utc)
+ return artifact
+
+
+def _producer_ctx(pre_run_prose: str | None = "Submit your request below.") -> SimpleNamespace:
+ baseline = {"visible_text_excerpt": pre_run_prose} if pre_run_prose is not None else None
+ return SimpleNamespace(
+ composition_page_evidence=baseline,
+ pre_run_page_reference=None,
+ workflow_verification_evidence=SimpleNamespace(),
+ )
+
+
+def _snapshot_from_ctx(ctx: SimpleNamespace, run_id: str) -> RunEvidenceSnapshot:
+ block_outputs: dict[str, object] = {}
+ block_output_sources: dict[str, EvidenceSourceKind] = {}
+ completion_module._bind_independent_post_run_page_evidence(ctx, run_id, block_outputs, block_output_sources)
+ return RunEvidenceSnapshot(
+ block_outputs=block_outputs,
+ block_output_sources=block_output_sources,
+ pre_run_page_reference_text=completion_module._pre_run_page_reference_text(ctx.pre_run_page_reference, run_id),
+ )
+
+
+def test_pre_run_baseline_provenance_valid_for_scout_evidence() -> None:
+ assert run_execution_module._pre_run_baseline_is_provenance_valid({"visible_text_excerpt": "a form"}) is True
+
+
+def test_pre_run_baseline_provenance_rejects_post_run_stamp() -> None:
+ stale = {"visible_text_excerpt": "a page", "observed_after_workflow_run": True}
+ assert run_execution_module._pre_run_baseline_is_provenance_valid(stale) is False
+
+
+def test_pre_run_baseline_provenance_rejects_foreign_run_id() -> None:
+ stale = {"visible_text_excerpt": "a page", "workflow_run_id": "wr_prior"}
+ assert run_execution_module._pre_run_baseline_is_provenance_valid(stale) is False
+
+
+def test_pre_run_baseline_provenance_rejects_non_mapping() -> None:
+ assert run_execution_module._pre_run_baseline_is_provenance_valid(None) is False
+
+
+async def test_dispatched_fetch_returns_none_without_artifacts(monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_app(monkeypatch, artifacts=[], retrieved={})
+ result = await run_execution_module._fetch_dispatched_terminal_page_evidence(
+ run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert result is None
+
+
+async def test_dispatched_fetch_skips_oversize_before_retrieval(monkeypatch: pytest.MonkeyPatch) -> None:
+ oversize = run_execution_module._MAX_REGISTERED_ARTIFACT_BYTES + 1
+ artifacts = [_html_artifact("art_big", ArtifactType.HTML_ACTION, file_size=oversize)]
+ retrieved_ids = _stub_app(monkeypatch, artifacts, {"art_big": _HTML_WITH_VALUE.encode()})
+ result = await run_execution_module._fetch_dispatched_terminal_page_evidence(
+ run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert result is None
+ assert retrieved_ids == []
+
+
+async def test_dispatched_fetch_rejects_bundled_zip_bytes(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_zip", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_zip": b"PK\x03\x04 whole zip archive bytes"})
+ result = await run_execution_module._fetch_dispatched_terminal_page_evidence(
+ run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert result is None
+
+
+async def test_dispatched_fetch_rejects_empty_bytes(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_empty", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_empty": b""})
+ result = await run_execution_module._fetch_dispatched_terminal_page_evidence(
+ run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert result is None
+
+
+async def test_dispatched_fetch_parses_terminal_html(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_action", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_action": _HTML_WITH_VALUE.encode()})
+ result = await run_execution_module._fetch_dispatched_terminal_page_evidence(
+ run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert result is not None
+ assert "WTR-1842-DEMO" in page_evidence_prose_text(result)
+
+
+async def test_dispatched_producer_confirms_value_only_post_run(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_action", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_action": _HTML_WITH_VALUE.encode()})
+ ctx = _producer_ctx()
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert ctx.composition_page_evidence["observed_after_workflow_run"] is True
+ assert ctx.composition_page_evidence["workflow_run_id"] == "wr_disp"
+ assert ctx.pre_run_page_reference is not None
+ assert ctx.pre_run_page_reference.workflow_run_id == "wr_disp"
+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), _snapshot_from_ctx(ctx, "wr_disp"))
+ assert verdict.state == "satisfied"
+ assert verdict.reason_code == "evidence_confirms"
+ assert verdict.evidence_source == "independent_page_evidence"
+
+
+def test_select_terminal_prefers_html_action_over_later_scrape() -> None:
+ early = datetime(2026, 7, 9, 10, 0, tzinfo=timezone.utc)
+ late = datetime(2026, 7, 9, 11, 0, tzinfo=timezone.utc)
+ artifacts = [
+ _html_artifact("art_action", ArtifactType.HTML_ACTION, created_at=early),
+ _html_artifact("art_scrape", ArtifactType.HTML_SCRAPE, created_at=late),
+ ]
+ selected = run_execution_module._select_terminal_page_artifact(artifacts)
+ assert selected is not None
+ assert selected.artifact_id == "art_action"
+
+
+def test_select_terminal_tiebreak_by_artifact_id_on_equal_created_at() -> None:
+ tie = datetime(2026, 7, 9, 10, 0, tzinfo=timezone.utc)
+ artifacts = [
+ _html_artifact("art_action_z", ArtifactType.HTML_ACTION, created_at=tie),
+ _html_artifact("art_action_a", ArtifactType.HTML_ACTION, created_at=tie),
+ ]
+ selected = run_execution_module._select_terminal_page_artifact(artifacts)
+ assert selected is not None
+ assert selected.artifact_id == "art_action_z"
+
+
+async def test_dispatched_producer_selects_terminal_html_action(monkeypatch: pytest.MonkeyPatch) -> None:
+ tie = datetime(2026, 7, 9, 10, 0, tzinfo=timezone.utc)
+ later = datetime(2026, 7, 9, 11, 0, tzinfo=timezone.utc)
+ artifacts = [
+ _html_artifact("art_action_a", ArtifactType.HTML_ACTION, created_at=tie),
+ _html_artifact("art_action_z", ArtifactType.HTML_ACTION, created_at=tie),
+ _html_artifact("art_scrape", ArtifactType.HTML_SCRAPE, created_at=later),
+ ]
+ _stub_app(
+ monkeypatch,
+ artifacts,
+ {
+ "art_action_a": _HTML_NO_VALUE.encode(),
+ "art_action_z": _HTML_WITH_VALUE.encode(),
+ "art_scrape": _HTML_SCRAPE_PREACTION.encode(),
+ },
+ )
+ ctx = _producer_ctx()
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ prose = page_evidence_prose_text(ctx.composition_page_evidence)
+ assert "WTR-1842-DEMO" in prose
+ assert "SCRAPEONLYTOKEN" not in prose
+
+
+async def test_dispatched_producer_confirms_from_html_scrape_when_only_family(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_scrape", ArtifactType.HTML_SCRAPE)]
+ _stub_app(monkeypatch, artifacts, {"art_scrape": _HTML_WITH_VALUE.encode()})
+ ctx = _producer_ctx()
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), _snapshot_from_ctx(ctx, "wr_disp"))
+ assert verdict.evidence_source == "independent_page_evidence"
+
+
+async def test_dispatched_producer_negative_control_value_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_action", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_action": _HTML_NO_VALUE.encode()})
+ ctx = _producer_ctx()
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), _snapshot_from_ctx(ctx, "wr_disp"))
+ assert verdict.reason_code != "evidence_confirms"
+
+
+async def test_dispatched_producer_value_in_baseline_does_not_confirm(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_action", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_action": _HTML_WITH_VALUE.encode()})
+ ctx = _producer_ctx(pre_run_prose="Prior page already showed WTR-1842-DEMO earlier.")
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), _snapshot_from_ctx(ctx, "wr_disp"))
+ assert verdict.reason_code != "evidence_confirms"
+
+
+async def test_dispatched_producer_stale_baseline_not_pinned_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ artifacts = [_html_artifact("art_action", ArtifactType.HTML_ACTION)]
+ _stub_app(monkeypatch, artifacts, {"art_action": _HTML_WITH_VALUE.encode()})
+ ctx = _producer_ctx(pre_run_prose=None)
+ ctx.composition_page_evidence = {
+ "visible_text_excerpt": "stale page from a prior turn",
+ "observed_after_workflow_run": True,
+ "workflow_run_id": "wr_prior",
+ }
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert ctx.pre_run_page_reference is None
+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), _snapshot_from_ctx(ctx, "wr_disp"))
+ assert verdict.reason_code != "evidence_confirms"
+
+
+async def test_dispatched_producer_abstains_without_terminal_artifact(monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_app(monkeypatch, artifacts=[], retrieved={})
+ ctx = _producer_ctx(pre_run_prose=None)
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx, run_id="wr_disp", organization_id="o_1", current_url=""
+ )
+ assert ctx.composition_page_evidence is None
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index 0a66ad39a..4e64b32d1 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -6,12 +6,10 @@ import asyncio
import json
from datetime import datetime, timezone
from types import SimpleNamespace
-from typing import Protocol
from unittest.mock import AsyncMock
import pytest
-from skyvern.core.script_generations import script_skyvern_page
from skyvern.core.script_generations.skyvern_page import SkyvernPage
from skyvern.forge import app
from skyvern.forge.agent import ForgeAgent
@@ -31,7 +29,6 @@ from skyvern.forge.sdk.workflow.models.code_block_recorder import (
RecordingPage,
user_code_line_from_exception,
)
-from skyvern.forge.sdk.workflow.models.code_block_recording import CodeBlockActionRecording
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
from skyvern.schemas.workflows import BlockStatus
from skyvern.webeye.actions.action_types import ActionType
@@ -39,10 +36,6 @@ from skyvern.webeye.actions.actions import Action, ActionStatus, ClickAction, Go
from skyvern.webeye.browser_artifacts import BrowserArtifacts
-class AiExtractSelf(Protocol):
- current_label: str | None
-
-
class FakeLocator:
def __init__(self) -> None:
self.calls: list[str] = []
@@ -86,8 +79,6 @@ class FakePage:
self.inner = FakeLocator()
self.keyboard = FakeKeyboard()
self.url = "about:blank"
- # playwright's AsyncBase.__init__ reads _loop off the wrapped impl object
- self._loop = asyncio.get_event_loop()
async def goto(self, url, **kwargs): # noqa: ANN001, ANN003, ANN201
return None
@@ -113,9 +104,6 @@ class FakePage:
async def evaluate(self, expression, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN201
return None
- async def extract(self, prompt, **kwargs): # noqa: ANN001, ANN003, ANN201
- return {"data": "extracted"}
-
async def complete(self, prompt=None, **kwargs): # noqa: ANN001, ANN003, ANN201
return None
@@ -123,15 +111,6 @@ class FakePage:
return None
-class FakePageWithoutExtract(FakePage):
- extract = None
-
-
-class FakeBrowserState:
- def __init__(self) -> None:
- self.scrape_website = AsyncMock(return_value=SimpleNamespace(url="https://example.com", extracted_text=""))
-
-
@pytest.mark.asyncio
async def test_records_goto_click_fill_with_types_and_order() -> None:
page = RecordingPage(FakePage())
@@ -167,200 +146,20 @@ async def test_page_evaluate_records_execute_js_action() -> None:
@pytest.mark.asyncio
-async def test_extract_high_level_call_records_extract_action_with_prompt() -> None:
- """page.extract() must surface on the run timeline as an EXTRACT action carrying its
- prompt, so a navigate+extract code block doesn't render as only repeated 'Goto URL'."""
+async def test_extract_does_not_resolve_on_a_raw_playwright_page() -> None:
+ """Code blocks run on a raw Playwright page and must never reach the LLM extraction path,
+ so page.extract neither resolves nor records a step."""
page = RecordingPage(FakePage())
- await page.goto("https://news.ycombinator.com/")
- await page.extract(prompt="Extract the URLs of the top 20 posts")
- recorded = page.recorded_actions()
- assert [a.action_type for a in recorded] == [ActionType.GOTO_URL, ActionType.EXTRACT]
- # The reader-facing prompt is the description verbatim (no "page.extract" prefix), so a
- # timeline row reads as plain language with or without a matching editor step.
- assert recorded[1].description == "Extract the URLs of the top 20 posts"
+ await page.goto("https://example.com/")
+ with pytest.raises(AttributeError):
+ await page.extract(prompt="Extract the URLs of the top 20 posts")
+ assert [a.action_type for a in page.recorded_actions()] == [ActionType.GOTO_URL]
-async def test_extract_positional_prompt_is_recorded_in_description() -> None:
- """The prompt is positional-or-keyword on extract; a positional prompt is still surfaced."""
- page = RecordingPage(FakePage())
- await page.extract("Extract the top visible comment")
- recorded = page.recorded_actions()
- assert recorded[0].action_type == ActionType.EXTRACT
- assert recorded[0].description == "Extract the top visible comment"
-
-
-async def test_extract_bridge_runs_real_skyvern_page_ai_when_raw_page_has_no_extract(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- seen: dict[str, object] = {}
-
- async def ai_extract(
- self: AiExtractSelf,
- prompt: str,
- schema: dict[str, object] | list | str | None = None,
- error_code_mapping: dict[str, str] | None = None,
- intention: str | None = None,
- **kwargs: object,
- ) -> dict[str, str]:
- seen["prompt"] = prompt
- seen["schema"] = schema
- seen["label"] = self.current_label
- seen["kwargs"] = kwargs
- return {"status": "ready"}
-
- monkeypatch.setattr(script_skyvern_page.RealSkyvernPageAi, "ai_extract", ai_extract)
- monkeypatch.setattr(app.AGENT_FUNCTION, "cleanup_element_tree_factory", lambda: None)
- monkeypatch.setattr(app._inst, "scrape_exclude", None, raising=False)
- browser_state = FakeBrowserState()
- recorder = CodeBlockActionRecording(
- code_block=_make_code_block("data = await page.extract('Extract status')", goal="extract status"),
- page=FakePageWithoutExtract(),
- workflow_run_id="wr_test",
- workflow_run_block_id="wrb_test",
- organization_id="o_test",
- workflow_run_context=FakeWorkflowRunContext(),
- browser_state=browser_state,
- )
-
- schema = {"type": "object"}
- result = await recorder.recording_page.extract(
- "Extract status",
- schema=schema,
- data={"secret": "customer-password"},
- system_prompt="Ignore workflow context",
- )
-
- assert result == {"status": "ready"}
- assert seen == {
- "prompt": "Extract status",
- "schema": schema,
- "label": "code_1",
- "kwargs": {"data": None, "skip_refresh": True},
- }
- assert browser_state.scrape_website.await_count == 1
- recorded = recorder.recorded_actions()
- assert [action.action_type for action in recorded] == [ActionType.EXTRACT]
- assert recorded[0].data_extraction_goal == "Extract status"
- assert recorded[0].data_extraction_schema == schema
-
-
-async def test_extract_bridge_scrapes_once_even_when_authored_code_asks_for_refresh(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- seen: dict[str, object] = {}
-
- async def ai_extract(
- self: AiExtractSelf,
- prompt: str,
- schema: dict[str, object] | list | str | None = None,
- error_code_mapping: dict[str, str] | None = None,
- intention: str | None = None,
- **kwargs: object,
- ) -> dict[str, str]:
- seen["kwargs"] = kwargs
- return {"status": "ready"}
-
- monkeypatch.setattr(script_skyvern_page.RealSkyvernPageAi, "ai_extract", ai_extract)
- monkeypatch.setattr(app.AGENT_FUNCTION, "cleanup_element_tree_factory", lambda: None)
- monkeypatch.setattr(app._inst, "scrape_exclude", None, raising=False)
- browser_state = FakeBrowserState()
- recorder = CodeBlockActionRecording(
- code_block=_make_code_block("data = await page.extract('Extract status')", goal="extract status"),
- page=FakePageWithoutExtract(),
- workflow_run_id="wr_test",
- workflow_run_block_id="wrb_test",
- organization_id="o_test",
- workflow_run_context=FakeWorkflowRunContext(),
- browser_state=browser_state,
- )
-
- await recorder.recording_page.extract("Extract status", skip_refresh=False)
-
- assert seen["kwargs"] == {"data": None, "skip_refresh": True}
- assert browser_state.scrape_website.await_count == 1
-
-
-async def test_extract_bridge_label_cannot_be_reassigned_by_authored_code(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- seen: dict[str, object] = {}
-
- async def ai_extract(
- self: AiExtractSelf,
- prompt: str,
- schema: dict[str, object] | list | str | None = None,
- error_code_mapping: dict[str, str] | None = None,
- intention: str | None = None,
- **kwargs: object,
- ) -> dict[str, str]:
- seen["label"] = self.current_label
- return {"status": "ready"}
-
- monkeypatch.setattr(script_skyvern_page.RealSkyvernPageAi, "ai_extract", ai_extract)
- monkeypatch.setattr(app.AGENT_FUNCTION, "cleanup_element_tree_factory", lambda: None)
- monkeypatch.setattr(app._inst, "scrape_exclude", None, raising=False)
- recorder = CodeBlockActionRecording(
- code_block=_make_code_block("data = await page.extract('Extract status')", goal="extract status"),
- page=FakePageWithoutExtract(),
- workflow_run_id="wr_test",
- workflow_run_block_id="wrb_test",
- organization_id="o_test",
- workflow_run_context=FakeWorkflowRunContext(),
- browser_state=FakeBrowserState(),
- )
-
- recorder.recording_page.current_label = "victim_block"
- recorder.recording_page._RecordingPage__current_label = "victim_block" # type: ignore[attr-defined]
- await recorder.recording_page.extract("Extract status")
-
- assert seen["label"] == "code_1"
-
-
- ("ignore_workflow_system_prompt", "expected_prompt"),
- [
- (False, "Extract using only visible page facts."),
- (True, None),
- ],
-)
-async def test_extract_bridge_materializes_workflow_system_prompt_decision(
- monkeypatch: pytest.MonkeyPatch,
- ignore_workflow_system_prompt: bool,
- expected_prompt: str | None,
-) -> None:
- async def ai_extract(
- self: AiExtractSelf,
- prompt: str,
- **kwargs: object,
- ) -> dict[str, str]:
- return {"label": self.current_label or ""}
-
- monkeypatch.setattr(script_skyvern_page.RealSkyvernPageAi, "ai_extract", ai_extract)
- monkeypatch.setattr(app.AGENT_FUNCTION, "cleanup_element_tree_factory", lambda: None)
- monkeypatch.setattr(app._inst, "scrape_exclude", None, raising=False)
- context = FakeWorkflowRunContext()
- context.workflow_system_prompt = "Extract using only visible page facts."
- block = _make_code_block("data = await page.extract('Extract status')", goal="extract status")
- block.ignore_workflow_system_prompt = ignore_workflow_system_prompt
- recorder = CodeBlockActionRecording(
- code_block=block,
- page=FakePageWithoutExtract(),
- workflow_run_id="wr_test",
- workflow_run_block_id="wrb_test",
- organization_id="o_test",
- workflow_run_context=context,
- browser_state=FakeBrowserState(),
- )
-
- result = await recorder.recording_page.extract("Extract status")
-
- assert result == {"label": "code_1"}
- assert context.get_block_workflow_system_prompt("code_1") == (True, expected_prompt)
+def test_extract_is_absent_from_the_code_block_vocabulary() -> None:
+ """Nothing may author or preview a page.extract call in a code block."""
+ assert "extract" not in _HIGH_LEVEL_ACTION_MAP
+ assert "extract" not in _METHOD_ACTION_TYPES
@pytest.mark.asyncio
@@ -387,7 +186,10 @@ def test_recorder_maps_cover_every_action_wrapped_skyvern_page_method() -> None:
assert {"extract", "click", "complete", "scroll"} <= live.keys()
recorder = {**_PAGE_ACTION_MAP, **_LOCATOR_ACTION_MAP, **_HIGH_LEVEL_ACTION_MAP}
- excluded = {"null_action"} # NULL_ACTION is a no-op probe, never a timeline step
+ excluded = {
+ "null_action", # NULL_ACTION is a no-op probe, never a timeline step
+ "extract", # code blocks run raw Playwright; page.extract must not reach the LLM path
+ }
for name, action_type in live.items():
if name in excluded:
@@ -563,8 +365,6 @@ class FakeWorkflowRunContext:
def __init__(self, secrets: dict[str, str] | None = None) -> None:
self.secrets = secrets or {}
- self.block_workflow_system_prompts: dict[str, tuple[bool, str | None]] = {}
- self.workflow_system_prompt: str | None = None
def get_block_metadata(self, label): # noqa: ANN001, ANN201
return {}
@@ -572,17 +372,6 @@ class FakeWorkflowRunContext:
def build_workflow_run_summary(self) -> str:
return ""
- def resolve_effective_workflow_system_prompt(self) -> str | None:
- return self.workflow_system_prompt
-
- def record_block_workflow_system_prompt(self, label: str, value: str | None) -> None:
- self.block_workflow_system_prompts[label] = (True, value)
-
- def get_block_workflow_system_prompt(self, label: str | None) -> tuple[bool, str | None]:
- if label is None:
- return False, None
- return self.block_workflow_system_prompts.get(label, (False, None))
-
def get_value(self, key): # noqa: ANN001, ANN201
return self.values.get(key)