Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-11276): bounded code-block self-heal floor (#6971)
pedrohsdb6ea5783a3e7a
diff --git a/skyvern/config.py b/skyvern/config.pyindex 0e3f76deb..bc0406e9b 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -205,6 +205,8 @@ class Settings(BaseSettings):# already-authenticated session (the first run and every login-replaying repair re-run alike).# Off (default) reuses the scout debug session (SKY-9328) for every run as today.COPILOT_FRESH_SESSION_FIRST_SYNTHESIZED_TEST_RUN: bool = False+ # Default for the bounded code-block self-heal; off by default.+ ENABLE_CODE_BLOCK_SELF_HEALING: bool = FalsePORT: int = 8000ALLOWED_ORIGINS: list[str] = ["*"]BLOCKED_HOSTS: list[str] = ["localhost"]diff --git a/skyvern/forge/sdk/copilot/block_goal_wrapping.py b/skyvern/forge/sdk/copilot/block_goal_wrapping.pyindex 05834d4c6..c9de6e365 100644--- a/skyvern/forge/sdk/copilot/block_goal_wrapping.py+++ b/skyvern/forge/sdk/copilot/block_goal_wrapping.py@@ -60,6 +60,10 @@ _WRAPPED_GOAL_RE = re.compile()+def compose_mini_goal(main_goal: str, mini_goal: str) -> str:+ return MINI_GOAL_TEMPLATE.format(main_goal=main_goal, mini_goal=mini_goal)++def wrap_block_goals(workflow_yaml: str, user_message: str) -> str:"""Return ``workflow_yaml`` with each block's ``navigation_goal``,``complete_criterion``, and ``terminate_criterion`` wrapped viadiff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex b011fb000..3db8b07fd 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -36,6 +36,7 @@ from jinja2.sandbox import SandboxedEnvironmentfrom jsonschema import Draft202012Validatorfrom jsonschema.exceptions import ValidationErrorfrom opentelemetry import trace as otel_trace+from playwright.async_api import Error as PlaywrightErrorfrom playwright.async_api import Pagefrom pydantic import BaseModel, Field, model_validator@@ -88,12 +89,14 @@ from skyvern.forge.sdk.api.llm.custom_llm_registry import is_custom_llm_model_nafrom skyvern.forge.sdk.api.llm.exceptions import InvalidLLMResponseFormat, InvalidLLMResponseTypefrom skyvern.forge.sdk.api.llm.schema_validator import validate_schemafrom skyvern.forge.sdk.artifact.models import ArtifactType+from skyvern.forge.sdk.copilot.block_goal_wrapping import compose_mini_goalfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.aiohttp_helper import aiohttp_requestfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.db.enums import TaskTypefrom skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_type+from skyvern.forge.sdk.experimentation.providers import NoOpExperimentationProviderfrom skyvern.forge.sdk.models import Step, StepStatusfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.task_v2 import TaskV2Status@@ -275,6 +278,16 @@ TASKV2_TO_BLOCK_STATUS: dict[TaskV2Status, BlockStatus] = {TaskV2Status.timed_out: BlockStatus.timed_out,}+ENABLE_CODE_BLOCK_SELF_HEALING_FLAG = "ENABLE_CODE_BLOCK_SELF_HEALING"++TASK_TO_BLOCK_STATUS: dict[TaskStatus, BlockStatus] = {+ TaskStatus.completed: BlockStatus.completed,+ TaskStatus.terminated: BlockStatus.terminated,+ TaskStatus.failed: BlockStatus.failed,+ TaskStatus.canceled: BlockStatus.canceled,+ TaskStatus.timed_out: BlockStatus.timed_out,+}+def extract_file_url_from_block_output(value: Any) -> str | None:"""Extract a file URL from block output values that wrap downloaded files."""@@ -1508,13 +1521,7 @@ class BaseTaskBlock(Block):raise UnexpectedTaskStatus(task_id=updated_task.task_id, status=updated_task.status)current_running_task = updated_task- block_status_mapping = {- TaskStatus.completed: BlockStatus.completed,- TaskStatus.terminated: BlockStatus.terminated,- TaskStatus.failed: BlockStatus.failed,- TaskStatus.canceled: BlockStatus.canceled,- TaskStatus.timed_out: BlockStatus.timed_out,- }+ block_status_mapping = TASK_TO_BLOCK_STATUSif updated_task.status == TaskStatus.completed or updated_task.status == TaskStatus.terminated:LOG.info("Task completed",@@ -3982,6 +3989,286 @@ async def wrapper({default_args}):)return value+ def _match_step_for_failing_line(self, failing_line: int) -> CodeBlockStep | None:+ """Advisory nearest-preceding-start match; a lone ``line_start`` (``line_end`` None) is+ open-ended. Step spans are display-oriented and can drift, so a miss never blocks the heal."""+ best: CodeBlockStep | None = None+ best_start = -1+ for step in self.steps or []:+ if step.line_start is None or step.line_start > failing_line:+ continue+ if step.line_end is not None and failing_line > step.line_end:+ continue+ if step.line_start > best_start:+ best = step+ best_start = step.line_start+ return best++ async def _self_heal_enabled(self, organization_id: str | None) -> bool:+ # Per-org PostHog dial over the env default, mirroring the master copilot flags: the env+ # default is the OSS/standalone fallback and a resolution failure degrades to it, never raising.+ env_enabled = settings.ENABLE_CODE_BLOCK_SELF_HEALING+ provider = app.EXPERIMENTATION_PROVIDER+ if not organization_id or isinstance(provider, NoOpExperimentationProvider):+ return env_enabled+ try:+ flag_enabled = await provider.is_feature_enabled_cached(+ ENABLE_CODE_BLOCK_SELF_HEALING_FLAG,+ organization_id,+ properties={"organization_id": organization_id},+ )+ return bool(flag_enabled) or env_enabled+ except Exception:+ LOG.warning(+ "Failed to resolve code-block self-heal flag; falling back to env default",+ organization_id=organization_id,+ exc_info=True,+ )+ return env_enabled++ def _is_healable_page_failure(self, exception: Exception, recording_page: RecordingPage) -> bool:+ """Heal genuine page failures only: a recorded page call raised, or an (unmapped) Playwright+ page error surfaced. A deliberate non-Playwright raise in user logic stays non-healable."""+ if recording_page.last_recorded_exception() is exception:+ return True+ return isinstance(exception, PlaywrightError) # locator/timeout/navigation errors subclass this++ async def _finalize_recovery_block(+ self,+ recovery_block_id: str | None,+ status: BlockStatus,+ organization_id: str | None,+ failure_reason: 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`.+ if recovery_block_id is None:+ return+ try:+ await app.DATABASE.observer.update_workflow_run_block(+ workflow_run_block_id=recovery_block_id,+ organization_id=organization_id,+ status=status,+ failure_reason=failure_reason,+ )+ except Exception:+ LOG.warning(+ "Failed to finalize self-heal recovery block",+ workflow_run_block_id=recovery_block_id,+ exc_info=True,+ )++ async def _fail_escalation_task(+ self,+ escalation_task: Task | None,+ escalation_step: Step | None,+ recovery_block_id: str | None,+ organization_id: str | 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)+ if escalation_task is None:+ return+ try:+ await app.DATABASE.tasks.update_task(+ task_id=escalation_task.task_id,+ organization_id=organization_id,+ status=TaskStatus.failed,+ )+ if escalation_step is not None:+ await app.DATABASE.tasks.update_step(+ task_id=escalation_task.task_id,+ step_id=escalation_step.step_id,+ status=StepStatus.failed,+ is_last=True,+ organization_id=organization_id,+ )+ except Exception:+ LOG.warning(+ "Failed to finalize stranded self-heal escalation task",+ task_id=escalation_task.task_id,+ exc_info=True,+ )++ async def _attempt_self_heal(+ self,+ *,+ exception: Exception,+ failing_line: int | None,+ recording_page: RecordingPage,+ workflow_run_context: WorkflowRunContext,+ workflow_run_id: str,+ workflow_run_block_id: str,+ organization_id: str | None,+ browser_session_id: str | 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+ heal was attempted, or None to fall through to the caller's fail-closed path."""+ if not await self._self_heal_enabled(organization_id):+ return None+ if not self._is_healable_page_failure(exception, recording_page):+ return None+ if not self.prompt:+ return None+ if not organization_id:+ return None+ organization = await app.DATABASE.organizations.get_organization(organization_id=organization_id)+ if organization is None:+ return None++ escalation_task: Task | None = None+ escalation_step: Step | None = None+ recovery_block_id: str | None = None+ try:+ # block.prompt is the operative goal; a confidently-matched step only narrows it. The match+ # is advisory (spans are display-oriented and render-shifted), so any miss heals on the prompt.+ safe_main = workflow_run_context.mask_secrets_in_data(self.prompt)+ matched_step = self._match_step_for_failing_line(failing_line) if failing_line is not None else None+ if matched_step is not None and matched_step.description:+ safe_mini = workflow_run_context.mask_secrets_in_data(matched_step.description)+ navigation_goal = compose_mini_goal(main_goal=safe_main, mini_goal=safe_mini)+ else:+ navigation_goal = safe_main++ workflow_system_prompt = (+ None+ if self.ignore_workflow_system_prompt+ else workflow_run_context.resolve_effective_workflow_system_prompt()+ )+ task_order, task_retry = await BaseTaskBlock.get_task_order(workflow_run_id, 0)+ # Bound by the global default but never above the org's per-run cap — execute_step gives+ # task.max_steps_per_run precedence over organization.max_steps_per_run.+ heal_max_steps = settings.MAX_STEPS_PER_RUN+ if organization.max_steps_per_run is not None:+ heal_max_steps = min(heal_max_steps, organization.max_steps_per_run)+ # Blank url: the heal takes over the live, half-mutated page rather than re-navigating to it+ # (a truthy task.url makes the browser manager reload the page on the browser-session path).+ escalation_task = await app.DATABASE.tasks.create_task(+ url="",+ title=self.label,+ navigation_goal=navigation_goal,+ data_extraction_goal=None,+ navigation_payload=None,+ organization_id=organization_id,+ workflow_run_id=workflow_run_id,+ order=task_order,+ retry=task_retry,+ max_steps_per_run=heal_max_steps,+ model=self.model,+ workflow_system_prompt=workflow_system_prompt,+ )+ escalation_task = await app.DATABASE.tasks.update_task(+ task_id=escalation_task.task_id,+ organization_id=organization_id,+ status=TaskStatus.running,+ )+ escalation_step = await app.DATABASE.tasks.create_step(+ escalation_task.task_id,+ order=0,+ retry_index=0,+ organization_id=organization_id,+ )+ # Child block parented to the code block, linked to the escalation task: the timeline attaches+ # the heal's actions to this nested node (actions join by task_id), while the code block keeps+ # the seat task so its own pre-failure actions stay visible too.+ recovery_block = await app.DATABASE.observer.create_workflow_run_block(+ workflow_run_id=workflow_run_id,+ parent_workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ task_id=escalation_task.task_id,+ label="Self-heal recovery",+ block_type=BlockType.TASK,+ )+ recovery_block_id = recovery_block.workflow_run_block_id++ # Attribute the heal's steps to the escalation task for its duration; restored in finally.+ current_context = skyvern_context.ensure_context()+ previous_task_id = current_context.task_id+ current_context.task_id = escalation_task.task_id+ try:+ # execute_step self-drives to a terminal across multiple steps (execute_all_steps),+ # bounded by the task's max_steps_per_run — not a single step.+ await app.agent.execute_step(+ organization=organization,+ task=escalation_task,+ step=escalation_step,+ task_block=None,+ browser_session_id=browser_session_id,+ close_browser_on_completion=False,+ )+ finally:+ current_context.task_id = previous_task_id++ 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)+ return await self.build_block_result(+ success=False,+ failure_reason=f"Self-heal escalation did not reach a final status for block {self.label}",+ output_parameter_value=None,+ status=BlockStatus.failed,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ if updated_task.status == TaskStatus.completed:+ downloaded_files: list[FileInfo] = []+ try:+ async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):+ downloaded_files = await app.STORAGE.get_downloaded_files(+ organization_id=organization_id,+ run_id=current_context.run_id if current_context.run_id else workflow_run_id,+ )+ except asyncio.TimeoutError:+ LOG.warning("Timeout getting downloaded files", task_id=updated_task.task_id)+ downloaded_files = filter_downloaded_files_for_current_iteration(+ downloaded_files,+ current_context.loop_internal_state,+ )+ task_output = TaskOutput.from_task(updated_task, downloaded_files)+ output_parameter_value = workflow_run_context.mask_secrets_in_data(task_output.model_dump())+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, output_parameter_value)+ await self._finalize_recovery_block(recovery_block_id, BlockStatus.completed, organization_id)+ return await self.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value=output_parameter_value,+ status=BlockStatus.completed,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )+ recovery_status = TASK_TO_BLOCK_STATUS.get(updated_task.status, BlockStatus.failed)+ recovery_failure_reason = (+ updated_task.failure_reason or f"Self-heal escalation finished with status {updated_task.status}"+ )+ await self._finalize_recovery_block(+ recovery_block_id, recovery_status, organization_id, failure_reason=recovery_failure_reason+ )+ return await self.build_block_result(+ success=False,+ failure_reason=recovery_failure_reason,+ output_parameter_value=None,+ status=recovery_status,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )+ except asyncio.CancelledError:+ # CancelledError is BaseException, not Exception — finalize explicitly, then never swallow it.+ await self._fail_escalation_task(escalation_task, escalation_step, recovery_block_id, organization_id)+ raise+ except Exception:+ LOG.warning(+ "Code block self-heal escalation failed; falling back to fail-closed",+ workflow_run_block_id=workflow_run_block_id,+ workflow_run_id=workflow_run_id,+ exc_info=True,+ )+ await self._fail_escalation_task(escalation_task, escalation_step, recovery_block_id, organization_id)+ return None+async def execute(self,workflow_run_id: str,@@ -4328,6 +4615,21 @@ async def wrapper({default_args}):))await _persist_recorded_actions(recorded)+ healed = await self._attempt_self_heal(+ exception=e,+ failing_line=failing_line,+ recording_page=recording_page,+ workflow_run_context=workflow_run_context,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ browser_session_id=browser_session_id,+ )+ if healed is not None:+ # Finalize the seat task to the heal outcome before the idempotent `finally` no-ops it,+ # so a healed success no longer leaves the seat row failed under a completed block.+ await _finalize_code_block_task(success=healed.success)+ return healedawait _finalize_code_block_task(success=False)return await self.build_block_result(success=False,diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.pynew file mode 100644index 000000000..679653fee--- /dev/null+++ b/tests/unit/workflow/test_code_block_escalation.py@@ -0,0 +1,680 @@+"""Bounded runtime self-heal escalation for a failed copilot-authored code block.++block.prompt is the operative goal; a confidently-matched step only narrows it, so a rotted+selector heals even when no step covers the failing line (the common case).+"""++from __future__ import annotations++import asyncio+from datetime import datetime, timezone+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+from playwright.async_api import TimeoutError as PlaywrightTimeoutError++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.schemas.files import FileInfo+from skyvern.forge.sdk.schemas.tasks import TaskStatus+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext+from skyvern.forge.sdk.workflow.models.block import BlockResult, BlockStatus, BlockType, CodeBlock, CodeBlockStep+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType+from skyvern.webeye.actions.actions import Action++SECRET_VALUE = "hunter2-super-secret"+DEFAULT_PROMPT = "Log in and download the report"++ExtractedInformation = list[Any] | dict[str, Any] | str | None+++def _make_code_block(steps: list[CodeBlockStep] | None = None, prompt: str | None = DEFAULT_PROMPT) -> CodeBlock:+ now = datetime.now(timezone.utc)+ output_parameter = OutputParameter(+ parameter_type=ParameterType.OUTPUT,+ key="code_output",+ description="test output",+ output_parameter_id="op_code",+ workflow_id="w_test",+ created_at=now,+ modified_at=now,+ )+ return CodeBlock(+ label="code_1",+ code="await page.click('#missing')",+ prompt=prompt,+ steps=steps,+ output_parameter=output_parameter,+ )+++def _make_context(*, with_secret: bool = False) -> WorkflowRunContext:+ context = WorkflowRunContext(+ workflow_title="wf",+ workflow_id="w_test",+ workflow_permanent_id="wpid_test",+ workflow_run_id="wr_test",+ aws_client=MagicMock(),+ )+ if with_secret:+ context.secrets["k_secret"] = SECRET_VALUE+ context.include_secrets_in_templates = True+ return context+++class _FakeTask:+ def __init__(+ self,+ task_id: str,+ status: TaskStatus,+ extracted_information: ExtractedInformation = None,+ ) -> None:+ self.task_id = task_id+ self.status = status+ self.extracted_information: ExtractedInformation = (+ extracted_information if extracted_information is not None else {"report": "ok"}+ )+ self.failure_reason: str | None = None if status == TaskStatus.completed else "agent gave up"+ self.errors: list[dict[str, Any]] = []+ self.failure_category: list[dict[str, Any]] | None = None+ self.order = 7+ self.retry = 0+++def _install_db_fakes(+ monkeypatch: pytest.MonkeyPatch,+ *,+ final_status: TaskStatus,+ organization: object | None = SimpleNamespace(organization_id="o_test", max_steps_per_run=None),+ downloaded_files: list[FileInfo] | None = None,+ extracted_information: ExtractedInformation = None,+) -> dict[str, Any]:+ created_task = _FakeTask("tsk_escalation", TaskStatus.running)+ updated_after_run = _FakeTask("tsk_escalation", final_status, extracted_information=extracted_information)+ state: dict[str, Any] = {+ "create_task_kwargs": None,+ "execute_step_calls": 0,+ "created_actions": [],+ "recovery_block_kwargs": None,+ "recovery_block_updates": [],+ }++ async def _create_task(**kwargs: object) -> _FakeTask:+ state["create_task_kwargs"] = kwargs+ return created_task++ async def _update_task(*args: object, **kwargs: object) -> _FakeTask:+ return created_task++ async def _create_step(*args: object, **kwargs: object) -> SimpleNamespace:+ return SimpleNamespace(step_id="stp_1", order=0, retry_index=0)++ async def _get_task(*args: object, **kwargs: object) -> _FakeTask:+ return updated_after_run++ async def _get_organization(*args: object, **kwargs: object) -> object | None:+ return organization++ async def _get_task_order(*args: object, **kwargs: object) -> tuple[int, int]:+ return 8, 0++ async def _execute_step(*args: object, **kwargs: object) -> tuple[None, None, None]:+ state["execute_step_calls"] += 1+ state["execute_step_kwargs"] = kwargs+ return None, None, None++ async def _get_downloaded_files(*args: object, **kwargs: object) -> list[FileInfo]:+ return list(downloaded_files or [])++ async def _create_action(action: Action) -> Action:+ state["created_actions"].append(action)+ return action++ monkeypatch.setattr(app.DATABASE.tasks, "create_task", AsyncMock(side_effect=_create_task))+ monkeypatch.setattr(app.DATABASE.tasks, "update_task", AsyncMock(side_effect=_update_task))+ monkeypatch.setattr(app.DATABASE.tasks, "update_step", AsyncMock(return_value=None))+ monkeypatch.setattr(app.DATABASE.tasks, "create_step", AsyncMock(side_effect=_create_step))+ monkeypatch.setattr(app.DATABASE.tasks, "get_task", AsyncMock(side_effect=_get_task))+ monkeypatch.setattr(app.DATABASE.organizations, "get_organization", AsyncMock(side_effect=_get_organization))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.BaseTaskBlock.get_task_order",+ AsyncMock(side_effect=_get_task_order),+ )+ monkeypatch.setattr(app.agent, "execute_step", AsyncMock(side_effect=_execute_step))+ monkeypatch.setattr(app.DATABASE.workflow_params, "create_action", AsyncMock(side_effect=_create_action))++ async def _create_workflow_run_block(**kwargs: object) -> SimpleNamespace:+ state["recovery_block_kwargs"] = kwargs+ return SimpleNamespace(workflow_run_block_id="wrb_recovery")++ async def _update_workflow_run_block(**kwargs: object) -> None:+ state["recovery_block_updates"].append(kwargs)++ monkeypatch.setattr(+ app.DATABASE.observer, "create_workflow_run_block", AsyncMock(side_effect=_create_workflow_run_block)+ )+ monkeypatch.setattr(+ app.DATABASE.observer, "update_workflow_run_block", AsyncMock(side_effect=_update_workflow_run_block)+ )+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(side_effect=_get_downloaded_files))+ monkeypatch.setattr(+ app.DATABASE.workflow_runs, "create_or_update_workflow_run_output_parameter", AsyncMock(return_value=None)+ )+ return state+++def _recording_page(exception: Exception | None) -> MagicMock:+ page = MagicMock()+ page.last_recorded_exception = MagicMock(return_value=exception)+ return page+++async def _heal(+ block: CodeBlock,+ context: WorkflowRunContext,+ exception: Exception,+ recording_page: MagicMock,+ *,+ failing_line: int | None = 1,+) -> BlockResult | None:+ with skyvern_context.scoped(SkyvernContext(organization_id="o_test", workflow_run_id="wr_test")):+ return await block._attempt_self_heal(+ exception=exception,+ failing_line=failing_line,+ recording_page=recording_page,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++[email protected](autouse=True)+def _self_heal_flag_resolves_to_env(monkeypatch: pytest.MonkeyPatch) -> None:+ # Unit stub provider returns a truthy AsyncMock for every flag; pin self-heal resolution to the+ # env default so per-test settings govern. PostHog-specific tests override the provider explicitly.+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", AsyncMock(return_value=False))+++async def test_flag_off_is_no_op(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is None+ assert state["execute_step_calls"] == 0+++async def test_posthog_flag_enables_heal_when_env_off(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)+ fake_provider = SimpleNamespace(is_feature_enabled_cached=AsyncMock(return_value=True))+ monkeypatch.setattr(app, "EXPERIMENTATION_PROVIDER", fake_provider)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None+ assert state["execute_step_calls"] == 1+ assert fake_provider.is_feature_enabled_cached.await_args.args[0] == "ENABLE_CODE_BLOCK_SELF_HEALING"+++async def test_posthog_resolution_failure_falls_back_to_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)+ fake_provider = SimpleNamespace(is_feature_enabled_cached=AsyncMock(side_effect=RuntimeError("posthog down")))+ monkeypatch.setattr(app, "EXPERIMENTATION_PROVIDER", fake_provider)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is None+ assert state["execute_step_calls"] == 0+++# --- The spine fix: a rotted page failure heals on block.prompt even with no covering step. ---+++ "steps, failing_line",+ [+ pytest.param(None, 1, id="no_steps"),+ pytest.param([CodeBlockStep(description="d", line_start=50, line_end=60)], 1, id="unmatched_step"),+ pytest.param([CodeBlockStep(description="d", line_start=1, line_end=1)], None, id="null_failing_line"),+ pytest.param([CodeBlockStep(description=None, line_start=1, line_end=1)], 1, id="step_without_description"),+ ],+)+async def test_prompt_only_heal_fires_without_a_matched_step(+ monkeypatch: pytest.MonkeyPatch, steps: list[CodeBlockStep] | None, failing_line: int | None+) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=steps)+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc), failing_line=failing_line)++ assert result is not None and result.success is True+ assert state["execute_step_calls"] == 1+ # No step narrows the goal, so it is the bare block prompt (no MINI_GOAL wrapper).+ assert state["create_task_kwargs"]["navigation_goal"] == DEFAULT_PROMPT+++async def test_matched_step_narrows_the_goal(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="click the export button", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc), failing_line=1)++ assert result is not None and result.success is True+ goal = state["create_task_kwargs"]["navigation_goal"]+ assert goal != DEFAULT_PROMPT+ assert "click the export button" in goal+ assert DEFAULT_PROMPT in goal+++async def test_unmapped_playwright_error_is_healed(monkeypatch: pytest.MonkeyPatch) -> None:+ # An unmapped Playwright call's exception is never registered as last_recorded_exception, but a+ # Playwright page error is still genuine page drift the type-classifier must catch (CORR-10).+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = PlaywrightTimeoutError("locator.click: Timeout 30000ms exceeded")++ result = await _heal(block, _make_context(), exc, _recording_page(None))++ assert result is not None and result.success is True+ assert state["execute_step_calls"] == 1+++async def test_deliberate_raise_is_not_healed(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ raised = ValueError("business logic refused")++ result = await _heal(block, _make_context(), raised, _recording_page(None))++ assert result is None+ assert state["execute_step_calls"] == 0+++ "kwargs, organization",+ [+ pytest.param({"prompt": None}, SimpleNamespace(organization_id="o_test"), id="no_prompt"),+ pytest.param({}, None, id="no_organization"),+ ],+)+async def test_no_op_guards_skip_escalation(+ monkeypatch: pytest.MonkeyPatch, kwargs: dict[str, Any], organization: object | None+) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed, organization=organization)+ block = _make_code_block(steps=[CodeBlockStep(description="d", line_start=1, line_end=1)], **kwargs)+ exc = RuntimeError("rotted selector")++ assert await _heal(block, _make_context(), exc, _recording_page(exc)) is None+ assert state["execute_step_calls"] == 0+++async def test_completed_heal_maps_to_success(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ record = AsyncMock(return_value=None)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", record)+ block = _make_code_block(steps=[CodeBlockStep(description="download the report", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None+ assert result.success is True+ assert result.status == BlockStatus.completed+ assert state["execute_step_calls"] == 1+ record.assert_awaited_once()+++async def test_completed_heal_records_task_output_envelope(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ record = AsyncMock(return_value=None)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", record)+ _install_db_fakes(+ monkeypatch,+ final_status=TaskStatus.completed,+ extracted_information={"order_total": "42.50", "currency": "USD"},+ )+ block = _make_code_block(steps=[CodeBlockStep(description="read the order total", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None+ output = result.output_parameter_value+ assert output["extracted_information"] == {"order_total": "42.50", "currency": "USD"}+ assert output["task_id"] == "tsk_escalation"+ assert output["status"] == TaskStatus.completed+ recorded = record.await_args.args[2]+ assert recorded["extracted_information"] == {"order_total": "42.50", "currency": "USD"}+++async def test_completed_heal_carries_downloaded_files_into_task_output(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ downloaded = [FileInfo(url="https://files.test/report.pdf", checksum="abc123", artifact_id="art_1")]+ _install_db_fakes(monkeypatch, final_status=TaskStatus.completed, downloaded_files=downloaded)+ record = AsyncMock(return_value=None)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", record)+ block = _make_code_block(steps=[CodeBlockStep(description="download the report", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None and result.success is True+ output = result.output_parameter_value+ assert output["downloaded_file_urls"] == ["https://files.test/report.pdf"]+ assert output["downloaded_file_artifact_ids"] == ["art_1"]+ assert output["downloaded_files"][0]["url"] == "https://files.test/report.pdf"+ recorded_output = record.await_args.args[2]+ assert recorded_output["downloaded_file_urls"] == ["https://files.test/report.pdf"]+++ "final_status, expected_status",+ [+ (TaskStatus.terminated, BlockStatus.terminated),+ (TaskStatus.timed_out, BlockStatus.timed_out),+ (TaskStatus.canceled, BlockStatus.canceled),+ (TaskStatus.failed, BlockStatus.failed),+ ],+)+async def test_non_completed_heal_maps_status_without_collapsing(+ monkeypatch: pytest.MonkeyPatch, final_status: TaskStatus, expected_status: BlockStatus+) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=final_status)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None+ assert result.success is False+ assert result.status == expected_status+ assert state["execute_step_calls"] == 1+++async def test_escalation_runs_its_own_task(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None and result.success is True+ assert state["execute_step_kwargs"]["task"].task_id == "tsk_escalation"+ assert state["created_actions"] == []+++async def test_secret_value_never_leaks_into_goal_or_task(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ block = _make_code_block(+ steps=[CodeBlockStep(description=f"submit token {SECRET_VALUE}", line_start=1, line_end=1)],+ prompt=f"Sign in with {SECRET_VALUE} and download",+ )+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(with_secret=True), exc, _recording_page(exc))++ assert result is not None+ goal = state["create_task_kwargs"]["navigation_goal"]+ assert SECRET_VALUE not in goal+ assert "*****" in goal+ for value in state["create_task_kwargs"].values():+ assert SECRET_VALUE not in str(value)+++async def test_completed_heal_masks_secret_in_recorded_output(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ record = AsyncMock(return_value=None)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", record)+ _install_db_fakes(+ monkeypatch,+ final_status=TaskStatus.completed,+ extracted_information={"token": SECRET_VALUE},+ )+ block = _make_code_block(steps=[CodeBlockStep(description="read the token", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(with_secret=True), exc, _recording_page(exc))++ assert result is not None+ recorded = record.await_args.args[2]+ assert SECRET_VALUE not in str(recorded)+ assert SECRET_VALUE not in str(result.output_parameter_value)+++async def test_max_steps_and_model_and_running_status_forwarded(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr("skyvern.config.settings.MAX_STEPS_PER_RUN", 7, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ update_calls: list[dict[str, object]] = []+ original_update = app.DATABASE.tasks.update_task++ async def _track_update(*args: object, **kwargs: object) -> object:+ update_calls.append(kwargs)+ return await original_update(*args, **kwargs)++ monkeypatch.setattr(app.DATABASE.tasks, "update_task", AsyncMock(side_effect=_track_update))+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ block.model = {"model_name": "gpt-5.5"}+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None+ assert state["create_task_kwargs"]["max_steps_per_run"] == 7+ assert state["create_task_kwargs"]["model"] == {"model_name": "gpt-5.5"}+ assert state["create_task_kwargs"]["order"] == 8+ assert any(call.get("status") == TaskStatus.running for call in update_calls)+ assert state["execute_step_kwargs"]["task_block"] is None+++async def test_heal_internal_exception_degrades_without_raising(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(app.DATABASE.tasks, "create_task", AsyncMock(side_effect=RuntimeError("db down")))+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is None+++async def test_escalation_task_finalized_when_execute_step_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ update_calls: list[dict[str, object]] = []+ original_update = app.DATABASE.tasks.update_task++ async def _track_update(*args: object, **kwargs: object) -> object:+ update_calls.append(kwargs)+ return await original_update(*args, **kwargs)++ monkeypatch.setattr(app.DATABASE.tasks, "update_task", AsyncMock(side_effect=_track_update))+ monkeypatch.setattr(app.agent, "execute_step", AsyncMock(side_effect=RuntimeError("agent boom")))+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is None+ # The escalation task was set running, then finalized to failed on cleanup — never left stranded.+ assert any(call.get("status") == TaskStatus.failed for call in update_calls)+++async def test_escalation_task_finalized_when_not_final(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ _install_db_fakes(monkeypatch, final_status=TaskStatus.running)+ update_calls: list[dict[str, object]] = []+ original_update = app.DATABASE.tasks.update_task++ async def _track_update(*args: object, **kwargs: object) -> object:+ update_calls.append(kwargs)+ return await original_update(*args, **kwargs)++ monkeypatch.setattr(app.DATABASE.tasks, "update_task", AsyncMock(side_effect=_track_update))+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None and result.success is False+ assert result.status == BlockStatus.failed+ assert any(call.get("status") == TaskStatus.failed for call in update_calls)+++async def test_lone_line_start_step_is_matched(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ block = _make_code_block(steps=[CodeBlockStep(description="open the menu", line_start=3, line_end=None)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc), failing_line=9)++ assert result is not None+ assert state["execute_step_calls"] == 1+ assert "open the menu" in state["create_task_kwargs"]["navigation_goal"]+++def test_match_step_picks_largest_preceding_start() -> None:+ block = _make_code_block(+ steps=[+ CodeBlockStep(description="first", line_start=1, line_end=3),+ CodeBlockStep(description="second", line_start=5, line_end=None),+ CodeBlockStep(description="third", line_start=8, line_end=12),+ ]+ )+ assert block._match_step_for_failing_line(2).description == "first"+ assert block._match_step_for_failing_line(6).description == "second"+ assert block._match_step_for_failing_line(10).description == "third"+ assert block._match_step_for_failing_line(4) is None+++async def test_heal_max_steps_capped_by_org(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr("skyvern.config.settings.MAX_STEPS_PER_RUN", 25, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ # Org caps runs at 4 steps; the heal must not exceed it even though the global default is 25.+ state = _install_db_fakes(+ monkeypatch,+ final_status=TaskStatus.completed,+ organization=SimpleNamespace(organization_id="o_test", max_steps_per_run=4),+ )+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None and result.success is True+ assert state["create_task_kwargs"]["max_steps_per_run"] == 4+++async def test_cancellation_finalizes_escalation_and_reraises(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ update_calls: list[dict[str, object]] = []+ original_update = app.DATABASE.tasks.update_task++ async def _track_update(*args: object, **kwargs: object) -> object:+ update_calls.append(kwargs)+ return await original_update(*args, **kwargs)++ monkeypatch.setattr(app.DATABASE.tasks, "update_task", AsyncMock(side_effect=_track_update))+ monkeypatch.setattr(app.agent, "execute_step", AsyncMock(side_effect=asyncio.CancelledError()))+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ with pytest.raises(asyncio.CancelledError):+ await _heal(block, _make_context(), exc, _recording_page(exc))++ # CancelledError (BaseException) must not strand the escalation task: finalized failed, then re-raised.+ assert any(call.get("status") == TaskStatus.failed for call in update_calls)+++async def test_recovery_child_block_created_and_finalized(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None and result.success is True+ # blocker #2: the heal takes over the live half-mutated page — the escalation task carries no url.+ assert state["create_task_kwargs"]["url"] == ""+ # blocker #1: a child block parented to the code block surfaces the recovery on the run timeline.+ rb = state["recovery_block_kwargs"]+ assert rb["parent_workflow_run_block_id"] == "wrb_test"+ assert rb["task_id"] == "tsk_escalation"+ assert rb["block_type"] == BlockType.TASK+ assert rb["label"]+ # the recovery block is finalized to the heal outcome, not left dangling in `running`.+ assert any(u.get("status") == BlockStatus.completed for u in state["recovery_block_updates"])+++async def test_recovery_block_finalized_to_non_completed_status(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.terminated)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert result is not None and result.success is False+ assert any(u.get("status") == BlockStatus.terminated for u in state["recovery_block_updates"])diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.pyindex 387a2c028..d65e1ab33 100644--- a/tests/unit/workflow/test_code_block_recorder.py+++ b/tests/unit/workflow/test_code_block_recorder.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonfrom datetime import datetime, timezone+from types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest@@ -541,6 +542,52 @@ async def test_goal_code_block_finalizes_step_on_cancellation(monkeypatch: pytesassert StepStatus.failed in step_statuses+async def test_self_heal_success_finalizes_seat_completed(monkeypatch: pytest.MonkeyPatch) -> None:+ """A healed code block finalizes its SEAT task to completed — never a completed block over a failed seat."""++ class ExplodingLocator(FakeLocator):+ async def click(self, **kwargs): # noqa: ANN003, ANN201+ raise RuntimeError("rotted selector")++ page = FakePage()+ page.inner = ExplodingLocator()+ context = FakeWorkflowRunContext()+ mocks = _patch_execute_environment(monkeypatch, page, context)+ # Stub the heal to a success result; this tests execute()'s seat-finalization wiring, not the heal itself.+ monkeypatch.setattr(CodeBlock, "_attempt_self_heal", AsyncMock(return_value=SimpleNamespace(success=True)))++ block = _make_code_block("await page.locator('#x').click()", goal="go")+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")++ assert result.success is True+ statuses = [call.kwargs.get("status") for call in mocks["update_task"].await_args_list]+ assert TaskStatus.completed in statuses+ assert TaskStatus.failed not in statuses+++async def test_self_heal_decline_finalizes_seat_failed(monkeypatch: pytest.MonkeyPatch) -> None:+ """When the heal declines (None), the block fails closed and the seat task is finalized failed."""++ class ExplodingLocator(FakeLocator):+ async def click(self, **kwargs): # noqa: ANN003, ANN201+ raise RuntimeError("rotted selector")++ page = FakePage()+ page.inner = ExplodingLocator()+ context = FakeWorkflowRunContext()+ mocks = _patch_execute_environment(monkeypatch, page, context)+ monkeypatch.setattr(CodeBlock, "_attempt_self_heal", AsyncMock(return_value=None))++ block = _make_code_block("await page.locator('#x').click()", goal="go")+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")++ assert result.success is False+ statuses = [call.kwargs.get("status") for call in mocks["update_task"].await_args_list]+ assert TaskStatus.failed in statuses++@pytest.mark.asyncioasync def test_goalless_code_block_creates_no_task_or_actions(monkeypatch: pytest.MonkeyPatch) -> None:"""Without a goal there is no task to hang actions on, so none are created or persisted."""