Skip to content

Automate browser based workflows with AI

Return the browser's own failure facts instead of constants when a code block fails (SKY-14625) (#8266)

Andrew Neilsonbfe921b79a25
diff --git a/skyvern/cli/mcp_tools/_element_state.py b/skyvern/cli/mcp_tools/_element_state.py
index a0f4d5187..065b9278c 100644
--- a/skyvern/cli/mcp_tools/_element_state.py
+++ b/skyvern/cli/mcp_tools/_element_state.py
@@ -4,6 +4,9 @@ import asyncio
import os
from typing import Any, Literal
+from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
+from skyvern.forge.sdk.forge_log import current_codeblock_log_redactor
+
from ._common import ErrorCode, make_error
DEFAULT_ACTION_TIMEOUT_MS = 30000
@@ -15,6 +18,7 @@ MAX_ACTION_TIMEOUT_MS = 60000
# state. It only runs after an action already failed, so a wider budget costs nothing on the happy
# path and buys an accurate reason on the path that needs one.
ELEMENT_STATE_PROBE_TIMEOUT_MS = 3000
+ELEMENT_STATE_ERROR_DETAIL_MAX_CHARS = 500
ACTION_TIMEOUT_DESCRIPTION = (
"Max time to wait for the element in ms. "
@@ -76,6 +80,14 @@ def resolve_action_timeout_ms(timeout: int | None, *, direct_action: bool) -> in
return _direct_action_timeout_default_ms() if direct_action else DEFAULT_ACTION_TIMEOUT_MS
+def _exception_text(exc: BaseException) -> str:
+ """A user-defined __str__ can raise or return a non-str; reading it must not raise here."""
+ try:
+ return str(exc)
+ except BaseException:
+ return ""
+
+
def is_pointer_interception_error(exc: Exception) -> bool:
message = str(exc).lower()
return "intercepts pointer events" in message or "intercepted by another element" in message
@@ -126,19 +138,33 @@ async def classify_element_state(page: Any, selector: str, *, pointer_intercepte
return "unknown"
+def _redacted_exception_detail(exc: Exception) -> str:
+ # Both redactors match on the text, so bounding first would leave a cut secret unmatched.
+ text = _exception_text(exc).strip()
+ redactor = current_codeblock_log_redactor()
+ if redactor is not None:
+ # forge_log.py guards the same call: a raising redactor must not turn a handled
+ # actionability failure into an unhandled one, and it must not fall through unredacted.
+ try:
+ redacted = redactor(text)
+ except BaseException:
+ redacted = ""
+ text = redacted if isinstance(redacted, str) else ""
+ return redact_raw_secrets_for_prompt(text)[:ELEMENT_STATE_ERROR_DETAIL_MAX_CHARS]
+
+
def element_state_error(state: ElementState, exc: Exception, *, selector: str, timeout_ms: int) -> dict[str, Any]:
code, message, hint = _STATE_ERRORS[state]
- return make_error(
- code,
- message,
- hint,
- details={
- "element_state": state,
- "selector": selector,
- "actionability_timeout_ms": timeout_ms,
- "exception_type": type(exc).__name__,
- },
- )
+ details: dict[str, Any] = {
+ "element_state": state,
+ "selector": selector,
+ "actionability_timeout_ms": timeout_ms,
+ "exception_type": type(exc).__name__,
+ }
+ detail = _redacted_exception_detail(exc)
+ if detail:
+ details["exception_detail"] = detail
+ return make_error(code, message, hint, details=details)
async def make_direct_action_error(page: Any, selector: str, exc: Exception, *, timeout_ms: int) -> dict[str, Any]:
diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.py
index 176dfb9d8..709cb851a 100644
--- a/skyvern/forge/sdk/copilot/tools/_shared.py
+++ b/skyvern/forge/sdk/copilot/tools/_shared.py
@@ -35,6 +35,7 @@ from skyvern.forge.sdk.copilot.enforcement import (
_requested_output_labels_by_path,
)
from skyvern.forge.sdk.copilot.runtime import AgentContext, resolve_browser_state_for_context
+from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.task_output_envelope import (
_TASK_ENVELOPE_BLOCK_TYPES,
_TASK_OUTPUT_PAYLOAD_FIELDS,
@@ -62,6 +63,9 @@ _FAILED_BLOCK_STATUSES: frozenset[str] = frozenset(
_DATA_PRODUCING_BLOCK_TYPES = frozenset({"EXTRACTION", "TEXT_PROMPT"})
+_EVIDENCE_ERROR_DETAIL_MAX_CHARS = 300
+
+
# Block types whose output can demonstrate an end-state outcome. Until a workflow
# contains one of these, an unmet outcome criterion means the build is still
# incomplete (no confirmation step yet), not a completed run that failed the goal.
@@ -746,6 +750,16 @@ def _requested_capture_targets(copilot_ctx: object) -> tuple[str, ...]:
return tuple(targets)
+def _bounded_evidence_error_detail(value: object) -> str:
+ # A hostile __str__ raising here would escape the caller's except clause and turn a handled
+ # evidence-capture failure into an unhandled one.
+ try:
+ text = str(value).strip()
+ except BaseException:
+ return ""
+ return redact_raw_secrets_for_prompt(text)[:_EVIDENCE_ERROR_DETAIL_MAX_CHARS]
+
+
async def _composition_get_structured_evidence_result(
copilot_ctx: Any,
*,
@@ -772,19 +786,34 @@ async def _composition_get_structured_evidence_result(
f"skyvern_evaluate timed out after {timeout_seconds:g}s while capturing structured page evidence",
)
except Exception as exc:
+ # Read the message once, through the guard: an unguarded str(exc) here would raise on a
+ # hostile __str__ before the guarded read below could contain it.
+ detail = _bounded_evidence_error_detail(exc)
LOG.warning(
"copilot_composition_structured_extract_failed",
error_type=type(exc).__name__,
- detail_present=bool(str(exc).strip()),
+ detail_present=bool(detail),
+ )
+ if detail:
+ return None, f"skyvern_evaluate raised while capturing structured page evidence: {detail}"
+ return None, (
+ "skyvern_evaluate raised while capturing structured page evidence, "
+ f"and {type(exc).__name__} carried no message"
)
- return None, "skyvern_evaluate failed while capturing structured page evidence"
if not isinstance(result, dict) or not result.get("ok"):
LOG.warning(
"copilot_composition_structured_extract_rejected",
result_is_mapping=isinstance(result, dict),
error_present=bool(result.get("error")) if isinstance(result, dict) else False,
)
- return None, "structured page evidence failed: evaluate returned an error"
+ raw_error = result.get("error") if isinstance(result, dict) else None
+ detail = _bounded_evidence_error_detail(raw_error) if raw_error else ""
+ if detail:
+ return None, f"skyvern_evaluate returned an error while capturing structured page evidence: {detail}"
+ return None, (
+ "skyvern_evaluate returned an error while capturing structured page evidence, "
+ "and the result carried no error detail"
+ )
raw = (result.get("data") or {}).get("result")
if isinstance(raw, str):
if len(raw) > _COMPOSITION_STRUCTURED_EVIDENCE_MAX_CHARS:
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 29abc158d..d2d221f2d 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -106,6 +106,7 @@ from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
repair_page_evidence_is_admissible,
same_run_typed_challenge_kind,
)
+from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.turn_halt import (
stash_turn_halt_from_blocker_signal,
@@ -426,14 +427,18 @@ async def _attach_action_traces(
}
output = action.output
code_line = output.get("code_line") if isinstance(output, dict) else None
- if (
- action.action_type == ActionType.NULL_ACTION
- and action.status == ActionStatus.failed
- and type(code_line) is int
- and action.description
- ):
- entry["description"] = action.description[:150]
- entry["code_line"] = code_line
+ if action.status == ActionStatus.failed:
+ # code_line is the code-block recorder's stamp. Gating on it keeps this to the
+ # recorder's own rows: personalize_action writes the typed-in field value to
+ # response, which is user data and must not reach the packet.
+ if type(code_line) is int:
+ entry["code_line"] = code_line
+ if action.action_type == ActionType.NULL_ACTION and action.description:
+ entry["description"] = action.description[:150]
+ if action.response:
+ # Persistence masks registered secrets and parameters; a token the block
+ # obtained at runtime is in neither registry, so screen it here too.
+ entry["response"] = redact_raw_secrets_for_prompt(action.response)[:300]
action_trace.append(entry)
block_result["action_trace"] = action_trace
@@ -517,6 +522,8 @@ async def _attach_failed_block_screenshots(
block_result["screenshot_b64"] = b64
if block.final_url:
block_result["final_url"] = block.final_url
+ if b64 is None and not block.final_url:
+ block_result["at_failure_evidence"] = "No at-failure screenshot or final URL was persisted for this block."
if b64 is not None or block.final_url:
LOG.info(
"Attached at-failure evidence to failed block",
@@ -584,6 +591,35 @@ def _block_end_urls_by_label(run_block_rows: list[WorkflowRunBlock]) -> dict[str
return end_urls
+NO_PERSISTED_END_URL = "No worker-persisted final URL exists for this run; the page it ended on is unknown."
+
+# block.py masks the at-failure URL before persisting it, so a login/MFA failure can leave a
+# final_url that parses but is not the page: it cannot be resumed and must not be reported as one.
+_SECRET_MASK = "*****"
+DISPATCHED_END_URL_MAX_CHARS = 2000
+
+
+def _dispatched_end_url(run_block_rows: list[WorkflowRunBlock]) -> str | None:
+ """Page the run ended on, read from the terminal worker-persisted row because the session is worker-owned.
+
+ Only the terminal row counts: an earlier block's URL is a different page, and reporting it would
+ answer "where did the run end" with a page the run left.
+ """
+ if not run_block_rows:
+ return None
+ final_url = _valid_runtime_anchor_url(run_block_rows[-1].final_url)
+ if final_url is None or _SECRET_MASK in final_url:
+ return None
+ # The mask only covers the secret and parameter registries; a token the block picked up at
+ # runtime is in neither, and a URL is as good a carrier for one as an error message is.
+ screened = redact_raw_secrets_for_prompt(final_url)
+ # Refuse rather than truncate: a cut URL still parses, so it would be reported as the page the
+ # run ended on while being unresumable -- the same thing the mask check above returns None for.
+ if len(screened) > DISPATCHED_END_URL_MAX_CHARS:
+ return None
+ return screened
+
+
def _summarize_action_trace(action_trace: list[dict[str, Any]] | None) -> list[str]:
"""Render the six newest action entries chronologically for the compact packet."""
if not action_trace:
@@ -596,13 +632,16 @@ def _summarize_action_trace(action_trace: list[dict[str, Any]] | None) -> list[s
status = entry.get("status") or ""
element = entry.get("element")
description = entry.get("description")
+ response = entry.get("response")
code_line = entry.get("code_line")
bits = [str(action)]
if element:
bits.append(str(element))
if status:
bits.append(str(status))
- if isinstance(description, str) and description:
+ if isinstance(response, str) and response:
+ bits.append(f"response={response}")
+ elif isinstance(description, str) and description:
bits.append(f"description={description}")
if type(code_line) is int:
bits.append(f"code_line={code_line}")
@@ -2411,6 +2450,7 @@ async def _run_blocks_and_collect_debug(
"overall_status": run.status if run is not None else None,
"failure_reason": user_facing_summary,
"current_url": current_url,
+ "current_url_live_observed": bool(current_url) and not dispatch_to_worker,
"page_title": page_title,
# Omitting this reads downstream as "run session unknown", which grants a
# scout-sourced page post-run identity on exactly the fresh-session path.
@@ -2547,17 +2587,19 @@ async def _run_blocks_and_collect_debug(
entry.pop("action_trace", None)
# Dispatched runs: the worker owns the run session; do not touch it over CDP from the API.
- # The frontier's per-block anchors come from the run rows the worker persisted instead;
- # current_url stays unset here, so what the model and the judges are told is unchanged.
+ # The frontier's anchors and the page the run ended on both come from the rows the worker
+ # persisted instead. A dispatched run has no page title to report.
block_end_urls = _block_end_urls_by_label(run_block_rows)
+ dispatched_end_url = _dispatched_end_url(run_block_rows) if dispatch_to_worker else None
current_url, page_title = (
- ("", "") if dispatch_to_worker else await _fallback_page_info(ctx, session_id_override=run_session_id)
+ (dispatched_end_url or "", "")
+ if dispatch_to_worker
+ else await _fallback_page_info(ctx, session_id_override=run_session_id)
)
screenshot_b64: str | None = None
# Dispatched runs: the worker owns the persistent browser session, so the API side must not
- # grab the live page over CDP. A worker-persisted screenshot artifact can be surfaced from
- # the DB instead (follow-up); for now the dispatched failure packet omits the inline capture.
+ # grab the live page over CDP. Their at-failure frames come from worker-persisted artifacts.
if not dispatch_to_worker and not run_ok and run_session_id:
try:
browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(
@@ -2629,6 +2671,10 @@ async def _run_blocks_and_collect_debug(
"page_title": page_title,
"action_trace_summary": action_trace_summary,
}
+ if not dispatch_to_worker and current_url:
+ result_data["current_url_live_observed"] = True
+ if dispatch_to_worker and dispatched_end_url is None:
+ result_data["current_url_evidence"] = NO_PERSISTED_END_URL
post_run_page_evidence = _same_run_page_evidence_for_result(ctx, workflow_run.workflow_run_id)
if post_run_page_evidence is not None:
result_data["post_run_page_evidence"] = post_run_page_evidence
@@ -2784,10 +2830,16 @@ async def _get_run_results(params: dict[str, Any], ctx: AgentContext) -> dict[st
organization_id=ctx.organization_id,
workflow_permanent_id=ctx.workflow_permanent_id,
)
- current_url, page_title = ("", "") if dispatch_to_worker else await _fallback_page_info(ctx)
+ dispatched_end_url = _dispatched_end_url(list(reversed(blocks))) if dispatch_to_worker else None
+ current_url, page_title = (dispatched_end_url or "", "") if dispatch_to_worker else await _fallback_page_info(ctx)
if current_url:
result_data["current_url"] = current_url
- result_data["page_title"] = page_title
+ if not dispatch_to_worker:
+ result_data["current_url_live_observed"] = True
+ if page_title:
+ result_data["page_title"] = page_title
+ if dispatch_to_worker and dispatched_end_url is None:
+ result_data["current_url_evidence"] = NO_PERSISTED_END_URL
if getattr(run, "failure_reason", None):
result_data["failure_reason"] = run.failure_reason
@@ -3028,7 +3080,12 @@ def _update_verification_evidence_from_run_result(copilot_ctx: AgentContext, res
current_url = _valid_runtime_anchor_url(data.get("current_url"))
if current_url is not None:
evidence.current_url = current_url
- evidence.live_page_state_verified = True
+ # Only a live read of the page verifies its state. A writer that omits the marker — a
+ # dispatched run reading worker-persisted rows, or a new caller — must not claim otherwise,
+ # so the absent case is the unverified one. The flag is only ever set True and survives an
+ # earlier live read, so it has to move with the URL it describes: leaving it set beside a
+ # worker-persisted URL would report a verification of a page this one is not.
+ evidence.live_page_state_verified = data.get("current_url_live_observed") is True
if data.get("observed_after_workflow_run") is True:
evidence.current_url_observed_after_workflow_run = True
evidence.current_url_may_encode_runtime_state = bool(urlparse(current_url).query)
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
index e62797b50..dce2d3467 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
@@ -25,6 +25,8 @@ CODE_BLOCK_FILENAME = "<code_block>"
CODE_LINE_OFFSET = 2
MAX_RECORDED_ACTION_VALIDATION_ERROR_FIELDS = 20
PENDING_CALL_DELAY_SECONDS = 20.0
+RECORDED_FAILURE_RESPONSE_MAX_CHARS = 500
+RECORDED_FAILURE_CAPTURE_MAX_CHARS = 8000
_PAGE_ACTION_MAP: dict[str, ActionType] = {
"goto": ActionType.GOTO_URL,
@@ -415,7 +417,18 @@ class _Recorder:
result = await call()
except BaseException as exc:
action.status = ActionStatus.failed
- action.response = "Browser operation failed."
+ # Generous rather than tight: the persistence path masks secrets by exact match, so a
+ # tight bound here could split one into an unmatched fragment. It cannot be unbounded --
+ # redact_codeblock_parameter_values counts disclosure characters across the whole payload
+ # and returns a replacement string past its budget, which would drop the row entirely.
+ # A user-defined __str__ can raise or return a non-str. Unguarded, that replaces the
+ # browser's failure with its own and skips both last_exception and the re-raise below,
+ # so the run would lose the fault this line exists to report.
+ try:
+ captured = str(exc)[:RECORDED_FAILURE_CAPTURE_MAX_CHARS]
+ except BaseException:
+ captured = ""
+ action.response = captured or type(exc).__name__
self.last_exception = exc
raise
finally:
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.py
index a527d3d48..9e64b8425 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recording.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py
@@ -13,6 +13,7 @@ from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.models import StepStatus
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.code_block_recorder import (
+ RECORDED_FAILURE_RESPONSE_MAX_CHARS,
PendingAction,
RecordingPage,
recorded_action_from_payload,
@@ -237,6 +238,9 @@ class CodeBlockActionRecording:
# A matching bool/number becomes a string placeholder, which typed Action fields reject.
# Null it recursively so subclass defaults cannot silently restore user-controlled values.
masked = _null_redacted_scalars(payload, masked) if isinstance(masked, dict) else {}
+ response = masked.get("response")
+ if isinstance(response, str):
+ masked["response"] = response[:RECORDED_FAILURE_RESPONSE_MAX_CHARS]
# IDs, timestamps, and implicit model defaults come from a snapshot taken before user
# code can mutate the action. Explicit page/action fields remain masked.
masked.update(metadata)
diff --git a/skyvern/webeye/actions/caching.py b/skyvern/webeye/actions/caching.py
index 0bf5da705..255512163 100644
--- a/skyvern/webeye/actions/caching.py
+++ b/skyvern/webeye/actions/caching.py
@@ -124,6 +124,11 @@ async def _retrieve_action_plan(task: Task, step: Step, scraped_page: ScrapedPag
updated_action.action_order = idx
# Reset the action response to None so we don't use the previous answers
updated_action.response = None
+ # The code-block recorder's line stamp belongs to the run that produced it. Carrying it into
+ # a reused action would point the model at unrelated code, and readers treat the stamp as
+ # proof the row came from the recorder. model_copy is shallow, so rebuild rather than mutate.
+ if isinstance(updated_action.output, dict) and "code_line" in updated_action.output:
+ updated_action.output = {k: v for k, v in updated_action.output.items() if k != "code_line"}
# Update the element id with the element id from the current scraped page, matched by element hash
if cached_action.skyvern_element_hash:
diff --git a/tests/unit/test_code_block_recording.py b/tests/unit/test_code_block_recording.py
index 91235a14a..ca1f6d291 100644
--- a/tests/unit/test_code_block_recording.py
+++ b/tests/unit/test_code_block_recording.py
@@ -23,8 +23,13 @@ from playwright.sync_api import sync_playwright
from structlog.testing import capture_logs
from skyvern.config import settings
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
from skyvern.forge.sdk.workflow.models.block import CodeBlock
-from skyvern.forge.sdk.workflow.models.code_block_recorder import CODE_BLOCK_FILENAME, RecordingPage
+from skyvern.forge.sdk.workflow.models.code_block_recorder import (
+ CODE_BLOCK_FILENAME,
+ RECORDED_FAILURE_RESPONSE_MAX_CHARS,
+ RecordingPage,
+)
from skyvern.forge.sdk.workflow.models.code_block_recording import CodeBlockActionRecording
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
from skyvern.webeye.actions.actions import (
@@ -122,6 +127,71 @@ async def test_capture_failure_still_persists_the_action_and_reports_page_state(
assert warning["page_closed"] is True
+async def test_a_secret_straddling_the_response_bound_is_masked_whole() -> None:
+ # The masker matches secret values by exact substring, so the recorded failure text has to be
+ # masked before it is bounded or the cut leaves an unmatchable fragment on the persisted row.
+ secret = "sk-live-" + "z" * 52
+ prefix = "Locator.click: Timeout exceeded. Call log: "
+ message = prefix.ljust(RECORDED_FAILURE_RESPONSE_MAX_CHARS - 30, "-") + secret + " intercepts pointer events"
+ assert secret not in message[:RECORDED_FAILURE_RESPONSE_MAX_CHARS]
+ assert secret[:30] in message[:RECORDED_FAILURE_RESPONSE_MAX_CHARS]
+
+ page = SimpleNamespace(
+ url="https://example.com/",
+ screenshot=AsyncMock(return_value=b"png"),
+ is_closed=lambda: False,
+ goto=AsyncMock(side_effect=RuntimeError(message)),
+ )
+ recording = _recording(page)
+ recording._workflow_run_context.secrets = {"api_token": secret}
+ unbound_mask = WorkflowRunContext.mask_secrets_in_data
+ recording._workflow_run_context.mask_secrets_in_data = unbound_mask.__get__( # type: ignore[method-assign]
+ recording._workflow_run_context
+ )
+ recording.recording_page = RecordingPage(page, on_action=recording._recorded_action_sink)
+ upsert = AsyncMock()
+
+ with (
+ patch(f"{_RECORDING_PATH}.DATABASE.workflow_params.upsert_recorded_action", upsert),
+ patch(f"{_RECORDING_PATH}.ARTIFACT_MANAGER.create_workflow_run_block_artifact", AsyncMock()),
+ pytest.raises(RuntimeError),
+ ):
+ await recording.recording_page.goto("https://example.com/next")
+
+ persisted = upsert.await_args.args[0]
+ assert len(persisted.response) == RECORDED_FAILURE_RESPONSE_MAX_CHARS
+ assert "sk-live" not in persisted.response
+ assert "Locator.click: Timeout exceeded." in persisted.response
+
+
+async def test_synthetic_failure_row_is_masked_before_it_is_bounded() -> None:
+ secret = "sk-live-" + "z" * 52
+ action = Action(
+ action_type=ActionType.NULL_ACTION,
+ status=ActionStatus.failed,
+ response="Failed to execute code block. Reason: ".ljust(RECORDED_FAILURE_RESPONSE_MAX_CHARS - 30, "-") + secret,
+ )
+ page = SimpleNamespace(
+ url="https://example.com/", screenshot=AsyncMock(return_value=b"png"), is_closed=lambda: False
+ )
+ recording = _recording(page)
+ recording._workflow_run_context.secrets = {"api_token": secret}
+ unbound_mask = WorkflowRunContext.mask_secrets_in_data
+ recording._workflow_run_context.mask_secrets_in_data = unbound_mask.__get__( # type: ignore[method-assign]
+ recording._workflow_run_context
+ )
+ upsert = AsyncMock()
+
+ with patch(f"{_RECORDING_PATH}.DATABASE.workflow_params.upsert_recorded_action", upsert):
+ await recording._persist_action(action, recording._remember_action_metadata(action))
+
+ persisted = upsert.await_args.args[0]
+ assert len(persisted.response) <= RECORDED_FAILURE_RESPONSE_MAX_CHARS
+ assert "sk-live" not in persisted.response
+
+
@pytest.mark.asyncio
async def test_parameter_redaction_preserves_trusted_metadata_and_logs_safely() -> None:
def redact(value: Any, parameters: dict[str, Any]) -> Any:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 7791bfd09..125b55d0e 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -226,6 +226,9 @@ workflow_definition:
"workflow_run_id": "wr_budget",
"overall_status": "canceled",
"current_url": "https://example.com/lookup",
+ # The watchdog reads the page live on the non-dispatched branch and stamps this
+ # alongside the URL; without it a live read cannot claim a verified page state.
+ "current_url_live_observed": True,
"page_title": "Example Lookup Registry",
"executed_block_labels": ["search_registry"],
"frontier_start_label": "search_registry",
diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.py
index ca4116dc7..d787fbd6b 100644
--- a/tests/unit/test_copilot_composition_evidence.py
+++ b/tests/unit/test_copilot_composition_evidence.py
@@ -3760,12 +3760,16 @@ async def test_capture_reports_structured_failure_without_calling_get_html() ->
)
assert evidence is None
- assert error == "structured page evidence failed: evaluate returned an error"
+ assert (
+ error
+ == "skyvern_evaluate returned an error while capturing structured page evidence: structured extract failed"
+ )
+ assert "structured page evidence failed: evaluate returned an error" not in error
assert server.calls.count("skyvern_get_html") == 0
@pytest.mark.asyncio
-async def test_capture_does_not_reflect_structured_exception_text_to_copilot() -> None:
+async def test_capture_redacts_raw_secrets_from_reflected_structured_exception_text() -> None:
server = _RecordingCompositionServer(
structured_json=None,
structured_exception=RuntimeError("https://example.com/callback?token=raw-secret"),
@@ -3777,8 +3781,9 @@ async def test_capture_does_not_reflect_structured_exception_text_to_copilot() -
)
assert evidence is None
- assert error == "skyvern_evaluate failed while capturing structured page evidence"
+ assert error.startswith("skyvern_evaluate raised while capturing structured page evidence: ")
assert "raw-secret" not in error
+ assert "[REDACTED_SECRET]" in error
@pytest.mark.asyncio
diff --git a/tests/unit/test_copilot_composition_scrape.py b/tests/unit/test_copilot_composition_scrape.py
index f5a6eaa0e..7a6b1f3e9 100644
--- a/tests/unit/test_copilot_composition_scrape.py
+++ b/tests/unit/test_copilot_composition_scrape.py
@@ -15,6 +15,7 @@ from skyvern.config import settings
from skyvern.forge.sdk.copilot import tools
from skyvern.forge.sdk.copilot.composition_evidence import parse_composition_structured
from skyvern.forge.sdk.copilot.tools import _normalized_inspect_url, _same_inspect_target
+from skyvern.forge.sdk.copilot.tools._shared import _composition_get_structured_evidence_result
from skyvern.forge.sdk.copilot.tools.scouting import _page_evidence_location_fingerprint
@@ -284,3 +285,85 @@ async def test_signalled_packet_survives_extractor_blinking_mid_loop(monkeypatch
assert evidence["challenge_state"]["detected"] is True
assert evidence["challenge_state"]["indicators"] == ["just a moment"]
get_html.assert_not_awaited()
+
+
+async def _structured_evidence(server: SimpleNamespace) -> tuple[dict | None, str | None]:
+ return await _composition_get_structured_evidence_result(
+ SimpleNamespace(discovery_mcp_server=server),
+ inspected_url="https://example.com/",
+ current_url="https://example.com/",
+ )
+
+
+async def test_structured_evidence_rejection_returns_the_underlying_error() -> None:
+ server = SimpleNamespace(
+ call_internal_tool=AsyncMock(return_value={"ok": False, "error": "SecurityError: blocked a frame with origin"})
+ )
+
+ evidence, error = await _structured_evidence(server)
+
+ assert evidence is None
+ assert error is not None
+ assert "SecurityError: blocked a frame with origin" in error
+ assert "structured page evidence failed: evaluate returned an error" not in error
+
+
+class _HostileStr(Exception):
+ def __str__(self) -> str:
+ raise RuntimeError("boom")
+
+
[email protected]("arm", ["error_payload", "raised_exception"])
+async def test_a_hostile_dunder_str_does_not_escape_the_evidence_error(arm: str) -> None:
+ """Both arms return the graceful (None, message); reading the value must not raise on either."""
+ server = SimpleNamespace(
+ call_internal_tool=AsyncMock(return_value={"ok": False, "error": _HostileStr()})
+ if arm == "error_payload"
+ else AsyncMock(side_effect=_HostileStr())
+ )
+
+ evidence, error = await _structured_evidence(server)
+
+ assert evidence is None
+ assert isinstance(error, str)
+
+
+async def test_structured_evidence_non_mapping_result_does_not_raise() -> None:
+ evidence, error = await _structured_evidence(
+ SimpleNamespace(call_internal_tool=AsyncMock(return_value="not-a-mapping"))
+ )
+
+ assert evidence is None
+ assert error == (
+ "skyvern_evaluate returned an error while capturing structured page evidence, "
+ "and the result carried no error detail"
+ )
+ assert "structured page evidence failed: evaluate returned an error" not in error
+
+
+async def test_structured_evidence_exception_returns_the_underlying_error() -> None:
+ evidence, error = await _structured_evidence(
+ SimpleNamespace(call_internal_tool=AsyncMock(side_effect=RuntimeError("CDP target detached")))
+ )
+
+ assert evidence is None
+ assert error is not None
+ assert "CDP target detached" in error
+
+
+async def test_structured_evidence_error_is_bounded_and_redacted() -> None:
+ server = SimpleNamespace(
+ call_internal_tool=AsyncMock(return_value={"ok": False, "error": "api_key=zzzz1111yyyy2222 " + "e" * 4000})
+ )
+
+ evidence, error = await _structured_evidence(server)
+
+ assert evidence is None
+ assert error is not None
+ assert "zzzz1111yyyy2222" not in error
+ assert len(error) < 400
diff --git a/tests/unit/test_copilot_screenshot_handling.py b/tests/unit/test_copilot_screenshot_handling.py
index 2f85bbe3a..2b003e4d5 100644
--- a/tests/unit/test_copilot_screenshot_handling.py
+++ b/tests/unit/test_copilot_screenshot_handling.py
@@ -20,7 +20,17 @@ from skyvern.forge.sdk.copilot.screenshot_utils import (
stage_screenshot_from_artifact,
)
from skyvern.forge.sdk.copilot.session_factory import copilot_call_model_input_filter
+from skyvern.forge.sdk.copilot.tools.run_execution import (
+ NO_PERSISTED_END_URL,
+ _attach_action_traces,
+ _attach_failed_block_screenshots,
+ _dispatched_end_url,
+ _resolve_run_screenshot_b64,
+ _summarize_action_trace,
+ _update_verification_evidence_from_run_result,
+)
from skyvern.forge.sdk.copilot.tools.scouting import _capture_post_interaction_screenshot
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from tests.unit.copilot_test_helpers import make_model_input_data
@@ -358,6 +368,7 @@ class TestAttachActionTraces:
element_id: str | None,
*,
description: str | None = None,
+ response: str | None = None,
output: dict[str, Any] | list | str | None = None,
) -> MagicMock:
action = MagicMock()
@@ -367,6 +378,7 @@ class TestAttachActionTraces:
action.reasoning = reasoning
action.element_id = element_id
action.description = description
+ action.response = response
action.output = output
return action
@@ -476,7 +488,7 @@ class TestAttachActionTraces:
assert "output" not in trace[0]
assert "arbitrary" not in trace[0]
assert "description" not in trace[1]
- assert "code_line" not in trace[1]
+ assert trace[1]["code_line"] == 17
assert "description" not in trace[2]
assert "code_line" not in trace[2]
assert "description" not in trace[3]
@@ -484,6 +496,116 @@ class TestAttachActionTraces:
assert "description" not in trace[4]
assert "code_line" not in trace[4]
+ @pytest.mark.asyncio
+ async def test_failed_direct_action_carries_browser_error_text_and_its_code_line(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ block = self._make_block("task-1", "failed")
+ result: dict[str, Any] = {"label": "accept_notice", "status": "failed"}
+ actionability_error = (
+ "Locator.click: Timeout 5000ms exceeded.\n"
+ "Call log:\n"
+ ' - waiting for locator("#continue")\n'
+ ' - <div class="privacy-notice-veil" role="dialog">…</div> intercepts pointer events'
+ )
+ actions = [
+ self._make_action(
+ "task-1",
+ "click",
+ "failed",
+ None,
+ "continue-1",
+ response=actionability_error,
+ output={"code_line": 19},
+ )
+ ]
+
+ mock_db = MagicMock()
+ mock_db.tasks = MagicMock()
+ mock_db.tasks.get_recent_actions_for_tasks = AsyncMock(return_value=actions)
+ _install_mock_database(monkeypatch, mock_db)
+
+ await _attach_action_traces([block], [result], "org-1")
+
+ entry = result["action_trace"][0]
+ assert entry["response"] != "Browser operation failed."
+ assert "privacy-notice-veil" in entry["response"]
+ assert "intercepts pointer events" in entry["response"]
+ assert entry["code_line"] == 19
+
+ summary = _summarize_action_trace(result["action_trace"])
+ assert "privacy-notice-veil" in summary[-1]
+ assert "code_line=19" in summary[-1]
+ assert "description=" not in summary[-1]
+
+ @pytest.mark.asyncio
+ async def test_browser_error_text_is_bounded_in_the_trace(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ block = self._make_block("task-1", "failed")
+ result: dict[str, Any] = {"label": "accept_notice", "status": "failed"}
+ actions = [
+ self._make_action("task-1", "click", "failed", None, None, response="y" * 4000, output={"code_line": 19})
+ ]
+
+ mock_db = MagicMock()
+ mock_db.tasks = MagicMock()
+ mock_db.tasks.get_recent_actions_for_tasks = AsyncMock(return_value=actions)
+ _install_mock_database(monkeypatch, mock_db)
+
+ await _attach_action_traces([block], [result], "org-1")
+
+ assert len(result["action_trace"][0]["response"]) == 300
+
+ @pytest.mark.asyncio
+ async def test_a_non_recorder_failed_action_keeps_its_response_out_of_the_trace(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """personalize_action writes the typed-in field value to response; only the recorder's own
+ rows, which carry a code_line, may surface it."""
+ block = self._make_block("task-1", "failed")
+ result: dict[str, Any] = {"label": "fill_ssn", "status": "failed"}
+ actions = [self._make_action("task-1", "input_text", "failed", None, "ssn-field", response="123-45-6789")]
+
+ mock_db = MagicMock()
+ mock_db.tasks = MagicMock()
+ mock_db.tasks.get_recent_actions_for_tasks = AsyncMock(return_value=actions)
+ _install_mock_database(monkeypatch, mock_db)
+
+ await _attach_action_traces([block], [result], "org-1")
+
+ assert "response" not in result["action_trace"][0]
+ assert "123-45-6789" not in str(result["action_trace"])
+
+ @pytest.mark.asyncio
+ async def test_repeated_identical_failures_are_neither_deduped_nor_labelled(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ block = self._make_block("task-1", "failed")
+ result: dict[str, Any] = {"label": "accept_notice", "status": "failed"}
+ repeated = '<div class="privacy-notice-veil">…</div> intercepts pointer events'
+ actions = [
+ self._make_action(
+ "task-1", "click", "failed", None, "continue-1", response=repeated, output={"code_line": 19}
+ )
+ for _ in range(3)
+ ]
+
+ mock_db = MagicMock()
+ mock_db.tasks = MagicMock()
+ mock_db.tasks.get_recent_actions_for_tasks = AsyncMock(return_value=actions)
+ _install_mock_database(monkeypatch, mock_db)
+
+ await _attach_action_traces([block], [result], "org-1")
+
+ trace = result["action_trace"]
+ assert len(trace) == 3
+ assert all(entry["response"] == repeated for entry in trace)
+ assert all(
+ set(entry) == {"action", "status", "reasoning", "element", "code_line", "response"} for entry in trace
+ )
+ summary = _summarize_action_trace(trace)
+ assert len(summary) == 3
+ assert len(set(summary)) == 1
+
@pytest.mark.asyncio
async def test_attach_action_traces_skips_success(self, monkeypatch: pytest.MonkeyPatch) -> None:
from skyvern.forge.sdk.copilot.tools import _attach_action_traces
@@ -696,6 +818,199 @@ class TestAttachFailedBlockScreenshots:
assert result["screenshot_b64"] == base64.b64encode(self.PNG_BYTES).decode("utf-8")
assert "final_url" not in result
+ @pytest.mark.asyncio
+ async def test_dispatched_failure_packet_carries_the_worker_persisted_frame_and_url(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ block = self._make_block(
+ workflow_run_block_id="wrb-dispatched",
+ task_id="tsk-v1-container",
+ final_url="https://example.com/step-2",
+ )
+ results: list[dict[str, Any]] = [{"label": "accept_notice", "status": "failed"}]
+
+ self._install_app(monkeypatch, run_block_artifact=MagicMock(), task_v2_artifacts=[])
+
+ await _attach_failed_block_screenshots([block], results, "org-1")
+ packet = {
+ "blocks": results,
+ "current_url": _dispatched_end_url([block]),
+ "screenshot_base64": _resolve_run_screenshot_b64(live_capture=None, results=results, run_ok=False),
+ }
+
+ assert packet["current_url"] == "https://example.com/step-2"
+ assert packet["screenshot_base64"] == base64.b64encode(self.PNG_BYTES).decode("utf-8")
+ assert results[0]["final_url"] == "https://example.com/step-2"
+ assert "at_failure_evidence" not in results[0]
+
+ @pytest.mark.asyncio
+ async def test_dispatched_failure_without_persisted_evidence_states_the_absence(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ block = self._make_block(workflow_run_block_id="wrb-bare", task_id="tsk-bare", final_url=None)
+ results: list[dict[str, Any]] = [{"label": "accept_notice", "status": "failed"}]
+
+ self._install_app(monkeypatch, run_block_artifact=None, task_v2_artifacts=[])
+
+ await _attach_failed_block_screenshots([block], results, "org-1")
+ end_url = _dispatched_end_url([block])
+ packet: dict[str, Any] = {
+ "blocks": results,
+ "screenshot_base64": _resolve_run_screenshot_b64(live_capture=None, results=results, run_ok=False),
+ }
+ if end_url is None:
+ packet["current_url_evidence"] = NO_PERSISTED_END_URL
+ else:
+ packet["current_url"] = end_url
+
+ assert results[0]["at_failure_evidence"] == (
+ "No at-failure screenshot or final URL was persisted for this block."
+ )
+ assert "final_url" not in results[0]
+ assert "screenshot_b64" not in results[0]
+ assert end_url is None
+ assert packet["current_url_evidence"] == NO_PERSISTED_END_URL
+ assert "current_url" not in packet
+ assert packet["screenshot_base64"] is None
+
+ @pytest.mark.asyncio
+ async def test_get_run_results_wires_the_persisted_end_url_into_the_packet(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Pins the call site, not the helper: reverting the dispatched branch to ("", "") must fail here."""
+ import skyvern.forge.sdk.copilot.tools.run_execution as run_execution_module
+
+ block = MagicMock()
+ block.label = "accept_notice"
+ block.block_type = SimpleNamespace(name="code")
+ block.status = "failed"
+ block.failure_reason = None
+ block.output = None
+ block.task_id = None
+ block.final_url = "https://example.com/step-2"
+ block.workflow_run_block_id = "wrb-1"
+
+ run = SimpleNamespace(
+ status="failed",
+ workflow_permanent_id="wpid-1",
+ failure_reason=None,
+ )
+
+ class _AppStub:
+ class DATABASE:
+ class workflow_runs:
+ get_workflow_run = AsyncMock(return_value=run)
+
+ class observer:
+ get_workflow_run_blocks = AsyncMock(return_value=[block])
+
+ class AGENT_FUNCTION:
+ should_dispatch_copilot_block_run_to_worker = AsyncMock(return_value=True)
+
+ monkeypatch.setattr(run_execution_module, "app", _AppStub())
+ monkeypatch.setattr(run_execution_module, "_attach_action_traces", AsyncMock())
+ monkeypatch.setattr(run_execution_module, "_attach_failed_block_screenshots", AsyncMock())
+
+ ctx = SimpleNamespace(organization_id="org-1", workflow_permanent_id="wpid-1")
+ result = await run_execution_module._get_run_results({"workflow_run_id": "wr-1"}, ctx)
+
+ assert result["data"]["current_url"] == "https://example.com/step-2"
+ assert "current_url_evidence" not in result["data"]
+ assert result["data"].get("current_url_live_observed") is not True
+
+ def test_an_earlier_blocks_url_is_not_reported_as_where_the_run_ended(self) -> None:
+ earlier = self._make_block(
+ workflow_run_block_id="wrb-earlier",
+ task_id="tsk-earlier",
+ final_url="https://example.com/step-1",
+ )
+ terminal = self._make_block(
+ workflow_run_block_id="wrb-terminal",
+ task_id="tsk-terminal",
+ final_url=None,
+ )
+
+ assert _dispatched_end_url([earlier, terminal]) is None
+
+ def test_a_worker_persisted_url_does_not_claim_the_live_page_was_verified(self) -> None:
+ ctx = SimpleNamespace(
+ workflow_verification_evidence=WorkflowVerificationEvidence(),
+ last_full_workflow_test_ok=False,
+ last_failure_category_top=None,
+ last_test_failure_reason=None,
+ )
+ result = {"ok": False, "data": {"current_url": "https://example.com/step-2"}}
+
+ _update_verification_evidence_from_run_result(ctx, result) # type: ignore[arg-type]
+
+ assert ctx.workflow_verification_evidence.current_url == "https://example.com/step-2"
+ assert ctx.workflow_verification_evidence.live_page_state_verified is False
+
+ def test_a_persisted_url_clears_a_verification_left_by_an_earlier_live_read(self) -> None:
+ """The flag is only ever set True elsewhere, so it must move with the URL it describes."""
+ evidence = WorkflowVerificationEvidence()
+ evidence.live_page_state_verified = True
+ evidence.current_url = "https://example.com/scouted"
+ ctx = SimpleNamespace(
+ workflow_verification_evidence=evidence,
+ last_full_workflow_test_ok=False,
+ last_failure_category_top=None,
+ last_test_failure_reason=None,
+ )
+ result = {"ok": False, "data": {"current_url": "https://example.com/persisted"}}
+
+ _update_verification_evidence_from_run_result(ctx, result) # type: ignore[arg-type]
+
+ assert evidence.current_url == "https://example.com/persisted"
+ assert evidence.live_page_state_verified is False
+
+ def test_a_live_observed_url_still_verifies_the_page_state(self) -> None:
+ ctx = SimpleNamespace(
+ workflow_verification_evidence=WorkflowVerificationEvidence(),
+ last_full_workflow_test_ok=False,
+ last_failure_category_top=None,
+ last_test_failure_reason=None,
+ )
+ result = {
+ "ok": False,
+ "data": {"current_url": "https://example.com/step-2", "current_url_live_observed": True},
+ }
+
+ _update_verification_evidence_from_run_result(ctx, result) # type: ignore[arg-type]
+
+ assert ctx.workflow_verification_evidence.live_page_state_verified is True
+
+ def test_an_over_long_url_is_refused_rather_than_truncated(self) -> None:
+ """A cut URL still parses, so truncating would report an unresumable page as the end state."""
+ terminal = self._make_block(
+ workflow_run_block_id="wrb-long",
+ task_id="tsk-long",
+ final_url="https://example.com/p?" + "x=1&" * 75000,
+ )
+
+ assert _dispatched_end_url([terminal]) is None
+
+ def test_a_runtime_token_in_the_end_url_is_screened(self) -> None:
+ terminal = self._make_block(
+ workflow_run_block_id="wrb-tok",
+ task_id="tsk-tok",
+ final_url="https://example.com/cb?access_token=abcdef1234567890xyz",
+ )
+
+ end_url = _dispatched_end_url([terminal])
+
+ assert end_url is not None
+ assert "abcdef1234567890xyz" not in end_url
+
+ def test_a_secret_masked_url_is_not_reported_as_a_resumable_page(self) -> None:
+ terminal = self._make_block(
+ workflow_run_block_id="wrb-masked",
+ task_id="tsk-masked",
+ final_url="https://example.com/callback?token=*****",
+ )
+
+ assert _dispatched_end_url([terminal]) is None
+
@pytest.mark.asyncio
async def test_successful_block_gets_no_evidence(self, monkeypatch: pytest.MonkeyPatch) -> None:
from skyvern.forge.sdk.copilot.tools.run_execution import _attach_failed_block_screenshots
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index 4a8d199b5..a1da9657a 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -22,10 +22,12 @@ from skyvern.cli.core.browser_ops import (
do_select_option,
)
from skyvern.cli.core.result import Artifact, BrowserContext, set_concise_responses
+from skyvern.cli.mcp_tools import _element_state
from skyvern.cli.mcp_tools import browser as mcp_browser
from skyvern.cli.mcp_tools import cdp_input as mcp_cdp_input
from skyvern.cli.mcp_tools import mcp
from skyvern.client.errors import InternalServerError, UnprocessableEntityError
+from skyvern.forge.sdk.forge_log import codeblock_parameter_log_redaction
from tests.unit._mcp_browser_fakes import (
make_mock_page,
make_probe_locator,
@@ -674,6 +676,93 @@ async def test_skyvern_click_direct_failure_reports_element_state(
locator.count.assert_awaited_once()
+ "bad_str",
+ [
+ pytest.param(lambda self: (_ for _ in ()).throw(RuntimeError("boom")), id="raising"),
+ pytest.param(lambda self: 7, id="non_str"),
+ ],
+)
+def test_a_hostile_dunder_str_cannot_raise_out_of_the_element_state_detail(bad_str) -> None: # noqa: ANN001
+ """Reading the message must not turn a handled actionability failure into an unhandled one."""
+
+ class Hostile(Exception):
+ __str__ = bad_str
+
+ assert _element_state._redacted_exception_detail(Hostile()) == ""
+
+
+async def test_skyvern_click_direct_failure_returns_the_underlying_error_text(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ message = (
+ "Locator.click: Timeout 5000ms exceeded.\n"
+ 'Call log:\n - <div class="privacy-notice-veil">Accept</div> intercepts pointer events'
+ )
+ click, _ = _direct_click_page(
+ monkeypatch,
+ count=1,
+ visible=True,
+ enabled=True,
+ click_error=mcp_browser.PlaywrightTimeoutError(message),
+ )
+
+ result = await mcp_browser.skyvern_click(selector="#target", selector_mode="direct")
+
+ details = result["error"]["details"]
+ assert "privacy-notice-veil" in details["exception_detail"]
+ assert "intercepts pointer events" in details["exception_detail"]
+ assert details["exception_detail"] != details["exception_type"]
+
+
+async def test_skyvern_click_direct_failure_redacts_a_secret_bearing_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ click, _ = _direct_click_page(
+ monkeypatch,
+ count=1,
+ visible=True,
+ enabled=True,
+ click_error=mcp_browser.PlaywrightTimeoutError(
+ "Locator.click: navigating to https://example.com/callback?access_token=abcd1234efgh5678 failed"
+ ),
+ )
+
+ result = await mcp_browser.skyvern_click(selector="#target", selector_mode="direct")
+
+ assert "abcd1234efgh5678" not in result["error"]["details"]["exception_detail"]
+
+
+async def test_skyvern_click_direct_failure_masks_a_parameter_straddling_the_detail_bound(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The codeblock redactor replaces parameter values by exact match, so bounding the text before
+ # it runs would leave a cut value behind as an unmatchable fragment.
+ parameter_value = "vault-secret-" + "q" * 40
+ prefix = "Locator.click: Timeout 5000ms exceeded. Call log: navigating to "
+ message = prefix.ljust(_element_state.ELEMENT_STATE_ERROR_DETAIL_MAX_CHARS - 30, "-") + parameter_value + " failed"
+ cut = message[: _element_state.ELEMENT_STATE_ERROR_DETAIL_MAX_CHARS]
+ assert parameter_value[:20] in cut and parameter_value not in cut
+
+ click, _ = _direct_click_page(
+ monkeypatch,
+ count=1,
+ visible=True,
+ enabled=True,
+ click_error=mcp_browser.PlaywrightTimeoutError(message),
+ )
+
+ with codeblock_parameter_log_redaction(lambda value: value.replace(parameter_value, "[REDACTED]")):
+ result = await mcp_browser.skyvern_click(selector="#target", selector_mode="direct")
+
+ detail = result["error"]["details"]["exception_detail"]
+ assert len(detail) <= _element_state.ELEMENT_STATE_ERROR_DETAIL_MAX_CHARS
+ assert "vault-secret" not in detail
+
+
@pytest.mark.asyncio
async def test_skyvern_click_direct_failure_probes_working_frame(monkeypatch: pytest.MonkeyPatch) -> None:
frame_locator = make_probe_locator(visible=False)
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index 755aaf6fd..9f7fc78a8 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -32,6 +32,8 @@ from skyvern.forge.sdk.workflow.models.code_block_recorder import (
_PAGE_ACTION_MAP,
CODE_BLOCK_FILENAME,
CODE_LINE_OFFSET,
+ RECORDED_FAILURE_CAPTURE_MAX_CHARS,
+ RECORDED_FAILURE_RESPONSE_MAX_CHARS,
PendingAction,
RecordingKeyboard,
RecordingLocator,
@@ -558,11 +560,19 @@ async def test_filter_locator_chain_click_is_recorded() -> None:
assert [a.action_type for a in recorded] == [ActionType.CLICK]
+_ACTIONABILITY_ERROR = (
+ "Locator.click: Timeout 5000ms exceeded.\n"
+ "Call log:\n"
+ ' - waiting for locator("#submit")\n'
+ ' - <div class="privacy-notice-veil" role="dialog">…</div> intercepts pointer events'
+)
+
+
@pytest.mark.asyncio
-async def test_failed_call_records_failed_action_and_reraises() -> None:
+async def test_failed_call_records_the_browser_error_text_and_reraises() -> None:
class ExplodingLocator(FakeLocator):
async def click(self, **kwargs): # noqa: ANN003, ANN201
- raise RuntimeError("element detached")
+ raise RuntimeError(_ACTIONABILITY_ERROR)
fake = FakePage()
fake.inner = ExplodingLocator()
@@ -572,8 +582,54 @@ async def test_failed_call_records_failed_action_and_reraises() -> None:
recorded = page.recorded_actions()
assert recorded[-1].action_type == ActionType.CLICK
assert recorded[-1].status == ActionStatus.failed
- assert "element detached" not in (recorded[-1].response or "")
- assert recorded[-1].response == "Browser operation failed."
+ assert recorded[-1].response != "Browser operation failed."
+ assert "privacy-notice-veil" in (recorded[-1].response or "")
+ assert "intercepts pointer events" in (recorded[-1].response or "")
+
+
+ "bad_str",
+ [
+ pytest.param(lambda self: (_ for _ in ()).throw(RuntimeError("__str__ exploded")), id="raising"),
+ pytest.param(lambda self: 42, id="non_str"),
+ ],
+)
+async def test_a_hostile_dunder_str_cannot_swallow_the_original_failure(bad_str) -> None: # noqa: ANN001
+ """Capturing the message must not cost the fault: the original exception still propagates."""
+
+ class Hostile(Exception):
+ __str__ = bad_str
+
+ class ExplodingLocator(FakeLocator):
+ async def click(self, **kwargs): # noqa: ANN003, ANN201
+ raise Hostile()
+
+ fake = FakePage()
+ fake.inner = ExplodingLocator()
+ page = RecordingPage(fake)
+ with pytest.raises(Hostile):
+ await page.locator("#x").click()
+ assert page.recorded_actions()[-1].response == "Hostile"
+
+
+async def test_a_huge_error_is_captured_above_the_mask_bound_but_still_capped() -> None:
+ """Unbounded capture would exceed the parameter redactor's disclosure budget, which returns a
+ replacement string instead of the payload and drops the whole row."""
+
+ class ExplodingLocator(FakeLocator):
+ async def click(self, **kwargs): # noqa: ANN003, ANN201
+ raise RuntimeError("x" * 70000)
+
+ fake = FakePage()
+ fake.inner = ExplodingLocator()
+ page = RecordingPage(fake)
+ with pytest.raises(RuntimeError):
+ await page.locator("#x").click()
+ captured = page.recorded_actions()[-1].response or ""
+ assert len(captured) > RECORDED_FAILURE_RESPONSE_MAX_CHARS
+ assert len(captured) == RECORDED_FAILURE_CAPTURE_MAX_CHARS
@pytest.mark.asyncio