Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Save the page DOM on every Task V3 turn step of sampled runs, and flush each turn as it ends (SKY-18892) (#9046)
pedrohsdb245583101d03
diff --git a/skyvern/config.py b/skyvern/config.pyindex 914e73387..2500b9828 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -577,6 +577,9 @@ class Settings(BaseSettings):TASK_V3_PRE_SUBMIT_CAPTURE_SAMPLE_RATE: float = 0.25# Kill switch: one page DOM per Task V3 block, saved after the loop as html_action (v1 saves html_scrape).TASK_V3_BLOCK_END_DOM: bool = True+ # Fraction of Task V3 runs (keyed like the pre-submit sample) that store the page DOM on every turn step and+ # flush each turn's archive as the turn ends; the rest keep one archive ZIP per block. 0 disables.+ TASK_V3_TURN_DOM_SAMPLE_RATE: float = 0.05# Kill switch for the tier-1 semantic commit read (SKY-15322): decisive-accept-only ARIA/value# probe consulted before the shape heuristics, which remain the fallback either way.TASK_V3_SEMANTIC_COMMIT_VERIFY: bool = Truediff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex c273a322c..8440b951f 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -236,6 +236,7 @@ from skyvern.forge.taskv3.run_arms import (resolve_run_arm,)from skyvern.forge.taskv3.target_label import compose_target_intention+from skyvern.forge.taskv3.turn_dom import TurnDomCapturefrom skyvern.forge.validation_evidence_router import (ValidationRouterMode,ValidationRouterResult,@@ -1777,17 +1778,23 @@ def _is_transient_page_read_refusal(exc: BaseException) -> bool:_BLOCK_END_DOM_TIMEOUT_SECONDS = 5.0+async def _read_page_html(browser_state: BrowserState) -> str | None:+ # v1's html_scrape content. Callers cap it: the page lookup can wait on a lost-page recovery, and get_content's+ # own timeout is 300 s.+ page = await browser_state.get_working_page(prune_excess_pages=False)+ if page is None:+ return None+ return await SkyvernFrame(frame=page, engine_selection=browser_state.engine_selection).get_content()++async def _save_block_end_dom(browser_state: BrowserState, step: Step, task_id: str) -> None:- # v1's html_scrape content, once per block after the loop. One cap covers the page lookup too,- # which can wait on a lost-page recovery; get_content's own timeout is 300 s.+ # Once per block after the loop.started = time.monotonic()html: str | None = Nonereason = "no_working_page"try:async with asyncio.timeout(_BLOCK_END_DOM_TIMEOUT_SECONDS):- page = await browser_state.get_working_page(prune_excess_pages=False)- if page is not None:- html = await SkyvernFrame(frame=page, engine_selection=browser_state.engine_selection).get_content()+ html = await _read_page_html(browser_state)except Exception as exc:reason = type(exc).__name__if html is None:@@ -3365,8 +3372,26 @@ class ForgeAgent:# action rows it wrote land on it. `step` keeps the run's status, billing and step-budget unit.v3_turn_step: Step | None = Nonev3_turn_step_open = False+ # Salted so this sample is independent of the pre-submit one, which buckets the same run key.+ turn_dom = (+ TurnDomCapture(+ functools.partial(_read_page_html, browser_state),+ app.ARTIFACT_MANAGER.accumulate_html_scrape_to_archive,+ )+ if not page_free_validation+ and is_run_sampled(+ f"turn_dom:{task.workflow_run_id or task.task_id}", settings.TASK_V3_TURN_DOM_SAMPLE_RATE+ )+ else None+ )async def _on_turn_start(turn: int) -> Step | None:+ turn_step = await _open_v3_turn_step(turn)+ if turn_dom is not None:+ turn_dom.start(turn_step, turn)+ return turn_step++ async def _open_v3_turn_step(turn: int) -> Step | None:nonlocal v3_turn_step, v3_turn_step_openv3_turn_step, v3_turn_step_open = None, Falsetry:@@ -3403,8 +3428,12 @@ class ForgeAgent:output=AgentStepOutput(llm_seconds=record.llm_seconds if record else None,tool_calls=record.tool_calls if record else None,+ page_dom=turn_dom.turn_output() if turn_dom is not None else None,),)+ if turn_dom is not None:+ # A sampled run keeps each turn durable as it ends; the rest share the block's ZIP.+ app.ARTIFACT_MANAGER.flush_step_archive_in_background(v3_turn_step)async def _on_turn_end(record: TurnRecord) -> None:if record.outcome_status == "canceled":@@ -3871,6 +3900,7 @@ class ForgeAgent:on_action_round=_on_action_round,on_turn_start=_on_turn_start,on_turn_end=_on_turn_end,+ turn_dom=turn_dom,on_pre_action=pre_submit_ring.capture if pre_submit_ring is not None else None,# A code status the model has moved past is no longer what the run ends on.on_page_action=verification_state.page_engaged,@@ -3915,6 +3945,8 @@ class ForgeAgent:StepStatus.canceled if isinstance(sys.exception(), asyncio.CancelledError) else StepStatus.failed,None,)+ if turn_dom is not None:+ turn_dom.cancel()# Frames are already in memory, so a loop that raised or ran out of budget still# persists what it captured; bounded so the unwind of a cancelled run is not held up.with contained_effect("task_v3 pre-submit frame persist", task_id=task.task_id):diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.pyindex d4844f1f8..6352b65d4 100644--- a/skyvern/forge/sdk/artifact/manager.py+++ b/skyvern/forge/sdk/artifact/manager.py@@ -45,6 +45,8 @@ if TYPE_CHECKING:LOG = structlog.get_logger(__name__)ARCHIVE_AGE_THRESHOLD = timedelta(days=90)+# Long enough for slow storage that still progresses; bounds the archive bytes a stalled store keeps alive.+BACKGROUND_FLUSH_TIMEOUT_SECONDS = 120.0def _ensure_aware_utc(value: datetime) -> datetime:@@ -249,6 +251,7 @@ class ArtifactManager:self.upload_aiotasks_map: dict[str, list[asyncio.Task[None]]] = defaultdict(list)# step_id -> accumulator for step archive artifactsself._step_archives: dict[str, StepArchiveAccumulator] = {}+ self._background_flushes: set[asyncio.Task[None]] = set()def _track_upload_aiotask(self,@@ -1799,6 +1802,10 @@ class ArtifactManager:filename = f"html_action_{action_idx}.html"self._add_to_step_archive(acc, filename, html_action, ArtifactType.HTML_ACTION)+ def accumulate_html_scrape_to_archive(self, step: Step, html: bytes) -> str:+ acc = self._get_or_create_step_archive(step, None, None, None)+ return self._add_to_step_archive(acc, "scrape.html", html, ArtifactType.HTML_SCRAPE)+def accumulate_screenshot_to_step_archive(self,step: Step,@@ -1890,6 +1897,25 @@ class ArtifactManager:await self._flush_step_archive_unbundled(accumulator)await self._apply_pending_action_screenshot_updates(accumulator)+ def flush_step_archive_in_background(self, step: Step) -> None:+ # wait_for_upload_aiotasks cancels what it tracks at its timeout, and a flush cancelled after it popped the+ # accumulator loses the archive, so the flush itself is shielded and held here until it ends.+ async def _flush() -> None:+ try:+ async with asyncio.timeout(BACKGROUND_FLUSH_TIMEOUT_SECONDS):+ await self.flush_step_archive(step.step_id)+ except Exception:+ LOG.warning("Failed to flush step archive", step_id=step.step_id, exc_info=True)++ flush = asyncio.create_task(_flush())+ self._background_flushes.add(flush)+ flush.add_done_callback(self._background_flushes.discard)++ async def _shielded() -> None:+ await asyncio.shield(flush)++ self._track_upload_aiotask(step.task_id, asyncio.create_task(_shielded()))+async def flush_task_step_archives_as_one(self, owner: Step) -> None:"""Persist every buffered archive of ``owner``'s task as one ZIP owned by ``owner``.diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex 195838d9e..dd4d351f9 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -91,6 +91,7 @@ from skyvern.forge.taskv3.tools import (apply_blank_page_guard,build_browser_tools,)+from skyvern.forge.taskv3.turn_dom import TurnDomCapturefrom skyvern.schemas.llm import LLMConfig, LLMRouterConfigfrom skyvern.schemas.workflows import BlockTypefrom skyvern.services.otp_service import iter_totp_from_navigation_inputs@@ -273,6 +274,7 @@ async def run_task_v3_agent_loop(on_action_round: ActionRoundSink | None = None,on_turn_start: TurnStart | None = None,on_turn_end: TurnEnd | None = None,+ turn_dom: TurnDomCapture | None = None,on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,on_page_action: Callable[[], None] | None = None,extra_tools: list[ToolSpec] | None = None,@@ -724,6 +726,7 @@ async def run_task_v3_agent_loop(on_action_round=on_action_round,on_turn_start=on_turn_start,on_turn_end=on_turn_end,+ on_model_returned=turn_dom.wait if turn_dom is not None else None,on_pre_action=on_pre_action,on_page_action=on_page_action,max_tokens=max_tokens,@@ -816,6 +819,8 @@ async def run_task_v3_agent_loop(no_tool_call_turns=outcome.no_tool_call_turns,duration_seconds=time.monotonic() - loop_started_at,block_type=block_type,+ dom_arm=turn_dom is not None,+ **(turn_dom.totals() if turn_dom is not None else {}),# State at the run's first failed/terminated finish that got past the failure-evidence gate, next to the# terminal attempt count; all None when no such finish happened.action_attempts=activity.action_attempts,diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex 59bb0e855..b455fe621 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -4005,6 +4005,8 @@ async def run_agent_tool_loop(on_action_round: ActionRoundSink | None = None,on_turn_start: TurnStart | None = None,on_turn_end: TurnEnd | None = None,+ # Awaited after each successful model call, before the turn touches the page.+ on_model_returned: Callable[[], Awaitable[None]] | None = None,on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,# Called before each page-touching tool call is dispatched.on_page_action: Callable[[], None] | None = None,@@ -4745,6 +4747,11 @@ async def run_agent_tool_loop(open_turn.record.llm_seconds = time.monotonic() - llm_started_atif st.outcome is not None:break+ if on_model_returned is not None:+ try:+ await on_model_returned()+ except Exception:+ LOG.warning("taskv3 on_model_returned callback failed", turn=st.turns, exc_info=True)usage = _get(response, "usage") or {}turn_tokens = _get(usage, "total_tokens")diff --git a/skyvern/forge/taskv3/turn_dom.py b/skyvern/forge/taskv3/turn_dom.pynew file mode 100644index 000000000..ffe0daa92--- /dev/null+++ b/skyvern/forge/taskv3/turn_dom.py@@ -0,0 +1,117 @@+import asyncio+import hashlib+import time+from collections.abc import Awaitable, Callable+from typing import Any++import structlog++from skyvern.forge.sdk.models import Step+from skyvern.schemas.steps import StepPageDom++LOG = structlog.get_logger()++TURN_DOM_CAP_SECONDS = 2.0+++class TurnDomCapture:+ """The page each Task V3 turn started from, read while the turn's model call is in flight.++ `start` runs when the turn's step exists and before its model call; `wait` runs after the call returns and+ before anything touches the page, so the stored page is the one the decision was made on.+ """++ def __init__(+ self,+ read_page: Callable[[], Awaitable[str | None]],+ store: Callable[[Step, bytes], str],+ cap_seconds: float = TURN_DOM_CAP_SECONDS,+ ) -> None:+ self._read_page = read_page+ self._store = store+ self._cap_seconds = cap_seconds+ self._task: asyncio.Task[tuple[StepPageDom, int, float]] | None = None+ self._turn = 0+ self._turn_output: StepPageDom | None = None+ self._last_digest: str | None = None+ self._last_artifact_id: str | None = None+ self._counts = {"stored": 0, "deduped": 0, "skipped": 0}+ self._wait_seconds = 0.0+ self._bytes = 0++ def start(self, step: Step | None, turn: int) -> None:+ self.cancel()+ self._turn = turn+ self._turn_output = None+ self._task = asyncio.create_task(self._capture(step))++ def cancel(self) -> None:+ if self._task is not None:+ self._task.cancel()+ self._task = None++ async def wait(self) -> None:+ task, self._task = self._task, None+ if task is None:+ return+ waited_from = time.monotonic()+ result = await task+ self._record(*result, wait_seconds=time.monotonic() - waited_from)++ def turn_output(self) -> StepPageDom | None:+ # A turn whose model call failed never reaches `wait`: keep a capture that already finished, stop one+ # still running before it stores into an archive the turn has handed off.+ task, self._task = self._task, None+ if task is not None:+ if task.done() and not task.cancelled():+ self._record(*task.result(), wait_seconds=0.0)+ else:+ task.cancel()+ return self._turn_output++ def _record(self, page_dom: StepPageDom, size: int, capture_seconds: float, *, wait_seconds: float) -> None:+ self._turn_output = page_dom+ self._counts[page_dom.status] += 1+ self._wait_seconds += wait_seconds+ self._bytes += size if page_dom.status == "stored" else 0+ LOG.info(+ f"taskv3 turn DOM {page_dom.status}",+ turn=self._turn,+ capture_seconds=round(capture_seconds, 3),+ wait_seconds=round(wait_seconds, 3),+ bytes=size,+ reason=page_dom.reason,+ )++ def totals(self) -> dict[str, Any]:+ return {+ "dom_captures": sum(self._counts.values()),+ "dom_stored": self._counts["stored"],+ "dom_deduped": self._counts["deduped"],+ "dom_skipped": self._counts["skipped"],+ "dom_wait_seconds": round(self._wait_seconds, 3),+ "dom_bytes": self._bytes,+ }++ async def _capture(self, step: Step | None) -> tuple[StepPageDom, int, float]:+ started = time.monotonic()+ if step is None:+ return StepPageDom(status="skipped", reason="no_turn_step"), 0, 0.0+ size = 0+ try:+ async with asyncio.timeout(self._cap_seconds):+ html = await self._read_page()+ if html is None:+ return StepPageDom(status="skipped", reason="no_working_page"), 0, time.monotonic() - started+ data = html.encode("utf-8")+ size = len(data)+ digest = hashlib.sha256(data).hexdigest()+ if digest == self._last_digest:+ page_dom = StepPageDom(status="deduped", artifact_id=self._last_artifact_id)+ else:+ artifact_id = self._store(step, data)+ self._last_digest, self._last_artifact_id = digest, artifact_id+ page_dom = StepPageDom(status="stored", artifact_id=artifact_id)+ except Exception as exc:+ page_dom = StepPageDom(status="skipped", reason=type(exc).__name__)+ return page_dom, size, time.monotonic() - starteddiff --git a/skyvern/schemas/steps.py b/skyvern/schemas/steps.pyindex d4759463c..4277d8942 100644--- a/skyvern/schemas/steps.py+++ b/skyvern/schemas/steps.py@@ -26,6 +26,15 @@ class StepToolCall(BaseModel):billable: bool = False+class StepPageDom(BaseModel):+ """The page a Task V3 turn started from: stored in the turn's archive, the same as an earlier turn's stored page+ (`artifact_id` names that copy), or skipped for `reason`."""++ status: Literal["stored", "deduped", "skipped"]+ artifact_id: str | None = None+ reason: str | None = None++class AgentStepOutput(BaseModel):"""Output of the agent step, this is recorded in the database.@@ -43,6 +52,7 @@ class AgentStepOutput(BaseModel):# Task V3 turn steps only: how long the turn's model call took (retries included) and what it called.llm_seconds: float | None = Nonetool_calls: list[StepToolCall] | None = None+ page_dom: StepPageDom | None = None@model_serializer(mode="wrap")def serialize_model(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex d4dad37ec..cfc522637 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -2694,7 +2694,7 @@ def check_existed_but_not_option_element_in_dom_factory(if not element_id:return Falsetry:- locator = frame.locator(f"[{SKYVERN_ID_ATTR}={element_id}]")+ locator = frame.locator(f'[{SKYVERN_ID_ATTR}="{element_id}"]')current_element = SkyvernElement(locator=locator,frame=frame,diff --git a/tests/unit/forge/sdk/artifact/test_manager.py b/tests/unit/forge/sdk/artifact/test_manager.pyindex 6b7a3897a..d2cd4a151 100644--- a/tests/unit/forge/sdk/artifact/test_manager.py+++ b/tests/unit/forge/sdk/artifact/test_manager.py@@ -1,3 +1,4 @@+import asyncioimport ioimport zipfilefrom datetime import datetime@@ -76,3 +77,83 @@ async def test_a_tasks_step_archives_flush_as_one_zip_with_each_file_on_its_own_rows.clear()await manager.flush_step_archive("stp_other")assert sorted(row.bundle_key for row in rows[1:]) == ["llm_request_0.json", "llm_response_0.json"]+++async def test_a_background_turn_flush_survives_the_upload_barrier_cancelling_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # A turn flushed on its own is one object per turn; a barrier that gives up and cancels the tracked task must not+ # lose an archive the flush already popped, and the block-end flush then finds nothing of those turns left.+ manager = ArtifactManager()+ block, turn_1, turn_2 = _step("stp_block", 0), _step("stp_turn_1", 1), _step("stp_turn_2", 2)+ for step in (block, turn_1, turn_2):+ manager.accumulate_llm_call_to_archive(step=step, request=f"{step.step_id} request".encode())+ manager.accumulate_html_scrape_to_archive(turn_1, b"<p>turn 1</p>")++ release = asyncio.Event()+ stored: list[tuple[str, bytes]] = []++ async def _store(artifact: Any, data: bytes) -> None:+ await release.wait()+ stored.append((artifact.step_id, data))++ async def _bulk_create(models: list[Any]) -> list[Any]:+ return models++ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager._bundling_enabled", lambda: True)+ monkeypatch.setattr(+ "skyvern.forge.sdk.artifact.manager.app.STORAGE",+ SimpleNamespace(build_uri=lambda **kwargs: f"s3://artifacts/{kwargs['artifact_id']}", store_artifact=_store),+ )+ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.bulk_create_artifacts", _bulk_create)++ manager.flush_step_archive_in_background(turn_1)+ manager.flush_step_archive_in_background(turn_2)+ await asyncio.sleep(0)+ assert set(manager._step_archives) == {"stp_block"}+ for tracked in list(manager.upload_aiotasks_map["tsk_block"]):+ tracked.cancel()+ await asyncio.sleep(0)+ release.set()+ await asyncio.gather(*manager._background_flushes)++ turn_zips = dict(stored)+ assert sorted(turn_zips) == ["stp_turn_1", "stp_turn_2"]+ with zipfile.ZipFile(io.BytesIO(turn_zips["stp_turn_1"])) as zf:+ assert (sorted(zf.namelist()), zf.read("scrape.html")) == (+ ["llm_request_0.json", "scrape.html"],+ b"<p>turn 1</p>",+ )+ stored.clear()+ await manager.flush_task_step_archives_as_one(block)+ [(owner, zip_bytes)] = stored+ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:+ assert (owner, zf.namelist()) == ("stp_block", ["llm_request_0.json"])+++async def test_a_background_turn_flush_against_a_stalled_store_ends_at_its_deadline(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manager = ArtifactManager()+ turn = _step("stp_turn_1", 1)+ manager.accumulate_llm_call_to_archive(step=turn, request=b"request")++ async def _never_returns(artifact: Any, data: bytes) -> None:+ await asyncio.Event().wait()++ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager.BACKGROUND_FLUSH_TIMEOUT_SECONDS", 0.05)+ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager._bundling_enabled", lambda: True)+ monkeypatch.setattr(+ "skyvern.forge.sdk.artifact.manager.app.STORAGE",+ SimpleNamespace(+ build_uri=lambda **kwargs: f"s3://artifacts/{kwargs['artifact_id']}", store_artifact=_never_returns+ ),+ )++ manager.flush_step_archive_in_background(turn)+ # The outer bound only keeps a regression from hanging the suite.+ await asyncio.wait_for(asyncio.gather(*manager._background_flushes), timeout=5)++ assert manager._background_flushes == set()diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 844fc2237..d57524a28 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -193,9 +193,11 @@ async def _run_execute_task_v3(# Off by default: the block-end DOM adds one get_working_page call after the loop.block_end_dom: bool = False,clean_up_task: AsyncMock | None = None,+ turn_dom_rate: float = 0.0,**task_overrides: Any,) -> tuple[Step, Any, AsyncMock, AsyncMock]:monkeypatch.setattr(settings, "TASK_V3_BLOCK_END_DOM", block_end_dom)+ monkeypatch.setattr(settings, "TASK_V3_TURN_DOM_SAMPLE_RATE", turn_dom_rate)agent = ForgeAgent()now = datetime.now(UTC)organization = make_organization(now)@@ -4845,6 +4847,108 @@ async def test_a_bare_v3_tasks_turn_files_are_one_zip_on_its_block_step(webhook.assert_awaited_once()[email protected]("sampled", [True, False])+async def test_a_sampled_v3_block_saves_each_turns_page_on_that_turn_and_flushes_each_turn(+ monkeypatch: pytest.MonkeyPatch, sampled: bool+) -> None:+ # SKY-18892: a sampled run stores the page each turn started from on that turn's step and makes each turn's+ # archive durable as the turn ends; an unsampled run reads no page per turn and keeps the block-end ZIP alone.+ pages = iter(["<p>start</p>", "<p>after click</p>"])++ async def _content() -> str:+ return next(pages)++ async def fake_create_step(**kwargs: Any) -> Any:+ return SimpleNamespace(step_id=f"turn-{kwargs['order']}", task_id="tsk-turns")++ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.create_step", fake_create_step)+ finish_turn = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.finish_step", finish_turn)+ accumulate = MagicMock(side_effect=lambda step, html: f"dom-{step.step_id}")+ monkeypatch.setattr("skyvern.forge.agent.app.ARTIFACT_MANAGER.accumulate_html_scrape_to_archive", accumulate)+ flush = MagicMock()+ monkeypatch.setattr("skyvern.forge.agent.app.ARTIFACT_MANAGER.flush_step_archive_in_background", flush)++ async def drive_turns(kwargs: dict[str, Any]) -> None:+ turn_dom = kwargs.get("turn_dom")+ assert (turn_dom is not None) is sampled+ for turn, outcome_status in ((1, None), (2, "completed")):+ await kwargs["on_turn_start"](turn)+ if turn_dom is not None:+ await turn_dom.wait()+ await kwargs["on_turn_end"](TurnRecord(turn=turn, tool_calls=[], outcome_status=outcome_status))++ await _run_execute_task_v3(+ monkeypatch,+ LoopOutcome(status="completed", reason="done", billable_actions=[]),+ on_loop_async=drive_turns,+ working_page=_ContentPage(_content),+ turn_dom_rate=1.0 if sampled else 0.0,+ data_extraction_goal=None,+ extracted_information_schema=None,+ )++ saved = [(call.args[0].step_id, call.args[1]) for call in accumulate.call_args_list]+ flushed = [call.args[0].step_id for call in flush.call_args_list]+ page_doms = [call.kwargs["output"].page_dom for call in finish_turn.await_args_list]+ if sampled:+ assert saved == [("turn-1", b"<p>start</p>"), ("turn-2", b"<p>after click</p>")]+ assert flushed == ["turn-1", "turn-2"]+ assert [(dom.status, dom.artifact_id) for dom in page_doms] == [+ ("stored", "dom-turn-1"),+ ("stored", "dom-turn-2"),+ ]+ else:+ assert (saved, flushed, page_doms) == ([], [], [None, None])+++async def test_a_sampled_v3_turn_cut_short_by_a_raising_loop_keeps_its_finished_page_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def _content() -> str:+ return "<p>start</p>"++ async def fake_create_step(**kwargs: Any) -> Any:+ return SimpleNamespace(step_id=f"turn-{kwargs['order']}", task_id="tsk-turns")++ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.create_step", fake_create_step)+ finish_turn = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.finish_step", finish_turn)+ monkeypatch.setattr(+ "skyvern.forge.agent.app.ARTIFACT_MANAGER.accumulate_html_scrape_to_archive",+ MagicMock(side_effect=lambda step, html: f"dom-{step.step_id}"),+ )+ flush = MagicMock()+ monkeypatch.setattr("skyvern.forge.agent.app.ARTIFACT_MANAGER.flush_step_archive_in_background", flush)++ async def start_a_turn_then_let_its_read_finish(kwargs: dict[str, Any]) -> None:+ await kwargs["on_turn_start"](1)+ await asyncio.sleep(0.05)++ with pytest.raises(RuntimeError, match="model call boom"):+ await _run_execute_task_v3(+ monkeypatch,+ LoopOutcome(status="completed", reason="done", billable_actions=[]),+ on_loop_async=start_a_turn_then_let_its_read_finish,+ loop_raises=RuntimeError("model call boom"),+ working_page=_ContentPage(_content),+ turn_dom_rate=1.0,+ data_extraction_goal=None,+ extracted_information_schema=None,+ )++ [finished] = finish_turn.await_args_list+ page_dom = finished.kwargs["output"].page_dom+ assert (finished.kwargs["status"], page_dom.status, page_dom.artifact_id) == (+ StepStatus.failed,+ "stored",+ "dom-turn-1",+ )+ assert [call.args[0].step_id for call in flush.call_args_list] == ["turn-1"]++@pytest.mark.asyncioasync def test_execute_task_v3_workflow_run_step_budget_caps_and_blocks(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_dom_scrape_crash_guards.js b/tests/unit/test_dom_scrape_crash_guards.jsindex d9d975219..d14eaa204 100644--- a/tests/unit/test_dom_scrape_crash_guards.js+++ b/tests/unit/test_dom_scrape_crash_guards.js@@ -660,8 +660,11 @@ test("isElementVisible: display:contents parent containing an option does not ov});}// Each frame is its own window whose element counter starts at 1, as in a browser.- const extractConst = (name) =>- src.match(new RegExp(`^const ${name} =[^;]*;`, "m"))[0];+ const extractConst = (name) => {+ const match = src.match(new RegExp(`^const ${name} =[^;]*;`, "m"));+ if (match === null) throw new Error(`const ${name} not found`);+ return match[0];+ };const idCode = [extractConst("UNIQUE_ID_CHARACTERS"),extractConst("UNIQUE_ID_COUNTER_LENGTH"),diff --git a/tests/unit/test_element_engine_selection_threading.py b/tests/unit/test_element_engine_selection_threading.pyindex 06b21c74d..58275ca6c 100644--- a/tests/unit/test_element_engine_selection_threading.py+++ b/tests/unit/test_element_engine_selection_threading.py@@ -5,6 +5,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+from bs4 import BeautifulSoupfrom skyvern.forge import agent_functionsfrom skyvern.webeye.actions import handler@@ -143,6 +144,20 @@ async def test_dom_filter_threads_dom_public_engine_selection(monkeypatch: pytesassert constructor.call_args.kwargs["engine_selection"] is selection+async def test_dom_filter_locator_selects_an_id_that_starts_with_a_digit() -> None:+ # Minted ids can start with a digit, and an unquoted CSS attribute value cannot.+ document = BeautifulSoup('<div unique_id="0AB"></div><div unique_id="0ABC"></div>', "html.parser")+ dom = MagicMock(engine_selection=None, check_id_in_dom=AsyncMock(return_value=True))+ frame = MagicMock()++ helper = handler.check_existed_but_not_option_element_in_dom_factory(dom)+ await helper({"id": "0AB", "tagName": "div"}, frame)++ (selector,) = frame.locator.call_args.args+ assert [tag["unique_id"] for tag in document.select(selector)] == ["0AB"]++@pytest.mark.asyncioasync def test_autocomplete_threads_one_fresh_selection_snapshot(monkeypatch: pytest.MonkeyPatch) -> None:selection = _selection()diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex a95a63e51..c92b32ba2 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -67,6 +67,7 @@ from skyvern.forge.taskv3.loop import ()from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, mask_opaque_urlsfrom skyvern.forge.taskv3.tools import PAGE_UNAVAILABLE_ERROR, DownloadFailureWatch+from skyvern.forge.taskv3.turn_dom import TurnDomCapturefrom skyvern.schemas.llm import LLMConfig, LLMRouterConfig, LLMRouterModelConfigfrom skyvern.utils.prompt_engine import PROMPT_HARD_CEILING_TOKENSfrom skyvern.utils.token_counter import count_tokens@@ -201,6 +202,39 @@ async def test_engine_exposes_browser_and_finish_tools_no_task_ecosystem() -> Noassert not ({"act", "extract", "validate", "run_task", "login"} & sent)+async def test_engine_joins_the_turn_page_read_after_each_model_call_and_logs_its_totals() -> None:+ saved: list[bytes] = []++ def store(_step: Any, html: bytes) -> str:+ saved.append(html)+ return f"a_{len(saved)}"++ turn_dom = TurnDomCapture(AsyncMock(return_value="<p>page</p>"), store)++ async def on_turn_start(turn: int) -> None:+ turn_dom.start(SimpleNamespace(step_id=f"turn-{turn}"), turn)++ caller = _ScriptedCaller([[("observe", {})], [("finish", {"status": "completed", "reason": "done"})]])+ with capture_logs() as logs:+ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=caller,+ goal="x",+ on_turn_start=on_turn_start,+ turn_dom=turn_dom,+ )++ finished = next(entry for entry in logs if entry["event"] == "taskv3 engine loop finished")+ assert (finished["dom_arm"], finished["dom_captures"], finished["dom_stored"], finished["dom_deduped"]) == (+ True,+ 2,+ 1,+ 1,+ )+ assert saved == [b"<p>page</p>"]++@pytest.mark.asyncioasync def test_engine_records_billable_actions() -> None:# observe/finish are not billable; type + click are — so per-action billing counts 2.diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex 26fe747c9..cf799ebf1 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -5109,6 +5109,50 @@ async def test_each_turn_runs_its_model_call_under_its_own_kwargs_and_reports_ev]+async def test_on_model_returned_runs_after_each_model_call_and_before_the_turn_touches_the_page() -> None:+ # The per-turn page capture joins here, so nothing that reads or acts on the page may run first:+ # not the batch fingerprint sample, not a tool, and not the nudge on a turn with no tool call.+ events: list[str] = []++ class _Caller(_ScriptedCaller):+ async def call(self, **kwargs: Any) -> dict[str, Any]:+ events.append("call")+ return await super().call(**kwargs)++ async def on_model_returned() -> None:+ events.append("returned")++ async def fingerprint() -> str | None:+ events.append("fingerprint")+ return "fp"++ async def click(_args: dict[str, Any]) -> ToolResult:+ events.append("click")+ return ToolResult.ok("clicked")++ tools = [+ ToolSpec(name="click", description="click", parameters={"type": "object"}, handler=click, billable=True),+ make_finish_tool(),+ ]+ script = [[("click", {"selector": "#go"})], [], [("finish", {"status": "completed", "reason": "done"})]]+ outcome = await run_agent_tool_loop(+ llm_caller=_Caller(script),+ system_prompt="sys",+ user_prompt="goal",+ tools=tools,+ max_turns=20,+ max_tool_calls=100,+ page_fingerprint=fingerprint,+ on_model_returned=on_model_returned,+ )++ assert outcome.status == "completed"+ assert events[:4] == ["call", "returned", "fingerprint", "click"]+ assert events.count("call") == events.count("returned") == 3+ assert all(events[i + 1] == "returned" for i, event in enumerate(events) if event == "call")++@pytest.mark.asyncioasync def test_on_action_round_prefers_content_over_reasoning_summary() -> None:round_texts: list[str | None] = []diff --git a/tests/unit/test_taskv3_turn_dom.py b/tests/unit/test_taskv3_turn_dom.pynew file mode 100644index 000000000..b2e15341a--- /dev/null+++ b/tests/unit/test_taskv3_turn_dom.py@@ -0,0 +1,161 @@+import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from skyvern.forge.taskv3 import turn_dom+from skyvern.forge.taskv3.turn_dom import TurnDomCapture++_TURN_STEP: Any = SimpleNamespace(step_id="stp_turn")+++class _Store:+ def __init__(self, raises: BaseException | None = None) -> None:+ self.saved: list[tuple[str, bytes]] = []+ self.called = asyncio.Event()+ self._raises = raises++ def __call__(self, step: Any, html: bytes) -> str:+ self.called.set()+ if self._raises is not None:+ raise self._raises+ self.saved.append((step.step_id, html))+ return f"a_{len(self.saved)}"+++def _pages(*htmls: str | None) -> Any:+ queue = list(htmls)++ async def read_page() -> str | None:+ return queue.pop(0)++ return read_page+++class _GatedPage:+ def __init__(self, html: str) -> None:+ self.html = html+ self.reading = asyncio.Event()+ self.release = asyncio.Event()+ self.stopped = asyncio.Event()++ async def __call__(self) -> str:+ self.reading.set()+ try:+ await self.release.wait()+ except asyncio.CancelledError:+ self.stopped.set()+ raise+ return self.html+++async def test_a_capture_that_finishes_during_the_model_call_costs_the_turn_no_wait(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ clock = [0.0]+ monkeypatch.setattr(turn_dom, "time", SimpleNamespace(monotonic=lambda: clock[0]))+ store = _Store()+ capture = TurnDomCapture(_pages("<html>a</html>"), store)++ capture.start(_TURN_STEP, 1)+ await store.called.wait()+ clock[0] = 10.0+ await capture.wait()++ page_dom = capture.turn_output()+ assert page_dom is not None and page_dom.status == "stored" and page_dom.artifact_id == "a_1"+ assert store.saved == [("stp_turn", b"<html>a</html>")]+ totals = capture.totals()+ assert (totals["dom_captures"], totals["dom_stored"], totals["dom_wait_seconds"]) == (1, 1, 0.0)+++async def test_a_hanging_capture_is_cut_at_its_cap_and_stores_nothing() -> None:+ store = _Store()+ page = _GatedPage("<p>never</p>")+ capture = TurnDomCapture(page, store, cap_seconds=0.05)+ capture.start(_TURN_STEP, 1)+ await capture.wait()++ page_dom = capture.turn_output()+ assert page_dom is not None and (page_dom.status, page_dom.reason) == ("skipped", "TimeoutError")+ assert page.stopped.is_set() and store.saved == []+++async def test_an_unchanged_page_stores_a_reference_to_the_earlier_copy() -> None:+ store = _Store()+ capture = TurnDomCapture(_pages("<p>x</p>", "<p>x</p>", "<p>y</p>"), store)+ outputs: list[Any] = []+ for turn in (1, 2, 3):+ capture.start(_TURN_STEP, turn)+ await capture.wait()+ outputs.append(capture.turn_output())++ assert [(o.status, o.artifact_id) for o in outputs] == [("stored", "a_1"), ("deduped", "a_1"), ("stored", "a_2")]+ assert [html for _, html in store.saved] == [b"<p>x</p>", b"<p>y</p>"]+ totals = capture.totals()+ assert (totals["dom_stored"], totals["dom_deduped"]) == (2, 1)+++ ("read_page", "store", "step", "reason"),+ [+ (_pages(None), _Store(), _TURN_STEP, "no_working_page"),+ (_pages(), _Store(), _TURN_STEP, "IndexError"),+ (_pages("<p>x</p>"), _Store(raises=RuntimeError("redaction failed")), _TURN_STEP, "RuntimeError"),+ # The block step's archive keys files by name, so a second page there would overwrite the first.+ (_pages("<p>x</p>"), _Store(), None, "no_turn_step"),+ ],+)+async def test_a_failing_capture_is_skipped_with_its_reason_and_never_raises(+ read_page: Any, store: _Store, step: Any, reason: str+) -> None:+ capture = TurnDomCapture(read_page, store)+ capture.start(step, 1)+ await capture.wait()++ page_dom = capture.turn_output()+ assert page_dom is not None and (page_dom.status, page_dom.reason) == ("skipped", reason)+ assert capture.totals()["dom_skipped"] == 1+ assert store.saved == []+++async def test_cancel_stops_a_capture_whose_turn_never_reached_the_page() -> None:+ store = _Store()+ page = _GatedPage("<p>x</p>")+ capture = TurnDomCapture(page, store)+ capture.start(_TURN_STEP, 1)+ await page.reading.wait()+ capture.cancel()+ await page.stopped.wait()+ await capture.wait()++ assert store.saved == []+ assert capture.turn_output() is None+ assert capture.totals()["dom_captures"] == 0+++async def test_a_turn_that_ends_without_the_join_still_reports_a_finished_capture_and_stops_a_running_one() -> None:+ # A failed model call ends the turn before the join: a capture already done is recorded, one still+ # running is stopped so it cannot store into an archive the turn has already handed off.+ store = _Store()+ capture = TurnDomCapture(_pages("<p>x</p>"), store)+ capture.start(_TURN_STEP, 1)+ await store.called.wait()+ page_dom = capture.turn_output()+ assert page_dom is not None and page_dom.status == "stored"+ assert capture.totals()["dom_stored"] == 1++ page = _GatedPage("<p>y</p>")+ slow = TurnDomCapture(page, store)+ slow.start(_TURN_STEP, 1)+ await page.reading.wait()+ assert slow.turn_output() is None+ await page.stopped.wait()+ assert [html for _, html in store.saved] == [b"<p>x</p>"]