Skip to content

Automate browser based workflows with AI

fix: replace instant download check with progress-aware polling loop (#SKY-8433) (#5142)

pedrohsdba128dc205743
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.py
index 328caaf84..91f0436fa 100644
--- a/skyvern/exceptions.py
+++ b/skyvern/exceptions.py
@@ -403,6 +403,13 @@ class NoFileDownloadTriggered(SkyvernException):
super().__init__(f"Clicking on element doesn't trigger the file download. element_id={element_id}")
+class CachedDownloadError(SkyvernException):
+ """Raised when a cached download block fails to produce a file on the local filesystem."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(f"Cached download error: {message}")
+
+
class BitwardenSecretError(SkyvernException):
def __init__(self, message: str) -> None:
super().__init__(f"Bitwarden secret error: {message}")
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index e08874812..7349df596 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -18,12 +18,18 @@ from fastapi import BackgroundTasks, HTTPException
from jinja2.sandbox import SandboxedEnvironment
from skyvern.config import settings
-from skyvern.constants import GET_DOWNLOADED_FILES_TIMEOUT, SAVE_DOWNLOADED_FILES_TIMEOUT
+from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX, GET_DOWNLOADED_FILES_TIMEOUT, SAVE_DOWNLOADED_FILES_TIMEOUT
from skyvern.core.script_generations.constants import SCRIPT_TASK_BLOCKS
from skyvern.core.script_generations.generate_script import _build_block_fn, create_or_update_script_block
from skyvern.core.script_generations.script_skyvern_page import script_run_context_manager
from skyvern.errors.errors import UserDefinedError
-from skyvern.exceptions import ScriptNotFound, ScriptTerminationException, StepTerminationError, WorkflowRunNotFound
+from skyvern.exceptions import (
+ CachedDownloadError,
+ ScriptNotFound,
+ ScriptTerminationException,
+ StepTerminationError,
+ WorkflowRunNotFound,
+)
from skyvern.forge import app
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.files import get_path_for_workflow_download_directory, list_files_in_directory, rename_file
@@ -1849,21 +1855,91 @@ async def download(
await _run_cached_function(cached_fn)
- # Check local filesystem for newly downloaded files.
- # This is the primary verification — it doesn't depend on S3/remote
- # storage and catches the case where download_selector() returned None
- # causing the click to silently succeed without downloading anything.
- local_files_after_download = (
- list_files_in_directory(local_download_dir) if local_download_dir.exists() else []
- )
- # Filter out incomplete .crdownload files from both lists for an accurate comparison
- local_new_files = set(local_files_after_download) - set(local_files_before)
- local_new_complete_files = [f for f in local_new_files if not f.endswith(".crdownload")]
- if not local_new_complete_files:
- raise Exception(
- "Cached download block did not produce a new file on the local filesystem. "
- f"Local files before: {len(local_files_before)}, after: {len(local_files_after_download)}"
- )
+ # Poll local filesystem for newly downloaded files.
+ #
+ # Two download mechanisms exist with different write patterns:
+ # 1. CDP Fetch interceptor (primary): streams body to memory, then
+ # writes the complete file atomically. File is usually on disk by
+ # the time page.click() returns.
+ # 2. Browser native download: creates a .crdownload temp file that
+ # grows incrementally, then renames to the final name on completion.
+ #
+ # Strategy:
+ # - Check immediately (catches fast CDP atomic writes).
+ # - If a .crdownload is detected, a browser-native download is in
+ # progress — keep polling until it completes or times out.
+ # - If nothing appears within a short grace period, the cached click
+ # likely did nothing (e.g. download_selector() returned None).
+ # Shorter than agent-path constants (BROWSER_DOWNLOAD_TIMEOUT=600,
+ # BROWSER_DOWNLOAD_MAX_WAIT_TIME=120) — cached fallback to AI is cheap.
+ _POLL_INTERVAL = 2 # seconds between filesystem checks
+ _GRACE_PERIOD = 6 # seconds to wait when no download activity detected
+ _DOWNLOAD_TIMEOUT = 300 # max seconds to wait for an in-progress download
+ _DISAPPEARED_TIMEOUT = 30 # seconds to wait after .crdownload vanishes without completion
+ _download_detected = False
+ _disappeared_at: float | None = None
+ _loop = asyncio.get_running_loop()
+ _poll_start = _loop.time()
+
+ while True:
+ _now = _loop.time()
+ _elapsed = _now - _poll_start
+ _local_files_now = list_files_in_directory(local_download_dir) if local_download_dir.exists() else []
+ _new_files = set(_local_files_now) - set(local_files_before)
+ _new_complete = [f for f in _new_files if not f.endswith(BROWSER_DOWNLOADING_SUFFIX)]
+ _new_downloading = [f for f in _new_files if f.endswith(BROWSER_DOWNLOADING_SUFFIX)]
+
+ # A complete file appeared — download succeeded
+ if _new_complete:
+ break
+
+ # A .crdownload file exists — browser-native download in progress
+ if _new_downloading:
+ if not _download_detected:
+ LOG.info(
+ "Download in progress — .crdownload file detected, waiting for completion",
+ workflow_run_id=run_id,
+ downloading_files=len(_new_downloading),
+ )
+ _download_detected = True
+ _disappeared_at = None # reset — file is (still) present
+ if _elapsed > _DOWNLOAD_TIMEOUT:
+ raise CachedDownloadError(
+ ".crdownload file never completed. "
+ f"Files before: {len(local_files_before)}, after: {len(_local_files_now)}"
+ )
+ await asyncio.sleep(_POLL_INTERVAL)
+ continue
+
+ # Download was detected earlier but .crdownload disappeared without a
+ # complete file replacing it (cancelled/failed). Use a shorter timeout
+ # measured from when the file vanished, not from poll start.
+ if _download_detected:
+ if _disappeared_at is None:
+ _disappeared_at = _now
+ if _now - _disappeared_at > _DISAPPEARED_TIMEOUT:
+ raise CachedDownloadError(
+ "Download disappeared without completing. "
+ f"Files before: {len(local_files_before)}, after: {len(_local_files_now)}"
+ )
+ await asyncio.sleep(_POLL_INTERVAL)
+ continue
+
+ # Nothing new at all — wait a grace period then give up
+ if _elapsed >= _GRACE_PERIOD:
+ LOG.warning(
+ "Cached download produced no file after grace period",
+ workflow_run_id=run_id,
+ elapsed=_elapsed,
+ files_before=len(local_files_before),
+ files_after=len(_local_files_now),
+ )
+ raise CachedDownloadError(
+ "No file produced after cached download. "
+ f"Files before: {len(local_files_before)}, after: {len(_local_files_now)}"
+ )
+
+ await asyncio.sleep(_POLL_INTERVAL)
# Rename newly downloaded files using download_suffix if provided.
# Rename runs BEFORE S3 upload so that remote storage receives the
@@ -1875,7 +1951,7 @@ async def download(
for file_path in new_files:
file_extension = Path(file_path).suffix
# Skip incomplete downloads
- if file_extension == ".crdownload":
+ if file_extension == BROWSER_DOWNLOADING_SUFFIX:
continue
final_file_name = download_suffix
target_path = local_download_dir / (final_file_name + file_extension)
diff --git a/tests/unit/test_cached_download_s3_upload.py b/tests/unit/test_cached_download_s3_upload.py
index e6a21a62b..7ca8038d7 100644
--- a/tests/unit/test_cached_download_s3_upload.py
+++ b/tests/unit/test_cached_download_s3_upload.py
@@ -189,20 +189,32 @@ async def test_download_suffix_rename_uses_file_path_directly(setup, tmp_path):
@pytest.mark.asyncio
async def test_verification_raises_when_no_new_file(setup):
- """When no new file appears on local filesystem, the cached path should raise
- and fall back to AI."""
+ """When no new file appears on local filesystem, the poll loop should exhaust
+ the grace period and fall back to AI."""
refs = setup(
get_side_effect=[[], [], [], []],
- list_files_side_effect=[[], []], # before=empty, after=still empty (local verification fails)
+ list_files_side_effect=[[] for _ in range(10)], # before + polls all empty
)
try:
from skyvern.services.script_service import download
- await download(prompt="Download invoice", label="test_block")
+ call_count = 0
+
+ def advancing_time():
+ nonlocal call_count
+ call_count += 1
+ return call_count * 3.0
+
+ with (
+ patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
+ patch(f"{MODULE}.asyncio.get_running_loop") as mock_loop,
+ ):
+ mock_loop.return_value.time = advancing_time
+ await download(prompt="Download invoice", label="test_block")
refs["fallback"].assert_called_once()
error_arg = refs["fallback"].call_args.kwargs.get("error")
- assert "did not produce a new file on the local filesystem" in str(error_arg)
+ assert "no file produced" in str(error_arg).lower() or "did not produce" in str(error_arg).lower()
finally:
_cleanup(refs)
@@ -420,69 +432,171 @@ async def test_block_marked_completed_on_success(setup, tmp_path):
@pytest.mark.asyncio
-async def test_local_verification_fails_when_no_file_downloaded(setup):
+async def test_poll_fails_when_no_file_downloaded(setup):
"""SKY-8433: When download_selector() returns None and click silently succeeds
- without downloading anything, the local filesystem check should detect
- no new files and trigger AI fallback instead of silently succeeding."""
+ without downloading anything, the poll loop should detect no new files
+ after the grace period and trigger AI fallback."""
+ # The poll loop checks list_files once per iteration. With a 6s grace period
+ # and 2s sleep, we need: 1 (before) + ~4 poll iterations of empty results.
refs = setup(
- get_side_effect=[[]], # S3 before-check only; local check fails before S3 after-check
- list_files_side_effect=[[], []], # before=empty, after=still empty
+ get_side_effect=[[]],
+ list_files_side_effect=[[] for _ in range(10)],
)
try:
from skyvern.services.script_service import download
- await download(prompt="Download invoice", label="test_block")
+ # Mock time to advance past grace period, mock sleep to not wait
+ call_count = 0
+
+ def advancing_time():
+ nonlocal call_count
+ call_count += 1
+ return call_count * 3.0 # each call advances 3s, exceeds 6s grace after 2 polls
+
+ with (
+ patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
+ patch(f"{MODULE}.asyncio.get_running_loop") as mock_loop,
+ ):
+ mock_loop.return_value.time = advancing_time
+ await download(prompt="Download invoice", label="test_block")
refs["fallback"].assert_called_once()
error_arg = refs["fallback"].call_args.kwargs.get("error")
- assert "did not produce a new file on the local filesystem" in str(error_arg)
- # S3 save should NOT be called since local check fails first
+ assert "no file produced" in str(error_arg).lower() or "did not produce" in str(error_arg).lower()
refs["storage"].save_downloaded_files.assert_not_called()
finally:
_cleanup(refs)
@pytest.mark.asyncio
-async def test_local_verification_ignores_crdownload_files(setup, tmp_path):
- """Incomplete .crdownload files should not count as successful downloads
- for local filesystem verification."""
+async def test_poll_waits_for_crdownload_to_complete(setup, tmp_path):
+ """When a .crdownload file appears (browser-native download in progress),
+ the poll loop should keep waiting until the complete file appears."""
download_dir = tmp_path / "downloads"
incomplete_file = str(download_dir / "invoice.pdf.crdownload")
+ complete_file = str(download_dir / "invoice.pdf")
refs = setup(
- get_side_effect=[[]],
- list_files_side_effect=[[], [incomplete_file]], # only incomplete file appeared
+ get_side_effect=[[], [complete_file]],
+ list_files_side_effect=[
+ [], # before
+ [incomplete_file], # poll 1: .crdownload detected, keep waiting
+ [incomplete_file], # poll 2: still downloading
+ [complete_file], # poll 3: download finished, .crdownload renamed
+ ],
)
try:
from skyvern.services.script_service import download
- await download(prompt="Download invoice", label="test_block")
+ with patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock):
+ await download(prompt="Download invoice", label="test_block")
- refs["fallback"].assert_called_once()
- error_arg = refs["fallback"].call_args.kwargs.get("error")
- assert "did not produce a new file on the local filesystem" in str(error_arg)
+ refs["fallback"].assert_not_called()
+ refs["update_block"].assert_called_once()
+ refs["storage"].save_downloaded_files.assert_called_once()
finally:
_cleanup(refs)
@pytest.mark.asyncio
-async def test_local_verification_passes_with_complete_file(setup, tmp_path):
- """When a complete file appears on the local filesystem after the cached
- function runs, the local verification should pass and allow the block
- to proceed to S3 upload and completion."""
+async def test_poll_passes_immediately_with_complete_file(setup, tmp_path):
+ """When a complete file appears immediately after the cached function
+ (CDP atomic write), the poll should pass on the first check with no waiting."""
download_dir = tmp_path / "downloads"
local_file = str(download_dir / "invoice.pdf")
refs = setup(
- get_side_effect=[[], [local_file]], # S3 verification also passes
- list_files_side_effect=[[], [local_file]], # local verification passes
+ get_side_effect=[[], [local_file]],
+ list_files_side_effect=[[], [local_file]], # before=empty, first poll=file present
)
try:
from skyvern.services.script_service import download
- await download(prompt="Download invoice", label="test_block")
+ sleep_mock = AsyncMock()
+ with patch(f"{MODULE}.asyncio.sleep", sleep_mock):
+ await download(prompt="Download invoice", label="test_block")
refs["fallback"].assert_not_called()
refs["update_block"].assert_called_once()
- # S3 save should be called since local check passed
refs["storage"].save_downloaded_files.assert_called_once()
+ # Should not have slept — file was there immediately
+ sleep_mock.assert_not_called()
+ finally:
+ _cleanup(refs)
+
+
+async def test_poll_grace_period_only_crdownload_fails(setup, tmp_path):
+ """If only .crdownload files appear and never complete within the timeout,
+ the poll should eventually fail and trigger AI fallback."""
+ download_dir = tmp_path / "downloads"
+ incomplete_file = str(download_dir / "invoice.pdf.crdownload")
+ refs = setup(
+ get_side_effect=[[]],
+ # Keep returning only .crdownload forever — simulate stalled download
+ list_files_side_effect=[[], *[[incomplete_file]] * 200],
+ )
+ try:
+ from skyvern.services.script_service import download
+
+ # Mock sleep to not actually wait, and mock time to advance past timeout
+ call_count = 0
+ real_time = asyncio.get_running_loop().time
+
+ def advancing_time():
+ nonlocal call_count
+ call_count += 1
+ # Each call advances 10s, so after ~30 calls we exceed _DOWNLOAD_TIMEOUT (300s)
+ return real_time() + (call_count * 10)
+
+ with (
+ patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
+ patch(f"{MODULE}.asyncio.get_running_loop") as mock_loop,
+ ):
+ mock_loop.return_value.time = advancing_time
+ await download(prompt="Download invoice", label="test_block")
+
+ refs["fallback"].assert_called_once()
+ error_arg = refs["fallback"].call_args.kwargs.get("error")
+ assert "never completed" in str(error_arg).lower() or "timed out" in str(error_arg).lower()
+ finally:
+ _cleanup(refs)
+
+
+async def test_poll_crdownload_disappears_without_complete_file(setup, tmp_path):
+ """When a .crdownload file appears then disappears (download cancelled/failed)
+ without a complete file replacing it, the loop should eventually time out
+ instead of looping forever."""
+ download_dir = tmp_path / "downloads"
+ incomplete_file = str(download_dir / "invoice.pdf.crdownload")
+ refs = setup(
+ get_side_effect=[[]],
+ list_files_side_effect=[
+ [], # before
+ [incomplete_file], # poll 1: .crdownload appears
+ [], # poll 2: .crdownload disappeared, no complete file
+ [], # poll 3+: still nothing
+ *[[] for _ in range(50)],
+ ],
+ )
+ try:
+ from skyvern.services.script_service import download
+
+ call_count = 0
+
+ def advancing_time():
+ nonlocal call_count
+ call_count += 1
+ return call_count * 10.0
+
+ with (
+ patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
+ patch(f"{MODULE}.asyncio.get_running_loop") as mock_loop,
+ ):
+ mock_loop.return_value.time = advancing_time
+ await download(prompt="Download invoice", label="test_block")
+
+ refs["fallback"].assert_called_once()
+ error_arg = refs["fallback"].call_args.kwargs.get("error")
+ assert "disappeared" in str(error_arg).lower() or "did not produce" in str(error_arg).lower()
finally:
_cleanup(refs)