Skip to content

Automate browser based workflows with AI

feat(SKY-11554): CodeBlock runner action + post-action screenshot broker (#6990)

Aaron Perezb3fb369d89c0
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index e6617b1b2..9a8c4ba62 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -617,28 +617,39 @@ class ForgeAgent:
) -> tuple[Task, Step]:
"""Container task v1 for a code block's recorded actions, also the seat for future agent fallback."""
task_order, task_retry = await BaseTaskBlock.get_task_order(workflow_run_id, 0)
- task = await app.DATABASE.tasks.create_task(
- url=task_url,
- title=code_block.label,
- navigation_goal=code_block.prompt,
- data_extraction_goal=None,
- navigation_payload=None,
- organization_id=organization_id,
- workflow_run_id=workflow_run_id,
- order=task_order,
- retry=task_retry,
- )
- task = await app.DATABASE.tasks.update_task(
- task_id=task.task_id,
- organization_id=organization_id,
- status=TaskStatus.running,
- )
- step = await app.DATABASE.tasks.create_step(
- task.task_id,
- order=0,
- retry_index=0,
- organization_id=organization_id,
- )
+ task: Task | None = None
+ try:
+ task = await app.DATABASE.tasks.create_task(
+ url=task_url,
+ title=code_block.label,
+ navigation_goal=code_block.prompt,
+ data_extraction_goal=None,
+ navigation_payload=None,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ order=task_order,
+ retry=task_retry,
+ )
+ task = await app.DATABASE.tasks.update_task(
+ task_id=task.task_id,
+ organization_id=organization_id,
+ status=TaskStatus.running,
+ )
+ step = await app.DATABASE.tasks.create_step(
+ task.task_id,
+ order=0,
+ retry_index=0,
+ organization_id=organization_id,
+ )
+ except Exception:
+ if task is not None:
+ with contextlib.suppress(Exception):
+ await app.DATABASE.tasks.update_task(
+ task_id=task.task_id,
+ organization_id=organization_id,
+ status=TaskStatus.failed,
+ )
+ raise
return task, step
async def create_task(self, task_request: TaskRequest, organization_id: str) -> Task:
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 3db8b07fd..b7499ed20 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -139,6 +139,7 @@ from skyvern.forge.sdk.workflow.models.code_block_recorder import (
RecordingPage,
user_code_line_from_exception,
)
+from skyvern.forge.sdk.workflow.models.code_block_recording import CodeBlockActionRecording
from skyvern.forge.sdk.workflow.models.parameter import (
PARAMETER_TYPE,
AWSSecretParameter,
@@ -149,7 +150,6 @@ from skyvern.forge.sdk.workflow.models.parameter import (
WorkflowParameterType,
)
from skyvern.schemas.runs import RunEngine
-from skyvern.schemas.steps import AgentStepOutput
from skyvern.schemas.workflows import (
AIFallbackMode,
BlockResult,
@@ -4441,138 +4441,30 @@ async def wrapper({default_args}):
if secure_code_block_result is not None:
return secure_code_block_result
- workflow_run_block = None
-
# A prompt-bearing code block gets a task v1 + step so its recorded calls render through
# the standard action/artifact timeline and the agent can later take over on failure.
# Promptless blocks have no task and persist neither actions nor screenshots.
- task: Task | None = None
- step: Step | None = None
- if self.prompt:
- task, step = await app.agent.create_task_and_step_from_code_block(
- code_block=self,
- organization_id=organization_id,
- workflow_run_id=workflow_run_id,
- task_url=page.url,
- )
-
- screenshot_tasks: list[asyncio.Task[None]] = []
-
- async def _screenshot_sink(action: Action) -> None:
- # No task means no action row will reference the screenshot, so skip it rather than orphan an artifact.
- nonlocal workflow_run_block
- if task is None:
- return
- # Every action that reaches this sink is one the recorder chose to surface on the timeline
- # (goto, click, input, page.evaluate, select, hover, ...), so each one earns a screenshot.
- # Re-listing eligible types here only drifts from the recorder's maps — which is exactly how
- # page.evaluate (EXECUTE_JS) ended up with no screenshot.
- # page.screenshot() shares the CDP channel with the user's page calls, so it must run synchronously
- # in the user-await chain (a backgrounded capture races the next action and clips a mid-nav frame);
- # only the page-free S3 upload is deferred off the critical path.
- try:
- if workflow_run_block is None:
- workflow_run_block = await app.DATABASE.observer.get_workflow_run_block(
- workflow_run_block_id=workflow_run_block_id, organization_id=organization_id
- )
- run_block = workflow_run_block
- screenshot = await page.screenshot(timeout=settings.BROWSER_SCREENSHOT_TIMEOUT_MS)
- except Exception:
- LOG.warning(
- "Code block screenshot capture failed",
- workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
- )
- return
-
- async def _upload() -> None:
- try:
- action.screenshot_artifact_id = await app.ARTIFACT_MANAGER.create_workflow_run_block_artifact(
- workflow_run_block=run_block,
- artifact_type=ArtifactType.SCREENSHOT_ACTION,
- data=screenshot,
- )
- except Exception:
- LOG.warning(
- "Code block screenshot upload failed",
- workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
- )
-
- screenshot_tasks.append(asyncio.create_task(_upload()))
-
- async def _drain_screenshots() -> None:
- if screenshot_tasks:
- await asyncio.gather(*screenshot_tasks, return_exceptions=True)
-
- recording_page = RecordingPage(page, on_action=_screenshot_sink)
-
- async def _persist_recorded_actions(recorded: list[Action]) -> None:
- # Best-effort like the screenshot sink: recording must never change block outcome.
- await _drain_screenshots()
- if not recorded or task is None or step is None:
- return
- try:
- masked = workflow_run_context.mask_secrets_in_data([a.model_dump(mode="json") for a in recorded])
- for raw in masked:
- action = Action.model_validate(raw)
- action.task_id = task.task_id
- action.step_id = step.step_id
- action.step_order = step.order
- action.organization_id = organization_id
- await app.DATABASE.workflow_params.create_action(action)
- except Exception:
- LOG.warning(
- "Failed to persist recorded code block actions",
- workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
- )
-
- finalized = False
-
- async def _finalize_code_block_task(success: bool) -> None:
- # Finalize both task and step on every exit path (incl. CancelledError via the finally); idempotent.
- nonlocal finalized
- if task is None or finalized:
- return
- finalized = True
- try:
- await app.DATABASE.tasks.update_task(
- task_id=task.task_id,
- organization_id=organization_id,
- status=TaskStatus.completed if success else TaskStatus.failed,
- )
- if step is not None:
- await app.DATABASE.tasks.update_step(
- task_id=task.task_id,
- step_id=step.step_id,
- status=StepStatus.completed if success else StepStatus.failed,
- output=AgentStepOutput(action_results=[]) if success else None,
- is_last=True,
- organization_id=organization_id,
- )
- except Exception:
- LOG.warning(
- "Failed to finalize code block task status",
- workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
- )
+ recorder = CodeBlockActionRecording(
+ code_block=self,
+ page=page,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ workflow_run_context=workflow_run_context,
+ )
+ await recorder.create_task_and_step()
+ recording_page = recorder.recording_page
try:
- if task is not None:
- await app.DATABASE.observer.update_workflow_run_block(
- workflow_run_block_id=workflow_run_block_id,
- task_id=task.task_id,
- organization_id=organization_id,
- )
+ await recorder.link_block()
user_function = self.generate_async_user_function(self.code, recording_page, parameter_values)
result = await self.execute_user_function_with_timeout(
user_function,
settings.CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS,
)
except InsecureCodeDetected as e:
- await _drain_screenshots()
- await _finalize_code_block_task(success=False)
+ await recorder.persist(recorder.recorded_actions())
+ await recorder.finalize(success=False)
return await self.build_block_result(
success=False,
failure_reason=str(e),
@@ -4582,8 +4474,8 @@ async def wrapper({default_args}):
organization_id=organization_id,
)
except asyncio.TimeoutError:
- await _persist_recorded_actions(recording_page.recorded_actions())
- await _finalize_code_block_task(success=False)
+ await recorder.persist(recorder.recorded_actions())
+ await recorder.finalize(success=False)
return await self.build_block_result(
success=False,
failure_reason=(
@@ -4601,8 +4493,8 @@ async def wrapper({default_args}):
# User code can raise an exception carrying a resolved secret (e.g.
# `raise Exception(await cred.otp())`); mask before it reaches the persisted reason.
failure_reason = workflow_run_context.mask_secrets_in_data(exc.message)
- recorded = recording_page.recorded_actions()
- if recording_page.last_recorded_exception() is not e:
+ recorded = recorder.recorded_actions()
+ if recorder.last_recorded_exception() is not e:
# The exception did not come from a recorded page call; add a synthetic failure row.
recorded.append(
Action(
@@ -4614,7 +4506,7 @@ async def wrapper({default_args}):
output={"code_line": failing_line},
)
)
- await _persist_recorded_actions(recorded)
+ await recorder.persist(recorded)
healed = await self._attempt_self_heal(
exception=e,
failing_line=failing_line,
@@ -4628,9 +4520,9 @@ async def wrapper({default_args}):
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)
+ await recorder.finalize(success=healed.success)
return healed
- await _finalize_code_block_task(success=False)
+ await recorder.finalize(success=False)
return await self.build_block_result(
success=False,
failure_reason=failure_reason,
@@ -4641,11 +4533,11 @@ async def wrapper({default_args}):
)
else:
- await _persist_recorded_actions(recording_page.recorded_actions())
- await _finalize_code_block_task(success=True)
+ await recorder.persist(recorder.recorded_actions())
+ await recorder.finalize(success=True)
finally:
- # Safety net for paths the except arms miss (CancelledError, update_workflow_run_block failure).
- await _finalize_code_block_task(success=False)
+ # Safety net for paths the except arms miss (CancelledError, link_block failure).
+ await recorder.finalize(success=False)
result = json.loads(
json.dumps(result, default=lambda value: f"Object '{type(value)}' is not JSON serializable")
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.py
new file mode 100644
index 000000000..667299b95
--- /dev/null
+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py
@@ -0,0 +1,193 @@
+"""Hangs CodeBlock page actions off a container task so they render on the run page."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import TYPE_CHECKING
+
+import structlog
+
+from skyvern.config import settings
+from skyvern.forge import app
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.models import StepStatus
+from skyvern.forge.sdk.schemas.tasks import TaskStatus
+from skyvern.forge.sdk.workflow.models.code_block_recorder import RecordingPage
+from skyvern.schemas.steps import AgentStepOutput
+from skyvern.webeye.actions.actions import Action
+
+if TYPE_CHECKING:
+ from playwright.async_api import Page
+
+ from skyvern.forge.sdk.models import Step
+ from skyvern.forge.sdk.schemas.tasks import Task
+ from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
+ from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+ from skyvern.forge.sdk.workflow.models.block import CodeBlock
+
+LOG = structlog.get_logger()
+
+
+class CodeBlockActionRecording:
+ """Records the page operations of one CodeBlock execution and persists them against a container task."""
+
+ def __init__(
+ self,
+ *,
+ code_block: CodeBlock,
+ page: Page,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None,
+ workflow_run_context: WorkflowRunContext,
+ ) -> None:
+ self._code_block = code_block
+ self._page = page
+ self._workflow_run_id = workflow_run_id
+ self._workflow_run_block_id = workflow_run_block_id
+ self._organization_id = organization_id
+ self._workflow_run_context = workflow_run_context
+ self._task: Task | None = None
+ self._step: Step | None = None
+ self._workflow_run_block: WorkflowRunBlock | None = None
+ self._screenshot_tasks: list[asyncio.Task[None]] = []
+ self._recording_enabled = False
+ self._finalized = False
+ self.recording_page = RecordingPage(page, on_action=self._screenshot_sink)
+
+ @property
+ def task(self) -> Task | None:
+ return self._task
+
+ def recorded_actions(self) -> list[Action]:
+ return self.recording_page.recorded_actions()
+
+ def last_recorded_exception(self) -> BaseException | None:
+ return self.recording_page.last_recorded_exception()
+
+ async def create_task_and_step(self) -> None:
+ """Create the task/step that can anchor recorded actions for prompt-bearing blocks."""
+ if not self._code_block.prompt:
+ return
+ try:
+ self._task, self._step = await app.agent.create_task_and_step_from_code_block(
+ code_block=self._code_block,
+ organization_id=self._organization_id,
+ workflow_run_id=self._workflow_run_id,
+ task_url=self._page.url,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to create code block recording task",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
+
+ async def link_block(self) -> None:
+ """Point the run block at the container task so the run-page timeline join resolves its actions."""
+ if self._task is None:
+ return
+ try:
+ await app.DATABASE.observer.update_workflow_run_block(
+ workflow_run_block_id=self._workflow_run_block_id,
+ task_id=self._task.task_id,
+ organization_id=self._organization_id,
+ )
+ self._recording_enabled = True
+ except Exception:
+ LOG.warning(
+ "Failed to link code block recording task to workflow run block",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
+ await self.finalize(success=False)
+
+ async def _screenshot_sink(self, action: Action) -> None:
+ if not self._recording_enabled:
+ return
+ # page.screenshot() shares the CDP channel with the user's page calls, so it must run synchronously
+ # in the user-await chain (a backgrounded capture races the next action and clips a mid-nav frame);
+ # only the page-free S3 upload is deferred off the critical path.
+ try:
+ if self._workflow_run_block is None:
+ self._workflow_run_block = await app.DATABASE.observer.get_workflow_run_block(
+ workflow_run_block_id=self._workflow_run_block_id, organization_id=self._organization_id
+ )
+ run_block = self._workflow_run_block
+ screenshot = await self._page.screenshot(timeout=settings.BROWSER_SCREENSHOT_TIMEOUT_MS)
+ except Exception:
+ LOG.warning(
+ "Code block screenshot capture failed",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
+ return
+
+ async def _upload() -> None:
+ try:
+ action.screenshot_artifact_id = await app.ARTIFACT_MANAGER.create_workflow_run_block_artifact(
+ workflow_run_block=run_block,
+ artifact_type=ArtifactType.SCREENSHOT_ACTION,
+ data=screenshot,
+ )
+ except Exception:
+ LOG.warning(
+ "Code block screenshot upload failed",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
+
+ self._screenshot_tasks.append(asyncio.create_task(_upload()))
+
+ async def _drain_screenshots(self) -> None:
+ if self._screenshot_tasks:
+ await asyncio.gather(*self._screenshot_tasks, return_exceptions=True)
+
+ async def persist(self, recorded: list[Action]) -> None:
+ # Best-effort like the screenshot sink: recording must never change block outcome. Drain first so
+ # each action's screenshot_artifact_id is set on the in-memory row before it is dumped.
+ await self._drain_screenshots()
+ if not recorded or not self._recording_enabled or self._task is None or self._step is None:
+ return
+ try:
+ masked = self._workflow_run_context.mask_secrets_in_data([a.model_dump(mode="json") for a in recorded])
+ for raw in masked:
+ action = Action.model_validate(raw)
+ action.task_id = self._task.task_id
+ action.step_id = self._step.step_id
+ action.step_order = self._step.order
+ action.organization_id = self._organization_id
+ await app.DATABASE.workflow_params.create_action(action)
+ except Exception:
+ LOG.warning(
+ "Failed to persist recorded code block actions",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
+
+ async def finalize(self, success: bool) -> None:
+ # Finalize both task and step on every exit path (incl. CancelledError via a finally); idempotent.
+ if self._task is None or self._finalized:
+ return
+ self._finalized = True
+ try:
+ await app.DATABASE.tasks.update_task(
+ task_id=self._task.task_id,
+ organization_id=self._organization_id,
+ status=TaskStatus.completed if success else TaskStatus.failed,
+ )
+ if self._step is not None:
+ await app.DATABASE.tasks.update_step(
+ task_id=self._task.task_id,
+ step_id=self._step.step_id,
+ status=StepStatus.completed if success else StepStatus.failed,
+ output=AgentStepOutput(action_results=[]) if success else None,
+ is_last=True,
+ organization_id=self._organization_id,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to finalize code block task status",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index d65e1ab33..5699aa034 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -479,6 +479,35 @@ async def test_create_task_and_step_from_code_block_maps_goal_to_task(monkeypatc
assert create_step.await_args.kwargs["order"] == 0
+async def test_create_task_and_step_from_code_block_fails_partial_task_on_step_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """If step creation fails after the container task is running, fail the task before the recorder degrades."""
+ create_task = AsyncMock(return_value=_FakeTask())
+ update_task = AsyncMock(return_value=_FakeTask())
+ create_step = AsyncMock(side_effect=RuntimeError("step unavailable"))
+ monkeypatch.setattr(app.DATABASE.tasks, "get_last_task_for_workflow_run", AsyncMock(return_value=None))
+ monkeypatch.setattr(app.DATABASE.tasks, "create_task", create_task)
+ monkeypatch.setattr(app.DATABASE.tasks, "update_task", update_task)
+ monkeypatch.setattr(app.DATABASE.tasks, "create_step", create_step)
+
+ block = _make_code_block("x = 1", goal="log into the portal")
+
+ with pytest.raises(RuntimeError, match="step unavailable"):
+ await ForgeAgent().create_task_and_step_from_code_block(
+ code_block=block,
+ organization_id="o_test",
+ workflow_run_id="wr_test",
+ task_url="https://example.com/login",
+ )
+
+ assert [call.kwargs["status"] for call in update_task.await_args_list] == [
+ TaskStatus.running,
+ TaskStatus.failed,
+ ]
+
+
@pytest.mark.asyncio
async def test_goal_code_block_marks_task_completed_on_success(monkeypatch: pytest.MonkeyPatch) -> None:
"""The container task must not dangle in 'running'; success drives it to completed."""
@@ -700,6 +729,50 @@ async def test_persist_failure_does_not_fail_the_block(monkeypatch: pytest.Monke
assert result.output_parameter_value["value"] == "ok"
+async def test_create_task_failure_does_not_fail_the_block(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Recording is best-effort: a DB hiccup creating the container task must not fail the block, and
+ with no task the recorder degrades to in-memory only (no orphaned actions or screenshots)."""
+ page = FakePage()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+ mocks["create_task_and_step"].side_effect = RuntimeError("db unavailable")
+
+ block = _make_code_block("await page.locator('#go').click()\nvalue = 'ok'", 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
+ assert result.status == BlockStatus.completed
+ assert result.output_parameter_value is not None
+ assert result.output_parameter_value["value"] == "ok"
+ assert mocks["create_action"].await_count == 0
+ assert mocks["create_artifact"].await_count == 0
+
+
+async def test_link_block_failure_fails_task_and_disables_recording(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A task created but not linked to the run block must not stay running or receive orphan actions."""
+ page = FakePage()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+
+ async def fail_link_only(**kwargs: object) -> None:
+ if kwargs.get("task_id") is not None:
+ raise RuntimeError("db unavailable")
+
+ mocks["update_workflow_run_block"].side_effect = fail_link_only
+
+ block = _make_code_block("await page.locator('#go').click()\nvalue = 'ok'", 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
+ assert result.status == BlockStatus.completed
+ assert mocks["create_action"].await_count == 0
+ assert mocks["create_artifact"].await_count == 0
+ assert [call.kwargs.get("status") for call in mocks["update_task"].await_args_list] == [TaskStatus.failed]
+ assert [call.kwargs.get("status") for call in mocks["update_step"].await_args_list] == [StepStatus.failed]
+
+
@pytest.mark.asyncio
async def test_caught_page_failure_then_unrelated_raise_persists_synthetic_action(
monkeypatch: pytest.MonkeyPatch,