Skip to content

Automate browser based workflows with AI

fix(SKY-8660): raise on fill_form 0-mapped to trigger AI fallback (#5939)

Aaron Perez23484379176c
diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.py
index e7ffe6327..9e52df448 100644
--- a/skyvern/core/script_generations/skyvern_page.py
+++ b/skyvern/core/script_generations/skyvern_page.py
@@ -1984,12 +1984,20 @@ class SkyvernPage(Page):
if not form_fields:
raise RuntimeError(
"fill_form found 0 form fields on the page. "
- "The page may not have finished rendering — try adding "
+ "The page may not have finished rendering - try adding "
"await page.wait(timeout_ms=5000) before fill_form()."
)
mapping = await self.dynamic_field_map(form_fields, data, prompt=prompt)
+ if data and not mapping:
+ raise RuntimeError(
+ f"fill_form mapped 0 of {len(form_fields)} form fields despite "
+ f"{len(data)} data keys provided. The field labels may not match the data keys, "
+ "or the form may not have finished rendering - try adding "
+ "await page.wait(timeout_ms=5000) before fill_form()."
+ )
+
if not await self.validate_mapping(form_fields, mapping, prompt):
raise ScriptTerminationException("fill_form validation failed: user termination conditions not met")
@@ -2038,6 +2046,7 @@ class SkyvernPage(Page):
start_time = time.monotonic()
pages_filled = 0
prev_field_signature: str | None = None
+ prev_unmapped_optional_page = False
consecutive_validation_failures = 0
for page_num in range(max_pages):
@@ -2078,6 +2087,11 @@ class SkyvernPage(Page):
# next-button click didn't navigate. Stop to avoid infinite loop.
field_sig = "|".join((f.get("label") or f.get("name") or f.get("placeholder") or "") for f in fillable)
if field_sig and field_sig == prev_field_signature:
+ if prev_unmapped_optional_page:
+ raise RuntimeError(
+ f"fill_multipage_form mapped 0 form fields on the previous optional page despite "
+ f"{len(data)} data keys provided, and the next click did not advance to a new page."
+ )
LOG.warning(
"fill_multipage_form: same fields detected, page did not advance — stopping",
page_num=page_num,
@@ -2106,6 +2120,24 @@ class SkyvernPage(Page):
mapping = await self.dynamic_field_map(form_fields, data, prompt=prompt)
+ required_fillable = [f for f in fillable if f.get("required")]
+ has_file_field = any(f.get("type") == "file" for f in fillable)
+ unmapped_optional_page = bool(data and not mapping and not required_fillable and not has_file_field)
+ if data and not mapping and required_fillable:
+ raise RuntimeError(
+ f"fill_multipage_form mapped 0 of {len(form_fields)} form fields on page {page_num} despite "
+ f"{len(data)} data keys provided. The field labels may not match the data keys, "
+ "or the form may not have finished rendering - try adding "
+ "await page.wait(timeout_ms=5000) before fill_multipage_form()."
+ )
+ if unmapped_optional_page:
+ LOG.info(
+ "fill_multipage_form: no fields mapped on optional page, continuing",
+ page_num=page_num,
+ field_count=len(form_fields),
+ data_key_count=len(data),
+ )
+
# Skip validation on intermediate pages — validate_mapping checks user
# instructions like "do not submit" which only apply to the final page.
# We'll validate after the loop if needed.
@@ -2140,12 +2172,14 @@ class SkyvernPage(Page):
if new_mapping:
await self.fill_from_mapping(rescan_fields, new_mapping, data=data)
await self._dump_html(debug_dir, f"p{page_num}_02_after_rescan_fill")
+ unmapped_optional_page = False
# Update field signature to use the new fields for stuck detection
fillable = rescan_fillable
form_fields = rescan_fields
prev_field_signature = "|".join(
(f.get("label") or f.get("name") or f.get("placeholder") or "") for f in fillable
)
+ prev_unmapped_optional_page = unmapped_optional_page
# Try to click the next/continue button
try:
@@ -2159,6 +2193,11 @@ class SkyvernPage(Page):
"fill_multipage_form: next button not found, stopping",
page_num=page_num,
)
+ if unmapped_optional_page:
+ raise RuntimeError(
+ f"fill_multipage_form mapped 0 of {len(form_fields)} form fields on page {page_num} "
+ f"despite {len(data)} data keys provided, and could not advance to another page."
+ )
break
await self._dump_html(debug_dir, f"p{page_num}_03_after_click_next")
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2 b/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2
index 16fee76e9..5e9fe7c30 100644
--- a/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2
+++ b/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2
@@ -206,6 +206,13 @@ If the existing code already has a `page.wait()` and it still failed, increase t
await page.fill_form(context.parameters, prompt='...')
```
+4. **Before `fill_form()`/`fill_multipage_form()` when 0 fields are mapped** — If the error message says "fill_form mapped 0 of N form fields despite K data keys provided" or "fill_multipage_form mapped 0 of N form fields", the page rendered some fields but not the ones the script expects to fill (or with different labels). Add `await page.wait(timeout_ms=5000)` **before** the form-fill call to let the right structure render:
+ ```python
+ await page.goto(url)
+ await page.wait(timeout_ms=5000) # wait for the expected form inputs to render
+ await page.fill_form(context.parameters, prompt='...')
+ ```
+
## What to do
1. Compare the episode's form fields to the existing FIELD_MAP.
2. For each field in the episode, first check if it matches a standard category listed above. If it does, do NOT add it to FIELD_MAP — canonical matching handles it automatically.
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer.j2 b/skyvern/forge/prompts/skyvern/script-reviewer.j2
index 97a7b9389..64df31f0b 100644
--- a/skyvern/forge/prompts/skyvern/script-reviewer.j2
+++ b/skyvern/forge/prompts/skyvern/script-reviewer.j2
@@ -266,6 +266,13 @@ If the existing code already has a `page.wait()` and it still failed, increase t
await page.fill_form(context.parameters, prompt='...')
```
+4. **Before `fill_form()`/`fill_multipage_form()` when 0 fields are mapped** — If the error message says "fill_form mapped 0 of N form fields despite K data keys provided" or "fill_multipage_form mapped 0 of N form fields", the page rendered some fields but not the ones the script expects to fill (or with different labels). Add `await page.wait(timeout_ms=5000)` **before** the form-fill call to let the right structure render:
+ ```python
+ await page.goto(url)
+ await page.wait(timeout_ms=5000) # wait for the expected form inputs to render
+ await page.fill_form(context.parameters, prompt='...')
+ ```
+
## What to do
{% for episode in episodes %}
diff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.py
index 06b1f0b47..a35361e15 100644
--- a/tests/unit/test_script_skyvern_page.py
+++ b/tests/unit/test_script_skyvern_page.py
@@ -1182,3 +1182,388 @@ class TestActionSubclassPersistence:
assert isinstance(action, Action)
assert not isinstance(action, VerificationCodeAction)
assert action.action_type == ActionType.VERIFICATION_CODE
+
+
+async def test_fill_form_raises_when_zero_fields_mapped_with_data(mock_scraped_page, mock_ai):
+ """RuntimeError when N>0 fields extracted, non-empty data, but mapping is empty."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [
+ {"label": "username", "type": "text", "selector": "#user"},
+ {"label": "password", "type": "password", "selector": "#pass"},
+ ]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "validate_mapping", new=AsyncMock(return_value=True)) as validate_mock,
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ ):
+ with pytest.raises(RuntimeError, match="mapped 0 of 2"):
+ await script_page.fill_form({"user_email": "[email protected]", "user_pw": "secret"})
+
+ validate_mock.assert_not_called()
+ fill_mock.assert_not_called()
+
+
+async def test_fill_form_does_not_raise_when_data_is_empty(mock_scraped_page, mock_ai):
+ """Empty data legitimately produces an empty mapping; the 0-mapped guard must not fire."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [{"label": "search", "type": "text", "selector": "#q"}]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "validate_mapping", new=AsyncMock(return_value=True)),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ ):
+ await script_page.fill_form({})
+ fill_mock.assert_called_once()
+
+
+async def test_fill_form_raises_for_all_file_form_when_mapping_empty(mock_scraped_page, mock_ai):
+ """0-mapped guard is unconditional - all-file forms also fall back to AI when mapping is empty,
+ since fill_from_mapping's post-fill heuristic match is unreliable enough to risk silent no-ops."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [
+ {"label": "resume", "type": "file", "selector": "#resume"},
+ {"label": "cover_letter", "type": "file", "selector": "#cl"},
+ ]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "validate_mapping", new=AsyncMock(return_value=True)),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ ):
+ with pytest.raises(RuntimeError, match="mapped 0 of 2"):
+ await script_page.fill_form({"resume_url": "https://example.com/resume.pdf"})
+ fill_mock.assert_not_called()
+
+
+async def test_fill_multipage_form_raises_when_zero_fields_mapped_with_data(mock_scraped_page, mock_ai):
+ """RuntimeError when a multi-page form has fillable fields and data but maps 0 fields."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [
+ {"label": "email", "type": "text", "tag": "input", "selector": "#email", "required": True},
+ {"label": "password", "type": "password", "tag": "input", "selector": "#password", "required": True},
+ ]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock()) as click_mock,
+ ):
+ with pytest.raises(RuntimeError, match="fill_multipage_form mapped 0 of 2"):
+ await script_page.fill_multipage_form({"username": "[email protected]", "user_pw": "secret"})
+
+ fill_mock.assert_not_called()
+ click_mock.assert_not_called()
+
+
+async def test_fill_multipage_form_does_not_raise_when_data_is_empty(mock_scraped_page, mock_ai):
+ """Empty data can legitimately produce an empty multi-page mapping."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [{"label": "search", "type": "text", "tag": "input", "selector": "#q"}]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock(side_effect=Exception)),
+ ):
+ pages_filled = await script_page.fill_multipage_form({})
+
+ assert pages_filled == 1
+ fill_mock.assert_called_once()
+
+
+async def test_fill_multipage_form_skips_unmapped_optional_intermediate_page(mock_scraped_page, mock_ai):
+ """Optional intermediate pages with no matching data should still advance."""
+ mock_page = create_mock_page()
+ mock_page.evaluate = AsyncMock(return_value=[])
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ first_page_fields = [{"label": "email", "type": "text", "tag": "input", "selector": "#email"}]
+ optional_page_fields = [
+ {
+ "label": "demographics",
+ "type": "radio_group",
+ "tag": "input",
+ "selector": "#demographics",
+ "required": False,
+ }
+ ]
+ final_page_fields = [{"label": "phone", "type": "text", "tag": "input", "selector": "#phone", "required": True}]
+
+ with (
+ patch.object(
+ script_page,
+ "extract_form_fields",
+ new=AsyncMock(
+ side_effect=[
+ first_page_fields,
+ first_page_fields,
+ optional_page_fields,
+ optional_page_fields,
+ final_page_fields,
+ final_page_fields,
+ ]
+ ),
+ ),
+ patch.object(
+ script_page, "dynamic_field_map", new=AsyncMock(side_effect=[{0: "[email protected]"}, {}, {0: "555-0100"}])
+ ),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock(side_effect=[None, None, Exception])) as click_mock,
+ patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new=AsyncMock()),
+ ):
+ pages_filled = await script_page.fill_multipage_form({"email": "[email protected]", "phone": "555-0100"})
+
+ assert pages_filled == 3
+ assert fill_mock.call_count == 3
+ assert click_mock.call_count == 3
+
+
+async def test_fill_multipage_form_skips_unmapped_optional_first_page(mock_scraped_page, mock_ai):
+ """Optional first pages with no matching data should still advance to later pages."""
+ mock_page = create_mock_page()
+ mock_page.evaluate = AsyncMock(return_value=[])
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ optional_page_fields = [
+ {
+ "label": "referral source",
+ "type": "radio_group",
+ "tag": "input",
+ "selector": "#referral",
+ "required": False,
+ }
+ ]
+ second_page_fields = [
+ {"label": "email", "type": "text", "tag": "input", "selector": "#email", "required": True}
+ ]
+
+ with (
+ patch.object(
+ script_page,
+ "extract_form_fields",
+ new=AsyncMock(
+ side_effect=[
+ optional_page_fields,
+ optional_page_fields,
+ second_page_fields,
+ second_page_fields,
+ ]
+ ),
+ ),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(side_effect=[{}, {0: "[email protected]"}])),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock(side_effect=[None, Exception])) as click_mock,
+ patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new=AsyncMock()),
+ ):
+ pages_filled = await script_page.fill_multipage_form({"email": "[email protected]"})
+
+ assert pages_filled == 2
+ assert fill_mock.call_count == 2
+ assert click_mock.call_count == 2
+
+
+async def test_fill_multipage_form_raises_when_unmapped_optional_page_cannot_advance(mock_scraped_page, mock_ai):
+ """An unmapped optional page must either advance or raise to avoid silent no-op success."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [
+ {
+ "label": "referral source",
+ "type": "radio_group",
+ "tag": "input",
+ "selector": "#referral",
+ "required": False,
+ }
+ ]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock(side_effect=Exception)) as click_mock,
+ ):
+ with pytest.raises(RuntimeError, match="could not advance"):
+ await script_page.fill_multipage_form({"email": "[email protected]"})
+
+ fill_mock.assert_called_once()
+ click_mock.assert_called_once()
+
+
+async def test_fill_multipage_form_raises_when_unmapped_optional_page_stays_put(mock_scraped_page, mock_ai):
+ """An unmapped optional page must not count as skippable if the next click does not advance."""
+ mock_page = create_mock_page()
+ mock_page.evaluate = AsyncMock(return_value=[])
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [
+ {
+ "label": "referral source",
+ "type": "radio_group",
+ "tag": "input",
+ "selector": "#referral",
+ "required": False,
+ }
+ ]
+
+ with (
+ patch.object(
+ script_page,
+ "extract_form_fields",
+ new=AsyncMock(side_effect=[form_fields, form_fields, form_fields]),
+ ),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock()) as click_mock,
+ patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new=AsyncMock()),
+ ):
+ with pytest.raises(RuntimeError, match="next click did not advance"):
+ await script_page.fill_multipage_form({"email": "[email protected]"})
+
+ fill_mock.assert_called_once()
+ click_mock.assert_called_once()
+
+
+async def test_fill_multipage_form_allows_unmapped_optional_file_page_to_stop(mock_scraped_page, mock_ai):
+ """Unmapped optional file pages may succeed through fill_from_mapping's URL fallback."""
+ mock_page = create_mock_page()
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.Page.__init__",
+ return_value=None,
+ ):
+ script_page = ScriptSkyvernPage(
+ scraped_page=mock_scraped_page,
+ page=mock_page,
+ ai=mock_ai,
+ )
+
+ form_fields = [
+ {
+ "label": "resume",
+ "type": "file",
+ "tag": "input",
+ "selector": "#resume",
+ "required": False,
+ }
+ ]
+
+ with (
+ patch.object(script_page, "extract_form_fields", new=AsyncMock(return_value=form_fields)),
+ patch.object(script_page, "dynamic_field_map", new=AsyncMock(return_value={})),
+ patch.object(script_page, "fill_from_mapping", new=AsyncMock()) as fill_mock,
+ patch.object(script_page, "click", new=AsyncMock(side_effect=Exception)) as click_mock,
+ ):
+ pages_filled = await script_page.fill_multipage_form({"resume_url": "https://example.com/resume.pdf"})
+
+ assert pages_filled == 1
+ fill_mock.assert_called_once()
+ click_mock.assert_called_once()