Skip to content

Automate browser based workflows with AI

Serve DataDragon report files in the dashboard through signed S3 links (SKY-11158) (#8690)

Andrew Neilsonf3adb6ec5d1d
diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.py
index bbeb8a3fc..aaecd72f6 100644
--- a/skyvern/forge/sdk/copilot/streaming_adapter.py
+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py
@@ -89,6 +89,8 @@ _OBSERVATION_TOOLS = {
}
_AUTHORING_TOOL_NAMES = frozenset({"update_and_run_blocks", "edit_block_and_run", "update_workflow"})
+# edit_block_and_run's top-level `label` names the existing block it edits, not a drafted one.
+_BLOCK_DEFINITION_TOOL_NAMES = frozenset({"update_and_run_blocks", "update_workflow"})
def _drain_code_write_diffs(ctx: CopilotContext, tool_name: str, call_id: str) -> list[CodeWriteDiff] | None:
@@ -101,10 +103,9 @@ def _drain_code_write_diffs(ctx: CopilotContext, tool_name: str, call_id: str) -
return diffs or None
-# Pure substring heuristic over raw (unparsed) JSON text: a free-text field (e.g. navigation_goal)
-# that happens to contain the literal "label:" would also match. Accepted trade-off of not
-# json.loads-ing the partial buffer; worst case is a spurious drafted-block entry.
-_CODEGEN_LABEL_RE = re.compile(r"label:\s*\\?\"?([A-Za-z0-9_][A-Za-z0-9_ \-]{0,79})")
+# Substring match over the unparsed argument buffer, covering JSON `"label": "x"` keys and YAML `label: x`
+# lines; free text containing "label:" also matches, and the worst case is a spurious drafted-block entry.
+_CODEGEN_LABEL_RE = re.compile(r"(?<![A-Za-z0-9_])label\"?:\s*\\?\"?(?!null\b)([A-Za-z0-9_][A-Za-z0-9_ \-]{0,79})")
_CODEGEN_MIN_GAP_SECONDS = 2.0
# Keep enough trailing context that a label split across two argument deltas still matches.
_CODEGEN_TAIL_OVERLAP = 96
@@ -134,6 +135,8 @@ class _CodegenCallState:
self.started_monotonic = time.monotonic()
def add_labels(self, text: str) -> bool:
+ if self.tool_name not in _BLOCK_DEFINITION_TOOL_NAMES:
+ return False
found_new = False
for match in _CODEGEN_LABEL_RE.finditer(text):
if match.end() == len(text):
@@ -752,15 +755,9 @@ def _update_enforcement_from_tool(
def _sanitize_input(raw_args: dict[str, Any]) -> dict[str, Any]:
- # Redacts tool-call args before they hit the SSE payload sent to the UI.
- # Distinct from output_utils.sanitize_tool_result_for_llm, which shapes
- # tool *results* for LLM context consumption.
- # Drop the large workflow YAML blob (it's displayed elsewhere in the UI),
- # then run the remaining args through the shared exact-match redactor to
- # strip values under sensitive key names like `password`, `api_key`,
- # `totp`, etc. Benign identifiers (`credential_id`, `page_token`,
- # `username`) pass through unchanged.
- trimmed = {k: v for k, v in raw_args.items() if k != "workflow_yaml"}
+ # Drop the submitted workflow or block definition (displayed elsewhere), then redact sensitive fields.
+ # Distinct from output_utils.sanitize_tool_result_for_llm, which shapes tool results for LLM context.
+ trimmed = {k: v for k, v in raw_args.items() if k not in ("workflow_yaml", "workflow", "block")}
redacted = redact_sensitive_fields(trimmed)
if isinstance(redacted, dict):
return redacted
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index f6d51e681..8286fe4e2 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -79,6 +79,7 @@ from skyvern.forge.sdk.copilot.workflow_yaml import (
stored_block_code,
stored_workflow_yaml,
)
+from skyvern.utils.yaml_loader import dump_workflow_yaml
from ._shared import _COMPOSITION_STRIPPED_HTML_MAX_CHARS as _COMPOSITION_STRIPPED_HTML_MAX_CHARS
from ._shared import _DISCOVERY_PER_CALL_TIMEOUT_SECONDS as _DISCOVERY_PER_CALL_TIMEOUT_SECONDS
@@ -317,16 +318,20 @@ def _mark_credential_deferred_draft(copilot_ctx: CopilotContext, result: dict[st
@function_tool(
failure_error_function=copilot_tool_failure,
name_override="update_workflow",
+ strict_mode=False,
tool_input_guardrails=[_WORKFLOW_YAML_OUTPUT_POLICY_GUARDRAIL],
)
async def update_workflow_tool(
ctx: RunContextWrapper,
- workflow_yaml: str,
+ workflow: dict[str, Any],
block_observation_refs: list[BlockObservationRef] | None = None,
code_artifact_metadata: list[CodeArtifactMetadata] | None = None,
) -> str:
- """Validate and update the workflow YAML definition.
- Provide the complete workflow YAML as a string.
+ """Validate and update the workflow definition.
+ Provide the complete workflow as a `workflow` object with the same keys as the workflow YAML, e.g.
+ `{"title": "Order lookup", "workflow_definition": {"parameters": [], "blocks": [{"block_type": "code",
+ "label": "read_total", "code": "line one\\nline two"}]}}`. String values, including multiline code, are
+ plain JSON strings.
Returns the validated workflow or validation errors.
A successful write is staged as a proposal, which the returned `persistence` and
@@ -350,6 +355,7 @@ async def update_workflow_tool(
declared goals, claimed outcomes, page dependencies, criteria, evidence
refs, observation refs, and terminal verifier expectations.
"""
+ workflow_yaml = dump_workflow_yaml(workflow)
copilot_ctx = ctx.context
# Mirrors the combined tool: a stale True from an earlier call in the same turn would
# misreport this call's authoring error as a credential ask.
@@ -694,7 +700,7 @@ async def edit_block_and_run_tool(
async def add_block_tool(
ctx: RunContextWrapper,
after_label: str,
- block_yaml: str,
+ block: dict[str, Any],
parameters: list[dict[str, Any]] | None = None,
code_artifact_metadata: list[CodeArtifactMetadata] | None = None,
block_observation_refs: list[BlockObservationRef] | None = None,
@@ -706,7 +712,8 @@ async def add_block_tool(
is not retyped. `after_label` must name a block that exists; the new block is linked in directly
after it and inherits what that block pointed at.
- Pass `block_yaml` as a single block mapping including its `label`. Declare any new top-level
+ Pass `block` as a single block object including its `label`, with the same keys as a block in the
+ workflow YAML; multiline code is a plain JSON string. Declare any new top-level
workflow parameters the block reads in `parameters` — a new block and the parameter it consumes
have to land in the same call, or the workflow is briefly saved in a state that cannot run. For a
code block pass its `code_artifact_metadata` row here too, since a brand-new block has none yet.
@@ -719,6 +726,7 @@ async def add_block_tool(
To change a block that already exists use edit_block; to remove one use delete_block.
"""
+ block_yaml = dump_workflow_yaml(block)
copilot_ctx = ctx.context
arguments = {"after_label": after_label, "parameters": parameters}
authority_error = _authority_tool_error(copilot_ctx, "add_block")
@@ -1315,7 +1323,7 @@ def _promote_executed_sources(
current_code = stored_block_code(workflow_yaml, label, allow_empty=True)
try:
if current_code is None:
- raise BlockEditError(f"Block {label!r} is not a code block in workflow_yaml; give it an empty `code`.")
+ raise BlockEditError(f"Block {label!r} is not a code block in `workflow`; give it an empty `code`.")
workflow_yaml = apply_block_edit(
workflow_yaml, label, expected_code=current_code, replacement_code=resolution.source
)
@@ -1336,14 +1344,16 @@ def _promote_executed_sources(
)
async def update_and_run_blocks_tool(
ctx: RunContextWrapper,
- workflow_yaml: str,
+ workflow: dict[str, Any],
block_labels: list[str],
block_observation_refs: list[BlockObservationRef] | None = None,
code_artifact_metadata: list[CodeArtifactMetadata] | None = None,
parameters: dict[str, Any] | None = None,
executed_source_references: dict[str, str] | None = None,
) -> Any:
- """Update the workflow YAML and immediately run the specified blocks in one step.
+ """Update the workflow and immediately run the specified blocks in one step.
+ Pass the complete workflow as a `workflow` object with the same keys as the workflow YAML, as in
+ update_workflow; string values, including multiline code, are plain JSON strings.
To save code you already ran with ``run_browser_code`` as a new block, map the block's label to that
cell's ``executed_source_reference`` in ``executed_source_references`` and leave the block's ``code``
empty: the cell's exact source becomes the block's code, so what gets tested is what you ran.
@@ -1358,7 +1368,7 @@ async def update_and_run_blocks_tool(
following edit must anchor to — plus `data.stored_code_rewritten` for the labels the server
rewrote away from what you submitted and `data.stored_code_withheld` for any too large to return.
- `block_labels` may be a tested frontier subset of the full workflow YAML;
+ `block_labels` may be a tested frontier subset of the full workflow;
save the complete reusable workflow, then run only the next 1-2 unverified
blocks when a long form/search/result chain can be verified incrementally.
@@ -1402,6 +1412,7 @@ async def update_and_run_blocks_tool(
submit/search control, account for challenge resolution before submit;
do not compose a click against a control observed as disabled.
"""
+ workflow_yaml = dump_workflow_yaml(workflow)
copilot_ctx = ctx.context
await await_pending_credential_pause(copilot_ctx)
copilot_ctx.completion_verification_result = None
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
index a154df682..a2284b151 100644
--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py
+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
@@ -211,7 +211,7 @@ AUTHORING_FAMILY_GUIDANCE = (
# only returned by get_block_schema, so a turn that is never told to read it never sees them.
SCHEMA_FIRST_GUIDANCE = (
"Call `get_block_schema` for a block type before authoring that type this turn, and follow the "
- "field names and nesting it returns rather than guessing the YAML shape."
+ "field names and nesting it returns rather than guessing the shape."
)
@@ -373,7 +373,7 @@ def _code_only_browser_schema_guidance(*, agent_blocks: bool = False, image_ocr:
)
return [
"Use one focused code block per durable browser goal, such as open, search, submit, expand, or extract.",
- "`code` is async Python with a Playwright `page` object and workflow parameters by key. Helper namespaces are pre-injected: no `import` statements, no dunder (`__name__`) names or attributes. Normalize parameter values before page inputs. Use YAML block scalars (`code: |`) and pass complete workflow YAML to update tools.",
+ "`code` is async Python with a Playwright `page` object and workflow parameters by key. Helper namespaces are pre-injected: no `import` statements, no dunder (`__name__`) names or attributes. Normalize parameter values before page inputs. Pass the complete workflow to update tools as a `workflow` object; multiline `code` is a plain JSON string.",
WRAPPER_SCOPE_RUNTIME_FACT,
"When a scouting tool offers a SYNTHESIZED CODE BLOCK it already encodes the interactions you scouted as deterministic Playwright: persist it verbatim and hand-author only the steps it does not cover. Direct browser evaluate is a scouting tool; a persisted code block must not use page.evaluate, page.evaluate_handle, page.request, or page.context. Use locators and locator DOM-reading methods such as inner_text, text_content, get_attribute, count, and is_visible instead.",
"For an extraction-intent `code` block, derive a typed `extraction_schema` from the goal and the scouted page, carry it as `code_artifact_metadata.extraction_schema`, and conform the block's `return` to it.",
diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.py
index 532d53064..bf97899eb 100644
--- a/skyvern/forge/sdk/copilot/tools/guardrails.py
+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.copilot.request_policy import CREDENTIAL_DEFERRED_DRAFT_R
from skyvern.forge.sdk.copilot.runtime import AgentContext, raw_secret_browser_denied
from skyvern.forge.sdk.copilot.tools.locator_inspection import TOOL_NAME as LOCATOR_INSPECTION_TOOL_NAME
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
+from skyvern.forge.sdk.copilot.workflow_yaml import tool_call_submitted_yaml
from skyvern.forge.sdk.workflow.models.parameter import (
OutputParameter,
WorkflowParameter,
@@ -55,10 +56,7 @@ def _workflow_yaml_output_policy_guardrail(data: ToolInputGuardrailData) -> Tool
tool_name=getattr(tool_context, "tool_name", None),
tool_call_id=getattr(tool_context, "tool_call_id", None),
)
- workflow_yaml_value = tool_arguments.get("workflow_yaml")
- workflow_yaml = workflow_yaml_value if isinstance(workflow_yaml_value, str) else None
-
- effective_yaml = workflow_yaml
+ effective_yaml = tool_call_submitted_yaml(tool_arguments)
verdict = evaluate_output_policy(
request_policy=getattr(getattr(tool_context, "context", None), "request_policy", None),
diff --git a/skyvern/forge/sdk/copilot/workflow_yaml.py b/skyvern/forge/sdk/copilot/workflow_yaml.py
index 0af210a64..fd6f626e6 100644
--- a/skyvern/forge/sdk/copilot/workflow_yaml.py
+++ b/skyvern/forge/sdk/copilot/workflow_yaml.py
@@ -1,5 +1,6 @@
"""Copilot workflow-YAML normalization, chain repair, and Workflow conversion."""
+import re
from collections.abc import Collection, Mapping
from copy import deepcopy
from datetime import datetime, timezone
@@ -766,6 +767,15 @@ def workflow_yaml_title(workflow_yaml: str | None) -> str | None:
return title.strip() if isinstance(title, str) and title.strip() else None
+def _yaml_scalar_forms(value: str) -> set[str]:
+ """``value`` as it appears inside a plain, single-quoted, or double-quoted YAML scalar."""
+ forms = {value}
+ for style in ("'", '"'):
+ dumped = yaml.safe_dump(value, default_style=style, allow_unicode=True, width=_YAML_NO_FOLD_WIDTH)
+ forms.add(dumped.rstrip("\n")[1:-1])
+ return forms
+
+
def redact_credentials_in_workflow_yaml(
workflow_yaml: str, workflow_permanent_id: str, credential_values: Collection[str]
) -> str:
@@ -787,7 +797,10 @@ def redact_credentials_in_workflow_yaml(
from skyvern.forge.sdk.copilot.secret_scrub import MIN_PERSISTED_REDACTION_LENGTH, REDACTED_SECRET_PLACEHOLDER
redactable = {
- value for value in credential_values if isinstance(value, str) and len(value) >= MIN_PERSISTED_REDACTION_LENGTH
+ form
+ for value in credential_values
+ if isinstance(value, str) and len(value) >= MIN_PERSISTED_REDACTION_LENGTH
+ for form in _yaml_scalar_forms(value)
}
# Redact to a marker no input can contain, then swap it for the placeholder at the end, so one
# secret is never matched inside the placeholder another secret just produced.
@@ -797,10 +810,14 @@ def redact_credentials_in_workflow_yaml(
redacted_count = 0
# Longest first so an overlapping shorter value never splits a longer one.
for secret in sorted(redactable, key=len, reverse=True):
- occurrences = workflow_yaml.count(secret)
- if occurrences:
- redacted_count += occurrences
- workflow_yaml = workflow_yaml.replace(secret, marker)
+ # A multiline value is dumped as a literal block, which indents every line after the first. Outer
+ # newlines are dropped so the match never swallows the line break before the next key.
+ body = secret.strip("\n")
+ if not body:
+ continue
+ pattern = r"\n *".join(re.escape(line) for line in body.split("\n"))
+ workflow_yaml, occurrences = re.subn(pattern, lambda _: marker, workflow_yaml)
+ redacted_count += occurrences
workflow_yaml = workflow_yaml.replace(marker, REDACTED_SECRET_PLACEHOLDER)
if redacted_count:
LOG.error(
@@ -1410,6 +1427,19 @@ def _merge_new_workflow_parameters(parsed: dict[str, Any], parameters: list[Any]
definition["parameters"] = existing
+def tool_call_submitted_yaml(arguments: Mapping[str, Any]) -> str | None:
+ """The YAML a write tool call submitted: accepts ``workflow`` or ``block`` objects and ``workflow_yaml`` or ``block_yaml`` strings, returning the corresponding YAML."""
+ for key in ("workflow", "block"):
+ structured = arguments.get(key)
+ if isinstance(structured, dict):
+ return dump_workflow_yaml(structured)
+ for key in ("workflow_yaml", "block_yaml"):
+ legacy = arguments.get(key)
+ if isinstance(legacy, str):
+ return legacy
+ return None
+
+
def add_block_to_workflow(
stored_yaml: str,
after_label: str,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index dee1d7131..1f33672a6 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -339,6 +339,7 @@ from skyvern.webeye.navigation import (
driver_nav_error_code,
is_egress_attributable_navigation_failure,
navigate_with_retry,
+ record_task_nav_error_code,
redact_url_secrets,
)
from skyvern.webeye.playwright_input import playwright_input_defaults_for_page
@@ -2888,6 +2889,10 @@ def _recovery_task_error_codes(task: Task, workflow_run_context: WorkflowRunCont
return kept or None
+def _unique_error_codes(*groups: list[str] | None) -> list[str] | None:
+ return list(dict.fromkeys(code for group in groups for code in group or [])) or None
+
+
def _recorded_task_nav_error_codes(task_id: str, workflow_run_context: WorkflowRunContext) -> list[str] | None:
context = skyvern_context.current()
code = context.task_nav_error_codes.get(task_id) if context is not None else None
@@ -5228,29 +5233,35 @@ def _declared_error_code_of(result: BlockResult) -> str | None:
return declared if isinstance(declared, str) and declared else None
-def _redact_codeblock_result(result: BlockResult, parameters: dict[str, Any]) -> BlockResult:
+def _redact_codeblock_error_codes(
+ error_codes: list[str] | None, parameters: dict[str, Any], declared: str | None = None
+) -> list[str]:
# A driver code survives masking whole: a parameter value occurring inside one ("net") would cut
# the verdict out of it, and the code carries nothing of its own to mask. A code that *is* a
# parameter value is left to the mask, which is the one case where keeping it would disclose.
carried_strings = parameter_strings(parameters)
- declared = _declared_error_code_of(result)
preserved = (
{}
if carried_strings is None
else {
index: code
- for index, code in enumerate(result.error_codes or [])
+ for index, code in enumerate(error_codes or [])
if isinstance(code, str)
and driver_nav_error_code(code) == code
and code != declared
and code not in carried_strings
}
)
- redacted_error_codes = app.AGENT_FUNCTION.redact_codeblock_parameter_values(result.error_codes, parameters)
- if isinstance(redacted_error_codes, list):
- for index, code in preserved.items():
- if index < len(redacted_error_codes):
- redacted_error_codes[index] = code
+ redacted_error_codes = app.AGENT_FUNCTION.redact_codeblock_parameter_values(error_codes, parameters)
+ if not isinstance(redacted_error_codes, list):
+ return []
+ for index, code in preserved.items():
+ if index < len(redacted_error_codes):
+ redacted_error_codes[index] = code
+ return redacted_error_codes
+
+
+def _redact_codeblock_result(result: BlockResult, parameters: dict[str, Any]) -> BlockResult:
return replace(
result,
failure_reason=_redact_codeblock_failure_text(result.failure_reason, parameters),
@@ -5259,7 +5270,7 @@ def _redact_codeblock_result(result: BlockResult, parameters: dict[str, Any]) ->
if not result.success
else result.output_parameter_value
),
- error_codes=redacted_error_codes if isinstance(redacted_error_codes, list) else [],
+ error_codes=_redact_codeblock_error_codes(result.error_codes, parameters, _declared_error_code_of(result)),
)
@@ -7612,6 +7623,7 @@ async def wrapper({default_args}):
status: BlockStatus,
organization_id: str | None,
failure_reason: str | None = None,
+ error_codes: list[str] | None = None,
) -> None:
# The child recovery block surfaces the heal's actions on the run timeline (parented to the code
# block); keep its status synced with the heal outcome so it doesn't dangle in `running`.
@@ -7623,6 +7635,7 @@ async def wrapper({default_args}):
organization_id=organization_id,
status=status,
failure_reason=failure_reason,
+ error_codes=error_codes,
)
except Exception:
LOG.warning(
@@ -7636,9 +7649,12 @@ async def wrapper({default_args}):
escalation_step: Step | None,
recovery_block_id: str | None,
organization_id: str | None,
+ error_codes: list[str] | None = None,
) -> None:
# Best-effort so an aborted heal never strands its escalation task/step/recovery block in `running`.
- await self._finalize_recovery_block(recovery_block_id, BlockStatus.failed, organization_id)
+ await self._finalize_recovery_block(
+ recovery_block_id, BlockStatus.failed, organization_id, error_codes=error_codes
+ )
if escalation_task is None:
return
try:
@@ -7678,6 +7694,7 @@ async def wrapper({default_args}):
record_output_parameter: bool = True,
redaction_parameters: dict[str, Any] | None = None,
trace: _HealAttemptTrace | None = None,
+ failed_nav_error_code: str | None = None,
) -> BlockResult | None:
"""Run one bounded agent mini-run on the same workflow-run browser to finish the block's goal
(narrowed to the failing step when one is confidently matched). Returns a BlockResult when a
@@ -7764,13 +7781,17 @@ async def wrapper({default_args}):
escalation_url = (
self._derive_escalation_navigation_url(failing_line, recording_page) if failing_line is not None else ""
)
+ escalation_nav_error: Exception | None = None
+ escalation_navigated = False
if escalation_url and browser_state is not None and page is not None:
# BROWSER_MANAGER can early-return a cached browser state without ever reading
# task.url, so escalation_task.url alone is not reliable navigation recourse.
# Drive the live browser_state/page the heal will run on directly instead.
try:
await browser_state.navigate_to_url(page=page, url=escalation_url)
- except Exception:
+ escalation_navigated = True
+ except Exception as nav_error:
+ escalation_nav_error = nav_error
LOG.warning(
"Self-heal dead-nav escalation navigation failed; continuing from current page",
workflow_run_block_id=workflow_run_block_id,
@@ -7853,6 +7874,13 @@ async def wrapper({default_args}):
)
if trace is not None:
trace.escalation_task_id = escalation_task.task_id
+ # The recovery starts on the navigation it inherits: this hop's failure, else the block's own unless the
+ # hop got past it. Its loop drops the code once it acts on the page, so the heal reports the code only
+ # when the recovery ended on that navigation.
+ if escalation_nav_error is not None:
+ await record_task_nav_error_code(escalation_task.task_id, escalation_nav_error, escalation_url)
+ elif failed_nav_error_code and not escalation_navigated:
+ skyvern_context.ensure_context().task_nav_error_codes[escalation_task.task_id] = failed_nav_error_code
escalation_task = await app.DATABASE.tasks.update_task(
task_id=escalation_task.task_id,
organization_id=organization_id,
@@ -7901,11 +7929,19 @@ async def wrapper({default_args}):
finally:
current_context.task_id = previous_task_id
+ ended_on_nav_codes = _recorded_task_nav_error_codes(escalation_task.task_id, workflow_run_context)
updated_task = await app.DATABASE.tasks.get_task(
task_id=escalation_task.task_id, organization_id=organization_id
)
if updated_task is None or not updated_task.status.is_final():
- await self._fail_escalation_task(escalation_task, escalation_step, recovery_block_id, organization_id)
+ await self._fail_escalation_task(
+ escalation_task,
+ escalation_step,
+ recovery_block_id,
+ organization_id,
+ error_codes=_redact_codeblock_error_codes(ended_on_nav_codes, resolved_redaction_parameters)
+ or None,
+ )
return await self.build_block_result(
success=False,
failure_reason=_redact_codeblock_failure_text(
@@ -7916,6 +7952,8 @@ async def wrapper({default_args}):
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ error_codes=_redact_codeblock_error_codes(ended_on_nav_codes, resolved_redaction_parameters)
+ or None,
)
if updated_task.status == TaskStatus.completed and not _declared_output_satisfied(
@@ -7928,8 +7966,15 @@ async def wrapper({default_args}):
f"AI fallback completed without the values block {self.label} declares it returns",
resolved_redaction_parameters,
)
+ unsatisfied_nav_codes = (
+ _redact_codeblock_error_codes(ended_on_nav_codes, resolved_redaction_parameters) or None
+ )
await self._finalize_recovery_block(
- recovery_block_id, BlockStatus.failed, organization_id, failure_reason=unsatisfied_reason
+ recovery_block_id,
+ BlockStatus.failed,
+ organization_id,
+ failure_reason=unsatisfied_reason,
+ error_codes=unsatisfied_nav_codes,
)
return await self.build_block_result(
success=False,
@@ -7938,6 +7983,7 @@ async def wrapper({default_args}):
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ error_codes=unsatisfied_nav_codes,
)
if updated_task.status == TaskStatus.completed:
@@ -7962,8 +8008,14 @@ async def wrapper({default_args}):
updated_task.failure_reason or f"Self-heal escalation finished with status {updated_task.status}",
resolved_redaction_parameters,
)
+ # Driver codes ride behind the recovery's own codes because its sentence cannot name them. The
+ # recovery block repeats this failure_reason and is newer, so readers attribute codes from it.
await self._finalize_recovery_block(
- recovery_block_id, recovery_status, organization_id, failure_reason=recovery_failure_reason
+ recovery_block_id,
+ recovery_status,
+ organization_id,
+ failure_reason=recovery_failure_reason,
+ error_codes=_redact_codeblock_error_codes(ended_on_nav_codes, resolved_redaction_parameters) or None,
)
return await self.build_block_result(
success=False,
@@ -7972,7 +8024,13 @@ async def wrapper({default_args}):
status=recovery_status,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
- error_codes=_recovery_task_error_codes(updated_task, workflow_run_context),
+ error_codes=_redact_codeblock_error_codes(
+ _unique_error_codes(
+ _recovery_task_error_codes(updated_task, workflow_run_context), ended_on_nav_codes
+ ),
+ resolved_redaction_parameters,
+ )
+ or None,
)
except asyncio.CancelledError:
# CancelledError is BaseException, not Exception — finalize explicitly, then never swallow it.
@@ -8551,6 +8609,7 @@ async def wrapper({default_args}):
attempt_started_at: datetime | None = None,
redaction_parameters: dict[str, Any] | None = None,
download_claim_outcome: DownloadClaimOutcome | None = None,
+ failed_nav_error_code: str | None = None,
) -> BlockResult:
resolved_redaction_parameters = redaction_parameters or {}
staged_frame: _StagedFrame | None = None
@@ -8799,6 +8858,7 @@ async def wrapper({default_args}):
record_output_parameter=False,
redaction_parameters=resolved_redaction_parameters,
trace=trace,
+ failed_nav_error_code=failed_nav_error_code,
)
recovery_wall_clock_ms = int((monotonic() - recovery_started_at) * 1000)
await self._write_heal_episode_safe(
@@ -9247,6 +9307,14 @@ async def wrapper({default_args}):
if (value := scrub_secure_failure_fact(raw_value)) is not None
}
+ # A failed recovery reports the worker's code, not the runner's, so a dead site behind the
+ # proxy carries the sentinel onto the recovery block instead of blaming our egress.
+ recovery_nav_code = (
+ recording_page.last_failed_nav_error_code() if secure_failure.nav_error_code else None
+ )
+ if recovery_nav_code and is_registered_secret(recovery_nav_code, workflow_run_context):
+ recovery_nav_code = None
+
async def build_secure_failure_result() -> BlockResult:
engine_block_result = secure_code_block_result.block_result
if engine_block_result is not None:
@@ -9302,7 +9370,10 @@ async def wrapper({default_args}):
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
- error_codes=secure_error_codes or None,
+ error_codes=_redact_codeblock_error_codes(
+ secure_error_codes, serialized_parameter_values
+ )
+ or None,
)
return await self._resolve_failure_with_heal(
@@ -9310,6 +9381,7 @@ async def wrapper({default_args}):
failing_line=secure_failure.failing_line,
build_failure_result=build_secure_failure_result,
classification=secure_classification,
+ failed_nav_error_code=recovery_nav_code,
recorder=recorder,
workflow_run_context=workflow_run_context,
workflow_run_id=workflow_run_id,
@@ -9822,7 +9894,7 @@ async def wrapper({default_args}):
# This block catches its own failures, so the driver's code never reaches the
# wrapper that stamps it. A consumer reading only failure_reason cannot tell a
# real browser error from a sentence describing one.
- error_codes=driver_nav_codes,
+ error_codes=_redact_codeblock_error_codes(driver_nav_codes, serialized_parameter_values) or None,
)
return await self._resolve_failure_with_heal(
@@ -9830,6 +9902,7 @@ async def wrapper({default_args}):
failing_line=failing_line,
build_failure_result=build_legacy_failure_result,
classification=legacy_classification,
+ failed_nav_error_code=inline_nav_code,
recorder=recorder,
workflow_run_context=workflow_run_context,
workflow_run_id=workflow_run_id,
diff --git a/skyvern/forge/taskv3/auth_tools.py b/skyvern/forge/taskv3/auth_tools.py
index 931edad96..e39aeeceb 100644
--- a/skyvern/forge/taskv3/auth_tools.py
+++ b/skyvern/forge/taskv3/auth_tools.py
@@ -57,7 +57,7 @@ from skyvern.webeye.actions.handler import (
generate_totp_value_from_secret,
get_totp_secret_with_task,
)
-from skyvern.webeye.navigation import revalidate_redirect_chain
+from skyvern.webeye.navigation import record_task_nav_error_code, revalidate_redirect_chain
LOG = structlog.get_logger()
@@ -893,6 +893,8 @@ def build_auth_tools(
task_id=task.task_id,
error_type=type(exc).__name__,
)
+ if navigated:
+ await record_task_nav_error_code(task.task_id, exc, validated_url)
session_possible = False
failure_data: dict[str, Any] | None = None
if navigated:
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index e5e8864df..acce2c0a6 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -43,7 +43,7 @@ from skyvern.forge.taskv3.goal_check import (
)
from skyvern.forge.taskv3.handoff_redaction import MAX_HANDOFF_URL_CHARS, sanitize_published_url
from skyvern.forge.taskv3.target_label import describe_target
-from skyvern.webeye.navigation import redact_url_secrets
+from skyvern.webeye.navigation import clear_task_nav_error_code, redact_url_secrets
LOG = structlog.get_logger()
@@ -4102,6 +4102,10 @@ async def run_agent_tool_loop(
_COVERED_LAYER.set(None)
dispatch_ctx = skyvern_context.current()
runtime_secrets_before = len(dispatch_ctx.runtime_secret_values) if dispatch_ctx is not None else 0
+ # As in V1/V2, acting on the page again means an earlier navigation failure is no longer what the
+ # task ends on; reads and finish keep it, since a run that ends there ended on that navigation.
+ if spec is not None and spec.touches_page and dispatch_ctx is not None and dispatch_ctx.task_id:
+ clear_task_nav_error_code(dispatch_ctx.task_id)
tool_started_at = time.monotonic()
if spec is None:
result = ToolResult.error(f"unknown_tool: {tool_name}")
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index b52465092..4bc891786 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -88,7 +88,7 @@ from skyvern.forge.taskv3.target_label import TARGET_KIND_TOKENS, TARGET_NAME_CA
from skyvern.webeye.actions.key_names import normalize_key_chord
from skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_error
from skyvern.webeye.browser_state import BLANK_PAGE_URLS
-from skyvern.webeye.navigation import driver_nav_error_code, redact_url_secrets
+from skyvern.webeye.navigation import driver_nav_error_code, record_task_nav_error_code, redact_url_secrets
from skyvern.webeye.utils.challenge_signature import CHALLENGE_VENDOR_SIGNATURE
from skyvern.webeye.utils.page import OTP_INPUT_PRIVACY_JS, OTP_SAFE_FRAGMENT_HTML_JS, mask_otp_values_in_html
@@ -15467,6 +15467,10 @@ def build_browser_tools(
# through the loop's raise line instead of flattening into a cause-less navigation_failed.
if not is_driver_error(exc) and nav_error_code is None:
raise
+ # Kept for the task block's result, which reads the code by task id as it does for V1/V2.
+ nav_context = skyvern_context.current()
+ if nav_context is not None and nav_context.task_id:
+ await record_task_nav_error_code(nav_context.task_id, exc, url)
# Playwright names the URL that failed, which after a redirect is not the ref: every URL
# in the cause was reached by following the ref, so the model sees it as the token. A URL
# that was never a ref is reduced to scheme and host instead — the driver names it whole,
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index fad29f330..f8e284e1d 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -223,7 +223,11 @@ from skyvern.webeye.cdp_download_interceptor import (
settle_browser_downloads_for_context,
)
from skyvern.webeye.main_world_eval import evaluate_in_main_world
-from skyvern.webeye.navigation import reported_nav_error_code, revalidate_redirect_chain
+from skyvern.webeye.navigation import (
+ clear_task_nav_error_code,
+ record_task_nav_error_code,
+ revalidate_redirect_chain,
+)
from skyvern.webeye.scraper.scraped_page import (
CleanupElementTreeFunc,
ElementTreeBuilder,
@@ -4759,7 +4763,7 @@ class ActionHandler:
# code no longer describes the failure this task will report. Terminate and complete are the
# exception: they are how a task ends, so the navigation before them is what it ends on.
if action.action_type not in _TASK_ENDING_ACTION_TYPES:
- _clear_task_nav_error_code(task)
+ clear_task_nav_error_code(task.task_id)
# Hydrated/cached actions can arrive with a prior finished_at; clear it so the
# exceptional-exit fallback below stamps this execution, not the previous one.
action.finished_at = None
@@ -11148,35 +11152,6 @@ async def handle_left_mouse_action(
return [ActionSuccess()]
-async def _record_task_nav_error_code(task: Task, error: BaseException, url: str | None = None) -> None:
- """Keep the driver's code for a navigation action that failed.
-
- These actions call the driver directly, so their failure becomes an ``ActionFailure`` and never
- reaches the typed navigation error. Without this the code is gone by the time anything decides
- who owned the failure, and an egress fault reads as a defect in the run.
- """
- context = skyvern_context.current()
- if context is None:
- return
- # Dropped before the current attempt is read, not only on success: an attempt that reports no
- # code of its own would otherwise be judged on the one before it.
- context.task_nav_error_codes.pop(task.task_id, None)
- code = await reported_nav_error_code(error, url)
- if code:
- context.task_nav_error_codes[task.task_id] = code
-
-
-def _clear_task_nav_error_code(task: Task) -> None:
- """Drop a code kept from an earlier attempt once this task navigates successfully.
-
- A retry that succeeds leaves the failure behind it, so a later failure of a different kind would
- otherwise inherit the old code and be reported as a network fault.
- """
- context = skyvern_context.current()
- if context is not None:
- context.task_nav_error_codes.pop(task.task_id, None)
-
-
@traced(name="skyvern.agent.action.goto_url")
async def handle_goto_url_action(
action: actions.GotoUrlAction,
@@ -11190,9 +11165,9 @@ async def handle_goto_url_action(
response = await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
except Exception as navigation_error:
- await _record_task_nav_error_code(task, navigation_error, url=validated_url)
+ await record_task_nav_error_code(task.task_id, navigation_error, url=validated_url)
raise
- _clear_task_nav_error_code(task)
+ clear_task_nav_error_code(task.task_id)
# Navigation invalidates the current scraped page's element ids; stop the batch so the
# next step re-scrapes before any later actions run against the new DOM.
result = ActionSuccess()
@@ -11210,9 +11185,9 @@ async def handle_go_back_action(
try:
await page.go_back(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
except Exception as navigation_error:
- await _record_task_nav_error_code(task, navigation_error)
+ await record_task_nav_error_code(task.task_id, navigation_error)
raise
- _clear_task_nav_error_code(task)
+ clear_task_nav_error_code(task.task_id)
return [ActionSuccess()]
@@ -11226,9 +11201,9 @@ async def handle_go_forward_action(
try:
await page.go_forward(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
except Exception as navigation_error:
- await _record_task_nav_error_code(task, navigation_error)
+ await record_task_nav_error_code(task.task_id, navigation_error)
raise
- _clear_task_nav_error_code(task)
+ clear_task_nav_error_code(task.task_id)
return [ActionSuccess()]
@@ -11244,9 +11219,9 @@ async def handle_reload_page_action(
except Exception as navigation_error:
# Unlike back and forward, whose target is a history entry rather than this URL, a reload
# names the page it is on -- so the resolver can be asked about the right host.
- await _record_task_nav_error_code(task, navigation_error, url=page.url)
+ await record_task_nav_error_code(task.task_id, navigation_error, url=page.url)
raise
- _clear_task_nav_error_code(task)
+ clear_task_nav_error_code(task.task_id)
# Reloading re-renders the DOM and invalidates the scraped page's element ids; stop the
# batch so the next step re-scrapes before any later actions run.
result = ActionSuccess()
@@ -11325,7 +11300,7 @@ async def handle_new_tab_action(
try:
await browser_state.navigate_to_url(page=new_page, url=validated_url)
except Exception as e:
- await _record_task_nav_error_code(task, e, url=validated_url)
+ await record_task_nav_error_code(task.task_id, e, url=validated_url)
# Don't leave a blank/failed tab as the newest page — the next scrape would fail it.
try:
await new_page.close()
diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.py
index 5562f825d..46a1db1d5 100644
--- a/skyvern/webeye/navigation.py
+++ b/skyvern/webeye/navigation.py
@@ -23,6 +23,7 @@ from skyvern.exceptions import (
InvalidUrl,
UnresolvableNavigationHost,
)
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.utils.url_validators import canonical_navigation_host, host_has_no_address_record, is_blocked_host
LOG = structlog.get_logger()
@@ -211,6 +212,27 @@ async def reported_nav_error_code(error: BaseException, url: str | None) -> str
return code
+async def record_task_nav_error_code(task_id: str, error: BaseException, url: str | None = None) -> None:
+ """Keep the driver's code for a failed navigation the task chose. Action paths catch the driver's error
+ themselves, so without this an egress fault reads as a defect in the run."""
+ context = skyvern_context.current()
+ if context is None:
+ return
+ # Dropped before the current attempt is read, not only on success: an attempt that reports no
+ # code of its own would otherwise be judged on the one before it.
+ context.task_nav_error_codes.pop(task_id, None)
+ code = await reported_nav_error_code(error, url)
+ if code:
+ context.task_nav_error_codes[task_id] = code
+
+
+def clear_task_nav_error_code(task_id: str) -> None:
+ """Drop a kept code once the task acts again: the earlier failure is no longer what it ends on."""
+ context = skyvern_context.current()
+ if context is not None:
+ context.task_nav_error_codes.pop(task_id, None)
+
+
def redact_url_secrets(url: str) -> str:
"""Reduce a URL to scheme and host for display.
diff --git a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
index a9c732b46..f6e572eaa 100644
--- a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
+++ b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
@@ -1819,13 +1819,12 @@ async def test_update_and_run_blocks_fills_a_new_block_from_the_executed_source(
monkeypatch: pytest.MonkeyPatch,
reference_is_valid: bool,
) -> None:
- submitted_yaml = """workflow_definition:
- parameters: []
- blocks:
- - block_type: code
- label: extract_rows
- code: |
-"""
+ submitted_workflow = {
+ "workflow_definition": {
+ "parameters": [],
+ "blocks": [{"block_type": "code", "label": "extract_rows", "code": ""}],
+ }
+ }
candidate = 'rows = {"WC-101": "Ironclad"}\nreturn rows'
ctx = make_copilot_context("workflow_definition:\n parameters: []\n blocks: []\n")
reference = browser_code_module.retain_executed_browser_code_source(
@@ -1857,7 +1856,7 @@ async def test_update_and_run_blocks_fills_a_new_block_from_the_executed_source(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
json.dumps(
{
- "workflow_yaml": submitted_yaml,
+ "workflow": submitted_workflow,
"block_labels": ["extract_rows"],
"executed_source_references": {
"extract_rows": reference if reference_is_valid else "browser_code_source:not:a:real:one"
@@ -1868,7 +1867,6 @@ async def test_update_and_run_blocks_fills_a_new_block_from_the_executed_source(
if reference_is_valid:
assert json.loads(result)["ok"] is True
- # Exact bytes, from the empty block scalar a model writes when told to leave the code empty.
assert stored_block_code(persisted[0]["workflow_yaml"], "extract_rows") == candidate
assert persisted[0]["_expected_exact_code_by_label"] == {"extract_rows": candidate}
run_updated.assert_awaited_once()
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 1f1ee7fa5..f2b3f0060 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -2642,7 +2642,7 @@ workflow_definition:
result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": workflow_yaml, "block_labels": ["extract_entry_output"]}),
+ json.dumps({"workflow": safe_load_no_dates(workflow_yaml), "block_labels": ["extract_entry_output"]}),
)
parsed = json.loads(result)
@@ -2712,11 +2712,11 @@ workflow_definition:
)
result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": clean_yaml, "block_labels": ["submit"], "parameters": {}}),
+ json.dumps({"workflow": safe_load_no_dates(clean_yaml), "block_labels": ["submit"], "parameters": {}}),
)
assert json.loads(result)["ok"] is True
- assert captured["workflow_yaml"] == clean_yaml
+ assert safe_load_no_dates(captured["workflow_yaml"]) == safe_load_no_dates(clean_yaml)
assert captured["run_called"] is True
assert "Achieve the following mini goal" not in captured["workflow_yaml"]
@@ -2775,11 +2775,13 @@ workflow_definition:
ctx = _ctx(block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER)
result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": workflow_yaml, "block_labels": ["submit"], "parameters": {"file": "x"}}),
+ json.dumps(
+ {"workflow": safe_load_no_dates(workflow_yaml), "block_labels": ["submit"], "parameters": {"file": "x"}}
+ ),
)
assert json.loads(result)["ok"] is True
- assert captured["workflow_yaml"] == workflow_yaml
+ assert safe_load_no_dates(captured["workflow_yaml"]) == safe_load_no_dates(workflow_yaml)
assert captured["run_called"] is True
@@ -3056,7 +3058,7 @@ workflow_definition:
failed_run["data"]["blocks"][0]["output"]["failure_page_state"] = failure_page_state
async def fake_update_workflow(payload, ctx, **_kwargs):
- assert payload["workflow_yaml"] == self._SAVED_WORKFLOW
+ assert safe_load_no_dates(payload["workflow_yaml"]) == safe_load_no_dates(self._SAVED_WORKFLOW)
ctx.workflow_yaml = self._SAVED_WORKFLOW
ctx.last_workflow_yaml = self._SAVED_WORKFLOW
ctx.last_workflow = SimpleNamespace(workflow_definition={"blocks": []})
@@ -3107,7 +3109,7 @@ workflow_definition:
with capture_logs() as logs:
await tools_module.update_workflow_tool.on_invoke_tool(
SimpleNamespace(context=update_then_run_ctx, tool_name="update_workflow"),
- json.dumps({"workflow_yaml": self._SAVED_WORKFLOW}),
+ json.dumps({"workflow": safe_load_no_dates(self._SAVED_WORKFLOW)}),
)
update_then_run = await tools_module.run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=update_then_run_ctx, tool_name="run_blocks_and_collect_debug"),
@@ -3115,7 +3117,13 @@ workflow_definition:
)
combined = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=combined_ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": self._SAVED_WORKFLOW, "block_labels": ["read_total"], "parameters": {}}),
+ json.dumps(
+ {
+ "workflow": safe_load_no_dates(self._SAVED_WORKFLOW),
+ "block_labels": ["read_total"],
+ "parameters": {},
+ }
+ ),
)
edited = await tools_module.edit_block_and_run_tool.on_invoke_tool(
SimpleNamespace(context=edit_ctx, tool_name="edit_block_and_run"),
diff --git a/tests/unit/test_copilot_budget_drain.py b/tests/unit/test_copilot_budget_drain.py
index d6a9f9d75..dbdf29e00 100644
--- a/tests/unit/test_copilot_budget_drain.py
+++ b/tests/unit/test_copilot_budget_drain.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatSender,
)
+from skyvern.utils.yaml_loader import safe_load_no_dates
from tests.unit.copilot_test_helpers import make_copilot_ctx
@@ -164,10 +165,10 @@ workflow_definition:
result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": workflow_yaml, "block_labels": ["staged_step"], "parameters": {}}),
+ json.dumps({"workflow": safe_load_no_dates(workflow_yaml), "block_labels": ["staged_step"], "parameters": {}}),
)
- assert ctx.staged_workflow_yaml == workflow_yaml
+ assert safe_load_no_dates(ctx.staged_workflow_yaml) == safe_load_no_dates(workflow_yaml)
assert ctx.has_staged_proposal is True
assert json.loads(result) == {
"ok": False,
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index 3783fbc64..f18fc6c35 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -50,6 +50,7 @@ from skyvern.forge.sdk.copilot.workflow_yaml import (
stored_workflow_yaml,
)
from skyvern.forge.sdk.services.google_oauth_service import GOOGLE_SHEETS_DATA_SCOPE
+from skyvern.utils.yaml_loader import safe_load_no_dates
from tests.unit._copilot_workflow_fakes import fake_workflow
@@ -1122,7 +1123,8 @@ _RETYPED_BY_SINGLE_CODE_WRITE = {"read_support_contact": {"from": "task", "to":
async def _public_update(monkeypatch: pytest.MonkeyPatch, ctx: CopilotContext, submitted: str) -> dict[str, object]:
monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", AsyncMock(return_value=None))
raw = await tools_module.update_workflow_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_workflow"), json.dumps({"workflow_yaml": submitted})
+ SimpleNamespace(context=ctx, tool_name="update_workflow"),
+ json.dumps({"workflow": safe_load_no_dates(submitted)}),
)
return json.loads(raw)
diff --git a/tests/unit/test_copilot_code_safety_repair_outcome.py b/tests/unit/test_copilot_code_safety_repair_outcome.py
index 5f2905a9f..a0bea2a1c 100644
--- a/tests/unit/test_copilot_code_safety_repair_outcome.py
+++ b/tests/unit/test_copilot_code_safety_repair_outcome.py
@@ -16,6 +16,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import scrub_all_registered_from_tex
from skyvern.forge.sdk.copilot.tools import workflow_update as workflow_update_module
from skyvern.forge.sdk.copilot.tools.workflow_update import _update_workflow
from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yaml
+from skyvern.utils.yaml_loader import safe_load_no_dates
pytestmark = pytest.mark.usefixtures("no_saved_workflow")
@@ -312,7 +313,7 @@ async def test_safe_helper_arm_persists_and_reaches_test_run(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
json.dumps(
{
- "workflow_yaml": _SAFE_HELPER_YAML,
+ "workflow": safe_load_no_dates(_SAFE_HELPER_YAML),
"block_labels": ["download_result"],
"parameters": {},
}
@@ -321,8 +322,8 @@ async def test_safe_helper_arm_persists_and_reaches_test_run(
parsed_result = json.loads(result)
assert parsed_result["ok"] is True, parsed_result.get("error")
- assert ctx.workflow_yaml == _SAFE_HELPER_YAML
+ assert safe_load_no_dates(ctx.workflow_yaml) == safe_load_no_dates(_SAFE_HELPER_YAML)
assert ctx.has_staged_proposal is True
assert len(run_calls) == 1
- assert run_calls[0]["workflow_yaml"] == _SAFE_HELPER_YAML
+ assert run_calls[0]["workflow_yaml"] == ctx.workflow_yaml
assert run_calls[0]["params"] == {"block_labels": ["download_result"], "parameters": {}}
diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.py
index fe9edf06b..3181a5a7d 100644
--- a/tests/unit/test_copilot_credential_pause.py
+++ b/tests/unit/test_copilot_credential_pause.py
@@ -2046,7 +2046,7 @@ _RUN_TOOLS_GATED_ON_AN_OPEN_ASK = [
"parameters": {},
},
),
- ("update_and_run_blocks", {"workflow_yaml": "title: draft", "block_labels": ["login"], "parameters": {}}),
+ ("update_and_run_blocks", {"workflow": {"title": "draft"}, "block_labels": ["login"], "parameters": {}}),
]
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index 171b05817..a1be8dc0b 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -49,6 +49,7 @@ from skyvern.forge.sdk.copilot.tools import (
)
from skyvern.forge.sdk.copilot.tools.run_execution import _watchdog_error_message
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
+from skyvern.utils.yaml_loader import safe_load_no_dates
# Assembled at runtime so the source never contains a token-shaped literal for secret scanners to flag.
_FAKE_OPENAI_KEY = "sk-" + string.ascii_lowercase[:24]
@@ -1878,6 +1879,36 @@ workflow_definition:
assert ctx.failed_tool_step_tracker == {"sentinel": 2}
+async def test_sdk_input_guardrail_blocks_a_workflow_object_that_moves_a_credential_to_a_new_origin() -> None:
+ ctx = _ctx(
+ request_policy=_policy(
+ resolved_credentials=[],
+ existing_workflow_credential_ids=["cred_safe"],
+ existing_workflow_credential_origins={"cred_safe": ["https://login.example.test"]},
+ credential_input_kind="none",
+ )
+ )
+ arguments = json.dumps(
+ {
+ "workflow": safe_load_no_dates(_workflow_yaml(url="https://evil.example.test/login")),
+ "block_labels": ["login"],
+ }
+ )
+
+ result = await _WORKFLOW_YAML_OUTPUT_POLICY_GUARDRAIL.run(
+ ToolInputGuardrailData(
+ context=ToolContext(
+ context=ctx, tool_name="update_and_run_blocks", tool_call_id="call-cred", tool_arguments=arguments
+ ),
+ agent=SimpleNamespace(),
+ )
+ )
+
+ assert result.behavior["type"] == "reject_content"
+ assert OutputPolicyReason.CREDENTIAL_SCOPE_BROADENED.value in result.behavior["message"]
+
+
@pytest.mark.asyncio
async def test_allowed_sdk_input_guardrail_does_not_record_consecutive_boundary() -> None:
ctx = _ctx()
diff --git a/tests/unit/test_copilot_sdk_argument_failures.py b/tests/unit/test_copilot_sdk_argument_failures.py
index f04bd6d86..4bd0e2044 100644
--- a/tests/unit/test_copilot_sdk_argument_failures.py
+++ b/tests/unit/test_copilot_sdk_argument_failures.py
@@ -78,7 +78,7 @@ async def invoke(arguments: str, ctx: CopilotContext) -> Any:
@pytest.mark.parametrize("metadata", ["<metadata truncated: 11234 chars>", "<metadata truncated: 11615 chars>"])
async def test_rejected_arguments_and_corrected_retry(handler_boundary: SimpleNamespace, metadata: str) -> None:
ctx = make_copilot_ctx()
- arguments = {"workflow_yaml": "title: Example", "block_labels": ["example"], "code_artifact_metadata": metadata}
+ arguments = {"workflow": {"title": "Example"}, "block_labels": ["example"], "code_artifact_metadata": metadata}
output = await invoke(json.dumps(arguments), ctx)
parsed = parse_tool_output(output)
assert parsed["ok"] is False
@@ -115,7 +115,7 @@ async def test_rejected_arguments_and_corrected_retry(handler_boundary: SimpleNa
async def test_handler_results_are_preserved(handler_boundary: SimpleNamespace, output: str) -> None:
handler_boundary.execute.return_value = output
ctx = make_copilot_ctx()
- arguments = json.dumps({"workflow_yaml": "title: Example", "block_labels": ["example"]})
+ arguments = json.dumps({"workflow": {"title": "Example"}, "block_labels": ["example"]})
actual = await invoke(arguments, ctx)
assert actual == output
handler_boundary.entered.assert_awaited_once()
@@ -125,7 +125,7 @@ async def test_handler_results_are_preserved(handler_boundary: SimpleNamespace,
@pytest.mark.asyncio
[email protected]("arguments", ['{"workflow_yaml": "unregistered-sensitive-value",', '{"block_labels": []}'])
[email protected]("arguments", ['{"workflow": "unregistered-sensitive-value",', '{"block_labels": []}'])
async def test_malformed_or_missing_arguments_do_not_echo_input(
handler_boundary: SimpleNamespace, arguments: str
) -> None:
@@ -141,7 +141,7 @@ async def test_exception_details_scrub_registered_secrets(handler_boundary: Simp
secret = "private-runtime-value"
register_secret_scrub_value(ctx, secret)
handler_boundary.execute.side_effect = RuntimeError(f"Execution rejected {secret}")
- arguments = json.dumps({"workflow_yaml": "title: Example", "block_labels": ["example"]})
+ arguments = json.dumps({"workflow": {"title": "Example"}, "block_labels": ["example"]})
output = await invoke(arguments, ctx)
assert parse_tool_output(output)["ok"] is False
assert secret not in output
diff --git a/tests/unit/test_copilot_secret_scrub.py b/tests/unit/test_copilot_secret_scrub.py
index db2ae72cf..eb1d4dd43 100644
--- a/tests/unit/test_copilot_secret_scrub.py
+++ b/tests/unit/test_copilot_secret_scrub.py
@@ -34,6 +34,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
scrub_secrets_from_text,
)
from skyvern.forge.sdk.copilot.workflow_yaml import redact_credentials_in_workflow_yaml
+from skyvern.utils.yaml_loader import dump_workflow_yaml, safe_load_no_dates
from tests.unit.copilot_test_helpers import make_model_input_data
_FAKE_PASSWORD = "fake-pa55w0rd-7x9"
@@ -351,6 +352,29 @@ class TestPersistenceSeam:
assert _FAKE_PASSWORD not in redacted
assert REDACTED_SECRET_PLACEHOLDER in redacted
+ @pytest.mark.parametrize(
+ "secret",
+ [
+ "a: b 'c' \"d\"",
+ "tab\tsecret1",
+ "bell\x07secret",
+ 'pa"ss: word1',
+ "multi\nline secret",
+ "gap\n\n indented",
+ "ends with newline\n",
+ ],
+ )
+ def test_redacts_a_credential_the_serializer_quoted(self, secret: str) -> None:
+ workflow_yaml = dump_workflow_yaml(
+ {"workflow_definition": {"blocks": [{"block_type": "code", "description": secret, "label": "x"}]}}
+ )
+
+ redacted = redact_credentials_in_workflow_yaml(workflow_yaml, "wpid_1", [secret])
+
+ block = safe_load_no_dates(redacted)["workflow_definition"]["blocks"][0]
+ assert block["description"].rstrip("\n") == REDACTED_SECRET_PLACEHOLDER
+ assert block["label"] == "x"
+
def test_a_value_that_looks_like_the_placeholder_is_still_redacted(self) -> None:
"""A password is an arbitrary string, including one that overlaps our own marker."""
for secret in ("REDACTED_SECRET", f"prefix{REDACTED_SECRET_PLACEHOLDER}suffix"):
diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.py
index 9924d4d01..803c73824 100644
--- a/tests/unit/test_copilot_streaming_adapter.py
+++ b/tests/unit/test_copilot_streaming_adapter.py
@@ -32,10 +32,13 @@ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotStreamMess
from tests.unit.copilot_test_helpers import FakeCopilotStream
-def test_strips_workflow_yaml() -> None:
- result = _sanitize_input({"workflow_yaml": "title: x", "block_labels": ["a"]})
- assert "workflow_yaml" not in result
- assert result["block_labels"] == ["a"]
+ ("key", "definition"),
+ [("workflow", {"title": "x"}), ("block", {"block_type": "code", "label": "a"}), ("workflow_yaml", "title: x")],
+)
+def test_strips_submitted_definition(key: str, definition: dict[str, str] | str) -> None:
+ result = _sanitize_input({key: definition, "block_labels": ["a"]})
+ assert result == {"block_labels": ["a"]}
def test_redacts_password_in_parameters() -> None:
@@ -1432,9 +1435,15 @@ def _codegen_payloads(sent: list[Any]) -> list[Any]:
async def test_codegen_progress_pins_incremental_label_extraction_on_raw_deltas() -> None:
"""Regression pin: fails on old code because RawResponsesStreamEvent is dropped at the
``isinstance(event, RunItemStreamEvent)`` skip, so zero CODEGEN_PROGRESS frames are ever sent."""
- delta1 = '{"workflow_yaml": "blocks:\\n- block_type: navigation\\n label: open_page\\n'
- delta2 = " navigation_goal: Navigate to the page\\n- block_type: task\\n label: fill_form\\n"
- delta3 = ' navigation_goal: Fill out the form\\n"'
+ delta1 = (
+ '{"workflow": {"workflow_definition": {"blocks": [{"block_type": "navigation", "label": "open_page", '
+ '"next_block_label": "branch_target", '
+ )
+ delta2 = (
+ '"navigation_goal": "Navigate to the page"}, {"block_type": "task", "label": "fill_form", '
+ '"next_block_label": null, '
+ )
+ delta3 = '"navigation_goal": "Fill out the form"}]}}'
delta4 = ', "block_labels": ["open_page", "fill_form"]}'
full_args = delta1 + delta2 + delta3 + delta4
@@ -1506,6 +1515,37 @@ async def test_codegen_progress_does_not_leak_truncated_label_split_across_delta
assert any(p.blocks_drafted == ["open_page"] for p in codegen_payloads)
+async def test_codegen_progress_does_not_report_the_block_edit_block_and_run_targets() -> None:
+ args = '{"label": "extract_totals", "code": "rows = []\\nreturn rows"}'
+ events = [
+ _item_added_event(0, "edit_block_and_run"),
+ _args_delta_event(0, args),
+ _args_done_event(0, args, "edit_block_and_run"),
+ _item_done_event(0, "edit_block_and_run", args),
+ ]
+
+ result = MagicMock()
+ result.stream_events = lambda: _stream_events_from(*events)
+ result.cancel = MagicMock()
+
+ sent: list[Any] = []
+
+ async def _send(payload: Any) -> bool:
+ sent.append(payload)
+ return True
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+ stream.send = _send
+
+ await stream_to_sse(result, stream, _new_ctx())
+
+ codegen_payloads = _codegen_payloads(sent)
+ assert codegen_payloads
+ assert all(p.blocks_drafted == [] for p in codegen_payloads)
+
+
@pytest.mark.asyncio
async def test_codegen_progress_throttles_no_new_label_deltas_then_emits_keepalive(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_copilot_workflow_update.py b/tests/unit/test_copilot_workflow_update.py
index 175afdd38..057d3354f 100644
--- a/tests/unit/test_copilot_workflow_update.py
+++ b/tests/unit/test_copilot_workflow_update.py
@@ -8,11 +8,14 @@ from unittest.mock import AsyncMock
import pytest
import yaml
+from agents import FunctionTool
+from agents.tool_context import ToolContext
from pydantic import ValidationError
from structlog.testing import capture_logs
from skyvern.exceptions import WorkflowNotFound
from skyvern.forge import app
+from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot import workflow_yaml as workflow_yaml_module
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import CopilotContext
@@ -26,10 +29,11 @@ from skyvern.forge.sdk.copilot.tools.workflow_update import (
_update_workflow,
carry_author_time_findings,
)
-from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml, apply_block_edit
+from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml, apply_block_edit, tool_call_submitted_yaml
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition
from skyvern.schemas.runs import ProxyLocation
from skyvern.schemas.workflows import WorkflowCreateYAMLRequest, WorkflowStatus
+from tests.unit.copilot_test_helpers import make_copilot_ctx
_SETTING_VALUES: dict[str, tuple[Any, Any]] = {
"is_saved_task": (True, False),
@@ -665,3 +669,135 @@ async def test_workflow_write_preserves_label_equal_to_private_value(
assert block.totp_identifier == private_value
assert block.totp_verification_url == private_url
assert yaml.safe_load(ctx.workflow_yaml)["workflow_definition"]["blocks"][0]["label"] == private_value
+
+
+_PUNCTUATED_TITLE = 'Member directory: "Page 3" export'
+_PUNCTUATED_DESCRIPTION = "Collect each ID: name pair, keep 'quoted' text\nand a second line: as written."
+_MULTILINE_CODE = 'status = "Status: active" \n\nrows = {"key": \'value: x\'}\nreturn {"output": rows}\n'
+
+
+def _first_submission(block_type: str = "code") -> dict[str, Any]:
+ return {
+ "title": _PUNCTUATED_TITLE,
+ "description": _PUNCTUATED_DESCRIPTION,
+ "workflow_definition": {
+ "parameters": [],
+ "blocks": [{"block_type": block_type, "label": "collect_members", "code": _MULTILINE_CODE}],
+ },
+ }
+
+
+def _authoring_ctx(workflow_yaml: str = "") -> CopilotContext:
+ ctx = make_copilot_ctx(workflow_yaml=workflow_yaml, stream=None)
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.request_policy = RequestPolicy(allow_update_workflow=True, allow_run_blocks=True)
+ ctx.google_connection_turn_start_bindings = ()
+ return ctx
+
+
+async def _invoke(tool: FunctionTool, ctx: CopilotContext, arguments: dict[str, Any]) -> dict[str, Any]:
+ raw_arguments = json.dumps(arguments)
+ raw = await tool.on_invoke_tool(
+ ToolContext(context=ctx, tool_name=tool.name, tool_call_id="call_submit", tool_arguments=raw_arguments),
+ raw_arguments,
+ )
+ return json.loads(raw)
+
+
+def dispatch(monkeypatch: pytest.MonkeyPatch, no_saved_workflow: None) -> AsyncMock:
+ monkeypatch.setattr(workflow_update_module, "_get_prior_workflow", AsyncMock(return_value=None))
+ run = AsyncMock(return_value=json.dumps({"ok": True, "data": {"workflow_run_id": "wr_first"}}))
+ monkeypatch.setattr(tools_module, "_run_updated_workflow_blocks", run)
+ return run
+
+
+async def test_first_submission_persists_punctuated_values_and_exact_code_then_dispatches_once(
+ dispatch: AsyncMock,
+) -> None:
+ submitted = _first_submission()
+ ctx = _authoring_ctx()
+
+ result = await _invoke(
+ tools_module.update_and_run_blocks_tool, ctx, {"workflow": submitted, "block_labels": ["collect_members"]}
+ )
+
+ assert result["ok"] is True, result
+ dispatch.assert_awaited_once()
+ saved = ctx.staged_workflow
+ assert saved is not None
+ assert (saved.title, saved.description) == (_PUNCTUATED_TITLE, _PUNCTUATED_DESCRIPTION)
+ assert saved.workflow_definition.blocks[0].code.encode() == _MULTILINE_CODE.encode()
+
+
+async def test_first_submission_of_an_ordinary_workflow_persists_and_dispatches_once(dispatch: AsyncMock) -> None:
+ submitted = {
+ "title": "Member directory export",
+ "workflow_definition": {
+ "parameters": [],
+ "blocks": [{"block_type": "code", "label": "collect_members", "code": 'return {"output": 1}'}],
+ },
+ }
+ ctx = _authoring_ctx()
+
+ result = await _invoke(
+ tools_module.update_and_run_blocks_tool, ctx, {"workflow": submitted, "block_labels": ["collect_members"]}
+ )
+
+ assert result["ok"] is True, result
+ dispatch.assert_awaited_once()
+ assert ctx.staged_workflow is not None
+ assert ctx.staged_workflow.title == "Member directory export"
+
+
+async def test_first_submission_with_an_unknown_block_type_keeps_its_validation_error(dispatch: AsyncMock) -> None:
+ invalid = _first_submission(block_type="not_a_block_type")
+ expected = await _update_workflow({"workflow_yaml": yaml.safe_dump(invalid, sort_keys=False)}, _authoring_ctx())
+ ctx = _authoring_ctx()
+
+ result = await _invoke(
+ tools_module.update_and_run_blocks_tool, ctx, {"workflow": invalid, "block_labels": ["collect_members"]}
+ )
+
+ assert result["ok"] is False
+ assert result["error"] == expected["error"]
+ assert ctx.has_staged_proposal is False
+ assert ctx.staged_workflow is None
+ dispatch.assert_not_awaited()
+
+
+async def test_add_block_splices_a_punctuated_multiline_block(dispatch: AsyncMock) -> None:
+ ctx = _authoring_ctx(yaml.safe_dump(_first_submission(), sort_keys=False))
+ new_block = {"block_type": "code", "label": "report_members", "code": _MULTILINE_CODE}
+
+ result = await _invoke(tools_module.add_block_tool, ctx, {"after_label": "collect_members", "block": new_block})
+
+ assert result["ok"] is True, result
+ assert ctx.staged_workflow is not None
+ spliced = ctx.staged_workflow.workflow_definition.blocks[1]
+ assert (spliced.label, spliced.code) == ("report_members", _MULTILINE_CODE)
+
+
+def test_workflow_write_tools_take_objects_not_yaml_strings() -> None:
+ for tool, field in (
+ (tools_module.update_workflow_tool, "workflow"),
+ (tools_module.update_and_run_blocks_tool, "workflow"),
+ (tools_module.add_block_tool, "block"),
+ ):
+ properties = tool.params_json_schema["properties"]
+ assert properties[field]["type"] == "object"
+ assert "workflow_yaml" not in properties
+ assert "block_yaml" not in properties
+
+
+def test_submitted_yaml_reads_a_structured_definition_before_any_legacy_string() -> None:
+ workflow = {"title": "Member directory", "definition": {"blocks": []}}
+ stale_yaml = "title: Old workflow"
+
+ submitted = tool_call_submitted_yaml({"workflow_yaml": stale_yaml, "workflow": workflow})
+
+ assert yaml.safe_load(submitted) == workflow
diff --git a/tests/unit/test_taskv3_auth_tools.py b/tests/unit/test_taskv3_auth_tools.py
index 9039788a4..8e7c5ca62 100644
--- a/tests/unit/test_taskv3_auth_tools.py
+++ b/tests/unit/test_taskv3_auth_tools.py
@@ -14,6 +14,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from structlog.testing import capture_logs
+import skyvern.webeye.navigation as navigation_module
from skyvern.exceptions import (
BlockedHost,
FailedToGetTOTPVerificationCode,
@@ -1407,6 +1408,30 @@ async def test_open_verification_link_consumes_the_link_so_the_next_call_polls_f
assert leak not in first.content and leak not in str(logs)
+async def test_open_verification_link_keeps_the_driver_code_through_the_return_navigation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The return navigation that puts the tab back is cleanup, not the navigation the task chose, so its
+ # success must not wipe the code of the link that failed.
+ monkeypatch.setattr(auth_tools, "resolve_otp_value", AsyncMock(return_value=OTPValue(value=_LINK, type=None)))
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: False)
+ page = _FakePage(
+ goto_error=Exception(f"net::ERR_TUNNEL_CONNECTION_FAILED at {_LINK}"),
+ url_after_goto_error="https://example.test/interstitial",
+ )
+ handlers = _link_tools(page)
+ context = SkyvernContext(task_id="tsk_1")
+ skyvern_context.set(context)
+ try:
+ result = await handlers["open_verification_link"]({})
+ finally:
+ skyvern_context.reset()
+ assert result.status == "error"
+ assert page.goto_calls[:2] == [_LINK, "https://app.test/login"]
+ assert context.task_nav_error_codes == {"tsk_1": "net::ERR_TUNNEL_CONNECTION_FAILED"}
+
+
@pytest.mark.asyncio
async def test_open_verification_link_navigation_failure_restores_the_page_and_spends_the_link(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 4c789f499..c70700a0e 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -274,6 +274,42 @@ async def test_finish_terminates_with_status_and_output() -> None:
assert observe_calls == [("observe", {})]
[email protected](("next_tool", "code_kept"), [("observe", True), ("click", False)])
+async def test_a_failed_navigation_code_survives_reads_but_not_a_later_action(next_tool: str, code_kept: bool) -> None:
+ async def _navigate_into_the_proxy(args: dict[str, Any]) -> ToolResult:
+ context = skyvern_context.current()
+ assert context is not None
+ context.task_nav_error_codes["tsk_v3"] = "net::ERR_TUNNEL_CONNECTION_FAILED"
+ return ToolResult.error("navigation failed")
+
+ navigate = ToolSpec(
+ name="navigate",
+ description="navigate",
+ parameters={"type": "object", "properties": {}},
+ handler=_navigate_into_the_proxy,
+ recordable=True,
+ )
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ navigate,
+ _recording_tool("observe", calls),
+ _recording_tool("click", calls, billable=True),
+ make_finish_tool(),
+ ]
+ script = [
+ [("navigate", {})],
+ [(next_tool, {})],
+ [("finish", {"status": "terminated", "reason": "unreachable"})],
+ ]
+ with skyvern_context.scoped(SkyvernContext(task_id="tsk_v3")) as context:
+ outcome, _ = await _run(script, tools)
+
+ assert outcome.status == "terminated"
+ assert calls == [(next_tool, {})]
+ assert ("tsk_v3" in context.task_nav_error_codes) is code_kept
+
+
@pytest.mark.asyncio
async def test_perception_is_on_demand_never_injected() -> None:
observe_calls: list[tuple[str, dict[str, Any]]] = []
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 60649ecec..43a637aad 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -19,7 +19,7 @@ from datetime import UTC, datetime
from html import escape as html_escape
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Awaitable, Callable
+from typing import Any, Awaitable, Callable, NoReturn
from unittest.mock import AsyncMock
import pyotp
@@ -34,12 +34,15 @@ from structlog.testing import capture_logs
import skyvern.forge.taskv3.loop as taskv3_loop
import skyvern.forge.taskv3.tools as taskv3_tools
+import skyvern.webeye.navigation as navigation_module
from skyvern.config import settings
+from skyvern.exceptions import NO_ADDRESS_RECORD_NAV_ERROR_CODE
from skyvern.forge import app
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.services import credentials as credentials_module
from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager, WorkflowRunContext
+from skyvern.forge.sdk.workflow.models.block import _recorded_task_nav_error_codes
from skyvern.forge.sdk.workflow.models.credential_release import (
CodeBlockCredentialReleaseError,
CredentialReleaseGuard,
@@ -1062,6 +1065,36 @@ async def test_navigate_that_never_commits_is_an_error_naming_the_url(monkeypatc
assert "net::ERR_CONNECTION_CLOSED at https://app.example.test/<redacted>" in secret.content
+ ("host_is_dead", "expected_code"),
+ [(False, "net::ERR_TUNNEL_CONNECTION_FAILED"), (True, NO_ADDRESS_RECORD_NAV_ERROR_CODE)],
+)
+async def test_navigate_failure_code_reaches_the_task_block(
+ monkeypatch: pytest.MonkeyPatch, host_is_dead: bool, expected_code: str
+) -> None:
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: host_is_dead)
+ page, tools = _readiness_tools(monkeypatch, "complete")
+
+ async def _tunnel_refused(url: str, timeout: int | None = None, wait_until: str | None = None) -> NoReturn:
+ raise _PlaywrightError(f"Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at {url}")
+
+ run_context = WorkflowRunContext(
+ workflow_title="t",
+ workflow_id="w_nav",
+ workflow_permanent_id="wp_nav",
+ workflow_run_id="wr_nav",
+ aws_client=None,
+ )
+ navigate = _tool(tools, "navigate").handler
+ with skyvern_context.scoped(SkyvernContext(task_id="tsk_v3")):
+ page.goto = _tunnel_refused # type: ignore[assignment]
+ failed = await navigate({"url": "https://jobs.example.test/acme/123"})
+ assert failed.status == "error", failed.content
+ assert (failed.data or {}).get("nav_error_code") == "net::ERR_TUNNEL_CONNECTION_FAILED"
+ assert _recorded_task_nav_error_codes("tsk_v3", run_context) == [expected_code]
+
+
@pytest.mark.asyncio
async def test_navigate_logs_the_landing_host_only_however_the_url_was_reached(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_workflow_copilot_prompt_rewrite.py b/tests/unit/test_workflow_copilot_prompt_rewrite.py
index cdda5d07c..f109231cf 100644
--- a/tests/unit/test_workflow_copilot_prompt_rewrite.py
+++ b/tests/unit/test_workflow_copilot_prompt_rewrite.py
@@ -181,6 +181,8 @@ def test_code_block_schema_guidance_states_the_runtime_without_prescribing_a_pro
assert "no `import` statements" in rendered
assert "derive a typed `extraction_schema`" in rendered
assert "ASK_QUESTION to confirm" not in rendered
+ assert "`workflow` object" in rendered
+ assert "YAML" not in rendered
def test_rendered_prompt_keeps_security_ask_telemetry_and_workflow_wide_edit_scope() -> None:
diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.py
index 07420129c..3782773db 100644
--- a/tests/unit/workflow/test_code_block_escalation.py
+++ b/tests/unit/workflow/test_code_block_escalation.py
@@ -19,17 +19,23 @@ import pytest
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from structlog.testing import capture_logs
+import skyvern.webeye.navigation as navigation_module
from skyvern.errors.errors import UserDefinedError
from skyvern.exceptions import NO_ADDRESS_RECORD_NAV_ERROR_CODE
from skyvern.forge import app
from skyvern.forge.agent_functions import CodeBlockEngineFailure, CodeBlockEngineResult
from skyvern.forge.sdk.api.llm.schema_validator import validate_and_fill_extraction_result, validate_schema
+from skyvern.forge.sdk.copilot.nav_attribution import (
+ block_nav_error_codes,
+ proxy_owns_nav_codes,
+ target_owns_nav_codes,
+)
from skyvern.forge.sdk.copilot.reached_download_target import REGISTERED_DOWNLOAD_OUTPUT_KEYS
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.repositories.workflow_runs import WorkflowRunsRepository
from skyvern.forge.sdk.schemas.files import FileInfo
-from skyvern.forge.sdk.schemas.tasks import TaskStatus
+from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
from skyvern.forge.sdk.workflow.models.block import (
BlockResult,
@@ -54,6 +60,7 @@ from skyvern.schemas.self_heal import HealClassification, HealSkipReason, HealSt
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action
from skyvern.webeye.browser_artifacts import BrowserArtifacts
+from skyvern.webeye.navigation import clear_task_nav_error_code, record_task_nav_error_code
SECRET_VALUE = "hunter2-super-secret"
SHORT_SECRET_VALUE = "abc"
@@ -3649,6 +3656,385 @@ async def test_recovery_error_codes_reach_the_block_result(
assert result.error_codes == ["account_locked"]
+async def _resolve_failed_heal(
+ block: CodeBlock, context: WorkflowRunContext, failed_nav_error_code: str | None, state: dict[str, Any]
+) -> tuple[BlockResult, list[str]]:
+ exception = PlaywrightTimeoutError("timeout")
+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())
+
+ async def _build_failure() -> BlockResult:
+ raise AssertionError("a heal that fired reports its own result")
+
+ with skyvern_context.scoped(SkyvernContext(organization_id="o_test", workflow_run_id="wr_test")):
+ result = await block._resolve_failure_with_heal(
+ exception=exception,
+ failing_line=1,
+ build_failure_result=_build_failure,
+ classification=HealClassification(healable=True, skip_reason=None),
+ recorder=recorder,
+ workflow_run_context=context,
+ workflow_run_id="wr_test",
+ workflow_run_block_id="wrb_test",
+ organization_id="o_test",
+ browser_session_id=None,
+ browser_state=_browser_state(),
+ page=MagicMock(),
+ failed_nav_error_code=failed_nav_error_code,
+ )
+ # The recovery block is persisted after the code block, so the reader sees it as the newer one.
+ recovery_block: dict[str, Any] = {}
+ for update in state["recovery_block_updates"]:
+ recovery_block.update({key: update.get(key) for key in ("failure_reason", "error_codes")})
+ blocks = [{"failure_reason": result.failure_reason, "error_codes": result.error_codes}, recovery_block]
+ return result, block_nav_error_codes({"data": {"blocks": blocks}}, result.failure_reason)
+
+
+ "driver_code", ["net::ERR_NAME_NOT_RESOLVED", "net::ERR_CERT_DATE_INVALID", NO_ADDRESS_RECORD_NAV_ERROR_CODE]
+)
+async def test_failed_recovery_keeps_the_driver_nav_code_behind_its_own_codes(
+ monkeypatch: pytest.MonkeyPatch,
+ ai_fallback_flag: Callable[[str | None], None],
+ driver_code: str,
+) -> None:
+ ai_fallback_flag("o_test")
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.failed)
+ state["updated_task"].errors = [{"error_code": "account_locked", "reasoning": "x", "confidence_float": 1.0}]
+ state["updated_task"].failure_reason = "The site is unreachable"
+ block = _make_code_block(error_code_mapping={"account_locked": "The account is locked"})
+
+ result, codes = await _resolve_failed_heal(block, _make_context(), driver_code, state)
+
+ assert result.success is False
+ assert state["heal_episodes"][0]["status"] == HealStatus.fired_failed
+ assert result.error_codes == ["account_locked", driver_code]
+ assert codes == [driver_code]
+ assert target_owns_nav_codes(codes) is True
+ assert proxy_owns_nav_codes(codes) is False
+
+
[email protected]("block_code", [None, "net::ERR_NAME_NOT_RESOLVED"])
+async def test_failed_recovery_reports_the_code_of_its_own_failed_navigation(
+ monkeypatch: pytest.MonkeyPatch, ai_fallback_flag: Callable[[str | None], None], block_code: str | None
+) -> None:
+ ai_fallback_flag("o_test")
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.failed)
+ state["updated_task"].failure_reason = "The site is unreachable"
+
+ async def _recovery_navigates_into_the_proxy(*args: object, task: Task, **kwargs: object) -> None:
+ context = skyvern_context.current()
+ assert context is not None
+ context.task_nav_error_codes[task.task_id] = "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+ monkeypatch.setattr(app.agent, "execute_step", AsyncMock(side_effect=_recovery_navigates_into_the_proxy))
+
+ result, codes = await _resolve_failed_heal(_make_code_block(), _make_context(), block_code, state)
+
+ # The recovery's navigation is what the heal ended on, so an earlier target code does not veto it.
+ assert result.error_codes == ["net::ERR_TUNNEL_CONNECTION_FAILED"]
+ assert codes == ["net::ERR_TUNNEL_CONNECTION_FAILED"]
+ assert proxy_owns_nav_codes(codes) is True
+
+
+ ("hop_refused", "expected_codes"), [(True, ["net::ERR_TUNNEL_CONNECTION_FAILED"]), (False, None)]
+)
+async def test_the_escalation_hop_before_the_recovery_runs_decides_what_the_heal_reports(
+ monkeypatch: pytest.MonkeyPatch,
+ ai_fallback_flag: Callable[[str | None], None],
+ hop_refused: bool,
+ expected_codes: list[str] | None,
+) -> None:
+ ai_fallback_flag("o_test")
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: False)
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.failed)
+ state["updated_task"].failure_reason = "The site is unreachable"
+ target_url = "https://dead-nav.example.com/login"
+ block = _make_code_block(code=f'await page.goto("{target_url}")')
+ exc = RuntimeError("navigation failed")
+ browser_state = _browser_state()
+ if hop_refused:
+ browser_state.navigate_to_url = AsyncMock(
+ side_effect=RuntimeError(f"Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at {target_url}")
+ )
+
+ with skyvern_context.scoped(SkyvernContext(organization_id="o_test", workflow_run_id="wr_test")):
+ result = await block._attempt_self_heal(
+ exception=exc,
+ failing_line=1,
+ recording_page=_recording_page(exc),
+ workflow_run_context=_make_context(),
+ workflow_run_id="wr_test",
+ workflow_run_block_id="wrb_test",
+ organization_id="o_test",
+ browser_session_id=None,
+ browser_state=browser_state,
+ page=MagicMock(),
+ failed_nav_error_code="net::ERR_NAME_NOT_RESOLVED",
+ )
+
+ # A hop that loaded got past the block's DNS failure, so the recovery does not inherit that code.
+ assert result is not None and result.success is False
+ assert result.error_codes == (expected_codes or [])
+ assert state["recovery_block_updates"][-1]["error_codes"] == expected_codes
+
+
[email protected]("final_status", [TaskStatus.failed, TaskStatus.completed])
+ ("recovery", "expected_codes"),
+ [
+ ("acts_past_it", None),
+ ("reads_the_error_page", ["net::ERR_NAME_NOT_RESOLVED"]),
+ ("navigates_into_the_proxy", ["net::ERR_TUNNEL_CONNECTION_FAILED"]),
+ ],
+)
+async def test_a_failed_heal_reports_the_navigation_its_recovery_ended_on(
+ monkeypatch: pytest.MonkeyPatch,
+ ai_fallback_flag: Callable[[str | None], None],
+ final_status: TaskStatus,
+ recovery: str,
+ expected_codes: list[str] | None,
+) -> None:
+ ai_fallback_flag("o_test")
+ # A completed recovery that misses the declared values fails the block through its own exit.
+ state = _install_db_fakes(monkeypatch, final_status=final_status, extracted_information={})
+ state["updated_task"].failure_reason = "The site is unreachable"
+
+ async def _recovery(*args: object, task: Task, **kwargs: object) -> None:
+ if recovery == "acts_past_it":
+ clear_task_nav_error_code(task.task_id)
+ elif recovery == "navigates_into_the_proxy":
+ await record_task_nav_error_code(
+ task.task_id, RuntimeError("Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/")
+ )
+
+ monkeypatch.setattr(app.agent, "execute_step", AsyncMock(side_effect=_recovery))
+ block = _make_code_block(
+ data_schema={"type": "object", "properties": {"order_total": {"type": "string"}}, "required": ["order_total"]}
+ )
+
+ result, codes = await _resolve_failed_heal(block, _make_context(), "net::ERR_NAME_NOT_RESOLVED", state)
+
+ assert result.success is False
+ assert result.error_codes == (expected_codes or [])
+ assert state["recovery_block_updates"][-1]["error_codes"] == expected_codes
+ assert target_owns_nav_codes(codes) is (recovery == "reads_the_error_page")
+
+
+async def test_recovery_without_a_final_status_keeps_the_driver_nav_code(
+ monkeypatch: pytest.MonkeyPatch, ai_fallback_flag: Callable[[str | None], None]
+) -> None:
+ ai_fallback_flag("o_test")
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.running)
+ block = _make_code_block()
+
+ result, codes = await _resolve_failed_heal(block, _make_context(), "net::ERR_NAME_NOT_RESOLVED", state)
+
+ assert result.success is False
+ assert result.error_codes == ["net::ERR_NAME_NOT_RESOLVED"]
+ assert state["recovery_block_updates"][-1]["error_codes"] == ["net::ERR_NAME_NOT_RESOLVED"]
+ assert target_owns_nav_codes(codes) is True
+
+
+async def test_a_net_code_named_only_in_the_recovery_sentence_is_not_carried(
+ monkeypatch: pytest.MonkeyPatch, ai_fallback_flag: Callable[[str | None], None]
+) -> None:
+ ai_fallback_flag("o_test")
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.failed)
+ state["updated_task"].failure_reason = "Navigation failed with net::ERR_TUNNEL_CONNECTION_FAILED"
+ block = _make_code_block()
+
+ result, codes = await _resolve_failed_heal(block, _make_context(), None, state)
+
+ assert result.success is False
+ assert result.error_codes == []
+ assert proxy_owns_nav_codes(codes) is False
+
+
+ ("engine", "driver_code", "recorder_code", "expected_codes"),
+ [
+ ("inline", "net::ERR_NAME_NOT_RESOLVED", None, ["net::ERR_NAME_NOT_RESOLVED"]),
+ ("inline", SECRET_VALUE, None, []),
+ ("secure", "net::ERR_NAME_NOT_RESOLVED", "net::ERR_NAME_NOT_RESOLVED", ["net::ERR_NAME_NOT_RESOLVED"]),
+ ("secure", SECRET_VALUE, SECRET_VALUE, []),
+ ("secure", None, "net::ERR_NAME_NOT_RESOLVED", []),
+ # The runner blames the tunnel; the worker's resolver found no address, so the site owns it.
+ (
+ "secure",
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ NO_ADDRESS_RECORD_NAV_ERROR_CODE,
+ [NO_ADDRESS_RECORD_NAV_ERROR_CODE],
+ ),
+ ],
+)
+async def test_executed_block_keeps_its_screened_driver_nav_code_through_a_failed_recovery(
+ monkeypatch: pytest.MonkeyPatch,
+ ai_fallback_flag: Callable[[str | None], None],
+ engine: str,
+ driver_code: str | None,
+ recorder_code: str | None,
+ expected_codes: list[str],
+) -> None:
+ ai_fallback_flag("o_test")
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.failed)
+ block = _make_code_block(code="raise RuntimeError('navigation failed')")
+ context = _make_context(with_secret=True)
+ fake_browser_state = SimpleNamespace(
+ get_working_page=AsyncMock(return_value=MagicMock()),
+ browser_artifacts=BrowserArtifacts(),
+ navigate_to_url=AsyncMock(return_value=None),
+ )
+ _patch_execute_chokepoint_environment(
+ monkeypatch, context=context, fake_browser_state=fake_browser_state, use_codeblock_runner=engine == "secure"
+ )
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "execute_code_block_override",
+ AsyncMock(
+ return_value=CodeBlockEngineResult(
+ block_result=None,
+ failure=CodeBlockEngineFailure(
+ error_code="user_code_error",
+ safe_message=None,
+ failure_reason="CodeBlock failed while running user code.",
+ exception_class="playwright._impl._errors.Error",
+ failing_line=1,
+ healability_hint=True,
+ nav_error_code=driver_code,
+ ),
+ )
+ if engine == "secure"
+ else None
+ ),
+ )
+ monkeypatch.setattr(CodeBlock, "_is_healable_page_failure", MagicMock(return_value=True))
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ FakeRecorder.reset(last_recorded_exception=None, last_failed_nav_error_code=recorder_code)
+
+ class _NavFailedRecorder(FakeRecorder):
+ def __init__(self, **kwargs: object) -> None:
+ super().__init__(**kwargs)
+ self.recording_page.failure_nav_error_code = MagicMock(return_value=driver_code)
+
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block.CodeBlockActionRecording", _NavFailedRecorder)
+
+ with skyvern_context.scoped(SkyvernContext(organization_id="o_test", workflow_run_id="wr_test")):
+ result = await block.execute(
+ workflow_run_id="wr_test",
+ workflow_run_block_id="wrb_test",
+ organization_id="o_test",
+ browser_session_id="pbs_test",
+ )
+
+ assert result.success is False
+ assert state["heal_episodes"][0]["status"] == HealStatus.fired_failed
+ assert result.failure_reason == "agent gave up"
+ assert [code for code in result.error_codes if code != "user_code_error"] == expected_codes
+
+
[email protected]("engine", ["inline", "secure"])
+ ("fallback_on", "final_status"),
+ [(False, TaskStatus.failed), (True, TaskStatus.failed), (True, TaskStatus.running)],
+ ids=["unhealed", "fired_failed", "never_final"],
+)
+async def test_no_persisted_block_row_keeps_a_nav_code_that_is_a_parameter_value(
+ monkeypatch: pytest.MonkeyPatch,
+ ai_fallback_flag: Callable[[str | None], None],
+ engine: str,
+ fallback_on: bool,
+ final_status: TaskStatus,
+) -> None:
+ parameter_code = "net::ERR_NAME_NOT_RESOLVED"
+ ai_fallback_flag("o_test" if fallback_on else None)
+ state = _install_db_fakes(monkeypatch, final_status=final_status)
+ block = _make_code_block(code="raise RuntimeError('navigation failed')")
+ fake_browser_state = SimpleNamespace(
+ get_working_page=AsyncMock(return_value=MagicMock()),
+ browser_artifacts=BrowserArtifacts(),
+ navigate_to_url=AsyncMock(return_value=None),
+ )
+ _patch_execute_chokepoint_environment(
+ monkeypatch,
+ context=_make_context(),
+ fake_browser_state=fake_browser_state,
+ use_codeblock_runner=engine == "secure",
+ )
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "serialize_codeblock_parameters", lambda parameters: {"site": parameter_code}
+ )
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "redact_codeblock_parameter_values",
+ lambda value, parameters: (
+ [item.replace(parameter_code, "[redacted]") for item in value]
+ if isinstance(value, list)
+ else value.replace(parameter_code, "[redacted]")
+ if isinstance(value, str)
+ else value
+ ),
+ )
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "execute_code_block_override",
+ AsyncMock(
+ return_value=CodeBlockEngineResult(
+ block_result=None,
+ failure=CodeBlockEngineFailure(
+ error_code="user_code_error",
+ safe_message=None,
+ failure_reason="CodeBlock failed while running user code.",
+ exception_class="playwright._impl._errors.Error",
+ failing_line=1,
+ healability_hint=True,
+ nav_error_code=parameter_code,
+ ),
+ )
+ if engine == "secure"
+ else None
+ ),
+ )
+ monkeypatch.setattr(CodeBlock, "_is_healable_page_failure", MagicMock(return_value=True))
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ FakeRecorder.reset(last_recorded_exception=None, last_failed_nav_error_code=parameter_code)
+
+ class _NavFailedRecorder(FakeRecorder):
+ def __init__(self, **kwargs: object) -> None:
+ super().__init__(**kwargs)
+ self.recording_page.failure_nav_error_code = MagicMock(return_value=parameter_code)
+
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block.CodeBlockActionRecording", _NavFailedRecorder)
+
+ with skyvern_context.scoped(SkyvernContext(organization_id="o_test", workflow_run_id="wr_test")):
+ result = await block.execute(
+ workflow_run_id="wr_test",
+ workflow_run_block_id="wrb_test",
+ organization_id="o_test",
+ browser_session_id="pbs_test",
+ )
+
+ persisted = {
+ update["workflow_run_block_id"]: update["error_codes"]
+ for update in state["workflow_run_block_updates"]
+ if update.get("error_codes")
+ }
+ assert result.success is False
+ assert bool(state["heal_episodes"]) is fallback_on
+ assert "[redacted]" in persisted["wrb_test"]
+ if final_status == TaskStatus.failed and fallback_on:
+ assert persisted["wrb_recovery"] == ["[redacted]"]
+ assert all(parameter_code not in codes for codes in persisted.values())
+
+
@pytest.mark.asyncio
async def test_a_recovery_error_code_that_is_a_run_secret_is_not_reported(
monkeypatch: pytest.MonkeyPatch, ai_fallback_flag: Callable[[str | None], None]