Skip to content

Automate browser based workflows with AI

fix: patch static click actions inside for-loops in generated scripts (#5052)

pedrohsdb1ed80110e414
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer.j2 b/skyvern/forge/prompts/skyvern/script-reviewer.j2
index a30c88711..0b6f7f54b 100644
--- a/skyvern/forge/prompts/skyvern/script-reviewer.j2
+++ b/skyvern/forge/prompts/skyvern/script-reviewer.j2
@@ -27,6 +27,7 @@ You are a script reviewer for a browser automation system. Your job is to update
await page.fill(selector='...', ai='proactive', prompt='Select how you heard about this job')
```
10. **URL PATTERNS**: When different variants come from different URL hosts or paths, add `url_patterns` to the `page.classify()` call for FREE Tier-0 disambiguation. Use regex on the URL path: `url_patterns={"variant_a": "example\\.com/form-a"}`. URL patterns are checked BEFORE text patterns and cost nothing.
+11. **FOR-LOOP BLOCKS**: When code runs inside a for-loop (e.g. by iterating over extracted items), every `page.click()`, `page.goto()`, or `page.download_file()` call MUST use the loop variable (`current_value`) to target the specific item. Never use a static selector or generic prompt that would resolve to the same element on every iteration. Prefer `page.goto(current_value["url"])` for direct URLs, or include the item's title/identifier in the selector: `selector=f'a:has-text("{current_value["title"]}")'`.
## Block Navigation Goal
```
diff --git a/skyvern/services/workflow_script_service.py b/skyvern/services/workflow_script_service.py
index 793e83f19..e1c12387d 100644
--- a/skyvern/services/workflow_script_service.py
+++ b/skyvern/services/workflow_script_service.py
@@ -432,6 +432,9 @@ async def generate_workflow_script(
LOG.error("Failed to generate workflow script source", exc_info=True)
return
+ # 3.5) Post-process: fix static actions inside for-loop blocks
+ python_src = _fix_static_actions_in_for_loops(python_src)
+
# 4) Persist script and files, then record mapping
content_bytes = python_src.encode("utf-8")
content_b64 = base64.b64encode(content_bytes).decode("utf-8")
@@ -479,6 +482,166 @@ async def generate_workflow_script(
)
+# ---------------------------------------------------------------------------
+# Post-processing: fix static actions inside for-loop blocks
+# ---------------------------------------------------------------------------
+# Matches `async for current_value in skyvern.loop(...):` blocks.
+_FOR_LOOP_RE = re.compile(
+ r"^(?P<indent> *)async for current_value in skyvern\.loop\(.*\):\s*$",
+)
+# Matches the start of an `await page.click(` call. We find the balanced
+# closing paren programmatically so CSS pseudo-selectors like `:has-text(...)`
+# or `:nth-child(2)` don't truncate the match — and we avoid a regex whose
+# nested quantifiers would cause exponential backtracking.
+_PAGE_CLICK_START_RE = re.compile(r"await page\.click\(")
+# Matches a prompt='...' or prompt="..." keyword argument inside a function call.
+_PROMPT_KWARG_RE = re.compile(r"""prompt\s*=\s*(['"])(.*?)\1""", re.DOTALL)
+
+
+def _find_click_calls(text: str) -> list[tuple[int, int, str]]:
+ """Find all ``await page.click(...)`` calls with balanced parentheses.
+
+ Returns a list of (start, end, args) tuples where *start*/*end* are byte
+ offsets into *text* spanning the full call and *args* is the text between
+ the outer parentheses.
+ """
+ results: list[tuple[int, int, str]] = []
+ for m in _PAGE_CLICK_START_RE.finditer(text):
+ start = m.start()
+ pos = m.end()
+ depth = 1
+ while pos < len(text) and depth > 0:
+ ch = text[pos]
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ pos += 1
+ if depth == 0:
+ results.append((start, pos, text[m.end() : pos - 1]))
+ return results
+
+
+def _fix_static_actions_in_for_loops(code: str) -> str:
+ """Detect page.click() calls inside for-loops that don't reference the loop variable.
+
+ When a click action inside a for-loop uses a static selector/prompt (not referencing
+ ``current_value``), it will resolve to the same element on every iteration — a common
+ bug in generated download scripts.
+
+ Fix: inject ``current_value`` into the prompt and upgrade ``ai='fallback'`` to
+ ``ai='proactive'`` so the LLM can disambiguate which element to click.
+ """
+ lines = code.split("\n")
+ result_lines: list[str] = []
+ i = 0
+ patched_count = 0
+
+ while i < len(lines):
+ line = lines[i]
+ m = _FOR_LOOP_RE.match(line)
+ if not m:
+ result_lines.append(line)
+ i += 1
+ continue
+
+ # Found a for-loop header. Collect the indented body.
+ loop_indent = m.group("indent")
+ body_indent_prefix = loop_indent + " " # 4-space indent inside loop
+ result_lines.append(line)
+ i += 1
+
+ # Gather body lines (lines that are indented deeper than the for-loop header or blank)
+ body_start = len(result_lines)
+ while i < len(lines):
+ body_line = lines[i]
+ # Body continues if the line is blank, or indented deeper than the for-loop
+ if body_line.strip() == "" or body_line.startswith(body_indent_prefix):
+ result_lines.append(body_line)
+ i += 1
+ else:
+ break
+
+ # Now check the body for static page.click() calls
+ body_text = "\n".join(result_lines[body_start:])
+ new_body_text = _patch_static_clicks_in_block(body_text)
+ if new_body_text != body_text:
+ patched_count += 1
+ # Replace body lines
+ result_lines[body_start:] = new_body_text.split("\n")
+
+ if patched_count > 0:
+ LOG.info("Fixed static click actions in for-loop blocks", patched_blocks=patched_count)
+ return "\n".join(result_lines)
+
+
+def _patch_static_clicks_in_block(body: str) -> str:
+ """Patch page.click() calls that don't reference current_value."""
+ calls = _find_click_calls(body)
+ if not calls:
+ return body
+
+ # Process matches in reverse order so earlier offsets stay valid.
+ for call_start, call_end, args in reversed(calls):
+ full = body[call_start:call_end]
+
+ # If the call already references current_value, leave it alone
+ if "current_value" in args:
+ continue
+
+ # Only patch clicks that explicitly use ai='fallback'. Proactive
+ # clicks already use the LLM, and clicks with no ai= kwarg are not
+ # part of the AI-fallback system so should be left alone.
+ if "ai='proactive'" in args or 'ai="proactive"' in args:
+ continue
+ has_fallback = "ai='fallback'" in args or 'ai="fallback"' in args
+ if not has_fallback:
+ continue
+
+ # Upgrade ai='fallback' to ai='proactive'
+ patched = full
+ if "ai='fallback'" in patched:
+ patched = patched.replace("ai='fallback'", "ai='proactive'")
+ elif 'ai="fallback"' in patched:
+ patched = patched.replace('ai="fallback"', 'ai="proactive"')
+
+ # Derive indentation from the position of the match in the body text
+ # so injected code is correctly aligned regardless of nesting level.
+ # Walk backwards from the match start to find the beginning of the line.
+ line_start = body.rfind("\n", 0, call_start)
+ if line_start == -1:
+ leading_text = body[:call_start]
+ else:
+ leading_text = body[line_start + 1 : call_start]
+ base_indent = leading_text if leading_text.isspace() or leading_text == "" else ""
+ kwarg_indent = base_indent + " "
+
+ # Append current_value context to the prompt so the LLM knows which item to target
+ # Look for an existing prompt= kwarg and append to it
+ prompt_match = _PROMPT_KWARG_RE.search(patched)
+ if prompt_match:
+ quote = prompt_match.group(1)
+ original_prompt = prompt_match.group(2)
+ # Use an f-string so current_value is evaluated at runtime
+ new_prompt = f"prompt=f{quote}{original_prompt} Target: {{current_value}}{quote}"
+ patched = patched[: prompt_match.start()] + new_prompt + patched[prompt_match.end() :]
+ else:
+ # No prompt= kwarg — add one with current_value context
+ # Insert before the closing paren
+ close_paren_idx = patched.rfind(")")
+ if close_paren_idx > 0:
+ before = patched[:close_paren_idx].rstrip().rstrip(",")
+ patched = (
+ before
+ + f",\n{kwarg_indent}prompt=f'Click the element for: {{current_value}}',\n{base_indent}"
+ + patched[close_paren_idx:]
+ )
+
+ body = body[:call_start] + patched + body[call_end:]
+
+ return body
+
+
_IMPORT_RE = re.compile(r"^(?:import |from \S+ import )")
@@ -774,6 +937,7 @@ async def create_script_version_from_review(
)
if main_py_content:
patched_main = _patch_main_py(main_py_content, updated_blocks)
+ patched_main = _fix_static_actions_in_for_loops(patched_main)
patched_bytes = patched_main.encode("utf-8")
patched_hash = hashlib.sha256(patched_bytes).hexdigest()
diff --git a/tests/unit/test_fix_static_actions_in_for_loops.py b/tests/unit/test_fix_static_actions_in_for_loops.py
new file mode 100644
index 000000000..602e62b5a
--- /dev/null
+++ b/tests/unit/test_fix_static_actions_in_for_loops.py
@@ -0,0 +1,380 @@
+"""Tests for _fix_static_actions_in_for_loops and _patch_static_clicks_in_block."""
+
+import textwrap
+
+from skyvern.services.workflow_script_service import (
+ _fix_static_actions_in_for_loops,
+ _patch_static_clicks_in_block,
+)
+
+# ---------------------------------------------------------------------------
+# _patch_static_clicks_in_block (low-level helper)
+# ---------------------------------------------------------------------------
+
+
+class TestPatchStaticClicksInBlock:
+ """Unit tests for the inner helper that patches individual click calls."""
+
+ def test_static_click_with_fallback_is_upgraded(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ prompt='Click the download link',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert "ai='proactive'" in result
+ assert "ai='fallback'" not in result
+
+ def test_static_click_prompt_gets_current_value(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ prompt='Click the download link',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert "current_value" in result
+ assert "prompt=f'" in result or 'prompt=f"' in result
+
+ def test_click_referencing_current_value_is_untouched(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector=f'a:has-text("{current_value["title"]}")',
+ ai='fallback',
+ prompt='Click the item',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert result == body
+
+ def test_already_proactive_click_is_untouched(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='a.download-link',
+ ai='proactive',
+ prompt='Click the download link',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert result == body
+
+ def test_double_quoted_fallback_is_upgraded(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector="a.download-link",
+ ai="fallback",
+ prompt="Click the download link",
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert 'ai="proactive"' in result
+ assert 'ai="fallback"' not in result
+ assert "current_value" in result
+
+ def test_double_quoted_proactive_is_untouched(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector="a.download-link",
+ ai="proactive",
+ prompt="Click the download link",
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert result == body
+
+ def test_click_without_prompt_gets_prompt_added(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert "ai='proactive'" in result
+ assert "prompt=f'" in result
+ assert "current_value" in result
+
+ def test_multiple_clicks_only_static_ones_patched(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='button.accept',
+ ai='fallback',
+ prompt='Accept terms',
+ )
+ await page.click(
+ selector=f'a:has-text("{current_value["name"]}")',
+ ai='fallback',
+ prompt='Click the item',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ # First click (static) should be patched
+ assert "ai='proactive'" in result
+ # Second click (has current_value) should keep fallback
+ assert "ai='fallback'" in result
+
+ def test_no_click_calls_returns_unchanged(self) -> None:
+ body = textwrap.dedent("""\
+ await page.goto(url='https://example.com')
+ data = await page.extract(prompt='Get items')""")
+ result = _patch_static_clicks_in_block(body)
+ assert result == body
+
+ def test_original_prompt_text_is_preserved(self) -> None:
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ prompt='Download the quarterly report',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert "Download the quarterly report" in result
+ assert "Target: {current_value}" in result
+
+
+# ---------------------------------------------------------------------------
+# _fix_static_actions_in_for_loops (top-level function)
+# ---------------------------------------------------------------------------
+
+
+class TestFixStaticActionsInForLoops:
+ """Integration tests for the full for-loop detection and patching."""
+
+ def test_static_click_inside_for_loop_is_patched(self) -> None:
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ prompt='Click the download link',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='proactive'" in result
+ assert "current_value" in result.split("prompt=")[1]
+
+ def test_click_outside_for_loop_is_untouched(self) -> None:
+ code = textwrap.dedent("""\
+ await page.click(
+ selector='button.submit',
+ ai='fallback',
+ prompt='Click submit',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert result == code
+
+ def test_click_after_for_loop_is_untouched(self) -> None:
+ """Code that follows the for-loop (at same or lesser indent) should not be patched."""
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ data = await page.extract(prompt='Get data')
+
+ await page.click(
+ selector='button.submit',
+ ai='fallback',
+ prompt='Click submit',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ # The click after the loop should still be fallback
+ lines_after_loop = result.split("await page.click(")[1]
+ assert "ai='fallback'" in lines_after_loop
+
+ def test_nested_indentation_preserved(self) -> None:
+ code = textwrap.dedent("""\
+ async def block_fn(page, context):
+ items = await page.extract(prompt='Get items')
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ prompt='Click link',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='proactive'" in result
+ # Verify the function def and extract are still there
+ assert "async def block_fn" in result
+ assert "await page.extract" in result
+
+ def test_multiple_for_loops_both_patched(self) -> None:
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items_a):
+ await page.click(
+ selector='a.link-a',
+ ai='fallback',
+ prompt='Click A',
+ )
+
+ async for current_value in skyvern.loop(items_b):
+ await page.click(
+ selector='a.link-b',
+ ai='fallback',
+ prompt='Click B',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert result.count("ai='proactive'") == 2
+ assert result.count("ai='fallback'") == 0
+
+ def test_for_loop_with_current_value_click_is_untouched(self) -> None:
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector=f'a:has-text("{current_value["title"]}")',
+ ai='fallback',
+ prompt='Click the item',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='fallback'" in result
+ assert "ai='proactive'" not in result
+
+ def test_for_loop_with_proactive_click_is_untouched(self) -> None:
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='a.download-link',
+ ai='proactive',
+ prompt='Click the download link',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert result == code
+
+ def test_code_with_no_for_loops_is_untouched(self) -> None:
+ code = textwrap.dedent("""\
+ async def block_fn(page, context):
+ await page.goto(url='https://example.com')
+ data = await page.extract(prompt='Get items')
+ return data""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert result == code
+
+ def test_empty_string(self) -> None:
+ assert _fix_static_actions_in_for_loops("") == ""
+
+ def test_realistic_download_script(self) -> None:
+ """Simulate the real-world bug: a download script with static click inside for-loop."""
+ code = textwrap.dedent("""\
+ async def download_block(page, context):
+ items = await page.extract(
+ data_extraction_goal='Extract all downloadable file names and links',
+ output_type='list',
+ )
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='a.file-download',
+ ai='fallback',
+ prompt='Click the download button for the file',
+ )
+ await page.wait_for_download()
+
+ return {"downloaded": len(items)}""")
+ result = _fix_static_actions_in_for_loops(code)
+ # The static click should be patched
+ assert "ai='proactive'" in result
+ assert "current_value" in result.split("prompt=f'")[1].split("'")[0]
+ # The wait_for_download and return should still be there
+ assert "await page.wait_for_download()" in result
+ assert 'return {"downloaded": len(items)}' in result
+
+ def test_for_loop_body_with_blank_lines(self) -> None:
+ """Blank lines inside the for-loop body should not break body detection."""
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ data = await page.extract(prompt='Get info')
+
+ await page.click(
+ selector='a.download',
+ ai='fallback',
+ prompt='Download file',
+ )
+
+ result = "done"
+ """)
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='proactive'" in result
+ # Code after the loop should be untouched
+ assert 'result = "done"' in result
+
+ def test_complex_loop_expression(self) -> None:
+ """Loop with complex expression in skyvern.loop() should still match."""
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(context.parameters["items"], max_iterations=10):
+ await page.click(
+ selector='button.process',
+ ai='fallback',
+ prompt='Process the item',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='proactive'" in result
+
+ def test_mixed_static_and_dynamic_clicks_in_loop(self) -> None:
+ """Only the static click should be patched; the dynamic one should be left alone."""
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='button.expand',
+ ai='fallback',
+ prompt='Expand the row',
+ )
+ await page.click(
+ selector=f'a:has-text("{current_value["name"]}")',
+ ai='fallback',
+ prompt='Click the specific item',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ # Static click patched
+ assert "ai='proactive'" in result
+ # Dynamic click preserved
+ assert "ai='fallback'" in result
+
+ def test_selector_with_nested_parens_is_matched(self) -> None:
+ """CSS pseudo-selectors with parens (e.g. :has-text()) must not truncate the regex match."""
+ code = textwrap.dedent("""\
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='a.file:has-text("Download")',
+ ai='fallback',
+ prompt='Click the link',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='proactive'" in result
+ assert "ai='fallback'" not in result
+ # The output must be syntactically coherent (no dangling args)
+ assert result.count("await page.click(") == 1
+
+ def test_selector_with_nth_child_parens(self) -> None:
+ """Selectors like :nth-child(2) must not break the regex."""
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='tr:nth-child(2)',
+ ai='fallback',
+ prompt='Click row',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert "ai='proactive'" in result
+ assert "ai='fallback'" not in result
+ assert "current_value" in result
+
+ def test_click_without_ai_kwarg_is_untouched(self) -> None:
+ """Clicks with no ai= kwarg should not be modified."""
+ body = textwrap.dedent("""\
+ await page.click(
+ selector='a.download-link',
+ prompt='Click the download link',
+ )""")
+ result = _patch_static_clicks_in_block(body)
+ assert result == body
+
+ def test_deeply_nested_click_indent_is_correct(self) -> None:
+ """When a click is inside a function + for-loop, injected prompt must align correctly."""
+ code = textwrap.dedent("""\
+ async def block_fn(page, context):
+ items = await page.extract(prompt='Get items')
+ async for current_value in skyvern.loop(items):
+ await page.click(
+ selector='a.download-link',
+ ai='fallback',
+ )""")
+ result = _fix_static_actions_in_for_loops(code)
+ assert "ai='proactive'" in result
+ # Verify the injected prompt line is indented deeper than the click call
+ for line in result.split("\n"):
+ if "prompt=f'" in line and "current_value" in line:
+ # The click `await` is at 8-space indent; kwarg should be at 12
+ leading = len(line) - len(line.lstrip())
+ assert leading == 12, f"Expected 12-space indent, got {leading}"
+ break
+ else:
+ raise AssertionError("Expected a prompt=f line with current_value")