Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Skip speculative extract-actions in script_mode workflows (#6057)
pedrohsdb13f96dd1b0e9
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 601f6a403..1a691bb78 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -2250,6 +2250,19 @@ class ForgeAgent:)return None+ ctx = skyvern_context.current()+ if ctx and ctx.script_mode:+ LOG.debug(+ "Skipping speculative extract-actions in script_mode workflow",+ step_id=current_step.step_id,+ task_id=task.task_id,+ )+ return None++ # Brief back-off so verification can short-circuit cheap CompleteAction cases+ # before we start the speculative scrape.+ await asyncio.sleep(1.0)+try:next_step.is_speculative = True@@ -4576,14 +4589,7 @@ class ForgeAgent:organization_id=task.organization_id,)- LOG.debug(- "Waiting before launching speculative plan",- step_id=step.step_id,- task_id=task.task_id,- )- await asyncio.sleep(1.0)-- speculative_task = asyncio.create_task(+ speculative_task: asyncio.Task[SpeculativePlan | None] = asyncio.create_task(self._speculate_next_step_plan(organization=organization,task=task,diff --git a/tests/unit/test_parallel_verification.py b/tests/unit/test_parallel_verification.pyindex edbe63f58..905957b99 100644--- a/tests/unit/test_parallel_verification.py+++ b/tests/unit/test_parallel_verification.py@@ -148,6 +148,291 @@ async def test_parallel_verification_skips_extraction_without_navigation_goal(run_data_extraction_mock.assert_not_awaited()+async def test_speculate_next_step_plan_skips_in_script_mode(monkeypatch: pytest.MonkeyPatch) -> None:+ """_speculate_next_step_plan returns None without doing any LLM work+ when ctx.script_mode is True."""+ agent = ForgeAgent()+ now = datetime.now(UTC)++ organization = make_organization(now)+ task = make_task(now, organization)+ current_step = make_step(now, task, step_id="step-cur", status=StepStatus.completed, order=0, output=None)+ next_step = make_step(now, task, step_id="step-next", status=StepStatus.created, order=1, output=None)++ sleep_mock = AsyncMock(return_value=None)+ monkeypatch.setattr("skyvern.forge.agent.asyncio.sleep", sleep_mock)++ build_prompt_mock = AsyncMock()+ monkeypatch.setattr(agent, "build_and_record_step_prompt", build_prompt_mock)++ browser_state, _scraped_page, _page = make_browser_state()++ context = SkyvernContext(+ task_id=task.task_id,+ step_id=None,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ tz_info=ZoneInfo("UTC"),+ )+ context.script_mode = True+ with skyvern_context.scoped(context):+ plan = await agent._speculate_next_step_plan(+ organization=organization,+ task=task,+ current_step=current_step,+ next_step=next_step,+ browser_state=browser_state,+ engine=RunEngine.skyvern_v1,+ )++ assert plan is None+ # No prompt build, no sleep — we exited before either.+ build_prompt_mock.assert_not_called()+ sleep_mock.assert_not_called()+++async def test_speculate_next_step_plan_proceeds_when_not_in_script_mode(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Sanity check: without ctx.script_mode, speculation proceeds past the gate+ (builds the prompt, sleeps for the verification head-start, calls the LLM)."""+ agent = ForgeAgent()+ now = datetime.now(UTC)++ organization = make_organization(now)+ task = make_task(now, organization)+ current_step = make_step(now, task, step_id="step-cur", status=StepStatus.completed, order=0, output=None)+ next_step = make_step(now, task, step_id="step-next", status=StepStatus.created, order=1, output=None)++ sleep_mock = AsyncMock(return_value=None)+ monkeypatch.setattr("skyvern.forge.agent.asyncio.sleep", sleep_mock)++ browser_state, scraped_page, page = make_browser_state()+ browser_state.get_working_page = AsyncMock(return_value=page)+ scraped_page.check_pdf_viewer_embed = MagicMock(return_value=False)+ scraped_page.screenshots = [b"img"]++ build_prompt_mock = AsyncMock(return_value=(scraped_page, "prompt", False, "extract-actions"))+ monkeypatch.setattr(agent, "build_and_record_step_prompt", build_prompt_mock)+ monkeypatch.setattr(agent, "register_async_operations", AsyncMock())++ llm_handler_mock = AsyncMock(return_value={"actions": []})+ monkeypatch.setattr(+ "skyvern.forge.agent.LLMAPIHandlerFactory.get_override_llm_api_handler",+ lambda *_args, **_kwargs: llm_handler_mock,+ )+ monkeypatch.setattr(agent.async_operation_pool, "run_operation", MagicMock())++ context = SkyvernContext(+ task_id=task.task_id,+ step_id=None,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ tz_info=ZoneInfo("UTC"),+ )+ # script_mode defaults to False+ with skyvern_context.scoped(context):+ plan = await agent._speculate_next_step_plan(+ organization=organization,+ task=task,+ current_step=current_step,+ next_step=next_step,+ browser_state=browser_state,+ engine=RunEngine.skyvern_v1,+ )++ assert plan is not None+ build_prompt_mock.assert_awaited_once()+ sleep_mock.assert_awaited() # verification head-start+++async def test_orchestrator_skips_speculative_in_script_mode_complete_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """End-to-end: with ctx.script_mode=True and complete_action=CompleteAction,+ _handle_completed_step_with_parallel_verification must take the discard branch+ without ever calling build_and_record_step_prompt (the first real LLM-tied+ side effect inside _speculate_next_step_plan)."""+ agent = ForgeAgent()+ now = datetime.now(UTC)+ organization = make_organization(now)+ # No data_extraction_goal — keeps the test focused on the gate and avoids the+ # post-complete extraction path (extraction_cache, etc.) which isn't relevant here.+ task = make_task(now, organization, data_extraction_goal=None)++ step = make_step(+ now,+ task,+ step_id="step-orc-c",+ status=StepStatus.completed,+ order=0,+ output=AgentStepOutput(action_results=[], actions_and_results=[]),+ )+ next_step = make_step(now, task, step_id="step-next-orc-c", status=StepStatus.created, order=1, output=None)++ complete_action = CompleteAction(reasoning="done", verified=True)+ mocks = setup_parallel_verification_mocks(+ agent,+ step=step,+ task=task,+ monkeypatch=monkeypatch,+ next_step=next_step,+ complete_action=complete_action,+ handle_action_responses=[[ActionSuccess()]],+ )+ # Restore the real _speculate_next_step_plan so the in-function gate runs.+ monkeypatch.setattr(agent, "_speculate_next_step_plan", ForgeAgent._speculate_next_step_plan.__get__(agent))+ # Mock build_and_record_step_prompt so we can assert the gate fired before LLM work began.+ build_prompt_mock = AsyncMock()+ monkeypatch.setattr(agent, "build_and_record_step_prompt", build_prompt_mock)++ browser_state, scraped_page, page = make_browser_state()+ browser_state.must_get_working_page = AsyncMock(return_value=page)++ context = SkyvernContext(+ task_id=task.task_id,+ step_id=None,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ tz_info=ZoneInfo("UTC"),+ )+ context.script_mode = True+ with skyvern_context.scoped(context):+ completed, _last_step, returned_next_step = await agent._handle_completed_step_with_parallel_verification(+ organization=organization,+ task=task,+ step=step,+ page=page,+ browser_state=browser_state,+ scraped_page=scraped_page,+ engine=RunEngine.skyvern_v1,+ )++ # Verification ran:+ mocks.check_user_goal_complete.assert_awaited_once()+ # Speculative LLM side-effect never happened (the gate inside _speculate_next_step_plan fired):+ build_prompt_mock.assert_not_called()+ # complete-action branch: task marked completed, returns (True, last_step, None):+ assert completed is True+ assert returned_next_step is None+++async def test_orchestrator_skips_speculative_in_script_mode_not_achieved_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """End-to-end: with ctx.script_mode=True and complete_action=None,+ _handle_completed_step_with_parallel_verification must take the+ sequential-continuation branch without ever calling build_and_record_step_prompt."""+ agent = ForgeAgent()+ now = datetime.now(UTC)+ organization = make_organization(now)+ task = make_task(now, organization)++ step = make_step(+ now,+ task,+ step_id="step-orc-na",+ status=StepStatus.completed,+ order=0,+ output=AgentStepOutput(action_results=[], actions_and_results=[]),+ )+ next_step = make_step(now, task, step_id="step-next-orc-na", status=StepStatus.created, order=1, output=None)++ mocks = setup_parallel_verification_mocks(+ agent,+ step=step,+ task=task,+ monkeypatch=monkeypatch,+ next_step=next_step,+ complete_action=None,+ handle_action_responses=[],+ )+ # Restore the real _speculate_next_step_plan so the gate inside it runs.+ monkeypatch.setattr(agent, "_speculate_next_step_plan", ForgeAgent._speculate_next_step_plan.__get__(agent))+ # Mock build_and_record_step_prompt so we can assert it was never called.+ build_prompt_mock = AsyncMock()+ monkeypatch.setattr(agent, "build_and_record_step_prompt", build_prompt_mock)+ monkeypatch.setattr(+ "skyvern.forge.agent.ForgeAgent._check_workflow_run_step_budget",+ AsyncMock(return_value=None),+ )++ browser_state, scraped_page, page = make_browser_state()++ context = SkyvernContext(+ task_id=task.task_id,+ step_id=None,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ tz_info=ZoneInfo("UTC"),+ )+ context.script_mode = True+ with skyvern_context.scoped(context):+ completed, _last_step, returned_next_step = await agent._handle_completed_step_with_parallel_verification(+ organization=organization,+ task=task,+ step=step,+ page=page,+ browser_state=browser_state,+ scraped_page=scraped_page,+ engine=RunEngine.skyvern_v1,+ )++ mocks.check_user_goal_complete.assert_awaited_once()+ build_prompt_mock.assert_not_called()+ # Sequential-continuation branch returns (None, None, next_step):+ assert completed is None+ assert returned_next_step == next_step+++async def test_speculate_next_step_plan_skips_for_cua_engine(monkeypatch: pytest.MonkeyPatch) -> None:+ """The CUA engine bypass short-circuits before the script_mode gate, even when+ script_mode is explicitly False (i.e. the nominal non-script_mode agent path)."""+ from skyvern.schemas.runs import CUA_ENGINES++ agent = ForgeAgent()+ now = datetime.now(UTC)+ organization = make_organization(now)+ task = make_task(now, organization)+ current_step = make_step(now, task, step_id="step-cur", status=StepStatus.completed, order=0, output=None)+ next_step = make_step(now, task, step_id="step-next", status=StepStatus.created, order=1, output=None)++ sleep_mock = AsyncMock(return_value=None)+ monkeypatch.setattr("skyvern.forge.agent.asyncio.sleep", sleep_mock)+ build_prompt_mock = AsyncMock()+ monkeypatch.setattr(agent, "build_and_record_step_prompt", build_prompt_mock)++ browser_state, _scraped_page, _page = make_browser_state()++ context = SkyvernContext(+ task_id=task.task_id,+ step_id=None,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ tz_info=ZoneInfo("UTC"),+ )+ # script_mode False — proves the CUA early-return runs first, regardless of the script_mode gate.+ cua_engine = next(iter(CUA_ENGINES))+ with skyvern_context.scoped(context):+ plan = await agent._speculate_next_step_plan(+ organization=organization,+ task=task,+ current_step=current_step,+ next_step=next_step,+ browser_state=browser_state,+ engine=cua_engine,+ )++ assert plan is None+ build_prompt_mock.assert_not_called()+ sleep_mock.assert_not_called()++def test_task_validate_update_requires_extracted_information() -> None:now = datetime.now(UTC)organization = make_organization(now)