Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-15889: Record CAPTCHA helper attempts across code executors (#8492)
Andrew Neilsonf31ddd13837a
diff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.pyindex 32da22cd8..f2e6a2e69 100644--- a/skyvern/forge/sdk/db/repositories/tasks.py+++ b/skyvern/forge/sdk/db/repositories/tasks.py@@ -30,6 +30,7 @@ from skyvern.forge.sdk.trace import tracedfrom skyvern.forge.sdk.utils.sanitization import sanitize_postgres_textfrom skyvern.schemas.runs import ProxyLocationInput, RunStatus, RunTypefrom skyvern.schemas.steps import AgentStepOutput+from skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.actions.actions import ActionLOG = structlog.get_logger()@@ -443,7 +444,13 @@ class TasksRepository(BaseRepository):return [hydrate_action(row) for row in rows]@db_operation("get_action_count_for_step")- async def get_action_count_for_step(self, step_id: str, task_id: str, organization_id: str) -> int:+ async def get_action_count_for_step(+ self,+ step_id: str,+ task_id: str,+ organization_id: str,+ exclude_action_types: Sequence[ActionType] | None = None,+ ) -> int:"""Get count of actions for a step. Uses composite index for efficiency."""async with self.Session() as session:query = (@@ -453,6 +460,8 @@ class TasksRepository(BaseRepository):.where(ActionModel.task_id == task_id).where(ActionModel.step_id == step_id))+ if exclude_action_types:+ query = query.where(ActionModel.action_type.notin_([t.value for t in exclude_action_types]))result = await session.scalar(query)return result or 0diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex af4cca397..42aa02135 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -4519,15 +4519,35 @@ async def _code_block_solve_captcha_builtin(Delegates to solve_challenge_ladder and translates its neutral unsolved-signal into thecode-block-specific error the code-block callers expect."""- try:- return await solve_challenge_ladder(++ async def solve() -> bool:+ try:+ return await solve_challenge_ladder(+ page,+ organization_id=organization_id,+ workflow_run_id=workflow_run_id,+ browser_session_id=browser_session_id,+ )+ except CaptchaChallengeUnsolvedError as exc:+ raise CodeBlockCaptchaError("CAPTCHA could not be solved.") from exc++ if isinstance(page, RecordingPage):+ return await page._record_solve_captcha(solve, workflow_run_id=workflow_run_id)+ return await solve()+++def _bind_code_block_solve_captcha(+ organization_id: str | None,+ workflow_run_id: str | None,+) -> Callable[[Page | RecordingPage], Awaitable[bool]]:+ async def solve_captcha(page: Page | RecordingPage) -> bool:+ return await _code_block_solve_captcha_builtin(page,organization_id=organization_id,workflow_run_id=workflow_run_id,- browser_session_id=browser_session_id,)- except CaptchaChallengeUnsolvedError as exc:- raise CodeBlockCaptchaError("CAPTCHA could not be solved.") from exc++ return solve_captchadef _register_code_block_secret(workflow_run_context: WorkflowRunContext, value: str) -> None:@@ -5235,7 +5255,7 @@ class CodeBlock(Block):"Exception": Exception,"ErrorCode": ErrorCode,"otp": _code_block_otp_builtin,- "solve_captcha": _code_block_solve_captcha_builtin,+ "solve_captcha": _bind_code_block_solve_captcha(None, None),# Unbound: carries no run destination, so it fails closed. generate_async_user_function# replaces it with the run-bound helper; the name is present so preflight allows it."click_and_claim_download": _bind_code_block_download_claim(@@ -5285,11 +5305,7 @@ class CodeBlock(Block):_code_block_safe_print,parameters=app.AGENT_FUNCTION.serialize_codeblock_parameters(parameters or {}),)- safe_vars["solve_captcha"] = partial(- _code_block_solve_captcha_builtin,- organization_id=organization_id,- workflow_run_id=workflow_run_id,- )+ safe_vars["solve_captcha"] = _bind_code_block_solve_captcha(organization_id, workflow_run_id)safe_vars["otp"] = partial(_code_block_otp_builtin,organization_id=organization_id,diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.pyindex b3d359ca4..3cb1edbbc 100644--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py@@ -363,6 +363,7 @@ class _Recorder:self.failed_locator: Locator | None = Noneself.failed_locator_exception: BaseException | None = Noneself.failure_operation_generation = 0+ self._next_action_order = 0self._on_action = on_actionself._on_pending_action = on_pending_actionself.credential_release_guard = credential_release_guard@@ -426,6 +427,11 @@ class _Recorder:self.failed_locator = Nonereturn self.failure_operation_generation+ def _reserve_action_order(self) -> int:+ action_order = self._next_action_order+ self._next_action_order += 1+ return action_order+async def record(self,action_type: ActionType,@@ -436,12 +442,15 @@ class _Recorder:kwargs: dict[str, Any],description: str | None = None,failure_locator: Locator | None = None,+ record_boolean_response: bool = False,+ workflow_run_id: str | None = None,+ record_failure_type_only: bool = False,) -> Any:generation = self.begin_failure_operation()started = time.monotonic()started_wall = naive_utc_now()code_line = _frame_user_line()- action_order = len(self.actions)+ action_order = self._reserve_action_order()# Input values may be credentials (incl. derived TOTP codes); never describe them.describe_args = () if action_type == ActionType.INPUT_TEXT else argscommon_fields = dict(@@ -450,6 +459,7 @@ class _Recorder:action_type=action_type,status=ActionStatus.completed,action_order=action_order,+ workflow_run_id=workflow_run_id,# A reader-facing prompt (page.extract/complete) is the action's own copy; prefer it over# the "page.method arg" form so the timeline reads as plain language even when the editor's# derived step is missing or stale and the UI falls back to this description.@@ -472,6 +482,8 @@ class _Recorder:)try:result = await call()+ if record_boolean_response and isinstance(result, bool):+ action.response = str(result).lower()except BaseException as exc:action.status = ActionStatus.failed# Generous rather than tight: the persistence path masks secrets by exact match, so a@@ -481,11 +493,14 @@ class _Recorder:# A user-defined __str__ can raise or return a non-str. Unguarded, that replaces the# browser's failure with its own and skips both last_exception and the re-raise below,# so the run would lose the fault this line exists to report.- try:- captured = str(exc)[:RECORDED_FAILURE_CAPTURE_MAX_CHARS]- except BaseException:- captured = ""- action.response = captured or type(exc).__name__+ if record_failure_type_only:+ action.response = type(exc).__name__+ else:+ try:+ captured = str(exc)[:RECORDED_FAILURE_CAPTURE_MAX_CHARS]+ except BaseException:+ captured = ""+ action.response = captured or type(exc).__name__self.last_exception = excif generation == self.failure_operation_generation:self.failed_locator_exception = exc@@ -732,7 +747,7 @@ class RecordingPage:return self.__pagedef recorded_actions(self) -> list[Action]:- return list(self.__recorder.actions)+ return sorted(self.__recorder.actions, key=lambda action: cast(int, action.action_order))def last_recorded_exception(self) -> BaseException | None:return self.__recorder.last_exception@@ -740,6 +755,27 @@ class RecordingPage:def failure_locator(self, exception: BaseException) -> Locator | None:return self.__recorder.failed_locator if self.__recorder.failed_locator_exception is exception else None+ async def _record_solve_captcha(+ self,+ call: Callable[[], Awaitable[bool]],+ *,+ workflow_run_id: str | None,+ ) -> bool:+ return cast(+ bool,+ await self.__recorder.record(+ ActionType.SOLVE_CAPTCHA,+ "solve_captcha",+ None,+ call,+ (),+ {},+ record_boolean_response=True,+ workflow_run_id=workflow_run_id,+ record_failure_type_only=True,+ ),+ )+def _brokered_default_timeout(self, scope: Literal["page", "context"]) -> float | None:"""Return the trusted timeout that a secure-runner block must restore."""if scope == "page":diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.pyindex 80a16d954..6931d5d2e 100644--- a/skyvern/forge/sdk/workflow/models/code_block_recording.py+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py@@ -48,6 +48,7 @@ _RECORDER_OWNED_ACTION_FIELDS = ("action_type","status","action_order",+ "workflow_run_id","screenshot_artifact_id","started_at","finished_at",diff --git a/tests/unit/test_code_block_captcha.py b/tests/unit/test_code_block_captcha.pyindex 16874d29e..4893bd4fc 100644--- a/tests/unit/test_code_block_captcha.py+++ b/tests/unit/test_code_block_captcha.py@@ -10,6 +10,9 @@ from skyvern.forge import appfrom skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.sdk.workflow.models import block as block_modulefrom skyvern.forge.sdk.workflow.models.block import CodeBlock, CodeBlockCaptchaError+from skyvern.forge.sdk.workflow.models.code_block_recorder import RecordingPage+from skyvern.webeye.actions.action_types import ActionType+from skyvern.webeye.actions.actions import ActionStatusfrom skyvern.webeye.utils import captcha_solver as captcha_solver_modulefrom skyvern.webeye.utils.captcha_solver import CaptchaChallengeUnsolvedError, solve_challenge_ladderfrom tests.unit.conftest import ScopeRecordingAgentFunction@@ -557,6 +560,111 @@ async def test_builtin_reports_whether_an_arm_ran(monkeypatch: pytest.MonkeyPatcassert agent_function.solve_recaptcha_token.await_args.kwargs["browser_session_id"] == "bs-1"[email protected]("result", [True, False])+async def test_builtin_records_one_solver_action_with_nested_probe(+ monkeypatch: pytest.MonkeyPatch,+ result: bool,+) -> None:+ async def ladder(page: RecordingPage, **_kwargs: object) -> bool:+ await page.locator("#challenge").click()+ return result++ monkeypatch.setattr(block_module, "solve_challenge_ladder", ladder)+ page = RecordingPage(FakePage())++ assert await block_module._code_block_solve_captcha_builtin(page, workflow_run_id="wr_test") is result++ actions = page.recorded_actions()+ assert [action.action_type for action in actions] == [ActionType.SOLVE_CAPTCHA, ActionType.CLICK]+ assert [action.action_order for action in actions] == [0, 1]+ assert actions[0].status == ActionStatus.completed+ assert actions[0].response == str(result).lower()+ assert actions[0].workflow_run_id == "wr_test"+++async def test_builtin_records_sanitized_unsolved_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ sensitive = "https://example.com/account?token=solver-secret#challenge"++ async def ladder(_page: RecordingPage, **_kwargs: object) -> bool:+ raise CaptchaChallengeUnsolvedError(sensitive)++ monkeypatch.setattr(block_module, "solve_challenge_ladder", ladder)+ page = RecordingPage(FakePage())++ with pytest.raises(CodeBlockCaptchaError, match="CAPTCHA could not be solved"):+ await block_module._code_block_solve_captcha_builtin(page)++ [action] = page.recorded_actions()+ assert action.action_type == ActionType.SOLVE_CAPTCHA+ assert action.status == ActionStatus.failed+ assert action.response == "CodeBlockCaptchaError"+ assert sensitive not in action.model_dump_json()+++async def test_builtin_records_only_the_unexpected_failure_type(monkeypatch: pytest.MonkeyPatch) -> None:+ sensitive = "https://example.com/account?token=solver-secret#challenge"+ error = RuntimeError(sensitive)++ async def ladder(_page: RecordingPage, **_kwargs: object) -> bool:+ raise error++ monkeypatch.setattr(block_module, "solve_challenge_ladder", ladder)+ page = RecordingPage(FakePage())++ with pytest.raises(RuntimeError) as exc_info:+ await block_module._code_block_solve_captcha_builtin(page, workflow_run_id="wr_test")++ assert exc_info.value is error+ [action] = page.recorded_actions()+ assert action.response == "RuntimeError"+ assert action.workflow_run_id == "wr_test"+ assert sensitive not in action.model_dump_json()+++async def test_authored_code_cannot_override_solver_workflow_run_id(monkeypatch: pytest.MonkeyPatch) -> None:+ ladder_calls = 0++ async def ladder(_page: RecordingPage, **_kwargs: object) -> bool:+ nonlocal ladder_calls+ ladder_calls += 1+ return False++ monkeypatch.setattr(block_module, "solve_challenge_ladder", ladder)+ page = RecordingPage(FakePage())+ block = CodeBlock.model_construct(+ code='await solve_captcha(page, workflow_run_id="wr_forged")',+ label="captcha_run_binding",+ )++ with pytest.raises(TypeError, match="workflow_run_id"):+ await block.generate_async_user_function(+ block.code,+ page,+ workflow_run_id="wr_coordinator",+ organization_id="o_coordinator",+ )()++ assert ladder_calls == 0+ assert page.recorded_actions() == []++ valid_page = RecordingPage(FakePage())+ valid_block = CodeBlock.model_construct(code="await solve_captcha(page)", label="captcha_run_binding")+ await valid_block.generate_async_user_function(+ valid_block.code,+ valid_page,+ workflow_run_id="wr_coordinator",+ organization_id="o_coordinator",+ )()++ [action] = valid_page.recorded_actions()+ assert ladder_calls == 1+ assert action.workflow_run_id == "wr_coordinator"++def test_solve_captcha_is_reserved_in_sandbox_namespace() -> None:assert "solve_captcha" in CodeBlock.build_safe_vars()diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.pyindex 848b72eef..db68ab3ca 100644--- a/tests/unit/workflow/test_code_block_recorder.py+++ b/tests/unit/workflow/test_code_block_recorder.py@@ -28,6 +28,7 @@ from skyvern.forge.sdk.db.utils import hydrate_actionfrom skyvern.forge.sdk.models import StepStatusfrom skyvern.forge.sdk.schemas.tasks import TaskStatusfrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext+from skyvern.forge.sdk.workflow.models import block as block_modulefrom skyvern.forge.sdk.workflow.models.block import CodeBlock, Credentialfrom skyvern.forge.sdk.workflow.models.code_block_recorder import (_HIGH_LEVEL_ACTION_MAP,@@ -55,7 +56,14 @@ from skyvern.forge.sdk.workflow.models.credential_release import (from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter, OutputParameter, ParameterTypefrom skyvern.schemas.workflows import BlockResult, BlockStatusfrom skyvern.webeye.actions.action_types import ActionType-from skyvern.webeye.actions.actions import Action, ActionStatus, ClickAction, GotoUrlAction, InputTextAction+from skyvern.webeye.actions.actions import (+ Action,+ ActionStatus,+ ClickAction,+ GotoUrlAction,+ InputTextAction,+ SolveCaptchaAction,+)from skyvern.webeye.browser_artifacts import BrowserArtifactsfrom skyvern.webeye.playwright_input import (PLAYWRIGHT_DEFAULT_TIMEOUT_MS,@@ -419,6 +427,56 @@ def test_recording_page_keeps_raw_page_behind_private_seam() -> None:assert recording_page._underlying_page is raw_page[email protected]("result", [True, False])+async def test_trusted_captcha_operation_records_boolean_result_around_nested_actions(result: bool) -> None:+ emitted: list[Action] = []++ async def emit(action: Action) -> None:+ emitted.append(action)++ page = RecordingPage(FakePage(), on_action=emit)++ async def solve() -> bool:+ await page.locator("#challenge").click()+ return result++ assert await page._record_solve_captcha(solve, workflow_run_id="wr_test") is result++ recorded = page.recorded_actions()+ assert [action.action_type for action in recorded] == [ActionType.SOLVE_CAPTCHA, ActionType.CLICK]+ assert [action.action_order for action in recorded] == [0, 1]+ assert [action.status for action in recorded] == [ActionStatus.completed, ActionStatus.completed]+ assert isinstance(recorded[0], SolveCaptchaAction)+ assert recorded[0].response == str(result).lower()+ assert recorded[0].workflow_run_id == "wr_test"+ assert {action.action_id for action in emitted} == {action.action_id for action in recorded}+ assert len(emitted) == 2+++async def test_trusted_captcha_operation_records_cancellation_and_reraises() -> None:+ emitted: list[Action] = []++ async def emit(action: Action) -> None:+ emitted.append(action)++ page = RecordingPage(FakePage(), on_action=emit)++ async def cancel() -> bool:+ raise asyncio.CancelledError()++ with pytest.raises(asyncio.CancelledError):+ await page._record_solve_captcha(cancel, workflow_run_id="wr_test")++ [action] = page.recorded_actions()+ assert action.action_type == ActionType.SOLVE_CAPTCHA+ assert action.status == ActionStatus.failed+ assert action.response == "CancelledError"+ assert action.workflow_run_id == "wr_test"+ assert [emitted_action.action_id for emitted_action in emitted] == [action.action_id]++@pytest.mark.asyncioasync def test_page_evaluate_records_execute_js_action() -> None:page = RecordingPage(FakePage())@@ -1698,6 +1756,85 @@ async def test_recorded_calls_persist_as_actions_on_the_step(monkeypatch: pytestassert [type(action) for action in hydrated] == [GotoUrlAction, InputTextAction, ClickAction][email protected]("outcome", ["solved", "no_widget", "caught_unsolved"])+async def test_code_block_solver_lifecycle_streams_one_persisted_action(+ monkeypatch: pytest.MonkeyPatch,+ outcome: str,+) -> None:+ page = FakePage()+ context = FakeWorkflowRunContext(secrets={"customer_path": "/account?token=solver-secret#challenge"})+ mocks = _patch_execute_environment(monkeypatch, page, context)++ async def ladder(recording_page: RecordingPage, **_kwargs: object) -> bool:+ await recording_page.locator("#challenge").click()+ if outcome == "caught_unsolved":+ raise block_module.CaptchaChallengeUnsolvedError(+ "https://example.com/account?token=solver-secret#challenge"+ )+ return outcome == "solved"++ monkeypatch.setattr(block_module, "solve_challenge_ladder", ladder)+ code = (+ "try:\n solver_result = await solve_captcha(page)\nexcept Exception:\n code_continued = True"+ if outcome == "caught_unsolved"+ else "solver_result = await solve_captcha(page)"+ )++ result = await _make_code_block(code, goal="handle challenge").execute(+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ assert result.success is True+ actions = sorted(_created_actions(mocks), key=lambda action: action.action_order)+ assert [action.action_type for action in actions] == [ActionType.SOLVE_CAPTCHA, ActionType.CLICK]+ assert [action.action_order for action in actions] == [0, 1]+ solve_action = actions[0]+ assert solve_action.task_id == "tsk_code"+ assert solve_action.step_id == "stp_code"+ assert solve_action.step_order == 0+ assert solve_action.workflow_run_id == "wr_test"+ if outcome == "caught_unsolved":+ assert solve_action.status == ActionStatus.failed+ assert solve_action.response == "CodeBlockCaptchaError"+ else:+ assert solve_action.status == ActionStatus.completed+ assert solve_action.response == ("true" if outcome == "solved" else "false")+ assert "solver-secret" not in solve_action.model_dump_json()+ solver_writes = [action for action in _upsert_calls(mocks) if action.action_type == ActionType.SOLVE_CAPTCHA]+ assert len(solver_writes) == 2+ assert solver_writes[0].action_id == solver_writes[1].action_id+++async def test_code_block_solver_cancellation_streams_failed_action_and_propagates(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ page = FakePage()+ context = FakeWorkflowRunContext()+ mocks = _patch_execute_environment(monkeypatch, page, context)++ async def cancel(_recording_page: RecordingPage, **_kwargs: object) -> bool:+ raise asyncio.CancelledError()++ monkeypatch.setattr(block_module, "solve_challenge_ladder", cancel)+ with pytest.raises(asyncio.CancelledError):+ await _make_code_block("await solve_captcha(page)", goal="handle challenge").execute(+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ [action] = _created_actions(mocks)+ assert action.action_type == ActionType.SOLVE_CAPTCHA+ assert action.status == ActionStatus.failed+ assert action.response == "CancelledError"+ assert action.task_id == "tsk_code"+ assert action.step_id == "stp_code"++@pytest.mark.asyncioasync def test_backgrounded_screenshots_are_drained_and_linked_before_persist(monkeypatch: pytest.MonkeyPatch,